text stringlengths 184 4.48M |
|---|
import Todos from "./todo-app/Todos";
import { Link, Route, Switch } from "react-router-dom";
import Demos from "./09-demos";
/*
Legen Sie eine neue Datei an und einer ähnlichen Funktion wie in App.tsx an.
Ersetzen Sie die App-Komponente in index.tsx durch die neu erstellte Funktion Root().
Verschieben Sie die Dateien der App-Komponente in einen Ordner 'AppDefault'.
*/
function Root() {
return (
<>
<h1>Root-Komponente der React App</h1>
<nav>
<button><Link to="/todos">Todos</Link></button>
<button><Link to="/demos">Demos</Link></button>
</nav>
<Switch>
<Route path="/todos" component={Todos} />
<Route path="/demos" component={Demos} />
</Switch>
</>
)
}
export default Root; |
import Link from "next/link"
import { useState, useEffect } from "react"
import { getCategories } from "../services"
const Categories = () => {
const [categories, setCategories] = useState([]);
useEffect(() => {
getCategories().then((newCategories) => {
setCategories(newCategories);
});
}, []);
return (
<div className="Categories-main shadow-lg">
<h3 className="Categories-heading">Categories</h3>
{categories.map((category, index) => (
<Link key={index} href={`/category/${category.slug}`}>
<div className="Categories-content">
<span className="Category-slug-main">
{category.name}
</span>
</div>
</Link>
))}
</div>
);
};
export default Categories |
import { defineStore } from 'pinia'
import { requiredValidator } from '@validators'
export const useAppointmentStore = defineStore('appointmentStore', {
state: () => ({
appointmentLabels: [
{
text: 'Type of Consultation',
value: 'type',
type: 'select',
rules: [requiredValidator],
items: ['Face to Face', 'Teleconsultation'],
noEdit: false,
},
{
text: 'Date',
value: 'date',
type: 'date',
rules: [requiredValidator],
noEdit: false,
},
{
text: 'Time',
value: 'time',
type: 'time',
rules: [requiredValidator],
noEdit: false,
},
{
text: 'Reason for Consultation',
value: 'description',
type: 'textarea',
rules: [requiredValidator],
noEdit: false,
},
],
current_appointment: {},
drawer: false,
loading: false,
error: null,
appointments: [],
showConfirm: false,
}),
actions: {
startLoading() {
this.loading = true
this.error = null
},
},
}) |
# Python 中的砖块排序算法[易于实现]
> 原文:<https://www.askpython.com/python/examples/brick-sort-algorithm>
在本教程中,我们将学习如何实现砖块排序算法,以便对数组中的元素进行排序。这在编码界是未知的,但学习一种新的排序技术没有坏处。
在用 python 编程语言实现 brick sort 之前,让我们先了解一下什么是 brick sort。
***也读作:[在 Python 中插入排序](https://www.askpython.com/python/examples/insertion-sort-in-python)***
* * *
## 砖块排序算法简介
**砖块排序**,又称**奇偶排序**,是**泡泡排序**的修改版本。排序算法分为两个阶段,即**奇数阶段和偶数阶段**。通过确保在每次迭代中执行偶数和奇数阶段,控制将一直运行,直到对数组进行排序。
现在你可能会问这些奇数和偶数阶段是什么意思?当控件执行奇数阶段时,我们将只对奇数索引处的元素进行排序。在事件阶段的执行过程中,以类似的模式,控件将只对偶数索引处的元素进行排序。
* * *
## 砖块排序算法实现
为了实现砖块排序,我们将遵循一些步骤,下面也将提到。
* 声明**砖块排序函数**来执行排序,并取一个变量到**在奇数和偶数阶段**之间切换。
* 创建一个变量 **isSort** ,初始值为 0。此变量的目的是跟踪当前阶段。
* 运行 while 循环进行迭代,直到 isSort 等于 1。
1. 创建一个内部 for 循环来对奇数条目进行排序。
2. 类似地,创建另一个内部 for 循环来对偶数条目进行排序。
* 一旦排序完成,我们**返回结果**。
* * *
## 在 Python 中实现砖块排序
让我们直接进入 Python 中的块排序算法的实现,并确保我们可以获得预期的输出。
```py
def brickSort(array, n):
isSort = 0
while isSort == 0:
isSort = 1
for i in range(1, n-1, 2):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
isSort = 0
for i in range(0, n-1, 2):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
isSort = 0
return
array = [31, 76, 18, 2, 90, -6, 0, 45, -3]
n = len(array)
print("Array input by user is: ", end="")
for i in range(0, n):
print(array[i], end =" ")
brickSort(array, n);
print("\nArray after brick sorting is: ", end="")
for i in range(0, n):
print(array[i], end =" ")
```
上面提到的代码如下所示。您可以看到数组排序成功。
```py
Array input by user is: 31 76 18 2 90 -6 0 45 -3
Array after brick sorting is: -6 -3 0 2 18 31 45 76 90
```
* * *
## 结论
我希望今天你学到了一种新的排序算法。虽然要求不多,但是口袋里有一些额外的知识总是好的!
感谢您的阅读!快乐学习!😇
* * * |
import React, { Component } from 'react';
import Latex from 'react-latex';
import './App.scss';
import ProgressTable from './ProgressTable';
import MinHash from './MinHash';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
strA: 'ABGTTABGT',
strB: 'ABGTABGTT',
k: 3,
m: 5,
inProgress: false,
results: {},
minHashInstance: undefined,
};
}
getResults(strId) {
const { results, minHashInstance, inProgress } = this.state;
if (!inProgress) {
return {};
}
const isA = strId === 'A';
const {
[isA ? 'aSteps' : 'bSteps']: steps,
[isA ? 'posA' : 'posB']: pos,
[isA ? 'strA' : 'strB']: str,
xorNumbers,
k,
m,
[isA ? 'minHashA' : 'minHashB']: minHash,
} = minHashInstance;
return {
steps,
pos,
str,
xorNumbers,
k,
m,
minHash,
hashValues: isA ? results.allHashValuesA : results.allHashValuesB,
};
}
step() {
const { minHashInstance } = this.state;
const res = minHashInstance.step();
this.setState(prevState => ({
results: {
allHashValuesA: [
...(prevState.results.allHashValuesA || []),
...(res.hashValuesA.length ? [res.hashValuesA] : []),
],
allHashValuesB: [
...(prevState.results.allHashValuesB || []),
...(res.hashValuesB.length ? [res.hashValuesB] : []),
],
},
done: res.done,
simValue: res.simValue,
match: res.match,
}));
}
finish() {
const { minHashInstance } = this.state;
const res = minHashInstance.finish();
this.setState(prevState => ({
results: {
allHashValuesA: [
...(prevState.results.allHashValuesA || []),
...(res.allHashValuesA.length ? res.allHashValuesA : []),
],
allHashValuesB: [
...(prevState.results.allHashValuesB || []),
...(res.allHashValuesB.length ? res.allHashValuesB : []),
],
},
done: res.done,
simValue: res.simValue,
match: res.match,
}));
}
render() {
const {
strA, strB, inProgress, k, m, done, simValue, match,
} = this.state;
const inputButtons = (
<div className="d-inline-flex col-8 justify-content-end">
<button
type="button"
className="btn btn-lg btn-outline-success m-2 px-5"
onClick={() => this.setState({
inProgress: true,
minHashInstance: new MinHash(strA, strB, k, m),
results: {},
done: false,
})}
>
Start
</button>
<button
type="button"
className="btn btn-lg btn-outline-danger m-2 px-4"
onClick={() => this.setState({ strA: '', strB: '' })}
>
Wyczyść
</button>
</div>
);
const actionButtons = (
<div className="d-inline-flex col-8 justify-content-end">
<button
type="button"
className="btn btn-lg btn-outline-success m-2 px-5"
onClick={() => this.step()}
disabled={done}
>
Krok
</button>
<button
type="button"
className="btn btn-lg btn-outline-primary m-2 px-4"
onClick={() => this.finish()}
disabled={done}
>
Do końca
</button>
<button
type="button"
className="btn btn-lg btn-outline-danger m-2 px-4"
onClick={() => this.setState({ inProgress: false })}
>
{done ? 'Restart' : 'Przerwij'}
</button>
</div>
);
const buttons = inProgress ? actionButtons : inputButtons;
const inputScreen = (
<div>
<div className="form-row w-100">
<div className="col">
<label htmlFor="stringA" className="">Podaj pierwszy łańcuch:</label>
<input
className="form-control form-control-lg"
id="stringA"
value={strA}
disabled={inProgress}
onChange={e => this.setState({ strA: e.target.value.toUpperCase() })}
/>
</div>
<div className="col">
<label htmlFor="stringB">Podaj drugi łańcuch:</label>
<input
className="form-control form-control-lg"
id="stringB"
value={strB}
disabled={inProgress}
onChange={e => this.setState({ strB: e.target.value.toUpperCase() })}
/>
</div>
</div>
<div className="form-row mt-3 w-100">
<div className="col-2">
<label htmlFor="k_value" className="">Podaj długość kmerów:</label>
<input
className="form-control form-control-lg"
id="k_value"
type="number"
min={1}
value={k}
disabled={inProgress}
onChange={e => this.setState({ k: parseInt(e.target.value, 10) })}
/>
</div>
<div className="col-2">
<label htmlFor="m_value">Podaj liczbę haszy:</label>
<input
className="form-control form-control-lg"
type="number"
id="m_value"
min={1}
value={m - 1}
disabled={inProgress}
onChange={e => this.setState({ m: parseInt(e.target.value, 10) + 1 })}
/>
</div>
{buttons}
</div>
</div>
);
const resultString = `Podobieństwo ${parseInt(simValue * 100, 10)}% (${match}/${m - 1})`;
const finalResult = (
<div className="d-flex justify-content-center">
<h3 className="border border-primary rounded mt-3 py-4 px-5">
{resultString}
</h3>
</div>
);
const resA = this.getResults('A');
const resB = this.getResults('B');
return (
<div className="p-3">
<h3 className="mb-3">Algorytm minHash</h3>
{inputScreen}
{(done && inProgress) && finalResult}
{inProgress && <ProgressTable data={resA} otherData={resB} />}
{inProgress && <ProgressTable data={resB} otherData={resA} />}
<div className="mt-5">
<p>
<Latex>
W aplikacji została zastosowana następująca funkcja haszująca:
</Latex>
</p>
<p>
<Latex>
{'$$ \\#(s) = \\sum_{i = 0}^{n - 1}{ascii(s_i) * p^i} \\pmod{q} $$'}
</Latex>
</p>
<p>
<Latex>
{'gdzie $ p \\equiv 21474799, q \\equiv 2147483647, n$ - długość ciągu znaków, '
+ '$i$ - indeks w ciągu znaków (liczony od 0), '
+ '$ascii(c)$ - zwraca wartość kodu ASCII dla znaku $c$'}
</Latex>
</p>
<p>
<Latex>
{'Wszystkie obliczenia odbywają się w pierścieniu N-bitowym ' +
'$\\langle0 - 2^N)$, gdzie $N = 32.$'}
</Latex>
</p>
</div>
</div>
);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
namespace Morsekoden
{
internal class Program
{
static void Main(string[] args)
{
// Loops until another key than R is pressed when asked
do
{
Console.Clear();
Console.WriteLine("Enter a text you want to translate to morse code");
// User input which will be translated
string userInputText = Console.ReadLine();
// 2-dimensional array which acts like a translator
string[,] morseAlphabet = {
{
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "æ", "ø", "å", "0",
"1", "2", "3", "4", "5", "6", "7", "8", "9", ".", ",", ":", "?", "'", "-",
"/", "(", ")", "\"", "×", "@", " "
},
{
// A-O
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---",
// P-Å
".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".-.-", "---.", ".--.-",
// 0-9
"-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
// "." "," ":" "?" "'" "-" "/" "(" ")" "\"" "×" "@" " "
".-.-.-", "--..--", "---...", "..--..", ".----.", "-....-", "-..-.", "-.--.", "-.--.-", ".-..-.", "-..-", ".--.-.", "/"
}
};
// Uses the translator and translates every single character in a text
string morse = "";
foreach(char s in userInputText.ToLower())
{
// Loops the columns of the 2-dimensional array which gives me every single character
for(int i = 0; i < morseAlphabet.GetLength(1); i++)
{
// Checks if the array contains the character and translates it to morse
if(morseAlphabet[0,i].Contains(s))
{
morse += morseAlphabet[1,i];
}
}
morse += ' ';
}
// Writes out the morse code
Console.Clear();
Console.WriteLine("You wrote: " + userInputText);
Console.WriteLine("In morse code: " + morse);
Console.WriteLine("\nPress R to translate a new morse code, or any other key for closing the program");
}while (Console.ReadKey(true).Key == ConsoleKey.R);
}
}
} |
import fs from 'fs';
import path from 'path';
import ejs from 'ejs';
import { getCanvasContextFromImagePath } from '../../api/canvas/getCanvasContextFromImagePath';
import { extractCromTileSources } from '../../api/crom/extractCromTileSources';
import { ICROMGenerator, CROMTile, CROMTileMatrix } from '../../api/crom/types';
import { CROM_TILE_SIZE_PX } from '../..//api/crom/constants';
import { denormalizeDupes } from '../../api/tile/denormalizeDupes';
import { sliceOutFrame } from '../../api/tile/sliceOutFrame';
import { CodeEmit, FileToWrite, Json } from '../../types';
type CromImageInput = {
name: string;
imageFile: string;
tileWidth?: number;
autoAnimation?: number;
[key: string]: unknown;
};
type CromImagesJsonSpec = {
inputs: CromImageInput[];
codeEmit?: CodeEmit[];
};
type CodeEmitTile = {
index: number;
paletteIndex: number;
autoAnimation?: 4 | 8;
};
type CodeEmitTileMatrixRow = Array<CodeEmitTile | null>;
type CodeEmitTileMatrix = CodeEmitTileMatrixRow[];
type CodeEmitImage = {
name: string;
imageFile: string;
tiles: CodeEmitTileMatrix;
custom: Record<string, unknown>;
};
function applyChildTiles(
masterFrame: CROMTile[][],
childFrames: CROMTile[][][]
) {
for (let f = 0; f < childFrames.length; ++f) {
for (let y = 0; y < childFrames[f].length; ++y) {
for (let x = 0; x < childFrames[f][y].length; ++x) {
// @ts-expect-error it wants this array to already be 3 or 7 in size
masterFrame[y][x].childAnimationFrames ??= [];
masterFrame[y][x].childAnimationFrames!.push(childFrames[f][y][x]);
childFrames[f][y][x].childOf = masterFrame[y][x];
}
}
}
}
function toCodeEmitTiles(
input: CromImageInput,
inputTiles: CROMTileMatrix
): CodeEmitTileMatrix {
// if this crom image is an auto animation, then the inputTiles has all the frames of the animation,
// but for code emit, we want to treat it just like an image, so just slice out the first frame
// and ignore the others. They got emitted into the crom properly
if (input.autoAnimation) {
inputTiles = sliceOutFrame(inputTiles, 0, input.tileWidth ?? 1);
}
return inputTiles.map((inputRow) => {
return inputRow.map((inputTile) => {
if (inputTile === null) {
return null;
}
return {
index: inputTile.cromIndex!,
paletteIndex: inputTile.paletteIndex!,
};
});
});
}
function getCustomPropObject(input: CromImageInput): Record<string, unknown> {
const { name, imageFile, tileWidth, ...custom } = input;
return custom;
}
function createImageDataForCodeEmit(
inputs: CromImageInput[],
tiles: CROMTileMatrix[]
): CodeEmitImage[] {
const finalTiles = denormalizeDupes(tiles, 'cromIndex');
return inputs.map((input, i) => {
return {
...input,
tiles: toCodeEmitTiles(input, finalTiles[i]),
custom: getCustomPropObject(input),
};
});
}
const cromImages: ICROMGenerator = {
jsonKey: 'cromImages',
getCROMSources(rootDir: string, inputJson: Json) {
const { inputs } = inputJson as CromImagesJsonSpec;
return inputs.map((input) => {
const context = getCanvasContextFromImagePath(
path.resolve(rootDir, input.imageFile)
);
const allTiles = extractCromTileSources(context);
if (input.autoAnimation) {
const tileWidth = input.tileWidth ?? 1;
const canvasWidthInTiles = context.canvas.width / CROM_TILE_SIZE_PX;
const frameCount = canvasWidthInTiles / tileWidth;
if (frameCount !== input.autoAnimation) {
throw new Error(
`cromImages: ${input.name} (${input.imageFile}) is an auto animation of ${input.autoAnimation} but has ${frameCount} frames`
);
}
if (allTiles.some((f) => f === null)) {
throw new Error(
`cromAnimations: ${input.name} (${input.imageFile}) is an auto animation of ${input.autoAnimation} but has blank frames. If a frame should be empty, use magenta instead of alpha=0`
);
}
const frames: CROMTileMatrix[] = [];
for (let x = 0; x < canvasWidthInTiles; x += tileWidth) {
const frame = sliceOutFrame(allTiles, x, x + tileWidth);
frames.push(frame);
}
applyChildTiles(
frames[0] as CROMTile[][],
frames.slice(1) as CROMTile[][][]
);
}
return allTiles;
});
},
getCROMSourceFiles(rootDir: string, inputJson: Json, tiles) {
const { inputs, codeEmit } = inputJson as CromImagesJsonSpec;
const images = createImageDataForCodeEmit(inputs, tiles);
return (codeEmit ?? []).map<FileToWrite>((codeEmit) => {
const templatePath = path.resolve(rootDir, codeEmit.template);
const template = fs.readFileSync(templatePath).toString();
const code = ejs.render(template, { images });
return {
path: path.resolve(rootDir, codeEmit.dest),
contents: Buffer.from(code),
};
});
},
};
export { cromImages }; |
/*
artifact generator: C:\My\wizzi\stfnbssl\wizzi.v07\packages\wizzi-js\lib\artifacts\ts\module\gen\main.js
package: wizzi-js@0.7.14
primary source IttfDocument: C:\My\wizzi\stfnbssl\wizzi.apps\packages\wizzi.editor\.wizzi\src\features\form\Form.tsx.ittf
*/
import * as React from 'react';
import {Register, Unregister, Update, FormValidation} from './types';
export type FormProps = {
onSubmit: () => void;
children: React.ReactNode;
};
type State = {
isValid: boolean;
};
export const FormValidationContext = React.createContext<FormValidation | undefined>(undefined);
export default class Form extends React.Component<FormProps, State> {
state = {
isValid: false
}
;
componentDidMount() {
this._update();
}
_key = 0;
_inputs: Array<{
key: number;
validate: () => Error | null;
focus: () => void;
}> = [];
_register: Register = ({
validate,
focus
}) => {
const key = this._key++;
this._inputs.push({
key,
validate,
focus
})
return key;
}
;
_unregister: Unregister = (key: number) =>
this._inputs = this._inputs.filter(it =>
it.key !== key
)
;
_update: Update = () =>
this.setState({
isValid: this._inputs.every(it =>
!it.validate()
)
})
;
_handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
for (const input of this._inputs) {
if (input.validate()) {
input.focus();
return ;
}
}
this.props.onSubmit();
}
;
render() {
return (
<FormValidationContext.Provider
value={{
register: this._register,
unregister: this._unregister,
update: this._update,
valid: this.state.isValid
}}>
<form
onSubmit={this._handleSubmit}>
{this.props.children}
</form>
</FormValidationContext.Provider>
)
;
}
} |
import React, { useState } from 'react'
import './CSS/LoginSignup.css'
export default function LoginSignup() {
const [state,setState] = useState("Login");
const [formData, setFormData] = useState({
username: "",
password: "",
email: "",
})
const changeHandler = (e) => {
setFormData({...formData,[e.target.name]:e.target.value})
}
const login = async ()=> {
console.log("Login Function executed", formData)
let responseData;
await fetch('https://mern-backend-j5ku.onrender.com/login', {
method: 'POST',
headers: {
Accept: "application/form-data",
'Content-Type' : 'application/json',
},
body: JSON.stringify(formData),
}).then((response)=> response.json()).then((data)=>responseData=data);
if(responseData.success) {
localStorage.setItem('auth-token', responseData.token);
window.location.replace('/')
}
else {
alert(responseData.errors)
}
}
const signup = async ()=> {
console.log("signup Function executed", formData);
let responseData;
await fetch('https://mern-backend-j5ku.onrender.com/signup', {
method: 'POST',
headers: {
Accept: "application/form-data",
'Content-Type' : 'application/json',
},
body: JSON.stringify(formData),
}).then((response)=> response.json()).then((data)=>responseData=data);
if(responseData.success) {
localStorage.setItem('auth-token', responseData.token);
window.location.replace('/')
}
else {
alert(responseData.errors)
}
}
return (
<div className='loginsignup'>
<div className="loginsignup-container">
<h1>{state}</h1>
<div className="loginsignup-fields">
{state==="Sign Up"?<input name='username' value={formData.username} onChange={changeHandler} type="text" placeholder='Your Name' />:<></>}
<input name='email' value={formData.email} onChange={changeHandler}type="email" placeholder='Email Address' />
<input name='password' value={formData.password} onChange={changeHandler} type="password" placeholder='Password' />
</div>
<button onClick={()=>{state==="Login"?login():signup()}}>Continue</button>
{state==="Sign Up"?<p className="loginsignup-login">Already have an account? <span onClick={()=>{setState("Login")}}>Login here</span></p>:
<p className="loginsignup-login">Create an account? <span onClick={()=>{setState("Sign Up")}}>click here</span></p>}
<div className="loginsignup-agree">
<input type="checkbox" name="" id="" />
<p>By continuing, i agree to the terms of use and privacy policy</p>
</div>
</div>
</div>
)
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video-Search-Engine</title>
</head>
<body>
<nav>
<div id="searchQueryPanel">
<img src="website\templates\youtube.jpeg" alt="Logo">
<input type="text" id="searchQuery" placeholder="Enter your search query">
<button id="searchButton">Search</button>
</div>
</nav>
<div id="panelsContainer">
<!-- Current Video Panel -->
<h3>Current Video</h3>
<div id="currentVideoPanel">
<div id="videoDetails"></div>
</div>
<!-- Search Results Panel -->
<h3>Search Results</h3>
<div id="searchResultsPanel">
<ul id="searchResultsList">
<!-- Video results will be dynamically added here -->
</ul>
</div>
</div>
<script>
document.getElementById("searchButton").addEventListener("click", search);
async function search() {
var searchQuery = document.getElementById("searchQuery").value;
try {
// Perform an AJAX request to Flask endpoint
const response = await fetch('/search', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'search_query=' + encodeURIComponent(searchQuery),
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Update the search results dynamically
const data = await response.json();
console.log('Fetched Video IDs:', data); // Log retrieved video IDs to the console
var searchResultsList = document.getElementById('searchResultsList');
searchResultsList.innerHTML = ''; // Clear previous results
data.forEach(video => {
var listItem = document.createElement('li');
listItem.innerHTML = `
<img src="${video.thumbnail}" alt="${video.title} Thumbnail">
<h4>${video.title}</h4>
<p>${video.description}</p>
`;
searchResultsList.appendChild(listItem);
});
} catch (error) {
console.error('Error:', error);
}
}
</script>
</body>
</html> |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>
void swap(int **list, int a, int b)
{
int tmp;
tmp = (*list)[a];
(*list)[a] = (*list)[b];
(*list)[b] = tmp;
}
void selection_sort(int **list, int n)
{
int *p;
int max;
p = *list;
for (int i = n - 1; i >= 0; --i)
{
max = i;
for (int j = 0; j < i; ++j)
{
if (p[max] < p[j])
max = j;
}
if (max != i)
swap(list, i, max);
}
}
void insertion_sort(int **list, int n)
{
int *p;
int key, j;
p = *list;
for (int i = 1; i < n; ++i)
{
key = p[i];
j = i - 1;
while (j >= 0 && key < p[j])
{
p[j + 1] = p[j];
j--;
}
p[j + 1] = key;
}
}
void get_A_time(int **A)
{
LARGE_INTEGER start, end, diff, ticksPerSec;
QueryPerformanceFrequency(&ticksPerSec);
QueryPerformanceFrequency(&start);
selection_sort(A, n);
QueryPerformanceCounter(&end);
diff.QuadPart = end.QuadPart - start.QuadPart;
printf("A time : %12f sec\n", ((double)diff.QuadPart/(double)ticksPerSec.QuadPart));
}
void get_B_time(int **B)
{
LARGE_INTEGER start, end, diff, ticksPerSec;
QueryPerformanceFrequency(&ticksPerSec);
QueryPerformanceFrequency(&start);
insertion_sort(B, n);
QueryPerformanceCounter(&end);
diff.QuadPart = end.QuadPart - start.QuadPart;
printf("B time : %12f sec\n", ((double)diff.QuadPart/(double)ticksPerSec.QuadPart));
}
int main()
{
int n;
int *A, *B;
int *RA, *RB;
scanf("%d", &n);
A = (int *)malloc(n * sizeof(int));
B = (int *)malloc(n * sizeof(int));
RA = (int *)malloc(n * sizeof(int));
RB = (int *)malloc(n * sizeof(int));
if (!A || !B || !RA || !RB)
return (-1);
//랜덤시행
srand(time(NULL));
for (int i = 0; i < n; ++i){
A[i] = rand();
B[i] = A[i];
}
printf("testing A\n");
get_A_time(&A);
get_B_time(&B);
printf("\ntesting B\n");
get_A_time(&A);
get_B_time(&B);
for (int i = 0; i < n; ++i){
RA[i] = A[n - i - 1];
RB[i] = B[n - i - 1];
}
printf("testing C\n");
get_A_time(&A);
get_B_time(&B);
free(A);
free(B);
free(RA);
free(RB);
return (0);
} |
//
// LocationDetailView.swift
// whatnext
//
// Created by Mike Dong on 2/4/24.
//
import SwiftUI
import CoreLocation
struct LocationDetailView: View {
let location: Location
let userLocation: CLLocation?
@AppStorage("userID") var loginUserID: String = ""
@State private var isFavorite: Bool = false
@State private var isVisited: Bool = false
private let profileService = ProfileService()
var body: some View {
ScrollView {
VStack(alignment: .leading) {
ZStack(alignment: .topTrailing) {
ImageView(imageUrl: location.imageUrl)
// Favorite and Visited buttons placed in the top right corner
HStack(spacing: 10) {
// Favorite Button
Button(action: {
self.isFavorite.toggle()
// Placeholder function to update favorite status
}) {
Image(systemName: isFavorite ? "heart.fill" : "heart")
.foregroundColor(isFavorite ? .red : .gray)
.padding(8)
.background(Circle().fill(Color.white))
.shadow(radius: 3)
}
// Visited Button
Button(action: {
self.isVisited.toggle()
// Placeholder function to update visited status
}) {
Image(systemName: isVisited ? "checkmark.circle.fill" : "checkmark.circle")
.foregroundColor(isVisited ? .green : .gray)
.padding(8)
.background(Circle().fill(Color.white))
.shadow(radius: 3)
}
}
.padding(8)
}
BusinessInfo(name: location.name, stars: location.stars, reviewCount: location.reviewCount)
PriceAndCategoryView(price: location.price, tag: location.tag)
HoursView(hours: location.hours)
ContactInfo(displayPhone: location.displayPhone, address: location.address, city: location.city, state: location.state, postalCode: location.postalCode)
if let userLocation = userLocation, let locationLatitude = location.latitude, let locationLongitude = location.longitude {
let locationCLLocation = CLLocation(latitude: locationLatitude, longitude: locationLongitude)
let distanceInMeters = userLocation.distance(from: locationCLLocation)
Text(String(format: "%.2f meters away", distanceInMeters))
.padding()
}
}
}
.background(Color(UIColor.systemBackground))
.cornerRadius(10)
.navigationBarTitleDisplayMode(.inline)
}
}
// ImageView for displaying the location's image
struct ImageView: View {
let imageUrl: String?
var body: some View {
if let imageUrl = imageUrl, let url = URL(string: imageUrl) {
AsyncImage(url: url) { phase in
if let image = phase.image {
image
.resizable()
.scaledToFill()
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 2.2)
.clipped()
} else if phase.error != nil {
Color.gray.opacity(0.3)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 2.2)
} else {
Color.gray.opacity(0.3)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 2.2)
}
}
} else {
Color.gray.opacity(0.3)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 2.2)
}
}
}
// BusinessInfo for displaying the business name and ratings
struct BusinessInfo: View {
let name: String
let stars: Double?
let reviewCount: Int?
var body: some View {
VStack(alignment: .leading) {
Text(name)
.font(.largeTitle)
.bold()
.foregroundColor(Color.primary)
HStack {
StarRatingView(stars: Int(stars ?? 0))
if let stars = stars, let reviewCount = reviewCount {
Text("\(String(format: "%.1f", stars)) (\(reviewCount) reviews)")
.font(.caption)
.foregroundColor(Color.primary)
}
}
}
.padding()
}
}
// StarRatingView for displaying star ratings
struct StarRatingView: View {
let stars: Int
var body: some View {
HStack {
ForEach(0..<5, id: \.self) { star in
Image(systemName: star < stars ? "star.fill" : "star")
.foregroundColor(star < stars ? .yellow : .gray)
}
}
}
}
// PriceAndCategoryView for displaying the price and categories
struct PriceAndCategoryView: View {
let price: String?
let tag: [String]?
var body: some View {
Divider()
.background(Color.blue)
HStack {
if let price = price {
Text(price)
.bold()
.padding(5)
.background(Color.gray.opacity(0.2))
.cornerRadius(5)
}
ForEach(tag?.map { $0.replacingOccurrences(of: "_", with: " ").capitalized } ?? [], id: \.self) { category in
Text(category)
.padding(6)
.background(Color.blue)
.cornerRadius(10)
.foregroundColor(.primary) // Adapts automatically to light/dark mode
}
}
.padding(.vertical, 20)
.padding(.horizontal)
.cornerRadius(10)
}
}
struct HoursView: View {
let hours: Hours?
@State private var isExpanded: Bool = false
var body: some View {
VStack(alignment: .leading, spacing: 5) {
Divider()
.background(Color.blue)
Button(action: {
withAnimation {
isExpanded.toggle()
}
}) {
HStack {
Text("Hours")
.foregroundColor(Color.primary)
.foregroundColor(isOpenNow(hours: hours) ? .green : .red)
Spacer()
Text(isOpenNow(hours: hours) ? "OPEN" : "CLOSED")
.foregroundColor(Color.primary)
.padding(5)
.background(isOpenNow(hours: hours) ? Color.green : Color.red)
.cornerRadius(10)
Image(systemName: "chevron.right")
.rotationEffect(.degrees(isExpanded ? 90 : 0))
.animation(.easeOut, value: isExpanded)
}
.padding(.vertical, 20)
.padding(.horizontal, 40)
.animation(.easeOut, value: isExpanded)
}
if isExpanded, let formattedHours = hours?.formattedHours.sorted(by: { $0.key < $1.key }) {
ForEach(formattedHours, id: \.key) { day, hours in
HStack {
Text(day + ":")
.bold()
Spacer()
Text(hours)
}
.padding(.horizontal, 40)
.padding(.vertical, 2)
.transition(.opacity.combined(with: .slide))
}
}
Divider()
.background(Color.blue)
}
}
private func isOpenNow(hours: Hours?) -> Bool {
let calendar = Calendar.current
let now = Date()
let dayOfWeek = calendar.weekdaySymbols[calendar.component(.weekday, from: now) - 1]
guard let todayHours = hours?.hours(for: dayOfWeek) else { return false }
if todayHours.open == "0000" && todayHours.close == "0000" {
return true
}
let currentTime = calendar.component(.hour, from: now) * 100 + calendar.component(.minute, from: now)
let openingTime = Int(todayHours.open.replacingOccurrences(of: ":", with: "")) ?? 0
let closingTime = Int(todayHours.close.replacingOccurrences(of: ":", with: "")) ?? 2400 // Use 2400 for end of day
if closingTime < openingTime {
return currentTime >= openingTime || currentTime < closingTime
} else {
return currentTime >= openingTime && currentTime < closingTime
}
}
}
// ContactInfo for displaying phone and address
struct ContactInfo: View {
let displayPhone: String?
let address: String?
let city: String?
let state: String?
let postalCode: String?
var body: some View {
VStack(alignment: .leading) {
if let displayPhone = displayPhone {
Text("Phone: \(displayPhone)")
}
}
.padding(.vertical, 20)
.padding(.horizontal, 40)
.cornerRadius(10)
Divider()
.background(Color.blue)
VStack(alignment: .leading) {
if let address = address, let city = city, let state = state, let postalCode = postalCode {
Text("Address: \(address), \(city), \(state) \(postalCode)")
}
}
.padding(.vertical, 20)
.padding(.horizontal, 40)
.cornerRadius(10)
}
}
// This extension is used in HoursView to format the hours string
extension String {
func insert(separator: String, every n: Int) -> String {
var result: String = ""
var count = 0
for char in self {
if count % n == 0 && count > 0 {
result += separator
}
result += String(char)
count += 1
}
return result
}
}
// This extension is used in HoursView to get a sorted array of key-value pairs
extension Dictionary where Key == String, Value == [String] {
var keyValuePairs: [(key: String, value: [String])] {
return map { (key, value) in (key, value) }.sorted { $0.key < $1.key }
}
}
struct LocationDetailView_Previews: PreviewProvider {
static var previews: some View {
LocationDetailView(location: Location(
businessId: "1",
name: "Shorehouse Kitchen",
imageUrl: "https://s3-media2.fl.yelpcdn.com/bphoto/cln5YeBlyDYnhYU8fASAng/o.jpg",
phone: "+18584593300",
displayPhone: "(858) 459-3300",
address: "2236 Avenida De La Playa",
city: "La Jolla",
state: "CA",
postalCode: "92037",
latitude: 32.8539270057529,
longitude: -117.254643428836,
stars: 4.5,
reviewCount: 2098,
curOpen: 0,
categories: ["New American", "Salad", "Sandwiches"],
tag: ["coffee", "breakfast_brunch", "newamerican"],
hours: Hours(
Monday: ["0730","1430"],
Tuesday: ["0730","1430"],
Wednesday: ["0730","1430"],
Thursday: ["0730","1430"],
Friday: ["0730","1530"],
Saturday: ["0730","1530"],
Sunday: ["0730","1530"]
),
location: GeoJSON(type: "Point", coordinates: [-117.254643428836, 32.8539270057529]),
price: "$$"
), userLocation: CLLocation(latitude: 32.88088, longitude: -117.2379))
}
} |
/**
* Mule Google Api Commons
*
* Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package com.google.gdata.data.photos;
import com.google.gdata.data.ExtensionDescription;
import com.google.gdata.data.ValueConstruct;
/**
* Simple value element for kml snippets.
*
*
*/
@ExtensionDescription.Default(
nsAlias = Namespaces.KML_ALIAS,
nsUri = Namespaces.KML,
localName = KmlSnippet.XML_NAME)
public class KmlSnippet extends ValueConstruct {
/** XML element name */
static final String XML_NAME = "Snippet";
/**
* Default mutable constructor.
*/
public KmlSnippet() {
this(null);
}
/**
* Constructor (mutable or immutable).
*
* @param value immutable kml snippet or <code>null</code> for a mutable kml
* snippet
*/
public KmlSnippet(String value) {
super(Namespaces.KML_NS, XML_NAME, null, value);
setRequired(false);
}
/**
* Returns the extension description, specifying whether it is required, and
* whether it is repeatable.
*
* @param required whether it is required
* @param repeatable whether it is repeatable
* @return extension description
*/
public static ExtensionDescription getDefaultDescription(boolean required,
boolean repeatable) {
ExtensionDescription desc =
ExtensionDescription.getDefaultDescription(KmlSnippet.class);
desc.setRequired(required);
desc.setRepeatable(repeatable);
return desc;
}
@Override
public String toString() {
return "{KmlSnippet value=" + getValue() + "}";
}
} |
"""
URL configuration for stew project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from main import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
#STEW
path('', views.home, name='home'),
path('courses/', views.courses, name='courses'),
path('createcourse/', views.createcourse, name='createcourse'),
path('joincourse/', views.joincourse, name='joincourse'),
path('course/<int:course_pk>/', views.coursehome, name='coursehome'),
path('addteachingassistant/<int:course_pk>/', views.addteachingassistant, name='addteachingassistant'),
path('removeteachingassistant/<int:course_pk>/', views.removeteachingassistant, name='removeteachingassistant'),
path('editcourseteamrules/<int:course_pk>/', views.editcourseteamrules, name='editcourseteamrules'),
#Teams
path('jointeam/', views.jointeam, name='jointeam'),
path('createteam/<int:course_pk>/<int:team_pk>/', views.createteam, name='createteam'),
path('team/<int:team_pk>/', views.teamhome, name='teamhome'),
#Meetings
path('addmeeting/<int:course_pk>/<int:team_pk>/', views.addmeeting, name='addmeeting'),
path('meetinginfo/<int:meeting_pk>/', views.meetinginfo, name='meetinginfo'),
path('editmeeting/<int:meeting_pk>/', views.editmeeting, name='editmeeting'),
#Tasks
path('assigntask/<int:course_pk>/<int:team_pk>/', views.assigntask, name='assigntask'),
path('viewtask/<int:task_pk>/', views.viewtask, name='viewtask'),
path('edittask/<int:task_pk>/', views.edittask, name='edittask'),
path('downloadtaskattachment/<int:task_pk>/', views.downloadtaskattachment, name='downloadtaskattachment'),
path('addtasksubmission/<int:task_pk>/', views.addtasksubmission, name='addtasksubmission'),
path('viewtasksubmission/<int:submission_pk>/', views.viewsubmission, name='viewsubmission'),
path('editsubmission/<int:submission_pk>/', views.editsubmission, name='editsubmission'),
path('gradesubmission/<int:submission_pk>/', views.gradesubmission, name='gradesubmission'),
path('downloadsubmissionattachment/<int:submission_pk>/', views.downloadsubmissionattachment, name='downloadsubmissionattachment'),
path('downloadgradingattachment/<int:submission_pk>/', views.downloadgradingattachment, name='downloadgradingattachment'),
path('commentsubmission/<int:submission_pk>/', views.commentsubmission, name='commentsubmission'),
path('editcomment/<int:comment_pk>/', views.editcomment, name='editcomment'),
path('downloadcommentattachment/<int:comment_pk>/', views.downloadcommentattachment, name='downloadcommentattachment'),
#FAQs
path('faq/', views.faq, name='faq'),
#Account Management
path('logout/', views.logoutaccount, name='logoutaccount'),
path('login/', views.loginaccount, name='loginaccount'),
path('signup/', views.signupaccount, name='signupaccount'),
path('user/<int:user_pk>/', views.userprofile, name='userprofile'),
path('edituser/<int:user_pk>/', views.edituserprofile, name='edituserprofile'),
path('test/', views.test, name='test')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
<template>
<h1 class="text-center pt-5">Shorten a long URL</h1>
<div class="toolbox">
<form
:class="{'row g-3 needs-validation': true, 'was-validated': this.form_css_was_validated}"
novalidate @submit.prevent="submit_form">
<div class="col-12">
<label for="long_url" class="form-label"><strong>Paste a long URL</strong></label>
<input type="text" class="form-control" name="long_url" id="long_url"
v-model="this.long_url"
:disabled="this.long_url_disable"
placeholder="Example: https://your-domain.com/your-url-too-long" aria-label="Enter a long link"
required="">
<div class="invalid-feedback">
The Long URL field is required.
</div>
</div>
<div v-if="!this.is_show_result" class="m-0">
<div class="row">
<div class="col-md-5 col-sm-12 mt-3">
<label for="basic-url" class="form-label"><strong>Domain</strong></label>
<input type="text" class="form-control" placeholder="zipit.link" aria-label="Enter a long link" readonly
disabled
aria-describedby="button-addon2">
</div>
<div class="col-md-7 col-sm-12 mt-3">
<label for="basic-url" class="form-label"><strong>Enter a back-half you want (optional)</strong> <span
ref="alias_name_info"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
class="bi bi-info-circle" viewBox="0 0 16 16">
<path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
<path
d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533L8.93 6.588zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/>
</svg></span>
</label>
<input type="text"
:class="{'form-control': true, 'error': this.alias_error_msg !== ''}"
name="alias_name" v-model="this.alias_name"
placeholder="Example: my-link"
aria-label="Enter a back-half you want"
v-on:change="this.process_alias_name(this.alias_name)"
>
<div class="invalid-feedback">
{{ this.alias_error_msg }}
</div>
</div>
</div>
<div class="row mt-3">
<div class="col text-center">
<button type="submit" class="btn btn-primary btn-large" @click="this.generate_short_link">
<span v-html="this.btn_zip_url_text"></span>
</button>
</div>
</div>
</div>
<div v-if="this.is_show_result">
<div class="row">
<div class="col-md-8 col-sm-12">
<label class="form-label" for="short_url"><strong>Your shorten URLs</strong></label>
<div class="input-group mb-3">
<input type="text" class="form-control" name="short_url" id="short_url" v-model="this.short_url"
placeholder="https://zipit.link/your-link"
aria-label="Enter a long link" readonly disabled
aria-describedby="button-addon2">
<button class="btn btn-outline-secondary" type="button" id="button-addon2"
@click="this.copy_url(this.short_url)">{{ this.btn_copy_text }}
</button>
</div>
<div v-for="(item, index) in this.list_alias">
<div class="input-group mb-3">
<input type="text" class="form-control" name="short_url" id="alias" v-model="item.alias_name"
placeholder="https://zipit.link/your-link"
aria-label="Enter a long link" readonly disabled
aria-describedby="button-addon2">
<button class="btn btn-outline-secondary" type="button" id="button-addon2"
@click="this.copy_alias_url(index)">{{ item.copied ? "Copied" : "Copy" }}
</button>
</div>
</div>
<div class="text-center d-none d-sm-block">
<button class="btn btn-secondary btn-large mx-2" data-bs-toggle="offcanvas"
data-bs-target="#offcanvas-urls-recent"
aria-controls="staticBackdrop"
@click="this.trigger_open_canvas()">My URLs
</button>
<button class="btn btn-primary btn-large" @click="this.zip_another_link">{{
this.btn_zip_another_text
}}
</button>
</div>
<div class="mb-4"></div>
</div>
<div class="col-md-4 col-sm-12">
<div class="text-center">
<div class="qrcode-box overflow-hidden">
<img :src="this.qrcode_base64" alt="QR Code" class="img-fluid">
<a :href="this.qrcode"
class="link-success link-offset-2 link-underline-opacity-25 link-underline-opacity-100-hover btn-download-qrcode">Download</a>
</div>
</div>
</div>
<div class="col-md-8 col-xs-12 mt-3 d-md-none d-lg-none d-xl-none d-xxl-none">
<div class="text-center">
<button class="btn btn-primary btn-large">My URLs</button>
<button class="btn btn-primary btn-large" @click="this.zip_another_link">{{
this.btn_zip_another_text
}}
</button>
</div>
</div>
</div>
</div>
</form>
<!-- History !-->
<div class="offcanvas offcanvas-end non-user-history-width" data-bs-backdrop="static"
tabindex="-1" id="offcanvas-urls-recent" aria-labelledby="staticBackdropLabel">
<div class="offcanvas-header">
<h5 class="offcanvas-title" id="offcanvasExampleLabel">Your recent URLs</h5>
<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<div class="offcanvas-body">
<div v-if="this.is_loading_urls_recent" class="row mb-2">
<div content="col">
<div class="w-100 text-center">
<div class="spinner-border text-center" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
</div>
</div>
<div class="card mb-2" v-for="(item, index) in this.urls_recent">
<div class="card-body">
<div class="row">
<div class="col-md-1">
<div class="text-center">
<img :src="item.destination_logo" alt="Title" class="img-fluid">
</div>
</div>
<div class="col-md-8 ps-0">
<h5 class="card-title">{{ item.public_id }} - Untitled</h5>
<h6 class="card-subtitle mb-2">
<a :href="item.short_url"
class="text-decoration-none"
target="_blank">{{ item.short_url }}</a></h6>
<p class="card-text">
{{ item.long_url }}
</p>
<a :href="item.short_url" target="_blank" class="btn btn-primary" ref="btn_url_recent_visit_url">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor"
class="bi bi-box-arrow-up-right" viewBox="0 0 16 16">
<path fill-rule="evenodd"
d="M8.636 3.5a.5.5 0 0 0-.5-.5H1.5A1.5 1.5 0 0 0 0 4.5v10A1.5 1.5 0 0 0 1.5 16h10a1.5 1.5 0 0 0 1.5-1.5V7.864a.5.5 0 0 0-1 0V14.5a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h6.636a.5.5 0 0 0 .5-.5z"/>
<path fill-rule="evenodd"
d="M16 .5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0 0 1h3.793L6.146 9.146a.5.5 0 1 0 .708.708L15 1.707V5.5a.5.5 0 0 0 1 0v-5z"/>
</svg>
</a>
<button class="mx-2 btn btn-success" @click="this.copy_url(item.short_url, true)" ref="btn_url_recent_copy">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor"
class="bi bi-clipboard" viewBox="0 0 16 16">
<path
d="M4 1.5H3a2 2 0 0 0-2 2V14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V3.5a2 2 0 0 0-2-2h-1v1h1a1 1 0 0 1 1 1V14a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3.5a1 1 0 0 1 1-1h1v-1z"/>
<path
d="M9.5 1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5h3zm-3-1A1.5 1.5 0 0 0 5 1.5v1A1.5 1.5 0 0 0 6.5 4h3A1.5 1.5 0 0 0 11 2.5v-1A1.5 1.5 0 0 0 9.5 0h-3z"/>
</svg>
</button>
<a :href="item.qrcode" class="me-2 btn btn-success" ref="btn_url_recent_download_qrcode">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-qr-code-scan" viewBox="0 0 16 16">
<path d="M0 .5A.5.5 0 0 1 .5 0h3a.5.5 0 0 1 0 1H1v2.5a.5.5 0 0 1-1 0v-3Zm12 0a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-1 0V1h-2.5a.5.5 0 0 1-.5-.5ZM.5 12a.5.5 0 0 1 .5.5V15h2.5a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5v-3a.5.5 0 0 1 .5-.5Zm15 0a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1 0-1H15v-2.5a.5.5 0 0 1 .5-.5ZM4 4h1v1H4V4Z"/>
<path d="M7 2H2v5h5V2ZM3 3h3v3H3V3Zm2 8H4v1h1v-1Z"/>
<path d="M7 9H2v5h5V9Zm-4 1h3v3H3v-3Zm8-6h1v1h-1V4Z"/>
<path d="M9 2h5v5H9V2Zm1 1v3h3V3h-3ZM8 8v2h1v1H8v1h2v-2h1v2h1v-1h2v-1h-3V8H8Zm2 2H9V9h1v1Zm4 2h-1v1h-2v1h3v-2Zm-4 2v-1H8v1h2Z"/>
<path d="M12 9h2V8h-2v1Z"/>
</svg>
</a>
<button class="me-2 btn btn-secondary opacity-50 disable d-none" ref="btn_url_recent_rename_link">Rename</button>
<button class="btn btn-secondary opacity-50 disable d-none" ref="btn_url_recent_edit_link">Edit</button>
</div>
<div class="col-md-3">
<div>
<img :src="item.qrcode_base64" alt="QR Code" class="img-fluid">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class=""></div>
</div>
</div>
</div>
</div>
<ToastHtml :header_content="this.toast.header_content" :date_friendly="this.toast.date_friendly" :message="this.toast.message" />
</template>
<script>
import axios from "axios";
import {convert_space_to_dash, get_border_spinner, remove_protocol, get_csrf, get_end_point} from "@/ultils/helper";
import Cookies from 'js-cookie';
import { v4 as uuidv4 } from 'uuid';
import {Toast, Tooltip} from 'bootstrap';
import ToastHtml from "@/components_share/ToastHtml.vue";
export default {
components: {ToastHtml},
data() {
return {
long_url: '',
long_url_disable: false,
alias_name: '',
alias_error_msg: '',
short_url: '',
is_show_result: false,
btn_copy_text: 'Copy',
btn_copy_text_alias: 'Copy',
btn_zip_url_text: 'Zip your URL',
btn_zip_another_text: 'Zip another URL',
form_css_was_validated: '',
qrcode_base64: '',
qrcode: '',
list_alias: [],
token_non_user: '',
urls_recent: [],
is_loading_urls_recent: true,
tooltips: {
edit_link: [],
visit_url: [],
},
toast: {
header_content: '',
date_friendly: '',
message: '',
},
}
},
setup() {
},
created() {
// this.heartbeat();
axios.defaults.headers.common['X-CSRFToken'] = get_csrf();
let zipit_uuid = Cookies.get('Zipit-Uuid');
if ( zipit_uuid === undefined ) {
zipit_uuid = uuidv4()
Cookies.set('Zipit-Uuid', zipit_uuid, { expires: 365 });
}
axios.defaults.headers.common['Zipit-Uuid'] = zipit_uuid;
},
mounted() {
new Tooltip(this.$refs.alias_name_info, {
title: "Special characters are not allowed.",
placement: 'top',
});
},
updated() {
if ( this.$refs.btn_url_recent_edit_link !== undefined ) {
for (let i = 0; i < this.$refs.btn_url_recent_edit_link.length; i++) {
new Tooltip(this.$refs.btn_url_recent_edit_link[i], {
title: "Please purchase a subscription to edit your destination link.",
placement: 'top',
});
this.tooltips['edit_link'].push(new Tooltip(this.$refs.btn_url_recent_edit_link[i], {
title: "Please purchase a subscription to edit your destination link.",
placement: 'top',
}));
new Tooltip(this.$refs.btn_url_recent_rename_link[i], {
title: "Please login to change your short link.",
placement: 'top',
});
new Tooltip(this.$refs.btn_url_recent_download_qrcode[i], {
title: "Download QRCODE",
placement: 'top',
});
new Tooltip(this.$refs.btn_url_recent_visit_url[i], {
title: "Visit URL",
placement: 'left',
});
}
}
},
methods: {
remove_protocol,
submit_form() {
},
trigger_open_canvas() {
this.is_loading_urls_recent = true;
this.get_urls();
},
process_alias_name(alias) {
this.alias_name = convert_space_to_dash(alias);
},
async generate_short_link() {
try {
this.long_url = this.long_url.trim();
this.alias_name = this.alias_name.trim();
if ( this.long_url === '' ) {
this.form_css_was_validated = 'was-validated';
return;
}
// reset error
this.alias_error_msg = '';
let btn_zip_url_text_ori = this.btn_zip_url_text;
this.btn_zip_url_text = get_border_spinner();
const response = await axios.post( import.meta.env.VITE_BE_URL + '/api/url/short-url', {
long_url: this.long_url,
alias_name: this.alias_name,
}).finally(() => {
this.btn_zip_url_text = btn_zip_url_text_ori;
});
let response_data = response.data
let short_link = response_data.short_link;
if (short_link !== '') {
this.short_url = short_link;
this.is_show_result = true;
this.long_url_disable = true;
this.qrcode_base64 = response_data.qrcode_base64;
this.qrcode = response_data.qrcode;
this.list_alias = response_data.list_alias;
// let urls_recent = {}
// if (localStorage.urls_recent) {
// urls_recent = JSON.parse(localStorage.urls_recent);
// }
// let public_id = response.data.public_id;
// // // Check if public_id is exist in urls_recent
// if (urls_recent[public_id] === undefined) {
// let url_recent = {
// long_url: this.long_url,
// short_url: response_data.list_alias.length > 0 ? response_data.list_alias[0]['alias_name'] : this.short_url,
// qrcode_base64: this.qrcode_base64,
// public_id: public_id,
// destination_logo: response_data.destination_logo,
// }
// urls_recent[public_id] = url_recent
// this.urls_recent.push(url_recent)
// localStorage.urls_recent = JSON.stringify(urls_recent);
// }
}
} catch (error) {
// get response from error
const data = error.response.data;
if ( data.type === 'alias_name' ) {
this.form_css_was_validated = 'was-validated';
this.alias_error_msg = data.message;
}
console.error('Error:', error);
}
},
async get_urls() {
const response = await axios.get( get_end_point() + '/api/url/short-url');
this.urls_recent = response.data.list_alias;
this.is_loading_urls_recent = false;
},
zip_another_link() {
this.long_url = '';
this.long_url_disable = false;
this.alias_name = '';
this.short_url = '';
this.is_show_result = false;
this.btn_copy_text = 'Copy';
this.qrcode_base64 = '';
this.qrcode = ''
},
copy_url(url, is_show_toast = false) {
navigator.clipboard.writeText(url);
if (is_show_toast) {
this.toast.header_content = "Success";
this.toast.message = "Copied to clipboard";
const toast_live = document.getElementById('live_toast');
const toast_bs = Toast.getOrCreateInstance(toast_live);
toast_bs.show();
setTimeout(() => {
toast_bs.hide();
}, 1500);
} else {
this.btn_copy_text = 'Copied';
setTimeout(() => {
this.btn_copy_text = 'Copy';
}, 1500);
}
},
copy_alias_url(index) {
const item = this.list_alias[index];
navigator.clipboard.writeText(item.alias_name);
item.copied = true;
setTimeout(() => {
item.copied = false;
}, 1500);
},
heartbeat() {
const url = get_end_point() + '/api/heartbeat';
setInterval(async function () {
await axios.get(url)
}, 10000)
},
}
};
</script> |
# Consigna 🎯
Utilizando los conceptos aprendidos en la unidad 13- Bases de datos relacionales (SQL DDL), resolver el siguiente ejercicio:
1. Instalar SQL Server Express
2. Instalar SQL Server Management Studio
3. Crear una base de datos
4. Crear 3 tablas: Alumno, Materia y Cursa.
- Alumno deberá tener los siguientes campos: Legajo, nombre, apellido y fecha de nacimiento
- Materia deberá tener los siguientes campos:
Código y descripción.
- Finalmente, la tabla Cursa deberá tener
los siguientes campos: legajo y código de materia.
- Para las tablas se deberá definir la clave primaria. También deben crearse las claves foráneas.
5. Insertar 5 tuplas en cada una de las tablas
6. Exportar el script de creación de la base de datos con sus datos.
7. Borrar la base creada.
8. Restaurar la base de datos desde el script generado en el punto 6.
# Notas 📄
- Se dispone el script "Cursadas.sql" el cuál se utilizó para crear y poblar la base de datos en un principio.
- Se dispone el script "Cursadas - Auto generado.sql" el cuál se generó a través del gestor de base de datos de manera automática, y al ejecutarlo nos genera el mismo resultado que el primer script. |
import {
applicationRootCamera1,
applicationRootCamera1ConsumerId, applicationRootCamera1CredentialId,
applicationRootCamera1UserId
} from "../../support/e2e";
describe('Camera 1 API tests (Basic Auth)', () => {
before(() => {
cy.loginBasicAuth(applicationRootCamera1);
})
it('should make a correct visit', () => {
cy.contains("Welcome to Healthy cameras!").should('exist');
})
it('should reload 10 times', () => {
for (let i = 0; i < 10; i++) {
cy.loginBasicAuth(applicationRootCamera1);
cy.contains('Welcome to Healthy cameras!').should('exist');
}
})
it('should read consumer name', () => {
cy.request({
method: 'GET',
url: applicationRootCamera1ConsumerId,
headers: {
'Content-Type': 'application/text',
'Authorization': `Basic ${btoa("cameraUser1:administrator")}`
},
}).then(response => {
console.log(JSON.stringify(response));
expect(response.body).to.be.eq('camera1');
})
})
it('should read no user', () => {
cy.request({
method: 'GET',
url: applicationRootCamera1UserId,
headers: {
'Content-Type': 'application/text',
'Authorization': `Basic ${btoa("cameraUser1:administrator")}`
},
}).then(response => {
console.log(JSON.stringify(response));
expect(response.body).to.be.eq('');
})
})
it('should read credential', () => {
cy.request({
method: 'GET',
url: applicationRootCamera1CredentialId,
headers: {
'Content-Type': 'application/text',
'Authorization': `Basic ${btoa("cameraUser1:administrator")}`
},
}).then(response => {
cy.log(JSON.stringify(response));
expect(response.body).to.be.eq('cameraUser1');
})
})
}) |
package de.tu_darmstadt.informatik.fop.main.dorfromantik.controller;
import java.util.List;
import org.newdawn.slick.geom.Vector2f;
import de.tu_darmstadt.informatik.fop.main.dorfromantik.animation.MoveByCubicAnimation;
import de.tu_darmstadt.informatik.fop.main.dorfromantik.animation.ScaleUpEaseOutBounceAnimation;
import de.tu_darmstadt.informatik.fop.main.dorfromantik.constants.Constants;
import de.tu_darmstadt.informatik.fop.main.dorfromantik.entity.Board;
import de.tu_darmstadt.informatik.fop.main.dorfromantik.entity.PlaceholderTile;
import de.tu_darmstadt.informatik.fop.main.dorfromantik.entity.Tile;
import eea.engine.entity.StateBasedEntityManager;
public class BoardController {
/**
* The board which this controller handles.
*/
private Board board;
/**
* Should textures be displayed?
*/
private boolean debug;
/**
* Constructor. Initializes a new Board.
*/
public BoardController(boolean debug) {
super();
this.board = new Board();
this.debug = debug;
}
/**
* @return the board.
*/
public Board getBoard() {
return board;
}
/**
* Sets the board.
* @param board the new board
*/
public void setBoard(Board board) {
this.board = board;
}
/**
* Updates the boards position so that the starting tile is in the center of the screen.
*/
public void centerBoardtoScreen(boolean animated) {
float deltaX = -Constants.GamePlay.boardSize.x/2 + Constants.Base.windowMiddle.x - this.board.getPosition().x;
float deltaY = -Constants.GamePlay.boardSize.y/2 + Constants.Base.windowMiddle.y - this.board.getPosition().y;
this.updateBoardPosition(new Vector2f(deltaX, deltaY), animated);
}
/**a
* Generates a new random Tile at index.
* @param index the index of the new tile
* @param placedByPlayer if true the player placed the tile and the count of tiles left should decrease.
* @return true, if the tile was placed successfully.
*/
public boolean addTileAtIndex(Vector2f index, Tile tile, boolean placedByPlayer) {
// if the index is not valid return
if (placedByPlayer && !this.board.validTileAtIndex(index)) {
FeedbackManager.getInstance().addFeedbackMessage("Kachel kann an dieser Position nicht platziert werden.");
return false;
}
// if there are no more moves left return
if (ScoreManager.getInstance().getTilesLeft() == 0 && placedByPlayer) return false;
System.out.println(index);
// update placeholder tiles. Must be called before the placing of the new
// tile because the existing placeholder tile must be removed before.
this.recalculatePlaceholderTilesAtIndex(index, placedByPlayer);
// transform the index to a position corresponding to the board coordinate system
Vector2f tile_position = this.board.transformIndexToScreenCoordinate(index);
// get generated tile and place it in the gamestate
this.board.setTileAtIndex(index, tile);
tile.setIndex(index);
tile.setPosition(tile_position);
if (placedByPlayer) {
//tile.runScaleAnimation();
tile.runAnimation(new ScaleUpEaseOutBounceAnimation(1f));
}
// if a tile was placed by the player decrease the tiles-left counter
if (placedByPlayer) {
ScoreManager.getInstance().reduceTilesLeftCounter();
}
return true;
}
/**
* Transforms a position into an index.
* @param position the position to transform
* @return the index of the position
*/
public Vector2f getIndexFromScreenPosition(Vector2f position) {
return this.board.transformScreenCoordinateToIndex(position);
}
/**
* Removes necessary existing placeholder tiles and adds new ones for the specified index.
* @param index placeholder tiles are placed around this index if there is no other tile.
* @param animated should the placement of placeholderTiles be animated?
*/
public void recalculatePlaceholderTilesAtIndex(Vector2f index, boolean animated) {
// remove existing placeholder (if one exists).
Tile placeholder = this.board.getTileAtIndex(index);
if (placeholder != null && placeholder.getID().equals("placeholder")) {
StateBasedEntityManager.getInstance().removeEntity(Constants.Base.GameScene, placeholder);
this.board.removeTileAtIndex(index);
}
// Place new placeholder tiles at neighbouring indizes where no tile is present.
List<Vector2f> neighborIndizes = this.board.getNeighbourIndizes(index);
for (Vector2f neighborIndex : neighborIndizes) {
if (this.board.getMap()[(int) neighborIndex.x][(int) neighborIndex.y] == null) {
PlaceholderTile newPlaceholder = new PlaceholderTile(this.debug);
this.board.setTileAtIndex(neighborIndex, newPlaceholder);
Vector2f tile_position = this.board.transformIndexToScreenCoordinate(neighborIndex);
newPlaceholder.setIndex(index);
newPlaceholder.setPosition(tile_position);
StateBasedEntityManager.getInstance().addEntity(Constants.Base.GameScene, newPlaceholder);
if (animated) newPlaceholder.runAnimation(new ScaleUpEaseOutBounceAnimation(2f));
}
}
}
/**
* Move the board and all its tiles based on the given delta.
* @param delta the vector by which the board should be moved
*/
public void updateBoardPosition(Vector2f delta, boolean animated) {
// update board position
if (animated) {
this.board.runAnimation(new MoveByCubicAnimation(0.5f, delta));
} else {
this.board.setPosition(new Vector2f(this.board.getPosition().x + delta.x, this.board.getPosition().y + delta.y));
}
for (int row = 0; row < Constants.GamePlay.boardDimension.x; row++) {
for (int col = 0; col < Constants.GamePlay.boardDimension.y; col++) {
if (this.board.getMap()[row][col] == null) {
continue;
}
// update tile position
Tile tile = this.board.getMap()[row][col];
if (animated) {
tile.runAnimation(new MoveByCubicAnimation(0.5f, delta));
} else {
tile.setPosition(new Vector2f(tile.getPosition().x + delta.x, tile.getPosition().y + delta.y));
}
}
}
}
} |
import { IMessageHandler } from './IMessageHandler';
import { MessageCallback, MessageQueueNode, MessageSubscriptionNode } from './MessageSubscriptionNode';
import { Message, MessagePriority } from './Message';
/** The message manager responsible for sending messages across the system. */
export class MessageBus {
private static _subscriptions: { [code: string]: MessageSubscriptionNode[] } = {};
private static _normalQueueMessagePerUpdate: number = 10;
private static _normalMessageQueue: MessageQueueNode[] = [];
/** Constructor hidden to prevent instantiation. */
private constructor() {}
/**
* Adds a subscription to the provided code using the provided handler.
* @param {string} code The code to listen for.
* @param {IMessageHandler} handler The handler to be subscribed.
* @param {MessageCallback} callback callback
*/
public static addSubscription(code: string, handler: IMessageHandler, callback: MessageCallback): void {
if (MessageBus._subscriptions[code] === undefined) {
MessageBus._subscriptions[code] = [];
}
let matches: MessageSubscriptionNode[] = [];
if (handler !== undefined) {
matches = MessageBus._subscriptions[code].filter((x) => x.handler === handler);
} else if (callback !== undefined) {
matches = MessageBus._subscriptions[code].filter((x) => x.callback === callback);
} else {
console.warn('Cannot add subscription where both the handler and callback are undefined.');
return;
}
if (matches.length === 0) {
const node = new MessageSubscriptionNode(code, handler, callback);
MessageBus._subscriptions[code].push(node);
} else {
console.warn('Attempting to add a duplicate handler/callback to code: ' + code + '. Subscription not added.');
}
}
/**
* Removes a subscription to the provided code using the provided handler.
* @param {string} code The code to no longer listen for.
* @param {IMessageHandler} handler The handler to be unsubscribed.
* @param {MessageCallback} callback callback
*/
public static removeSubscription(code: string, handler: IMessageHandler, callback: MessageCallback): void {
if (MessageBus._subscriptions[code] === undefined) {
console.warn('Cannot unsubscribe handler from code: ' + code + ' Because that code is not subscribed to.');
return;
}
let matches: MessageSubscriptionNode[] = [];
if (handler !== undefined) {
matches = MessageBus._subscriptions[code].filter((x) => x.handler === handler);
} else if (callback !== undefined) {
matches = MessageBus._subscriptions[code].filter((x) => x.callback === callback);
} else {
console.warn('Cannot remove subscription where both the handler and callback are undefined.');
return;
}
for (const match of matches) {
const nodeIndex = MessageBus._subscriptions[code].indexOf(match);
if (nodeIndex !== -1) {
MessageBus._subscriptions[code].splice(nodeIndex, 1);
}
}
}
/**
* Posts the provided message to the message system.
* @param {Message} message The message to be sent.
*/
public static post(message: Message): void {
// console.log('Message posted:', message);
const handlers = MessageBus._subscriptions[message.code];
if (handlers === undefined) {
return;
}
for (const h of handlers) {
if (message.priority === MessagePriority.HIGH) {
if (h.handler !== undefined) {
h.handler.onMessage(message);
} else {
if (h.callback !== undefined) {
h.callback(message);
} else {
// NOTE: Technically shouldn't be possible, but...
console.log('There is no hander OR callback for message code: ' + message.code);
}
}
} else {
MessageBus._normalMessageQueue.push(new MessageQueueNode(message, h.handler, h.callback));
}
}
}
/**
* Performs update routines on this message bus.
* @param {number} time The delta time in milliseconds since the last update.
*/
public static update(time: number): void {
if (MessageBus._normalMessageQueue.length === 0) {
return;
}
const messageLimit = Math.min(MessageBus._normalQueueMessagePerUpdate, MessageBus._normalMessageQueue.length);
for (let i = 0; i < messageLimit; ++i) {
const node = MessageBus._normalMessageQueue.pop();
if (node.handler !== undefined) {
node.handler.onMessage(node.message);
} else if (node.callback !== undefined) {
node.callback(node.message);
} else {
console.warn('Unable to process message node because there is no handler or callback: ' + node);
}
}
}
} |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="jakarta.tags.core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List of projects</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
function confirmer(url) {
var rep = confirm("Are you sure you want to delete?");
if (rep == true) {
document.location = url;
}
}
function redirectToReference(url) {
window.location.href = url;
}
</script>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<div class="container-fluid">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" href="controller">Project Management</a>
</li>
<li class="nav-item">
<a class="nav-link" href="controller?view=project">Project</a>
</li>
<li class="nav-item">
<a class="nav-link" href="controller?view=task">Task</a>
</li>
</ul>
</div>
</nav>
<div class="container p-5 my-5">
<h1>List of Tasks</h1><br>
<c:if test="${ model.mode == 'projectView' }">
<table class="table table-hover text-center">
<tr>
<th>CODE</th> <th>DESCRIPTION</th> <th>START DATE</th> <th>END DATE</th><th>REMOVE FROM PROJECT</th><th>UPDATE</th>
</tr>
<c:forEach items="${model.tasks}" var="t">
<tr>
<td>${t.code}</td>
<td>${t.description}</td>
<td>${t.startDate}</td>
<td>${t.endDate}</td>
<td><button class="btn btn-outline-danger" onclick="javascript:confirmer('projectController?action=removeTask&taskCode=${ t.code }&projectCode=${ model.project.code }')">Remove</button></td>
<td><button class="btn btn-outline-secondary" onclick="window.location.href='taskController?mode=update&taskCode=${ t.code }'">Update</button></td>
</tr>
</c:forEach>
</table>
<div class="btn-group d-flex align-items-center justify-content-center">
<button type="button" class="btn btn-primary btn-block" onclick="redirectToReference('projectController?action=addTask&projectCode=${ model.project.code }')">Add a Task</button>
</div>
</c:if>
<c:if test="${ model.mode == 'taskView' }">
<form action="taskController" method="post">
<table class="table table-hover ">
<tr>
<td class="fw-bold">SEARCH BY CODE </td>
<td><input class="form-control" name="taskCode" required/></td>
<td><button type="submit" class="btn btn-primary" name="action" value="search">Search</button></td>
</tr>
</table>
</form>
<br>
<table class="table table-hover text-center">
<tr>
<th>CODE</th> <th>DESCRIPTION</th> <th>START DATE</th> <th>END DATE</th> <th>Associated Project</th><th>REMOVE</th><th>UPDATE</th>
</tr>
<c:forEach items="${model.tasks}" var="t">
<tr>
<td>${t.code}</td>
<td>${t.description}</td>
<td>${t.startDate}</td>
<td>${t.endDate}</td>
<td><a href="projectController?action=projectTasks&projectCode=${t.project.code}">${t.project.code}</a></td>
<td><button class="btn btn-outline-danger" onclick="javascript:confirmer('taskController?action=remove&taskCode=${ t.code }')">Remove</button></td>
<td><button class="btn btn-outline-secondary" onclick="window.location.href='taskController?mode=update&taskCode=${ t.code }'">Update</button></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
</c:if> |
import datetime
from django.contrib import admin
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.question_text
# Decorator ref: https://docs.djangoproject.com/en/5.0/intro/tutorial07/#customize-the-admin-change-list
@admin.display(
boolean=True,
ordering="pub_date",
description="Published recently?",
)
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
'''
# Pre-test was_published_recently
# https://docs.djangoproject.com/en/5.0/intro/tutorial05/#running-tests
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
'''
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text |
from .models import SpotifyToken
from django.utils import timezone
from datetime import timedelta
from requests import post
from .credentials import CLIENT_ID, CLIENT_SECRET
def get_user_tokens(session_id):
user_tokens = SpotifyToken.objects.filter(user=session_id)
if user_tokens.exists():
return user_tokens[0]
else:
return None
def update_or_create_user_tokens(
session_id, access_token, token_type, expires_in, refresh_token
):
tokens = get_user_tokens(session_id)
expires_in = timezone.now() + timedelta(seconds=expires_in)
if tokens:
tokens.access_token = access_token
tokens.refresh_token = refresh_token
tokens.expires_in = expires_in
tokens.token_type = token_type
tokens.save(
update_fields=[
"access_token",
"refresh_token",
"expires_in",
"token_type",
]
)
else:
tokens = SpotifyToken(
user=session_id,
access_token=access_token,
refresh_token=refresh_token,
token_type=token_type,
expires_in=expires_in,
)
tokens.save()
def is_spotify_authenticated(session_id):
tokens = get_user_tokens(session_id)
if tokens:
expiry = tokens.expires_in
if expiry <= timezone.now():
refresh_spotify_token(session_id)
return True
return False
def refresh_spotify_token(session_id):
refresh_token = get_user_tokens(session_id).refresh_token
reponse = post(
"https://accounts.spotify.com/api/token",
data={
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
},
).json()
access_token = reponse.get("access_token")
token_type = reponse.get("token_type")
expires_in = reponse.get("expires_in")
refresh_token = reponse.get("refresh_token")
update_or_create_user_tokens(
session_id, access_token, token_type, expires_in, refresh_token
) |
class Description():
desc = dict({
'desc_0': """
<h3>Continuous</h3>
<p>Continuous data is a type of numerical data that refers to the unspecified number of possible measurements between two realistic points.</p>
<p>These numbers are not always clean and tidy like those in discrete data, as they're usually collected from precise measurements. Over time, measuring a particular subject allows us to create a defined range, where we can reasonably expect to collect more data.</p>
<p>Continuous data is all about accuracy. Variables in these data sets often carry decimal points, with the number to the right stretched out as far as possible. This level of detail is paramount for scientists, doctors, and manufacturers, to name a few.</p>
<p>Some examples of continuous data include:</p>
<ul>
<li>The weight of new born babies</li>
<li>The daily wind speed</li>
<li>The temperature of a freezer</li>
</ul>
<p>When you think of experiments or studies involving constant measurements, they're likely to be continuous variables to some extent. If you have a number like “2.86290” anywhere on a spreadsheet, it's not a number you could have quickly arrived at yourself — think measurement devices like stopwatches, scales, thermometers, and the like.</p>
<h3>Discrete, Categorical</h3>
<p>Discrete data is a numerical type of data that includes whole, concrete numbers with specific and fixed data values determined by counting. Continuous data includes complex numbers and varying data values that are measured over a specific time interval.</p>
<p>Some examples of discrete data one might gather:</p>
<ul>
<li>The number of customers who bought different items</li>
<li>The number of computers in each department</li>
<li>The number of items you buy at the grocery store each week</li>
</ul>
<p>Discrete data can also be qualitative. The nationality you select on a form is a piece of discrete data. The nationalities of everyone in your workplace, when grouped, can be valuable information in evaluating your hiring practices.</p>
""",
'desc_1': """
<h3>Relationships</h3>
<p>Relationships in probability and statistics can generally be one of three things: deterministic, random, or statistical. Relationship has been divided by 3 types of relationship.</p>
<ul>
<li><b>Deterministic Relationship</b></li>
<p>A deterministic relationship involves an exact relationship between two variables.</p>
<li><b>Random Relationship</b></li>
<p>A random relationship is a bit of a misnomer because there is no relationship between the variables. However, random processes may make it seem like there is a relationship.</p>
<li><b>Statistical Relationship</b></li>
<p>A statistical relationship is a mixture of deterministic and random relationships.</p>
</ul>
<h3>Differences</h3>
<p>
Statistical difference refers to significant differences between groups of objects or people. Scientists calculate this difference to determine whether the data from an experiment is reliable before drawing conclusions and publishing results. When studying the relationship between two variables, scientists use the chi-square calculation method. When comparing two groups, scientists use the t-distribution method
</p>
<ul>
<li><b>Chi-Square Method</b></li>
<p>Create a data table with a row for each possible result and a column for each group involved in the experiment. For example, if you are trying to answer the question of whether picture flash cards or word flash cards better help children pass a vocabulary test, you would create a table with three columns and two rows. The first column would be marked, "Passed Test?" and two rows beneath the heading would be marked "Yes" and "No." The next column would be labelled "Picture Cards" and the final column would be labelled "Word Cards."</p>
<li><b>T-Test Method</b></li>
<p>Make a data table showing the number of observations for each of two groups, the mean of the results for each group, the standard deviation from each mean and the variance for each mean. Subtract the group two mean from the group one mean. Divide each variance by the number of observations minus 1. For example, if one group had a variance of 2186753 and 425 observations, you would divide 2186753 by 424. Take the square root of each result. Divide each result by the corresponding result from Step 2. Calculate the degrees of freedom by totalling the number of observations for both groups and dividing by 2.</p>
</ul>
""",
'desc_11': """
<h3>Independent variable?</h3>
<p><i>The two main variables in an experiment are the independent and dependent variable.</i></p>
<p>An independent variable is the variable that is changed or controlled in a scientific experiment to test the effects on the dependent variable. A dependent variable is the variable being tested and measured in a scientific experiment.</p>
<p><i>What's the Difference Between Homogeneous and Heterogeneous?</i></p>
<p>The dependent variable is 'dependent' on the independent variable. As the experimenter changes the independent variable, the effect on the dependent variable is observed and recorded.</p>
<p><i>Independent and Dependent Variable Example.</i></p>
<p>For example, a scientist wants to see if the brightness of light has any effect on a moth being attracted to the light. The brightness of the light is controlled by the scientist. This would be the independent variable. How the moth reacts to the different light levels (distance to light source) would be the dependent variable.</p>
<p><i>How to Tell the Variables Apart.</i></p>
<p>The independent and dependent variables may be viewed in terms of cause and effect. If the independent variable is changed, then an effect is seen in the dependent variable. Remember, the values of both variables may change in an experiment and are recorded. The difference is that the value of the independent variable is controlled by the experimenter, while the value of the dependent variable only changes in response to the independent variable.</p>
""",
'desc_12': """
<h3>Means</h3>
<p>In statistics, the mean summarizes an entire dataset with a single number representing the data's center point or typical value. It is also known as the arithmetic average, and it is one of several measures of central tendency.</p>
<p>Ideally, the mean indicates the region where most values in a distribution fall. Statisticians refer to it as the central location of a distribution. You can think of it as the tendency of data to cluster around a middle value.</p>
<h3>Tests for Equal Variances</h3>
<p>Use a test for equal variances to test the equality of variances between populations or factor levels. Many statistical procedures, such as analysis of variance (ANOVA) and regression, assume that although different samples can come from populations with different means, they have the same variance.</p>
<p>Because the susceptibility of different procedures to unequal variances varies greatly, so does the need to do a test for equal variances. For example, ANOVA inferences are only slightly affected by inequality of variance if the model contains only fixed factors and has equal or almost equal sample sizes. Alternatively, ANOVA models with random effects and/or unequal sample sizes could be substantially affected.</p>
<p>For example, you plan to do an ANOVA testing the length of time callers are put on hold where the main fixed factor is the calling center. You use the ANOVA general linear model (GLM) because you have unequal sample sizes. Because this unbalanced condition increases the susceptibility to unequal variances, you decide to test the assumption of equal variances. If the resulting p-value is greater than adequate choices of alpha, you fail to reject the null hypothesis of the variances being equal. You can feel confident that the assumption of equal variances is being met.</p>
<p>For tests for equal variances, the hypotheses are:</p>
<ul>
<li>H0: All variances are equal</li>
<li>H1: Not all variances are equal</li>
</ul>
""",
'desc_112': """
<h3>Correlation Analysis</h3>
<p>Correlation Analysis is statistical method that is used to discover if there is a relationship between two variables/datasets, and how strong that relationship may be.</p>
<p>In terms of market research this means that, correlation analysis is used to analyse quantitative data gathered from research methods such as surveys and polls, to identify whether there is any significant connections, patterns, or trends between the two.</p>
<p>Essentially, correlation analysis is used for spotting patterns within datasets. A positive correlation result means that both variables increase in relation to each other, while a negative correlation means that as one variable decreases, the other increases.</p>
<h3>Parametric</h3>
<p><i>(Pearson's Coefficient)</i> Where the data must be handled in relation to the parameters of populations or probability distributions. Typically used with quantitative data already set out within said parameters.</p>
<p>Advantage of Parametric:</p>
<ul>
<li>Parametric tests can provide trustworthy results with distributions that are skewed and nonnormal</li>
<li>Parametric tests can provide trustworthy results when the groups have different amounts of variability</li>
<li>Parametric tests have greater statistical power</li>
</ul>
<h3>Nonparametric</h3>
<p><i>(Spearman's Rank)</i> Where no assumptions can be made about the probability distribution. Typically used with qualitative data but can be used with quantitative data if Spearman's Rank proves inadequate.</p>
<p>Advantage of Nonparametric:</p>
<ul>
<li>Nonparametric tests assess the median which can be better for some study areas</li>
<li>Nonparametric tests are valid when our sample size is small, and your data are potentially nonnormal</li>
<li>Nonparametric tests can analyse ordinal data, ranked data, and outliers</li>
</ul>
<p>If we have a small dataset, the distribution can be a deciding factor. However, in many cases, this issue is not critical because of the following:</p>
<ul>
<li>Parametric analyses can analyse nonnormal distributions for many datasets.</li>
<li>Nonparametric analyses have other firm assumptions that can be harder to meet.</li>
</ul>
<p>The answer is often contingent upon whether the mean or median is a better measure of central tendency for the distribution of your data.</p>
<ul>
<li>If the mean is a better measure and you have a sufficiently large sample size, a parametric test usually is the better, more powerful choice.</li>
<li>If the median is a better measure, consider a nonparametric test regardless of your sample size.</li>
</ul>
""",
'above_this': 'is from hidir',
'below_this': 'is from google',
'desc_111': """
<h3>Regression Analysis</h3>
<p>
Regression analysis is a set of statistical methods used for the estimation of
relationships between a dependent variable and one or more independent variables.
It can be utilized to assess the strength of the relationship
between variables and for modeling the future relationship between them.
Regression analysis includes several variations, such as linear, multiple linear, and nonlinear.
The most common models are simple linear and multiple linear.
Nonlinear regression analysis is commonly used for more complicated data sets
in which the dependent and independent variables show a nonlinear relationship.
</p>
""",
'desc_1121': """
<h3>Pearson's R</h3>
<p>
In Statistics, the Pearson's Correlation Coefficient is also referred to as Pearson's r,
the Pearson product-moment correlation coefficient (PPMCC), or bivariate correlation.
It is a statistic that measures the linear correlation between two variables.
Like all correlations, it also has a numerical value that lies between -1.0 and +1.0.
Pearson's correlation coefficient is the covariance of the two variables divided by
the product of their standard deviations. The form of the definition involves a
"product moment", that is, the mean (the first moment about the origin) of
the product of the mean-adjusted random variables; hence the modifier product-moment in the name.
Pearson's Correlation Coefficient is named after Karl Pearson.
He formulated the correlation coefficient from a related idea by Francis Galton in the 1880s.
</p>
""",
'desc_1122': """
<h3>Spearman's Rank Correlation</h3>
<p>
The Spearman's Rank Correlation Coefficient is used to discover the strength of
a link between two sets of data. This example looks at the strength of
the link between the price of a convenience item (a 50cl bottle of water)
and distance from the Contemporary Art Museum in El Raval, Barcelona.
</p>
""",
'desc_121': """
<h3>Fmax Test</h3>
<p>
The Fmax test (also called Hartley's Fmax) is a test for
homogenity of variance. In other words, the spread (variance)
of your data should be similar across groups or levels.
Compared to Levene's test, Hartley's test is fairly simple
to figure out by hand. An assumption of the Fmax test is that
there are an equal number of participants in each group.
</p>
<h3>Brown & Smythe's Test</h3>
<p>
The Brown-Forsythe test is a statistical test for the equality
of group variances based on performing an Analysis of Variance
(ANOVA) on a transformation of the response variable.
When a one-way ANOVA is performed, samples are assumed to
have been drawn from distributions with equal variance.
If this assumption is not valid, the resulting F-test is invalid.
The Brown-Forsythe test statistic is the F statistic resulting
from an ordinary one-way analysis of variance on the absolute
deviations of groups/treatments data from their individual medians.
</p>
""",
'desc_122': """
<h3>Two groups</h3>
<p>
Independent sample t-test is a statistical technique that is
used to analyze the mean comparison of two independent groups.
In independent samples t-test, when we take two samples from
the same population, then the mean of the two samples may be
identical. But when samples are taken from two different
populations, then the mean of the sample may differ. In this
case, it is used to draw conclusions about the means of two
populations, and used to tell whether or not they are similar.
</p>
<h3>More than two groups</h3>
<p>
For a comparison of more than two group means the one-way analysis
of variance (ANOVA) is the appropriate method instead of the t test.
As the ANOVA is based on the same assumption with the t test,
the interest of ANOVA is on the locations of the distributions
represented by means too. Then why is the method comparing several
means the 'analysis of variance', rather than 'analysis of means'
themselves? It is because that the relative location of the several
group means can be more conveniently identified by variance among
the group means than comparing many group means directly when
number of means are large.
</p>
""",
'desc_1221': """
<h3>Parametric assumptions satisfied</h3>
<p>
In statistical analysis, all parametric tests assume some certain
characteristic about the data, also known as assumptions. Violation
of these assumptions changes the conclusion of the research and
interpretation of the results. Therefore all research, whether for
a journal article, thesis, or dissertation, must follow these
assumptions for accurate interpretation Depending on the
parametric analysis, the assumptions vary.
</p>
""",
'desc_12211': """
<h3>Unpaired T-Test</h3>
<p>
An unpaired t-test (also known as an independent t-test) is a
statistical procedure that compares the averages/means of
two independent or unrelated groups to determine if there
is a significant difference between the two.
</p>
<h3>Paired T-Test</h3>
<p>
A paired t-test (also known as a dependent or correlated t-test)
is a statistical test that compares the averages/means
and standard deviations of two related groups to determine
if there is a significant difference between the two groups.
</p>
""",
'desc_12212': """
<h3>Data Transform</h3>
<p>
Data Transformation in a statistics context means the application
of a mathematical expression to each point in the data. In contrast,
in a Data Engineering context Transformation can also mean transforming
data from one format to another in the Extract Transform Load (ETL) process.
</p>
""",
'desc_122121': """
<h3>Unpaired T-Test</h3>
<p>
An unpaired t-test (also known as an independent t-test) is a
statistical procedure that compares the averages/means of
two independent or unrelated groups to determine if there
is a significant difference between the two.
</p>
<h3>Paired T-Test</h3>
<p>
A paired t-test (also known as a dependent or correlated t-test)
is a statistical test that compares the averages/means
and standard deviations of two related groups to determine
if there is a significant difference between the two groups.
</p>
""",
'desc_122122': """
<h3>Mann-Whitney U</h3>
<p>
The Mann-Whitney U test is used to compare differences between two
independent groups when the dependent variable is either ordinal or
continuous, but not normally distributed. For example, you could use
the Mann-Whitney U test to understand whether attitudes towards pay
discrimination, where attitudes are measured on an ordinal scale,
differ based on gender (i.e., your dependent variable would be
"attitudes towards pay discrimination" and your independent variable
would be "gender", which has two groups: "male" and "female").
</p>
<h3>Wilcoxon Rank Sums Test</h3>
<p>
The Wilcoxon test, which can refer to either the Rank Sum test
or the Signed Rank test version, is a nonparametric statistical
test that compares two paired groups. The tests essentially
calculate the difference between sets of pairs and analyzes
these differences to establish if they are statistically
significantly different from one another.
</p>
""",
'desc_1222': """
<h3>Parametric assumptions satisfied</h3>
<p>
In statistical analysis, all parametric tests assume some certain
characteristic about the data, also known as assumptions. Violation
of these assumptions changes the conclusion of the research and
interpretation of the results. Therefore all research, whether for
a journal article, thesis, or dissertation, must follow these
assumptions for accurate interpretation Depending on the
parametric analysis, the assumptions vary.
</p>
""",
'desc_12221': """
<h3>ANOVA Test</h3>
<p>
Analysis of variance (ANOVA) is an analysis tool used in statistics
that splits an observed aggregate variability found inside a data
set into two parts: systematic factors and random factors.
The systematic factors have a statistical influence on the given data set,
while the random factors do not. Analysts use the ANOVA test to
determine the influence that independent variables have
on the dependent variable in a regression study.
</p>
<h3>Tukey's Test</h3>
<p>
The Tukey Test (or Tukey procedure), also called Tukey's Honest Significant
Difference test, is a post-hoc test based on the studentized range
distribution. An ANOVA test can tell you if your results are significant
overall, but it won't tell you exactly where those differences lie.
After you have run an ANOVA and found significant results,
then you can run Tukey's HSD to find out which specific
groups's means (compared with each other) are different.
The test compares all possible pairs of means.
</p>
<h3>Bonferroni's Test</h3>
<p>
The Bonferroni test is a type of multiple comparison test used
in statistical analysis. When performing a hypothesis test with
multiple comparisons, eventually a result could occur that appears
to demonstrate statistical significance in the
dependent variable, even when there is none.
</p>
""",
'desc_12222': """
<h3>Data transform</h3>
<p>
Data Transformation in a statistics context means the application
of a mathematical expression to each point in the data. In contrast,
in a Data Engineering context Transformation can also mean transforming
data from one format to another in the Extract Transform Load (ETL) process.
</p>
""",
'desc_122221': """
<h3>ANOVA Test</h3>
<p>
Analysis of variance (ANOVA) is an analysis tool used in statistics
that splits an observed aggregate variability found inside a data
set into two parts: systematic factors and random factors.
The systematic factors have a statistical influence on the given data set,
while the random factors do not. Analysts use the ANOVA test to
determine the influence that independent variables have
on the dependent variable in a regression study.
</p>
<h3>Tukey's Test</h3>
<p>
The Tukey Test (or Tukey procedure), also called Tukey's Honest Significant
Difference test, is a post-hoc test based on the studentized range
distribution. An ANOVA test can tell you if your results are significant
overall, but it won't tell you exactly where those differences lie.
After you have run an ANOVA and found significant results,
then you can run Tukey's HSD to find out which specific
groups's means (compared with each other) are different.
The test compares all possible pairs of means.
</p>
<h3>Bonferroni's Test</h3>
<p>
The Bonferroni test is a type of multiple comparison test used
in statistical analysis. When performing a hypothesis test with
multiple comparisons, eventually a result could occur that appears
to demonstrate statistical significance in the
dependent variable, even when there is none.
</p>
""",
'desc_122222': """
<h3>Kruskal-Wallis Test</h3>
<p>
The Kruskal Wallis test is the non parametric alternative to the
One Way ANOVA. Non parametric means that the test doesn't assume
your data comes from a particular distribution. The H test is
used when the assumptions for ANOVA aren't met (like the assumption
of normality). It is sometimes called the one-way ANOVA on ranks,
as the ranks of the data values are used in the
test rather than the actual data points.
</p>
<h3>Dunn's Test</h3>
<p>
Dunn's test is a non-parametric pairwise multiple comparisons
procedure based on rank sums, often used as a post hoc procedure
following rejection of a Kruskal-Wallis test. As such,
it is a non-parametric analog to multiple pairwise t tests
following rejection of an ANOVA null hypothesis.
</p>
""",
'desc_2': """
<h3>Chi-Square Tests One and Two Sample</h3>
<p>
A Chi-square test is a hypothesis testing method.
Two common Chi-square tests involve checking if observed
frequencies in one or more categories match expected frequencies.
You use a Chi-square test for hypothesis tests about whether your
data is as expected. The basic idea behind the test is to compare
the observed values in your data to the expected values
that you would see if the null hypothesis is true.
</p>
""",
'desc_zero': """
<h3>Non-Probability Methods</h3>
<p>Non-Probability Methods description.</p>
<h3>Probability Methods</h3>
<p>Probability Methods description.</p>
""",
'desc_a': """
<h3>Convenience Method</h3>
<p>Convenience Method description.</p>
<h3>Quota Samples</h3>
<p>Quota Samples description.</p>
<h3>Judgemental Samples</h3>
<p>Judgemental Samples description.</p>
""",
'desc_aa': """
<h3>Convenience Method</h3>
<p>Convenience Method description.</p>
""",
'desc_ab': """
<h3>Quota Samples</h3>
<p>Quota Samples description.</p>
""",
'desc_ac': """
<h3>Judgemental Samples</h3>
<p>Judgemental Samples description.</p>
""",
'desc_b': """
<h3>Stratified Sampling</h3>
<p>Stratified Sampling description.</p>
<h3>Simple Random Sampling</h3>
<p>Simple Random Sampling description.</p>
<h3>Cluster Sampling</h3>
<p>Cluster Sampling description.</p>
""",
'desc_ba': """
<h3>Stratified Sampling</h3>
<p>Stratified Sampling description.</p>
""",
'desc_bb': """
<h3>Simple Random Sampling</h3>
<p>Simple Random Sampling description.</p>
""",
'desc_bc': """
<h3>Cluster Sampling</h3>
<p>Cluster Sampling description.</p>
""",
}) |
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
'use strict';
import { Context } from 'moleculer';
import { Service, Get } from '@ourparentcenter/moleculer-decorators-extended';
import { QueryOptions } from 'moleculer-db';
import { dbBlockMixin } from '../../mixins/dbMixinMongoose';
import {
ErrorCode,
ErrorMessage,
GetBlockRequest,
MoleculerDBService,
ResponseDto,
} from '../../types';
import { IBlock, IValidator } from '../../entities';
import { LIST_NETWORK } from '../../common/constant';
/**
* @typedef {import('moleculer').Context} Context Moleculer's Context
*/
@Service({
name: 'block',
version: 1,
mixins: [dbBlockMixin],
})
export default class BlockService extends MoleculerDBService<
{
rest: 'v1/block';
},
IBlock
> {
@Get('/', {
name: 'getByChain',
params: {
chainid: {
type: 'string',
optional: false,
enum: LIST_NETWORK.map((e) => e.chainId),
},
blockHeight: { type: 'number', optional: true, convert: true },
blockHash: { type: 'string', optional: true },
operatorAddress: { type: 'string', optional: true },
consensusHexAddress: { type: 'string', optional: true },
pageLimit: {
type: 'number',
optional: true,
default: 10,
integer: true,
convert: true,
min: 1,
max: 100,
},
pageOffset: {
type: 'number',
optional: true,
default: 0,
integer: true,
convert: true,
min: 0,
max: 100,
},
countTotal: {
type: 'boolean',
optional: true,
default: false,
convert: true,
},
nextKey: {
type: 'number',
optional: true,
default: null,
convert: true,
},
reverse: {
type: 'boolean',
optional: true,
default: false,
convert: true,
},
},
cache: {
ttl: 10,
},
})
async getByChain(ctx: Context<GetBlockRequest, Record<string, unknown>>) {
let response: ResponseDto = {} as ResponseDto;
try {
const query: QueryOptions = {};
const blockHeight = ctx.params.blockHeight;
const blockHash = ctx.params.blockHash;
const operatorAddress = ctx.params.operatorAddress;
const consensusHexAddress = ctx.params.consensusHexAddress;
const sort = ctx.params.reverse ? 'block.header.height' : '-block.header.height';
let needNextKey = true;
if (blockHeight) {
query['block.header.height'] = blockHeight;
}
if (operatorAddress) {
const operatorList: IValidator[] = await this.broker.call(
'v1.validator.getByCondition',
{
query: {
'custom_info.chain_id': ctx.params.chainid,
// eslint-disable-next-line camelcase, quote-props
operator_address: operatorAddress,
},
},
);
if (operatorList.length > 0) {
query['block.header.proposer_address'] = operatorList[0].consensus_hex_address;
}
}
if (consensusHexAddress) {
query['block.header.proposer_address'] = consensusHexAddress;
}
if (blockHash) {
query['block_id.hash'] = blockHash;
needNextKey = false;
}
// eslint-disable-next-line camelcase
const projection: any = { custom_info: 0 };
if (!blockHash && !blockHeight) {
projection['block.last_commit'] = 0;
projection['block.evidence'] = 0;
}
if (ctx.params.nextKey) {
// Query._id = { $lt: new ObjectId(ctx.params.nextKey) };
query['block.header.height'] = { $lt: Number(ctx.params.nextKey) };
}
const network = LIST_NETWORK.find((x) => x.chainId === ctx.params.chainid);
if (network && network.databaseName) {
this.adapter.useDb(network.databaseName);
}
const [resultBlock, resultCount]: [any[], any] = await Promise.all([
this.adapter.lean({
query,
projection,
limit: ctx.params.pageLimit + 1,
offset: ctx.params.pageOffset,
// @ts-ignore
// Sort: '-block.header.height',
sort,
}),
ctx.params.countTotal === true
? this.adapter.countWithSkipLimit({
query,
skip: 0,
limit: ctx.params.pageLimit * 5,
})
: 0,
]);
let nextKey = null;
if (resultBlock.length > 0) {
if (resultBlock.length === 1) {
if (needNextKey) {
nextKey = resultBlock[resultBlock.length - 1]?.block.header.height;
}
} else {
if (needNextKey) {
nextKey = resultBlock[resultBlock.length - 2]?.block.header.height;
}
}
if (resultBlock.length <= ctx.params.pageLimit) {
nextKey = null;
}
if (nextKey) {
resultBlock.pop();
}
}
response = {
code: ErrorCode.SUCCESSFUL,
message: ErrorMessage.SUCCESSFUL,
data: {
blocks: resultBlock,
count: resultCount,
nextKey,
},
};
} catch (error) {
response = {
code: ErrorCode.WRONG,
message: ErrorMessage.WRONG,
data: {
error,
},
};
}
return response;
}
/**
* @swagger
* /v1/block:
* get:
* tags:
* - Block
* summary: Get latest block
* description: Get latest block
* parameters:
* - in: query
* name: chainid
* required: true
* schema:
* type: string
* enum: ["aura-testnet-2","serenity-testnet-001","halo-testnet-001","theta-testnet-001","osmo-test-4","evmos_9000-4","euphoria-2","cosmoshub-4"]
* description: "Chain Id of network need to query"
* example: "aura-testnet-2"
* - in: query
* name: blockHeight
* required: false
* schema:
* type: string
* description: "Block height of transaction"
* - in: query
* name: blockHash
* required: false
* schema:
* type: string
* description: "Block hash"
* - in: query
* name: operatorAddress
* required: false
* schema:
* type: string
* description: "operator address who proposed this block"
* - in: query
* name: consensusHexAddress
* required: false
* schema:
* type: string
* description: "consensus hex address who proposed this block"
* - in: query
* name: pageLimit
* required: false
* schema:
* type: number
* default: 10
* description: "number record return in a page"
* - in: query
* name: pageOffset
* required: false
* schema:
* type: number
* default: 0
* description: "Page number, start at 0"
* - in: query
* name: countTotal
* required: false
* schema:
* type: boolean
* default: false
* description: "count total record"
* - in: query
* name: nextKey
* required: false
* schema:
* type: string
* description: "key for next page"
* - in: query
* name: reverse
* required: false
* schema:
* enum: ["true","false"]
* default: "false"
* type: string
* description: "reverse is true if you want to get the oldest record first, default is false"
* responses:
* '200':
* description: Block result
* content:
* application/json:
* schema:
* type: object
* properties:
* code:
* type: number
* example: 200
* message:
* type: string
* example: "Successful"
* data:
* type: object
* properties:
* blocks:
* type: array
* items:
* type: object
* properties:
* block_id:
* type: object
* properties:
* parts:
* type: object
* properties:
* total:
* type: number
* example: 1
* hash:
* type: string
* example: "7D045310732FBDB9DB3C31CE644E831BA450B89C6FC46E298B1589AE6BC61FCE"
* hash:
* type: string
* example: "0FC0669C5CC9F8C7A891F6BCE43334D5391BA36F1E178D0C10C2E77BAA5CFB9F"
* block:
* type: object
* properties:
* header:
* type: object
* properties:
* version:
* type: object
* properties:
* block:
* type: number
* example: 11
* last_block_id:
* type: object
* properties:
* parts:
* type: object
* properties:
* total:
* type: number
* example: 1
* hash:
* type: string
* example: "7D045310732FBDB9DB3C31CE644E831BA450B89C6FC46E298B1589AE6BC61FCE"
* hash:
* type: string
* example: "0FC0669C5CC9F8C7A891F6BCE43334D5391BA36F1E178D0C10C2E77BAA5CFB9F"
* chain_id:
* type: string
* example: "aura"
* height:
* type: number
* example: 123
* time:
* type: string
* example: "2022-09-06T03:05:37.931Z"
* last_commit_hash:
* type: string
* example: "406AA52905BBAD518B7E39EDEA4108F3569779EA5BCDCEB5D44BED7BC296F2E0"
* data_hash:
* type: string
* example: "5BA80BD845CB59539CD027253AC8F39DE8983C0713D7E22DA8867B9D08981837"
* validators_hash:
* type: string
* example: "EB5CDC9D3D506F56E9E10C49FCCF3098755B8699D67F35BF3748A5572EEA033A"
* next_validators_hash:
* type: string
* example: "EB5CDC9D3D506F56E9E10C49FCCF3098755B8699D67F35BF3748A5572EEA033A"
* consensus_hash:
* type: string
* example: "048091BC7DDC283F77BFBF91D73C44DA58C3DF8A9CBC867405D8B7F3DAADA22F"
* app_hash:
* type: string
* example: "5C97FF89AA5464245766A3BAD7C21B658D8AE405E71304B93F499DB960738633"
* last_results_hash:
* type: string
* example: "21DB2576AE5F49F6FDE57AC1F1A6081134A63534956C536DCE6A25BD72917C75"
* evidence_hash:
* type: string
* example: "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855"
* proposer_address:
* type: string
* example: "8690272AC41B780D3F009C9F50C36461C967B0C1"
* data:
* type: object
* properties:
* txs:
* type: array
* items:
* type: string
* example: "CqY2trMDNyNnQECgIIARjc/ghZ4RNjYnIhHVZfhQtdsAP+tVumfrCKifITaDFaZIiEORBlgmZSk="
* evidence:
* type: object
* properties:
* evidence:
* type: array
* items:
* type: object
* custom_info:
* type: object
* properties:
* chain_id:
* type: string
* example: "aura"
* chain_name:
* type: string
* example: "Aura network"
* count:
* type: number
* nextKey:
* type: string
* '422':
* description: Bad request
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* example: "ValidationError"
* message:
* type: string
* example: "Parameters validation error!"
* code:
* type: number
* example: 422
* type:
* type: string
* example: "VALIDATION_ERROR"
* data:
* type: array
* items:
* type: object
* properties:
* type:
* type: string
* example: "required"
* message:
* type: string
* example: "The 'chainid' field is required."
* field:
* type: string
* example: chainid
* nodeID:
* type: string
* example: "node1"
* action:
* type: string
* example: "v1.block.chain"
*/
} |
{{-- @extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
@csrf
<div class="row mb-3">
<label for="name" class="col-md-4 col-form-label text-md-end">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
@error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="password-confirm" class="col-md-4 col-form-label text-md-end">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection --}}
@extends('layouts.auth')
@section('title')
Register
@endsection
@section('content')
<div class="card-img" >
<img src="{{URL::asset('img/login_bg.jpg')}}" alt="login">
</div>
<div class="card-form" style="width: 100%; padding: 4%">
<a href="/" class="mb-5 flex">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path></svg><strong class="text-red-500">wommate</strong>
</a>
<form method="POST" action="{{ route('register') }}" >
@csrf
<div class="row">
<div class="flex">
<div class="form-groups flex-1 flex-col">
<label for="first_name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
Prenom<strong
class="text-red-500">*</strong></label>
<input id="firstName" type="text"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
name="first_name"
tabindex="1" placeholder="Prenom" value="{{ old('name') }}"
autofocus required>
<div class="invalid-feedback">
{{ $errors->first('first_name', 'verifier ') }}
</div>
</div>
<div class="form-groups flex-1 flex-col ml-2">
<label for="last_name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
Nom<strong
class="text-red-500">*</strong></label>
<input id="last_name" type="text"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
name="last_name"
tabindex="1" placeholder="Nom" value="{{ old('name') }}"
autofocus required>
<div class="invalid-feedback">
{{ $errors->first('first_name', 'verifier ') }}
</div>
</div>
</div>
<div class="mt-4 flex">
<div class="form-group flex-1 flex-col">
<label for="username" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
Pseudo<strong
class="text-red-500">*</strong></label>
<input id="username" type="text"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
placeholder="Entrer votre pseudo"
name="username" tabindex="1"
value="{{ old('username') }}"
required autofocus>
<div class="invalid-feedback">
{{ $errors->first('username') }}
</div>
</div>
<div class="form-group flex-1 flex-col ml-2">
<label for="email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
Email<strong
class="text-red-500">*</strong></label>
<input id="email" type="email"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
placeholder="Entrer votre address email"
name="email" tabindex="1"
value="{{ old('email') }}"
required autofocus>
<div class="invalid-feedback">
{{ $errors->first('email') }}
</div>
</div>
</div>
<div class="mt-4">
<div class="form-group">
<label for="password"class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Password
<strong
class="text-red-500">*</strong</label>
<input id="password" type="password"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
placeholder="Entrez votre password"
name="password" tabindex="1" required>
<div class="invalid-feedback">
{{ $errors->first('password') }}
</div>
</div>
<div class="form-group">
<label for="password_confirmation"
class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Confirmer votre mot de pass <strong
class="text-red-500">*</strong></label>
<input id="password_confirmation" type="password" placeholder="Confirm account password"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
name="password_confirmation" tabindex="2">
<div class="invalid-feedback">
{{ $errors->first('password_confirmation') }}
</div>
</div>
</di flex-1v>
<div class="mt-4">
<div class="form-group">
<input type="submit" value="s'inscrire" class="text-white bg-gradient-to-r from-teal-400 via-teal-500 to-teal-600 hover:bg-gradient-to-br focus:ring-4 focus:outline-none focus:ring-teal-300 dark:focus:ring-teal-800 font-medium rounded-lg text-sm px-5 py-2.5 text-center mr-2 mb-2" tabindex="4">
</div>
</div>
</div>
</form>
<div class="-mt-9 text-muted text-center">
Déja un compte ? <a
href="{{ route('login') }}">S'inscrire</a>
</div>
</div>
@endsection |
import { Input, Button, Spinner } from "@material-tailwind/react";
import { useState } from "react";
import { toast } from "react-toastify";
import axios from "axios";
import Header from "./Layout/Header";
import { useNavigate } from "react-router-dom";
import { useLocation } from "react-router-dom";
function ResetPassword() {
const [loading, setLoading] = useState(false);
const [userData, setUserData] = useState({
password: "",
});
const [formSubmitted, setFormSubmitted] = useState(false);
const navigate = useNavigate();
const location = useLocation();
const u = new URLSearchParams(location.search).get("u");
const t = new URLSearchParams(location.search).get("t");
console.log(u, t);
const passwordIsInvalid =
userData.password.length < 8 ||
!/[A-Z]/.test(userData.password) ||
!/\d/.test(userData.password);
const handleInput = (e) => {
const { name, value } = e.target;
setUserData({ ...userData, [name]: value });
};
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setFormSubmitted(true);
if (passwordIsInvalid) {
console.log("error");
setLoading(false);
} else {
try {
const response = await axios.post(
`http://localhost:5237/api/auth/forgot-password/reset-password?authUserId=${u}&resetToken=${t}&newPassword=${userData.password}`
);
console.log("response", response);
if (!response.data.success) {
// setFrontError(response.data.validationResult.errors);
toast.error("There has been an error");
console.log(
"validationResult",
response.data.validationResult.errors
);
} else {
// setFrontError([]);
toast.success("Password changed successfully");
navigate("/login");
console.log("something good");
}
} catch (err) {
console.error(err);
// setErrorServer(true);
} finally {
setLoading(false);
}
}
};
return (
<div>
<Header></Header>
<div className="text-red-700 font-bold text-center text-2xl mt-20">
PLEASE INPUT YOUR NEW PASSWORD
</div>
<div className="flex flex-col items-center justify-center content-end">
<form className="mt-8" onSubmit={handleSubmit}>
{loading ? (
<div className="flex flex-col items-center">
<Spinner
className=" flex justify-center items-center mt-40 h-12 w-12"
color="red"
/>
</div>
) : (
<div className="w-72 mx-auto mt-20 flex flex-col gap-4">
<Input
onChange={(e) => handleInput(e)}
type="password"
label="New Password"
name="password"
value={userData.email}
error={passwordIsInvalid && formSubmitted}
/>
{passwordIsInvalid && formSubmitted && (
<div className="text-red-500">Invalid email format </div>
)}
<Button className="bg-red-800" type="submit">
submit
</Button>
</div>
)}
</form>
</div>
</div>
);
}
export default ResetPassword; |
---
title: "Homework 4: Machine Learning"
author: "Edward Davies"
date: "`r Sys.Date()`"
output:
html_document:
theme: flatly
highlight: zenburn
number_sections: yes
toc: yes
toc_float: yes
code_folding: show
pdf_document:
toc: yes
---
```{r}
#| label: load-libraries
#| echo: false # This option disables the printing of code (only output is displayed).
#| message: false
#| warning: false
options(scipen = 999) #disable scientific notation
library(tidyverse)
library(tidymodels)
library(GGally)
library(sf)
library(leaflet)
library(janitor)
library(rpart.plot)
library(here)
library(scales)
library(vip)
library(reshape)
library(Cubist)
library(C50)
library(kknn)
library(igraph)
```
# The Bechdel Test
https://fivethirtyeight.com/features/the-dollar-and-cents-case-against-hollywoods-exclusion-of-women/
The [Bechdel test](https://bechdeltest.com) is a way to assess how women are depicted in Hollywood movies. In order for a movie to pass the test:
1. It has to have at least two [named] women in it
2. Who talk to each other
3. About something besides a man
There is a nice article and analysis you can find here https://fivethirtyeight.com/features/the-dollar-and-cents-case-against-hollywoods-exclusion-of-women/
We have a sample of 1394 movies and we want to fit a model to predict whether a film passes the test or not.
```{r read_data}
bechdel <- read_csv(here::here("data", "bechdel.csv")) %>%
mutate(test = factor(test))
glimpse(bechdel)
```
How many films fail/pass the test, both as a number and as a %?
```{r}
# Assuming the column with pass/fail information is 'test' and pass is represented as 'Pass'
pass_fail_counts <- bechdel %>%
count(test)
# To calculate the percentage
pass_fail_counts <- pass_fail_counts %>%
mutate(percent = n/sum(n) * 100)
# Display the counts and percentages
pass_fail_counts
```
## Movie scores
```{r}
ggplot(data = bechdel, aes(
x = metascore,
y = imdb_rating,
colour = test
)) +
geom_point(alpha = .3, size = 3) +
scale_colour_manual(values = c("tomato", "olivedrab")) +
labs(
x = "Metacritic score",
y = "IMDB rating",
colour = "Bechdel test"
) +
theme_light()
```
# Split the data
```{r}
# **Split the data**
set.seed(123)
data_split <- initial_split(bechdel, # updated data
prop = 0.8,
strata = test)
bechdel_train <- training(data_split)
bechdel_test <- testing(data_split)
```
Check the counts and % (proportions) of the `test` variable in each set.
```{r}
# For the training set
train_counts <- bechdel_train %>%
count(test) %>%
mutate(percent = n/sum(n) * 100)
# For the test set
test_counts <- bechdel_test %>%
count(test) %>%
mutate(percent = n/sum(n) * 100)
# Display the counts and percentages
train_counts
test_counts
```
## Feature exploration
```{r}
# Perform summary statistics for each of the features in the training data
summary(bechdel_train)
```
Grouped Summary Statistics:
```{r}
grouped_data <- bechdel_train %>% group_by(test) %>% summarise(mean_budget = mean(budget_2013), mean_domgross = mean(domgross_2013), mean_intgross = mean(intgross_2013), mean_metascore = mean(metascore), mean_imdb_rating = mean(imdb_rating))
print(grouped_data)
```
mean_budget: On average, films that fail the Bechdel test have a higher budget (approximately 6.85 in 2013 dollars) compared to films that pass the test (approximately 4.67 in 2013 dollars). This could suggest that films with larger budgets are less likely to have substantial female roles or female-centric narratives.
mean_domgross: Films that fail the Bechdel test also, on average, earn more at the domestic box office (around 10.65 in 2013 dollars) compared to films that pass the test (around 8.09 in 2013 dollars). This might indicate that films with less focus on female characters or narratives have historically performed better in domestic markets, although the difference is not substantial.
mean_intgross: Similar to domestic gross, films that fail the Bechdel test tend to earn more in international box office (approximately 23.25 in 2013 dollars) compared to films that pass the test (approximately 17.40 in 2013 dollars). This suggests that, like domestic markets, international audiences have also tended to favor films that do not pass the Bechdel test.
mean_metascore: Films that fail the Bechdel test have a slightly higher average Metascore (around 59.14) compared to films that pass the test (around 57.80). This might indicate that critics, on average, slightly favor films that fail the Bechdel test. However, the difference is minimal, indicating that whether a film passes or fails the Bechdel test does not significantly impact its critical reception.
mean_imdb_rating: Similarly, films that fail the Bechdel test have a slightly higher average IMDb rating (around 6.92) compared to films that pass the test (around 6.61). This might suggest that viewers have slightly favored films that fail the Bechdel test, although, like Metascore, the difference is not significant.
Proportions of Rated Groups:
```{r}
bechdel_train %>%
group_by(rated) %>%
summarise(n = n(), prop = n() / nrow(bechdel_train)) %>%
ggplot(aes(x = reorder(rated, -prop), y = prop)) +
geom_col() +
labs(x = "Rated", y = "Proportion")
```
This bar graph shows how data is distributed across the different rated groups within the dataset. There are many R and PG rated films, with very few NC-17 films. This makes sense as NC-17 are very rare.
## Any outliers?
```{r}
bechdel %>%
select(test, budget_2013, domgross_2013, intgross_2013, imdb_rating, metascore) %>%
pivot_longer(cols = 2:6,
names_to = "feature",
values_to = "value") %>%
ggplot()+
aes(x=test, y = value, fill = test)+
coord_flip()+
geom_boxplot()+
facet_wrap(~feature, scales = "free")+
theme_bw()+
theme(legend.position = "none")+
labs(x=NULL,y = NULL)
```
For budget, domestic gross and international gross, there are multiple outliers on the upper end but not the lower. This makes sense as although most films range within the 7 figures for budget, there are some "blockbusters" that have far higher budgets, and therefore generate far more revenue. Franchise films such as the Avengers or Fast & Furious fall under this category.
The rating measures, including the IMDB and Metascore rating, are far more consistent apart from a smaller number of outliers on the lower end, particularly for IMDB. This is likely due to reviews on either end of the spectrum being more common, with harsh reviews tending the be on the far lower end. The reason as the why the IMDB score contains more negative outliers is due to it being based on both critic and audience reviews (which tend to be harsher), whilst Metascore only contains critic scores.
## Scatterplot - Correlation Matrix
Write a paragraph discussing the output of the following
```{r, warning=FALSE, message=FALSE}
bechdel %>%
select(test, budget_2013, domgross_2013, intgross_2013, imdb_rating, metascore)%>%
ggpairs(aes(colour=test), alpha=0.2)+
theme_bw()
```
The correlation between imdb_rating and metascore for Fail group is 0.739, and for Pass it's 0.743. These are strong positive correlations, suggesting that movies with higher IMDB ratings also tend to have higher Metascore, regardless of whether they pass or fail the test. The correlation is almost the same for both groups, suggesting the relationship between IMDB rating and Metascore is similarly strong for both movies that pass and fail the Bechdel test.
The strong correlation between domestic gross and international gross for both Fail (0.927) and Pass (0.956) groups suggests that films that perform well domestically also tend to perform well internationally, regardless of whether they pass or fail the Bechdel test. This could imply that factors influencing domestic success also translate to international markets, such as genre, star power, or the film's overall quality. This relationship is slightly stronger for films that pass the Bechdel test.
On the other hand, the low correlation between the budget and both IMDb rating and Metascore suggests that a higher budget does not necessarily result in better critical ratings. The quality of a film, as assessed by both viewers (IMDb rating) and critics (Metascore), does not seem to be directly related to its production budget, whether it passes or fails the Bechdel test. This could be because film quality is determined by many factors beyond budget, such as script, direction, performances, etc. Therefore, spending more money on a film's production does not guarantee it will be better received by audiences or critics.
## Categorical variables
Write a paragraph discussing the output of the following
```{r}
bechdel %>%
group_by(genre, test) %>%
summarise(n = n()) %>%
mutate(prop = n/sum(n))
bechdel %>%
group_by(rated, test) %>%
summarise(n = n()) %>%
mutate(prop = n/sum(n))
```
Looking at the ratings, it seems that films rated G have approximately a 61.54% chance of failing the Bechdel test, and a 38.46% chance of passing. Films rated NC-17 have a much higher chance of failing the Bechdel test (83.33%) and a very low chance of passing (16.67%). PG-rated films are more evenly distributed with a failure rate of 56.10% and a pass rate of 43.90%. This is similar for PG-13 rated films, which have a failure rate of 52.90% and a pass rate of 47.10%. R-rated films have a higher chance of failing the Bechdel test (56.75%) than passing it (43.25%).
These findings suggest that films with more restricted ratings (NC-17 and R) are more likely to fail the Bechdel test. Conversely, films with more general audience ratings (G, PG, and PG-13) are somewhat more balanced, although they still fail the test more often than not. This could be due to a variety of factors, including differences in storytelling and character focus based on target audience demographics, or perhaps more mature or complex themes and narratives in R and NC-17 films that don't lend themselves as readily to passing the Bechdel test.
# Train first models. `test ~ metascore + imdb_rating`
```{r}
lr_mod <- logistic_reg() %>%
set_engine(engine = "glm") %>%
set_mode("classification")
lr_mod
tree_mod <- decision_tree() %>%
set_engine(engine = "C5.0") %>%
set_mode("classification")
tree_mod
```
```{r}
lr_fit <- lr_mod %>% # parsnip model
fit(test ~ metascore + imdb_rating, # a formula
data = bechdel_train # dataframe
)
tree_fit <- tree_mod %>% # parsnip model
fit(test ~ metascore + imdb_rating, # a formula
data = bechdel_train # dataframe
)
```
## Logistic regression
```{r}
lr_fit %>%
broom::tidy()
lr_preds <- lr_fit %>%
augment(new_data = bechdel_train) %>%
mutate(.pred_match = if_else(test == .pred_class, 1, 0))
```
### Confusion matrix
```{r}
lr_preds %>%
conf_mat(truth = test, estimate = .pred_class) %>%
autoplot(type = "heatmap")
```
This model only returns a 58% accuracy rate, and therefore is not very reliable.
## Decision Tree
```{r}
tree_preds <- tree_fit %>%
augment(new_data = bechdel) %>%
mutate(.pred_match = if_else(test == .pred_class, 1, 0))
```
```{r}
tree_preds %>%
conf_mat(truth = test, estimate = .pred_class) %>%
autoplot(type = "heatmap")
```
This model has a very similar, but albeit slightly smaller accuracy rate, at just under 58%.
## Draw the decision tree
```{r}
draw_tree <-
rpart::rpart(
test ~ metascore + imdb_rating,
data = bechdel_train, # uses data that contains both birth weight and `low`
control = rpart::rpart.control(maxdepth = 5, cp = 0, minsplit = 10)
) %>%
partykit::as.party()
plot(draw_tree)
```
# Cross Validation
Run the code below. What does it return?
```{r}
set.seed(123)
bechdel_folds <- vfold_cv(data = bechdel_train,
v = 10,
strata = test)
bechdel_folds
```
This code creates a 10-fold cross-validation plan with the bechdel_train data, with the folds being created in a stratified manner according to the test variable. This means that each fold will have roughly the same proportion of pass/fail as the original data. The output will be a tibble with two columns: .folds and .id. Each row in the .folds column is a list-column that contains the split objects for the resamples.
## `fit_resamples()`
Trains and tests a resampled model.
```{r}
lr_fit <- lr_mod %>%
fit_resamples(
test ~ metascore + imdb_rating,
resamples = bechdel_folds
)
tree_fit <- tree_mod %>%
fit_resamples(
test ~ metascore + imdb_rating,
resamples = bechdel_folds
)
```
## `collect_metrics()`
Unnest the metrics column from a tidymodels `fit_resamples()`
```{r}
collect_metrics(lr_fit)
collect_metrics(tree_fit)
```
```{r}
tree_preds <- tree_mod %>%
fit_resamples(
test ~ metascore + imdb_rating,
resamples = bechdel_folds,
control = control_resamples(save_pred = TRUE) #<<
)
# What does the data for ROC look like?
tree_preds %>%
collect_predictions() %>%
roc_curve(truth = test, .pred_Fail)
# Draw the ROC
tree_preds %>%
collect_predictions() %>%
roc_curve(truth = test, .pred_Fail) %>%
autoplot()
```
# Build a better training set with `recipes`
## Preprocessing options
- Encode categorical predictors
- Center and scale variables
- Handle class imbalance
- Impute missing data
- Perform dimensionality reduction
- ... ...
## To build a recipe
1. Start the `recipe()`
1. Define the variables involved
1. Describe **prep**rocessing [step-by-step]
## Collapse Some Categorical Levels
Do we have any `genre` with few observations? Assign genres that have less than 3% to a new category 'Other'
```{r}
#| echo = FALSE
bechdel %>%
count(genre) %>%
mutate(genre = fct_reorder(genre, n)) %>%
ggplot(aes(x = genre,
y = n)) +
geom_col(alpha = .8) +
coord_flip() +
labs(x = NULL) +
geom_hline(yintercept = (nrow(bechdel_train)*.03), lty = 3)+
theme_light()
```
```{r}
movie_rec <-
recipe(test ~ .,
data = bechdel_train) %>%
# Genres with less than 5% will be in a catewgory 'Other'
step_other(genre, threshold = .03)
```
## Before recipe
```{r}
#| echo = FALSE
bechdel_train %>%
count(genre, sort = TRUE)
```
## After recipe
```{r}
movie_rec %>%
prep() %>%
bake(new_data = bechdel_train) %>%
count(genre, sort = TRUE)
```
## `step_dummy()`
Converts nominal data into numeric dummy variables
```{r}
#| results = "hide"
movie_rec <- recipe(test ~ ., data = bechdel) %>%
step_other(genre, threshold = .03) %>%
step_dummy(all_nominal_predictors())
movie_rec
```
## Let's think about the modelling
What if there were no films with `rated` NC-17 in the training data?
- Will the model have a coefficient for rated NC-17?
No, the model will not have a coefficient for rated NC-17 if there were no films with this rating in the training data. Coefficients in a model represent the relationship between the predictors in the training data and the outcome variable. If a category does not exist in the training data, there is no way to estimate its effect, hence, it will not have a coefficient.
- What will happen if the test data includes a film with rated NC-17?
If the test data includes a film with rated NC-17 and the training data does not have this category, the model will not be able to make an accurate prediction for this film. This is because the model has not learned any relationship between films with rated NC-17 and the outcome variable. The prediction may fail, or the model may treat this category as if it were the reference category or as missing data.
## `step_novel()`
Adds a catch-all level to a factor for any new values not encountered in model training, which lets R intelligently predict new levels in the test set.
```{r}
movie_rec <- recipe(test ~ ., data = bechdel) %>%
step_other(genre, threshold = .03) %>%
step_novel(all_nominal_predictors) %>% # Use *before* `step_dummy()` so new level is dummified
step_dummy(all_nominal_predictors())
```
## `step_zv()`
Intelligently handles zero variance variables (variables that contain only a single value)
```{r}
movie_rec <- recipe(test ~ ., data = bechdel) %>%
step_other(genre, threshold = .03) %>%
step_novel(all_nominal(), -all_outcomes()) %>% # Use *before* `step_dummy()` so new level is dummified
step_dummy(all_nominal(), -all_outcomes()) %>%
step_zv(all_numeric(), -all_outcomes())
```
## `step_normalize()`
Centers then scales numeric variable (mean = 0, sd = 1)
```{r}
movie_rec <- recipe(test ~ ., data = bechdel) %>%
step_other(genre, threshold = .03) %>%
step_novel(all_nominal(), -all_outcomes()) %>% # Use *before* `step_dummy()` so new level is dummified
step_dummy(all_nominal(), -all_outcomes()) %>%
step_zv(all_numeric(), -all_outcomes()) %>%
step_normalize(all_numeric())
```
## `step_corr()`
Removes highly correlated variables
```{r}
movie_rec <- recipe(test ~ ., data = bechdel) %>%
step_other(genre, threshold = .03) %>%
step_novel(all_nominal(), -all_outcomes()) %>% # Use *before* `step_dummy()` so new level is dummified
step_dummy(all_nominal(), -all_outcomes()) %>%
step_zv(all_numeric(), -all_outcomes()) %>%
step_normalize(all_numeric()) %>%
step_corr(all_predictors(), threshold = 0.75, method = "spearman")
movie_rec
```
# Define different models to fit
```{r}
## Model Building
# 1. Pick a `model type`
# 2. set the `engine`
# 3. Set the `mode`: regression or classification
# Logistic regression
log_spec <- logistic_reg() %>% # model type
set_engine(engine = "glm") %>% # model engine
set_mode("classification") # model mode
# Show your model specification
log_spec
# Decision Tree
tree_spec <- decision_tree() %>%
set_engine(engine = "C5.0") %>%
set_mode("classification")
tree_spec
# Random Forest
library(ranger)
rf_spec <-
rand_forest() %>%
set_engine("ranger", importance = "impurity") %>%
set_mode("classification")
# Boosted tree (XGBoost)
library(xgboost)
xgb_spec <-
boost_tree() %>%
set_engine("xgboost") %>%
set_mode("classification")
# K-nearest neighbour (k-NN)
knn_spec <-
nearest_neighbor(neighbors = 4) %>% # we can adjust the number of neighbors
set_engine("kknn") %>%
set_mode("classification")
```
# Bundle recipe and model with `workflows`
```{r}
log_wflow <- # new workflow object
workflow() %>% # use workflow function
add_recipe(movie_rec) %>% # use the new recipe
add_model(log_spec) # add your model spec
# show object
log_wflow
## A few more workflows
tree_wflow <-
workflow() %>%
add_recipe(movie_rec) %>%
add_model(tree_spec)
rf_wflow <-
workflow() %>%
add_recipe(movie_rec) %>%
add_model(rf_spec)
xgb_wflow <-
workflow() %>%
add_recipe(movie_rec) %>%
add_model(xgb_spec)
knn_wflow <-
workflow() %>%
add_recipe(movie_rec) %>%
add_model(knn_spec)
```
HEADS UP
1. How many models have you specified?
2. What's the difference between a model specification and a workflow?
3. Do you need to add a formula (e.g., `test ~ .`) if you have a recipe?
# Model Comparison
You now have all your models. Adapt the code from slides `code-from-slides-CA-housing.R`, line 400 onwards to assess which model gives you the best classification.
```{r}
## Using `workflow()`, `fit()`, and `predict()`
# Fit the logistic regression workflow using the training data
log_fit <- log_wflow %>%
fit(data = bechdel_train)
# Make predictions using the logistic regression model on the test data
log_preds <- log_fit %>%
predict(new_data = bechdel_test) %>%
bind_cols(bechdel_test)
# View the predictions
head(log_preds)
# Repeat the process for the other models
# Decision Tree
tree_fit <- tree_wflow %>%
fit(data = bechdel_train)
tree_preds <- tree_fit %>%
predict(new_data = bechdel_test) %>%
bind_cols(bechdel_test)
# Random Forest
rf_fit <- rf_wflow %>%
fit(data = bechdel_train)
rf_preds <- rf_fit %>%
predict(new_data = bechdel_test) %>%
bind_cols(bechdel_test)
# Boosted Tree
xgb_fit <- xgb_wflow %>%
fit(data = bechdel_train)
xgb_preds <- xgb_fit %>%
predict(new_data = bechdel_test) %>%
bind_cols(bechdel_test)
# K-NN
knn_fit <- knn_wflow %>%
fit(data = bechdel_train)
knn_preds <- knn_fit %>%
predict(new_data = bechdel_test) %>%
bind_cols(bechdel_test)
# Let's see the classification metrics for all models
# Log Reg
log_metrics <- log_preds %>%
metrics(truth = test, estimate = .pred_class)
# Decision Tree
tree_metrics <- tree_preds %>%
metrics(truth = test, estimate = .pred_class)
# Random Forest
rf_metrics <- rf_preds %>%
metrics(truth = test, estimate = .pred_class)
# Boosted Tree
xgb_metrics <- xgb_preds %>%
metrics(truth = test, estimate = .pred_class)
# K-NN
knn_metrics <- knn_preds %>%
metrics(truth = test, estimate = .pred_class)
# Combine all metrics into a single dataframe for easy comparison
combined_metrics <- bind_rows(
log_metrics %>% add_column(Model = "Logistic Regression"),
tree_metrics %>% add_column(Model = "Decision Tree"),
rf_metrics %>% add_column(Model = "Random Forest"),
xgb_metrics %>% add_column(Model = "Boosted Tree"),
knn_metrics %>% add_column(Model = "K-NN")
)
# View the combined metrics
combined_metrics
```
#Logistic Regression:
Accuracy: 0.4321429. This means that the logistic regression model correctly predicted the class of the target variable approximately 43.21% of the time. This is generally considered low accuracy.
Kappa: -0.1052632. Kappa is an evaluation metric that takes into account the possibility of a correct prediction by chance. It's usually between 0 (random classification) and 1 (perfect classification). A negative value means the classifier is doing worse than random chance.
#Decision Tree:
Accuracy: 0.5892857. The decision tree model correctly predicted the class about 58.93% of the time. This is better than the logistic regression model.
Kappa: 0.1445271. The model's predictions are not random, but the value is still low, indicating a limited level of agreement.
#Random Forest:
Accuracy: 0.5785714. The random forest model had an accuracy of approximately 57.86%, which is slightly lower than the decision tree.
Kappa: 0.1158683. The kappa value is lower than that of the decision tree, suggesting that the model's predictions are not as reliable.
#Boosted Tree:
Accuracy: 0.5785714. The boosted tree model matched the random forest in accuracy, predicting correctly about 57.86% of the time.
Kappa: 0.1339450. Its kappa value is slightly higher than the random forest's, suggesting a better level of agreement.
#K-NN (K-Nearest Neighbors):
Accuracy: 0.5535714. The K-NN model predicted correctly about 55.36% of the time.
Kappa: 0.0000000. The kappa value of 0 indicates that this model's predictions are as good as random.
In summary, out of these models, the Decision Tree performed the best based on both accuracy and kappa metrics. Furthermore, these are not the only metrics to assess model performance, and the choice of metrics should be based on the specific use-case and problem at hand.
# Deliverables
There is a lot of explanatory text, comments, etc. You do not need these, so delete them and produce a stand-alone document that you could share with someone. Knit the edited and completed R Markdown (Rmd) file as a Word or HTML document (use the "Knit" button at the top of the script editor window) and upload it to Canvas. You must be commiting and pushing your changes to your own Github repo as you go along.
# Details
- Who did you collaborate with: TYPE NAMES HERE
- Approximately how much time did you spend on this problem set: ANSWER HERE
- What, if anything, gave you the most trouble: ANSWER HERE
**Please seek out help when you need it,** and remember the [15-minute rule](https://dsb2023.netlify.app/syllabus/#the-15-minute-rule){target="_blank"}. You know enough R (and have enough examples of code from class and your readings) to be able to do this. If you get stuck, ask for help from others, post a question on Slack-- and remember that I am here to help too!
> As a true test to yourself, do you understand the code you submitted and are you able to explain it to someone else?
# Rubric
13/13: Problem set is 100% completed. Every question was attempted and answered, and most answers are correct. Code is well-documented (both self-documented and with additional comments as necessary). Used tidyverse, instead of base R. Graphs and tables are properly labelled. Analysis is clear and easy to follow, either because graphs are labeled clearly or you've written additional text to describe how you interpret the output. Multiple Github commits. Work is exceptional. I will not assign these often.
8/13: Problem set is 60--80% complete and most answers are correct. This is the expected level of performance. Solid effort. Hits all the elements. No clear mistakes. Easy to follow (both the code and the output). A few Github commits.
5/13: Problem set is less than 60% complete and/or most answers are incorrect. This indicates that you need to improve next time. I will hopefully not assign these often. Displays minimal effort. Doesn't complete all components. Code is poorly written and not documented. Uses the same type of plot for each graph, or doesn't use plots appropriate for the variables being analyzed. No Github commits. |
import "./sidebar.scss";
import DashboardIcon from "@mui/icons-material/Dashboard";
import PersonOutlineIcon from "@mui/icons-material/PersonOutline";
import LocalShippingIcon from "@mui/icons-material/LocalShipping";
import CreditCardIcon from "@mui/icons-material/CreditCard";
import StoreIcon from "@mui/icons-material/Store";
import { Link } from "react-router-dom";
import { DarkModeContext } from "../../context/darkModeContext";
import { useContext } from "react";
const Sidebar = () => {
const { dispatch } = useContext(DarkModeContext);
return (
<div className="sidebar">
<div className="top">
<Link to="/" style={{ textDecoration: "none" }}>
<span className="logo">Admin</span>
</Link>
</div>
<hr />
<div className="center">
<ul>
<p className="title">MAIN</p>
<Link to="/" style={{ textDecoration: "none" }}>
<li>
<DashboardIcon className="icon" />
<span>Dashboard</span>
</li>
</Link>
<p className="title">LISTS</p>
<Link to="/users" style={{ textDecoration: "none" }}>
<li>
<PersonOutlineIcon className="icon" />
<span>Users</span>
</li>
</Link>
</ul>
</div>
<div className="bottom">
<div
className="colorOption"
onClick={() => dispatch({ type: "LIGHT" })}
></div>
<div
className="colorOption"
onClick={() => dispatch({ type: "DARK" })}
></div>
</div>
</div>
);
};
export default Sidebar; |
package frc.robot.subsystems;
import com.revrobotics.RelativeEncoder;
import com.ctre.phoenix6.hardware.CANcoder;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkLowLevel.MotorType;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.SwerveModulePosition;
import edu.wpi.first.math.kinematics.SwerveModuleState;
import edu.wpi.first.math.util.Units;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import frc.robot.Constants.DriveConstants;
import frc.robot.Constants.ModuleConstants;
public class SwerveModule {
private final CANSparkMax driveMotor;
private final CANSparkMax turningMotor;
private final RelativeEncoder driveEncoder;
private final RelativeEncoder turningEncoder;
private final PIDController turningPidController;
private final double kAbsoluteEncoderOffset;
private final boolean kAbsoluteEncoderReversed;
private CANcoder absoluteEncoder ;
private SwerveModuleState desiredState = new SwerveModuleState(0.0, new Rotation2d());
public SwerveModule(int driveMotorId, int turningMotorId, boolean driveMotorReversed, boolean turningMotorReversed,
int absoluteEncoderId, double absoluteEncoderOffset, boolean absoluteEncoderReversed) {
kAbsoluteEncoderOffset = absoluteEncoderOffset;
kAbsoluteEncoderReversed = absoluteEncoderReversed;
this.absoluteEncoder = new CANcoder(absoluteEncoderId);
driveMotor = new CANSparkMax(driveMotorId, MotorType.kBrushless);
turningMotor = new CANSparkMax(turningMotorId, MotorType.kBrushless);
driveMotor.setInverted(driveMotorReversed);
turningMotor.setInverted(turningMotorReversed);
driveEncoder = driveMotor.getEncoder();
turningEncoder = turningMotor.getEncoder();
driveEncoder.setPositionConversionFactor(ModuleConstants.kDriveEncoderRot2Meter);
driveEncoder.setVelocityConversionFactor(ModuleConstants.kDriveEncoderRPM2MeterPerSec);
turningEncoder.setPositionConversionFactor(ModuleConstants.kTurningEncoderRot2Rad);
turningEncoder.setVelocityConversionFactor(ModuleConstants.kTurningEncoderRPM2RadPerSec);
turningPidController = new PIDController(ModuleConstants.kPTurning, 0, 0);
turningPidController.enableContinuousInput(-Math.PI, Math.PI);
resetEncoders();
}
public SwerveModuleState getState() {
return new SwerveModuleState(getDriveVelocity(), new Rotation2d(getAbsoluteEncoderRad()));
}
public SwerveModulePosition getPosition(){
return( new SwerveModulePosition(getDrivePosition(), new Rotation2d(getAbsoluteEncoderRad())));
}
public void setDesiredState(SwerveModuleState state) {
state = SwerveModuleState.optimize(state, getState().angle);
double desiredTurnSpeed = turningPidController.calculate(getAbsoluteEncoderRad(), state.angle.getRadians());
turningMotor.set(desiredTurnSpeed);
driveMotor.set(state.speedMetersPerSecond);
desiredState = state;
SmartDashboard.putString("Swerve[" + absoluteEncoder.getDeviceID() + "] state", state.toString());
}
public void resetEncoders() {
driveEncoder.setPosition(0.0);
turningEncoder.setPosition(this.getAbsoluteEncoderRotations());
}
public SwerveModuleState getDesiredState() {
return desiredState;
}
public double getDrivePosition() {
return driveEncoder.getPosition();
}
public double getDriveVelocity() {
return driveEncoder.getVelocity();
}
// public double getAbsoluteEncoderRad() {
// // Get the absolute position of the encoder in degrees.
// double absolutePositionDegrees = this.absoluteEncoder.getAbsolutePosition().getValue();
// // Convert degrees to radians
// double radians = Math.toRadians(absolutePositionDegrees*360);
// return radians;
// }
public double getAbsoluteEncoderRotations() {
double angle = absoluteEncoder.getAbsolutePosition().getValueAsDouble(); // Returns percent of a full rotation
return angle * (kAbsoluteEncoderReversed ? -1.0 : 1.0); // Look up ternary or conditional operators in java
}
public double getAbsoluteEncoderRad() {
double angle = absoluteEncoder.getAbsolutePosition().getValueAsDouble(); // Returns percent of a full rotation
angle = Units.rotationsToRadians(angle);
return angle * (kAbsoluteEncoderReversed ? -1.0 : 1.0); // Look up ternary or conditional operators in java
}
// public void setDesiredState(SwerveModuleState state) {
// if (Math.abs(state.speedMetersPerSecond) < 0.001) {
// stop();
// return;
// }
// state = SwerveModuleState.optimize(state, getState().angle);
// driveMotor.set(state.speedMetersPerSecond / DriveConstants.kPhysicalMaxSpeedMetersPerSecond);
// turningMotor.set(turningPidController.calculate(getTurningPosition(), state.angle.getRadians()));
// }
public void stop() {
driveMotor.set(0);
turningMotor.set(0);
}
} |
import { createContext, useState } from 'react';
import { Hotel } from 'interfaces/Hotel/Hotel';
import { SortOption } from 'interfaces/SortOption';
import { DEFAULT, LOW } from 'constants/sortKeys';
import { TSortKeys, TSortOrder } from 'types/sort';
export interface IHotelsContext {
isLoading: boolean;
setIsLoading: (isLoading: boolean) => void;
error: object;
setError: (error: object) => void;
hotels: Hotel[];
setHotels: (hotels: Hotel[]) => void;
sortOptions: SortOption[];
setSortOptions: (sortOptions: SortOption[]) => void;
selectedSort: SortOption;
setSelectedSort: (sort: SortOption) => void;
}
const HotelsContext = createContext<IHotelsContext | null>(null);
const HotelsProvider = ({ children }) => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [hotels, setHotels] = useState<Hotel[]>([]);
const [sortOptions, setSortOptions] = useState<SortOption[]>([]);
const [selectedSort, setSelectedSort] = useState({
id: DEFAULT as TSortKeys,
order: LOW as TSortOrder,
});
return (
<HotelsContext.Provider
value={{
isLoading,
setIsLoading,
error,
setError,
hotels,
setHotels,
sortOptions,
setSortOptions,
selectedSort,
setSelectedSort,
}}>
{children}
</HotelsContext.Provider>
);
};
export { HotelsContext, HotelsProvider }; |
<!DOCTYPE html>
<html lang="ru">
<head>
{% block title %}
<title>Сайт местной библиотеки</title>
{% endblock %}
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
crossorigin="anonymous">
{% load static %}
<link rel="stylesheet" href="{% static 'css/styles.css' %}" />
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2">
{% block sidebar %}
<ul class="sidebar-nav">
<li><a href="{% url 'index' %}">Домашняя страница</a></li>
<li><a href="{% url 'books' %}">Список книг</a></li>
<li><a href="{% url 'authors' %}">Список авторов</a></li>
</ul>
{% endblock %}
</div>
<div class="col-sm-10 ">
{% block content %}{% endblock %}
{% block pagination %}
{% if is_paginated %}
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
<a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">пред.</a>
{% endif %}
<span class="page-current">
Страница {{ page_obj.number }} из {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="{{ request.path }}?page={{ page_obj.next_page_number }}">след.</a>
{% endif %}
</span>
</div>
{% endif %}
{% endblock %}
</div>
</div>
</div>
</body>
</html> |
#include "boton.h"
#include <QPainter>
#include <QMouseEvent>
Boton::Boton(QWidget *parent) : QWidget(parent), m_color(Qt::red) {}
void Boton::colorear(Color color) {
switch (color) {
case Rojo:
m_color = Qt::red;
break;
case Azul:
m_color = Qt::blue;
break;
case Verde:
m_color = Qt::green;
break;
}
update(); // Fuerza la actualización del widget
}
void Boton::setText(const QString &text) {
m_text = text;
update(); // Fuerza la actualización del widget para mostrar el nuevo texto
}
QString Boton::text() const {
return m_text;
}
void Boton::paintEvent(QPaintEvent *event) {
Q_UNUSED(event);
QPainter painter(this);
painter.fillRect(rect(), m_color);
painter.drawText(rect(), Qt::AlignCenter, m_text); // Dibuja el texto en el centro del botón
}
void Boton::mousePressEvent(QMouseEvent *event) {
Q_UNUSED(event);
// Cambiar de color al hacer clic, alternando entre rojo, azul y verde.
if (m_color == Qt::red) {
colorear(Azul);
} else if (m_color == Qt::blue) {
colorear(Verde);
} else {
colorear(Rojo);
}
emit signal_clic(); // Emitir la señal cuando se hace clic
} |
<div class="col-md-{{ size }}">
<template v-if="dataSource && dataSource.length > 0 && !loading" v-cloak>
<table class="table"
:class="tableClass"
v-cloak
>
<thead>
<tr>
<template v-for="column in columns">
<template v-if="column.sortable">
<th width="{{ column.width }}"
class="sortable"
:class="column.class"
@click="orderBy(column.name)"
>
<i v-if="column.icon" :class="column.icon"></i>
{{ column.text }}
</th>
</template>
<template v-if="!column.sortable">
<th width="{{ column.width}} " :class="column.class">
<i v-if="column.icon" :class="column.icon"></i>
{{ column.text ? column.text : column.name }}
</th>
</template>
</template>
<template v-if="actions.length > 0">
<th width="1%" style="{ margin-left: 6px; margin-right: 6px; }" nowrap></th>
</template>
</tr>
</thead>
<tbody>
<tr v-for="item in dataSource | orderBy sortOrder.column sortOrder.direction" @click="onRowClicked(item)">
<template v-for="column in columns">
<td>
{{ item[column.name] }}
</td>
</template>
<template v-if="actions.length > 0">
<td nowrap>
<template v-for="action in actions">
<template v-if="action.type == undefined">
<button class="action"
:class="action.class"
@click="callAction(action.name, item, $event)"
>
<i v-if="action.icon" :class="action.icon"></i>
{{ action.label }}
</button>
</template>
<template v-if="action.type == 'link'">
<a href class="action" :class="action.class"
@click="callAction(action.name, item, $event)"
>
<i v-if="action.icon" :class="action.icon"></i>
{{ action.label }}
</a>
</template>
</template>
</td>
</template>
</tr>
</tbody>
</table>
</template>
<template v-if="dataSource && dataSource.length == 0 && !loading" v-cloak>
<h3>{{ nodataText }}</h3>
</template>
</div> |
# pytorch implementation of the DIV2K dataset. Extends VisionDataset to
# integrate with torchvision
from pathlib import Path
from torchvision.datasets import VisionDataset
from torchvision.datasets.utils import download_and_extract_archive
from typing import List, Tuple, Optional, Tuple, Callable, Any
from PIL import Image
from torch import Tensor
from torchvision.transforms import Compose
class DIV2K(VisionDataset):
_base_url = "http://data.vision.ee.ethz.ch/cvl/DIV2K/"
_download_url_train = _base_url + "DIV2K_train_HR.zip"
_download_url_valid = _base_url + "DIV2K_valid_HR.zip"
def __init__(
self,
root_dir: Path,
train: bool = True,
transform=None,
target_transform=None,
common_transform=None,
sample_target_generator: Optional[Callable[[Any],
Tuple[Tensor,
Tensor]]] = None,
download: bool = False,
):
super().__init__(str(root_dir),
transform=transform,
target_transform=target_transform)
self.train = train
self.root_dir: Path = Path(root_dir)
self.dataset_dir: Path = self.root_dir / "DIV2K"
self.transform = transform
self.target_transform = target_transform
self.common_transform = common_transform
self.sample_target_generator: Optional[Callable[[Any], Tuple[
Tensor, Tensor]]] = sample_target_generator
self.folder_basename: str = ("DIV2K_train_HR"
if self.train else "DIV2K_valid_HR")
self.image_folder = self.dataset_dir / self.folder_basename
self.image_folder = self.image_folder.resolve()
self.image_files: List[str] = [
f"{i:04d}.png"
for i in (range(1, 801) if self.train else range(801, 901))
]
if download:
self.download()
if not self._check_integrity():
raise RuntimeError("Dataset not found or corrupted. "
"You can use download=True to download it")
def _check_integrity(self):
return self.image_folder.exists() and self.image_folder.is_dir()
def download(self):
if not self._check_integrity():
download_and_extract_archive(
url=self._download_url_train
if self.train else self._download_url_valid,
extract_root=str(self.dataset_dir),
download_root=str(self.dataset_dir),
remove_finished=True)
def __len__(self) -> int:
return len(self.image_files)
def __getitem__(
self,
idx: int,
) -> Tuple[Image.Image | Tensor, Image.Image | Tensor]:
image: Image.Image = Image.open(self.image_folder /
self.image_files[idx]).convert("RGB")
if self.sample_target_generator is not None:
return self.sample_target_generator(image)
if self.common_transform is not None:
image = self.common_transform(image)
if isinstance(image, Image.Image):
target = image.copy() # image is a PIL image
elif isinstance(image, Tensor):
target = image.clone() # image is a tensor
else:
raise TypeError("Image is not of a known type")
if self.transform is not None:
image = self.transform(image)
if self.target_transform is not None:
target = self.target_transform(target)
return image, target |
import { HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { TokenService } from "../token.service";
@Injectable()
export class HttpTokenInterceptor implements HttpInterceptor {
constructor(
private tokenService: TokenService,
) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.tokenService.token
if (token) {
const authReq = request.clone({
headers: new HttpHeaders({
Authorization: 'Bearer ' + token
})
});
return next.handle(authReq)
}
return next.handle(request)
}
} |
import './App.css';
import { useState, useEffect } from 'react';
function App() {
const [characterName, setCharacterName] = useState('');
const [classType, setClassType] = useState('');
const [weapon, setWeaponType] = useState('');
const [roles, setRoles] = useState([]);
const [roleDescription, setRoleDescription] = useState('');
const [characterSelected, setCharacterSelected] = useState(false)
const [response, setResponse] = useState([]);
const [loading, setLoading] = useState(false);
const [region, setRegion] = useState(null)
useEffect(() => {
fetch('http://127.0.0.1:5000/api/roles')
.then((response) => response.json())
.then((data) => setRoles(data))
.catch((error) => console.error('Error fetching roles:', error));
}, []);
const handleRoleChange = (e) => {
const selectedRoleId = e.target.value;
const selectedRole = roles.find((role) => role.id === parseInt(selectedRoleId));
if (selectedRole) {
setClassType(selectedRole.name);
setRoleDescription(selectedRole.description);
}
};
function onCharacterSelect(){
setCharacterSelected(characterSelected => !characterSelected)
}
function findRegions() {
setLoading(true);
fetch('http://127.0.0.1:5000/api/regions')
.then((response) => response.json())
.then((data) => {
console.log(data.regions)
setResponse(data.regions);
setLoading(false);
})
.catch((error) => {
console.error('Error fetching regions:', error);
setLoading(false);
});
}
function handleRegionSelect(land){
setRegion(land)
console.log(region)
}
function startJourney(){
console.log(characterName)
console.log(classType)
console.log(region)
const newCharacter = {
name: characterName,
weapon: weapon,
role_name: classType
}
{/*must add region to character model,
create weapon input on react, and create a
response script through OpenAi
to fetch newly created character and return response*/}
fetch('http://127.0.0.1:5000/api/characters', {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newCharacter)
})
.then(r => r.json())
.then(data => console.log(data))
}
return (
<div>
{ characterSelected ?
<div className="App">
<form>
<label>Enter your Character Name:</label>
<input
type="text"
value={characterName}
onChange={(e) => setCharacterName(e.target.value)}
></input>
<select
id="classType"
value={classType}
onChange={handleRoleChange}
>
<option value="">Select a role</option>
{roles.map((role) => (
<option key={role.id} value={role.id}>
{role.name}
</option>
))}
</select>
</form>
{classType}
{roleDescription && (
<p>Role Description: {roleDescription}</p>
)}
<button onClick={onCharacterSelect}>Next</button>
</div>
:
<div>
<p>Character Name: {characterName}</p>
<p> Class: {classType}</p>
<button onClick={onCharacterSelect}>Back</button>
<button onClick={findRegions}>Submit</button>
</div>
}
<div>
{loading ? (
<p>Loading...</p>
) : (
<ul>
{response.map((r) => (
<li key={r.name}
onClick= {()=> handleRegionSelect(r)}
style={{ cursor: 'pointer', backgroundColor: region === r ? 'lightblue' : 'white' }}
>{r.name} <p key={r.description}>{r.description}</p></li>
))}
</ul>
)}
</div>
<div>
{ region === null ? <div></div> : ( <div>
<h3>Ready to Start your Journey?</h3>
<button>Start</button>
</div>
)
}
</div>
</div>
);
}
export default App; |
<div class="wrapper">
<div class="content">
<a href="#" class="app-title">
<img class="w-8 h-8 mr-2" src="https://flowbite.s3.amazonaws.com/blocks/marketing-ui/logo.svg" alt="logo" />
Sample App
</a>
<div class="form-container">
<div class="form-content">
<h1 class="form-title">
Change Password
</h1>
<form [formGroup]="formControl" (ngSubmit)="onSubmit()">
<mat-form-field>
<mat-label>Current Password</mat-label>
<input type="password" matInput formControlName="current_password">
<mat-error
*ngIf="formControl.controls['current_password'].errors && formControl.controls['current_password'].errors['required']">
Current Password is <strong>required</strong>
</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>New Password</mat-label>
<input type="password" matInput formControlName="new_password">
<mat-error
*ngIf="formControl.controls['new_password'].errors && formControl.controls['new_password'].errors['required']">
New Password is <strong>required</strong>
</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Re-type New Password</mat-label>
<input type="password" matInput formControlName="retype_new_password">
<mat-error
*ngIf="formControl.controls['retype_new_password'].errors && formControl.controls['retype_new_password'].errors['required']">
Re-type New Password is <strong>required</strong>
</mat-error>
</mat-form-field>
<button type="submit" mat-stroked-button [disabled]="disableSubmitButton">Change Password
<mat-spinner *ngIf="disableSubmitButton"></mat-spinner></button>
<p><a routerLink="/">Go Back</a></p>
</form>
</div>
</div>
</div>
</div> |
from flask import Flask
from random import randint
from gremlin_python import statics
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.driver.protocol import GremlinServerError
from gremlin_python.driver import serializer
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.process.traversal import T
from gremlin_python.structure.graph import Graph
from aiohttp.client_exceptions import ClientConnectorError
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import ReadOnlyCredentials
from types import SimpleNamespace
import os, sys, backoff, math
from flask import render_template
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
app = Flask(__name__)
reconnectable_err_msgs = [
'ReadOnlyViolationException',
'Server disconnected',
'Connection refused',
'Connection was already closed',
'Connection was closed by server',
'Failed to connect to server: HTTP Error code 403 - Forbidden'
]
retriable_err_msgs = ['ConcurrentModificationException'] + reconnectable_err_msgs
network_errors = [OSError, ClientConnectorError]
retriable_errors = [GremlinServerError, RuntimeError, Exception] + network_errors
def prepare_iamdb_request(database_url):
service = 'neptune-db'
method = 'GET'
access_key = os.environ['AWS_ACCESS_KEY_ID']
secret_key = os.environ['AWS_SECRET_ACCESS_KEY']
region = os.environ['SERVICE_REGION']
session_token = os.environ['AWS_SESSION_TOKEN']
creds = SimpleNamespace(
access_key=access_key, secret_key=secret_key, token=session_token, region=region,
)
request = AWSRequest(method=method, url=database_url, data=None)
SigV4Auth(creds, service, region).add_auth(request)
return (database_url, request.headers)
def create_remote_connection():
(database_url, headers) = connection_info()
return DriverRemoteConnection(
database_url,
'g',
pool_size=1,
message_serializer=serializer.GraphSONSerializersV2d0(),
headers=headers)
def connection_info():
database_url = 'wss://{}:{}/gremlin'.format(os.environ['neptuneEndpoint'], os.environ['neptunePort'])
if 'USE_IAM' in os.environ and os.environ['USE_IAM']=="true":
return prepare_iamdb_request(database_url)
else:
return (database_url,{})
@app.route("/")
def hello_world():
graph = Graph()
conn = create_remote_connection()
g = graph.traversal().withRemote(conn)
node_data = g.V().elementMap().toList()
print("Sending request to neptune for nodes...")
edge_data = g.E().elementMap().toList()
print("Sending request to neptune for edges...")
conn.close()
id_node_name = {n["id"]:n["entity_id"] for n in node_data}
nodes=[]
links=[]
for n in node_data:
nodes.append({
"id":n["entity_id"],
"attributes":"",
"type":""
})
for e in edge_data:
links.append({
"source":id_node_name[e["IN"]["id"]],
"target":id_node_name[e["OUT"]["id"]],
"label":e["label"],
"strength":1.0
})
# union find to get list of not connected components
parent = {n["id"]:n["id"] for n in nodes}
rank = {n["id"]:1 for n in nodes}
def find(n):
while n!=parent[n]:
parent[n]=parent[parent[n]]
n=parent[n]
return n
def union(n1,n2):
p1,p2 = find(n1),find(n2)
if rank[p1]>rank[p2]:
rank[p1]+=1
parent[p2]=p1
else:
rank[p2]+=1
parent[p1]=p2
for e in links:
s,t = e["source"],e["target"]
union(s,t)
top_level_parents = set()
for n,p in parent.items():
top_level_parents.add(find(n))
if len(top_level_parents)>1:
for i,v in enumerate(top_level_parents):
if i ==0:
nodes.append({})
nodes[-1]["id"]="Knowledge"
nodes[-1]["attributes"]=""
nodes[-1]["type"]=""
links.append({
"source":v,
"target":"Knowledge",
"label":"ManuallyAdded",
"strength":1.0
})
out = {"links":links,"nodes":nodes}
return render_template("index.html", data=out_data)
if __name__ == "__main__":
app.run(host='0.0.0.0') |
package com.algorithms.ctci.normal.recursionanddp;
import java.util.Arrays;
public class StaircaseThreeStepHopping {
/**
* Triple Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a
* time. Implement a method to count how many possible ways the child can run up the stairs.
* <p>
* There are n stairs, and a person is allowed to jump next stair, skip one stair or skip two stairs. So there are
* n stairs. So if a person is standing at i-th stair, the person can move to i+1, i+2, i+3-th stair.
* <p>
* Brute Force Solution:
* Like the Fibonacci problem, the runtime of this algorithm is exponential (roughly 0(3^n)), since each call
* branches out to three more calls.
* <p>
* Time Complexity: O(3^n).
* The time complexity of the above solution is exponential, a close upper bound will be O(3^n). From each state,
* 3 recursive function are called. So the upperbound for n states is O(3^n).
* Space Complexity: O(N).
* Auxiliary Space required by the recursive call stack is O(depth of recursion tree).
* <p>
* Note that, we just need to add the number of these paths together instead of multiplying.
*/
int countWays(int n) {
if (n < 0) {
return 0;
} else if (n == 0) {
return 1;
} else {
return countWays(n - 1) + countWays(n - 2) + countWays(n - 3);
}
}
/**
* DP using Memoization (Top-down approach)
* <p>
* We can avoid the repeated work done in method 1(recursion) by storing the number of ways calculated so far.
* <p>
* We just need to store all the values in an array.
* <p>
* The previous solution for countWays is called many times for the same values, which is unnecessary.
* We can fix this through memoization.
* <p>
* NOTE:
* Regardless of whether or not you use memoization, note that the number of ways will quickly overflow the bounds
* of an integer. By the time you get to just n = 37, the result has already overflowed.
* Using a long will delay, but not completely solve, this issue.
* <p>
* Time Complexity: O(n). Only one traversal of the array is needed. So Time Complexity is O(n).
* Space Complexity: O(n). To store the values in a DP, n extra space is needed. Also, stack space for recursion is
* needed which is again O(n)
*/
int countWaysV1(int n) {
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
return countWays(n, memo);
}
private int countWays(int n, int[] memo) {
if (n < 0) {
return 0;
} else if (n == 0) {
return 1;
} else if (memo[n] > -1) {
return memo[n];
} else {
memo[n] = countWays(n - 1, memo) + countWays(n - 2, memo) + countWays(n - 3, memo);
return memo[n];
}
}
/**
* Bottom-Up Approach: Another way is to take an extra space of size n and start computing values of states
* from 1, 2 .. to n, i.e. compute values of i, i+1, i+2 and then use them to calculate the value of i+3.
* <p>
* Time Complexity: O(n). Only one traversal of the array is needed. So Time Complexity is O(n).
* Space Complexity: O(n). To store the values in a DP, n extra space is needed.
*/
public static int countWaysV2(int n) {
final int[] result = new int[n + 1];
result[0] = 1;
result[1] = 1;
result[2] = 2;
for (int i = 3; i <= n; i++) {
result[i] = result[i - 1] + result[i - 2] + result[i - 3];
}
return result[n];
}
/**
* Using four variables
* <p>
* The idea is based on the Fibonacci series but here with 3 sums. we will hold the values of the first three
* stairs in 3 variables and will use the fourth variable to find the number of ways.
* <p>
* Time Complexity: O(n)
* Auxiliary Space: O(1), since no extra space has been taken.
*/
static int countWaysV3(int n) {
// Declaring three variables and holding the ways for first three stairs
int a = 1, b = 2, c = 4;
if (n == 0 || n == 1 || n == 2) {
return n;
}
if (n == 3) {
return c;
}
// Fourth variable
int count = 0;
for (int i = 4; i <= n; i++) {
count = c + b + a;
a = b;
b = c;
c = count;
}
return count;
}
} |
# user fact table
# basic min, max, first, last, lifetime metrics
# doing some cleaning/exclusions to account for oddities
view: pdt_user_fact {
derived_table: {
distribution_style: even
sortkeys: ["id"]
sql_trigger_value: SELECT COUNT(*) FROM ${shop_orders.SQL_TABLE_NAME};;
sql: select
users.id
, sum(shop_orders.total_price) as lifetime_order_amount
, min(shop_orders.created_at) as first_order_timestamp
, max(shop_orders.created_at) as most_recent_order_timestamp
, count(distinct shop_orders.id) as lifetime_order_count
, avg(shop_orders.total_price) as average_order_amount
FROM mysql_heroku_app_db.users
LEFT JOIN ${shop_orders.SQL_TABLE_NAME} as shop_orders ON users.id = shop_orders.user_id
WHERE 1=1
--exclude orders where the carrier charge = the total price, these were often post shipment shipping charges
and (case
when carrier_charge is null and total_price is not null then true
when carrier_charge <> total_price then true
else false end)
GROUP BY users.id
;;
}
##### Dimensions ###############
dimension: id {
type: number
sql: ${TABLE}.id ;;
hidden: yes
primary_key: yes
}
dimension: lifetime_order_amount_dim {
type: number
sql: ${TABLE}.lifetime_order_amount ;;
hidden: yes
}
dimension_group: first_order {
type: time
timeframes: [date, week, month]
sql: ${TABLE}.first_order_timestamp ;;
}
dimension_group: most_recent_order {
type: time
timeframes: [date, week, month]
sql: ${TABLE}.most_recent_order_timestamp ;;
}
dimension: lifetime_order_count_dim {
type: number
sql: ${TABLE}.lifetime_order_count ;;
hidden: yes
}
dimension: average_order_amount {
type: number
sql: ${TABLE}.average_order_amount ;;
value_format_name: usd
}
dimension: lifetime_revenue_grouping {
type: string
sql: CASE WHEN ${TABLE}.lifetime_order_amount is NULL THEN '8. Not available'
WHEN ${TABLE}.lifetime_order_amount < 25 THEN '1. Under $25'
WHEN ${TABLE}.lifetime_order_amount < 50 THEN '2. $25 - $49.99'
WHEN ${TABLE}.lifetime_order_amount < 75 THEN '3. $50 - $74.99'
WHEN ${TABLE}.lifetime_order_amount < 100 THEN '4. $75 - $99.99'
WHEN ${TABLE}.lifetime_order_amount < 150 THEN '5. $100 - $149.99'
WHEN ${TABLE}.lifetime_order_amount < 250 THEN '6. $150 - $249.99'
ELSE '7. Over $250' END ;;
}
dimension: average_order_amount_grouping {
type: string
sql: CASE WHEN ${TABLE}.average_order_amount is NULL THEN '8. Not available'
WHEN ${TABLE}.average_order_amount < 5 THEN '1. Under $5'
WHEN ${TABLE}.average_order_amount < 10 THEN '2. $5 - $9.99'
WHEN ${TABLE}.average_order_amount < 15 THEN '3. $10 - $14.99'
WHEN ${TABLE}.average_order_amount < 20 THEN '4. $15 - $19.99'
WHEN ${TABLE}.average_order_amount < 25 THEN '5. $20 - $24.99'
WHEN ${TABLE}.average_order_amount < 30 THEN '6. $25 - $29.99'
ELSE '7. Over $30' END;;
}
#### Measures #################
dimension: lifetime_revenue {
type: number
sql: ${TABLE}.lifetime_revenue ;;
value_format_name: usd
}
measure: lifetime_order_count {
type: sum
sql: ${TABLE}.lifetime_order_count ;;
}
} |
# Code by AkinoAlice@Tyrant_Rex
# Docs (in debug mode): https://{api.url.com}/docs/
from fastapi import FastAPI, UploadFile, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pandas import read_excel, notnull
from setup import SettingSetupHandler
from shutil import copyfileobj
from inspect import stack
from authenticate import AUTHENTICATION
from handler import SQLHandler, LOGGER
from permission import PERMISSION
import datetime
import hashlib
import json
import uuid
import os
try:
assert os.path.exists("./setting.json")
except AssertionError:
SettingSetupHandler().file_setup()
with open("./setting.json", "r") as f:
json_file = json.load(f)
DEBUG = json_file["debug"]
app = FastAPI(debug=DEBUG)
# CORS config
ALLOW_ORIGINS = json_file["CORS"]["ALLOW_ORIGINS"]
ALLOW_ORIGINS_REGEX = json_file["CORS"]["ALLOW_ORIGINS_REGEX"]
print("Allowed site:", ALLOW_ORIGINS)
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOW_ORIGINS,
allow_origin_regex=ALLOW_ORIGINS_REGEX,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/", status_code=200)
async def get_test(data: str = "None"):
return {
"data": data,
}
@app.post("/", status_code=200)
async def post_test(data: str = "None"):
return {
"data": data,
}
# login api
@app.get("/login/", status_code=200)
async def login(nid: str, password: str):
"""login api
Args:
nid (str): NID
password (str): Password
Returns:
access: [bool] allow access or not
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token = access.authenticate(nid, password)
if token["authenticate"]:
return {
"access": True,
"token": token,
}
else:
return {
"access": False,
}
@app.get("/logout/", status_code=200)
async def logout(nid: str, token: str):
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
success = access.logout(nid, token)
if success:
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
# token validation
@app.get("/getPermissionLevel/", status_code=200)
async def getPermissionLevel(nid: str, token: str):
"""get user permission level
Args:
nid (str): NID
token (str): jwt token
Returns:
permission_level: [int] user permission level from 1-3
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [nid, token]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
return PERMISSION(nid).get_levels()
@app.get("/JWTValidation/", status_code=200)
async def JWTValidation(nid: str, token: str):
"""api of JWT validation
Args:
nid (str): NID
token (str): JWT
Returns:
access: [bool] the succession of jwt validation
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [nid, token]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if token_validation:
return {
"access": True,
"token": token,
}
else:
return {
"access": False,
}
@app.get("/TimeoutStatus/", status_code=200)
async def TimeoutStatus(nid: str, token: str):
"""Check if the jwt expired or not
Args:
nid (str): NID
token (str): jwt
Returns:
timeout: [bool] timed out or not
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [nid, token]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
timeout = access.verify_timeout(nid, token)
if not all([token_validation, timeout]):
return {
"status_code": 403,
"timeout": True
}
return {
"status_code": 200,
"timeout": False
}
# Administration
@app.get("/getLogs/", status_code=200)
def getLog(nid: str, token: str):
"""Log history
Args:
nid (str): NID
token (str): jwt
Returns:
record: [
tuple[time[str], event[str],args[tuple]]
] a tuple of log
e.g. 2023-11-25 11:57:57.653000[time] getPermission[event] ('D1234567',)[args]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [nid, token]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
return LOGGER().record()
@app.post("/forceChangePassword/", status_code=200)
def forceChangePassword(nid: str, token: str, target_nid: str, password: str):
"""Admin API to force change password
Args:
nid (str): NID
token (str): jwt
target_nid (str): the motherfucker who forget the password
password (str): the motherfucker's new password
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [target_nid, password]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
if access.forceChangePassword(target_nid, password):
return {
"status_code": 200
}
else:
return {
"status_code": 400
}
# admin
@app.post("/importUsers/", status_code=200)
def importUsers(nid: str, token: str, file_: UploadFile):
"""Admin API to add users to database
Args:
nid (str): NID
token (str): jwt
file_ (UploadFile): the xlsx file to import
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
with open("./temp/tempUser.temp", "wb+") as f:
copyfileobj(file_.file, f)
df = read_excel("./temp/tempUser.temp")
df = df.where(notnull(df), None)
user_data = df.to_dict("records")
permission_map = {
"D": 1,
"T": 2,
}
try:
for i in user_data:
record = i
record["PERMISSION"] = permission_map[record["NID"][0]]
hashed_password = hashlib.sha256(
record["PASSWORD"].encode("utf-8")).hexdigest()
salt = AUTHENTICATION().add_salt(
record["NID"], hashed_password)
record["PASSWORD"] = salt[0]
record["SALT"] = salt[1]
if not SQLHandler().importUsers(record):
return HTTPException(400, record)
except Exception as error:
return {
"status_code": 422,
"message": str(error)
}
return {
"status_code": 200,
"message": "導入成功"
}
# Subject
@app.get("/getSubject/", status_code=200)
def getSubject(nid: str, token: str):
"""Get subject items
Args:
nid (str): NID
token (str): jwt
Returns:
subject_data_list: [
dict[
"subjectUUID": [str]
"name": [str]
"year": [int]
"startDate": [datetime|str]
"endDate": [datetime|str]
"settlementStartDate": [datetime|str]
"settlementEndDate": [datetime|str]
]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
subject_data = SQLHandler().getSubjectData(nid)
data_ = []
if subject_data or subject_data == []:
for i in subject_data:
data_.append({
"subjectUUID": i[0],
"name": i[1],
"year": i[2],
"startDate": i[3],
"endDate": i[4],
"settlementStartDate": i[5],
"settlementEndDate": i[6],
})
return data_
else:
return HTTPException(status_code=500, detail="No data available")
@app.post("/createSubject/", status_code=200)
def createSubject(
nid: str,
token: str,
subjectName: str,
year: int,
startDate: str,
endDate: str,
settlementStartDate: str,
settlementEndDate: str):
"""Create a new subject
Args:
nid (str): NID
token (str): jwt
subjectName (str): name of the subject
year (int): subject year
startDate (str): subject starts date
endDate (str): subject ends date
settlementStartDate (str): subject settlement starts date
settlementEndDate (str): subject settlement ends date
Returns:
subjectUUID: the uuid of the subject
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [subjectName, year, startDate, endDate, settlementStartDate, settlementEndDate]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
subjectData = {
"subjectUUID": str(uuid.uuid4()),
"projectUUID": str(uuid.uuid4()),
"subjectName": subjectName,
"year": year,
"startDate": startDate,
"endDate": endDate,
"settlementStartDate": settlementStartDate,
"settlementEndDate": settlementEndDate,
"nid": nid
}
if SQLHandler().createSubjectData(subjectData):
return {
"status_code": 200,
"subjectUUID": subjectData["subjectUUID"]
}
else:
return {
"status_code": 500
}
@app.delete("/deleteSubject/", status_code=200)
def deleteSubject(nid: str, token: str, subjectUUID: str):
"""delete a subject
Args:
nid (str): NID
token (str): jwt
subjectUUID (str): delete target
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
if not AUTHENTICATION().SQLInjectionCheck(prompt=subjectUUID):
return {
"SQLInjectionCheck": subjectUUID,
"status_code": 400
}
success = SQLHandler().deleteSubjectData(subjectUUID)
if success:
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
# project
@app.get("/getProject/", status_code=200)
def getProject(nid: str, token: str, subjectUUID: str):
"""get project items
Args:
nid (str): NID
token (str): jwt
subjectUUID (str): target subjectUUID
Returns:
project_list: [
dict[
"name": [str]
"announcements": [str]
"student": [str]
"teacher": [str]
"group": [str]
"assignment": [str]
"projectID": [str]
]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [subjectUUID]:
if not access.SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
projectData = {
"subjectUUID": subjectUUID,
"NID": nid
}
project_data = SQLHandler().getProjectData(projectData)
if project_data or project_data == []:
data_ = []
for i in zip(
project_data["name"],
project_data["announcements"],
project_data["student"],
project_data["teacher"],
project_data["group"],
project_data["assignment"],
project_data["projectID"],
):
data_.append(
{
"name": i[0][0],
"announcements": i[1][0],
"student": i[2][0],
"teacher": i[3][0],
"group": i[4][0],
"assignment": i[5][0],
"projectID": i[6][0],
}
)
return data_
else:
return {
"status_code": 500
}
@app.post("/createProject/", status_code=200)
def createProject(nid: str, token: str, subjectUUID: str, projectName: str):
"""Create a new project from a subject
Args:
nid (str): NID
token (str): jwt token
subjectUUID (str): subjectUUID
projectName (str): name of the project
Returns:
status_code: [int] status code
projectUUID: [str] projectUUID
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [subjectUUID, projectName]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
params = {
"subjectUUID": subjectUUID,
"projectUUID": str(uuid.uuid4()),
"projectName": projectName,
"nid": nid,
}
if SQLHandler().createProjectData(params):
return {
"status_code": 200,
"projectUUID": params["projectUUID"],
}
else:
return {
"status_code": 500
}
@app.delete("/deleteProject/", status_code=200)
def deleteProject(nid: str, token: str, projectUUID: str):
"""delete target project
Args:
nid (str): NID
token (str): jwt
projectUUID (str): project uuid
Returns:
status_code: [int] status
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
success = SQLHandler().deleteProjectData(projectUUID)
if success:
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.get("/getProjectInfo/", status_code=200)
def getProjectInfo(nid: str, token: str, projectUUID: str):
"""get project info
Args:
nid (str): NID
token (str): TOKEN
projectUUID (str): projectUUId
Returns:
project_list: [
dict[
"subjectUUID": [str]
"subjectName": [str]
"year": [int]
"startDate": [datetime]
"endDate": [datetime]
"settlementStartDate": [datetime]
"settlementEndDate": [datetime]
]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
projectInfo = SQLHandler().getProjectInfo(projectUUID)
data = {
"subjectUUID": projectInfo[0],
"subjectName": projectInfo[1],
"year": projectInfo[2],
"startDate": projectInfo[3],
"endDate": projectInfo[4],
"settlementStartDate": projectInfo[5],
"settlementEndDate": projectInfo[6],
}
return data
# student
@app.get("/getStudentData/", status_code=200)
def getStudentData(nid: str, token: str, projectUUID: str):
"""get student items
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
Returns:
students_list: [
nid: [str]
name: [str]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
studentData = SQLHandler().getStudentData(projectUUID)
if studentData or studentData == []:
data = []
for i in studentData:
data.append({
"nid": i[0],
"name": i[1],
})
return data
else:
return {
"status_code": 500,
}
@app.get("/getStudentList/", status_code=200)
def getStudentList(nid: str, token: str, projectUUID: str):
"""get student list for add new student
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
Returns:
students_list: [
nid: [str]
name: [str]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
studentList = SQLHandler().getStudentList()
data = []
if studentList or studentList == []:
for i in studentList:
data.append({
"nid": i[0],
"name": i[1]
})
return data
else:
return {
"status_code": 500
}
@app.post("/newStudent/", status_code=200)
def newStudent(nid: str, token: str, projectUUID: str, studentNID: str):
"""add new student to project
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
studentNID (str): student NID
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [projectUUID, studentNID]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
params = {
"nid": studentNID,
"projectUUID": projectUUID,
}
success = SQLHandler().newStudent(params)
if success:
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.delete("/deleteStudent/", status_code=200)
def deleteStudent(nid: str, token: str, studentNID: str, projectUUID: str):
"""delete target student
Args:
nid (str): NID
token (str): jwt
studentNID (str): target student NID
projectUUID (str): projectUUID
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [studentNID, projectUUID]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
params = {
"nid": studentNID,
"projectUUID": projectUUID
}
if SQLHandler().deleteStudent(params):
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.get("/getStudentInfo/", status_code=200)
def getStudentInfo(nid: str, token: str, studentNID: str):
"""get target student information
Args:
nid (str): NID
token (str): jwt
studentNID (str): target student NID
Returns:
name: [str] name of the student
permission: [int] permission level 1-3
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=studentNID):
return {
"SQLInjectionCheck": studentNID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
studentInfo = SQLHandler().getStudentInfo(studentNID)
if studentInfo:
return {
"name": studentInfo[0],
"permission": studentInfo[1]
}
else:
return {
"status_code": 500
}
@app.post("/importStudent/", status_code=200)
def importStudent(nid: str, token: str, projectUUID: str, file_: UploadFile):
"""import student data from xlsx file
Args:
nid (str): NID
token (str): jwt
projectUUID (str): target project
file_ (UploadFile): xlsx file
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
if not AUTHENTICATION().SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
with open("./temp/tempStudent.temp", "wb+") as f:
copyfileobj(file_.file, f)
df = read_excel("./temp/tempStudent.temp")
for i in df["NID"]:
if not i.startswith("D"):
continue
params = {
"nid": i,
"projectUUID": projectUUID,
}
success = SQLHandler().newStudent(params)
if not success:
return {
"status_code": 500
}
return {
"status_code": 200
}
# teacher
@app.get("/getTeacherData/", status_code=200)
def getTeacherData(nid: str, token: str, projectUUID: str):
"""get teacher items
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
Returns:
teacher_list: [
nid: [str]
name: [str]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
teacherData = SQLHandler().getTeacherData(projectUUID)
if teacherData or teacherData == []:
data = []
for i in teacherData:
data.append({
"nid": i[0],
"name": i[1],
})
return data
else:
return {
"status_code": 500,
}
@app.get("/getTeacherList/", status_code=200)
def getTeacherList(nid: str, token: str, projectUUID):
"""get teacher list
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
Returns:
teacher_list: [
nid: [str]
name: [str]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
teacherList = SQLHandler().getTeacherList()
data = []
if teacherList or teacherList == []:
for i in teacherList:
data.append({
"nid": i[0],
"name": i[1]
})
return data
else:
return {
"status_code": 500
}
@app.post("/newTeacher/", status_code=200)
def newTeacher(nid: str, token: str, projectUUID: str, teacherNID: str):
"""add new teacher to project
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
teacherNID (str): target teacher NID
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [projectUUID, teacherNID]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
params = {
"nid": teacherNID,
"projectUUID": projectUUID,
}
success = SQLHandler().newTeacher(params)
if success:
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.delete("/deleteTeacher/", status_code=200)
def deleteTeacher(nid: str, token: str, teacherNID: str, projectUUID: str):
"""delete target teacher from project
Args:
nid (str): NID
token (str): jwt
teacherNID (str): target teacher NID
projectUUID (str): target projectUUID
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [teacherNID, projectUUID]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
params = {
"nid": teacherNID,
"projectUUID": projectUUID
}
if SQLHandler().deleteTeacher(params):
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.get("/getTeacherInfo/", status_code=200)
def getTeacherInfo(nid: str, token: str, teacherNID: str):
"""get target teacher info
Args:
nid (str): NID
token (str): jwt
teacherNID (str): target teacher NID
Returns:
name: [str] name of the teacher
permission: [int] permission level 1-3
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=teacherNID):
return {
"SQLInjectionCheck": teacherNID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
teacherInfo = SQLHandler().getTeacherInfo(teacherNID)
if teacherInfo:
return {
"name": teacherInfo[0],
"permission": teacherInfo[1]
}
else:
return {
"status_code": 500
}
@app.post("/importTeacher/", status_code=200)
def importTeacher(nid: str, token: str, projectUUID: str, file_: UploadFile):
"""import teacher from xlsx file
Args:
nid (str): NID for
token (str): jwt
projectUUID (str): target projectUUID
file_ (UploadFile): xlsx file
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
if not AUTHENTICATION().SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
with open("./temp/tempTeacher.temp", "wb+") as f:
copyfileobj(file_.file, f)
df = read_excel("./temp/tempTeacher.temp")
for i in df["NID"]:
if not i.startswith("T"):
continue
params = {
"nid": i,
"projectUUID": projectUUID,
}
success = SQLHandler().newTeacher(params)
if not success:
return {
"status_code": 500
}
return {
"status_code": 200
}
# announcement
@app.get("/getAnnouncementData/", status_code=200)
def getAnnouncementData(nid: str, token: str, projectUUID: str):
"""get announcement data
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUDi
Returns:
project_data: [
"announcementUUID": [str]
"author": [str]
"title": [str]
"date": [str]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
announcementData = SQLHandler().getAnnouncementData(projectUUID)
data = []
if announcementData or announcementData == []:
for i in announcementData:
data.append({
"announcementUUID": i[0],
"author": i[1],
"title": i[2],
"date": i[3]
})
return data
else:
return {
"status_code": 500
}
@app.post("/createAnnouncement/", status_code=200)
def createAnnouncement(nid: str, token: str, projectUUID: str, title: str, context: str):
"""create a new announcement
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
title (str): announcement title
context (str): announcement content
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [projectUUID, title, context]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400,
}
params = {
"PROJECT_ID": projectUUID,
"ANNOUNCEMENTS_ID": str(uuid.uuid4()),
"TITLE": title,
"ANNOUNCEMENTS": context,
"AUTHOR": nid,
"LAST_EDIT": datetime.date.today()
}
success = SQLHandler().createAnnouncement(params)
if success:
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.delete("/deleteAnnouncement/", status_code=200)
def deleteAnnouncement(nid: str, token: str, projectUUID: str, announcementUUID: str):
"""delete target announcement
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
announcementUUID (str): target announcementUUID
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [projectUUID, announcementUUID]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
params = {
"projectUUID": projectUUID,
"announcementUUID": announcementUUID
}
if SQLHandler().deleteAnnouncement(params):
return {
"status_code": 200
}
return {
"status_code": 500
}
@app.get("/getAnnouncementInfo/", status_code=200)
def getAnnouncementInfo(nid: str, token: str, announcementUUID: str):
"""get the announcement information
Args:
nid (str): NID
token (str): jwt
announcementUUID (str): announcementUUID
Returns:
author: [str] author of the announcement
title: [str] title of the announcement
context: [str] content
date: [datetime] announcement create time
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=announcementUUID):
return {
"SQLInjectionCheck": announcementUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
announcementInfo = SQLHandler().getAnnouncementInfo(announcementUUID)
if announcementInfo:
return {
"author": announcementInfo[0],
"title": announcementInfo[1],
"context": announcementInfo[2],
"date": announcementInfo[3]
}
else:
return {
"status_code": 500
}
# group
@app.get("/getGroupData/", status_code=200)
def getGroupData(nid: str, token: str, projectUUID: str):
"""get group data
Args:
nid (str): NID
token (str): jwt
projectUUID (str): target projectUUID
Returns:
group_id: [str] groupUUID
teacher_count: [int] number of teacher in a group
student_count: [int] number of student in a group
name: [str] group name
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
params = {
"projectUUID": projectUUID,
"nid": nid,
}
groupData = SQLHandler().getGroupData(params)
if groupData or groupData == []:
return groupData
else:
return {
"status_code": 500
}
@app.post("/newGroup/", status_code=200)
def newGroup(nid: str, token: str, projectUUID: str, member: str, group_name: str, GID: str):
"""create a new group
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
member (str): group member
group_name (str): group name
GID (str): groupUUID
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
if not AUTHENTICATION().SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
params = {
"projectUUID": projectUUID,
"name": group_name,
"nid": member,
"GID": GID
}
if SQLHandler().newGroup(params):
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.get("/getGroupToken/", status_code=200)
def getGroupToken(nid: str, token: str):
"""get group_id
Args:
nid (str): NID
token (str): jwt
Returns:
GID: [str] a uuid4 string for group id
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
if not AUTHENTICATION().SQLInjectionCheck(prompt=nid):
return {
"SQLInjectionCheck": nid,
"status_code": 400
}
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
return {
"GID": str(uuid.uuid4())
}
@app.get("/getGroupTeacherData/", status_code=200)
def getGroupTeacherData(nid: str, token: str, projectUUID: str):
"""get the teacher list in project
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
Returns:
teacher_list: [
nid: [str] NID
name: [str] name of teacher
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not AUTHENTICATION().SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
teacher_data = SQLHandler().getGroupTeacherData(projectUUID)
teacher_list = []
for i in teacher_data:
teacher_list.append({
"nid": i[0],
"name": i[1],
})
if teacher_list:
return teacher_list
else:
return []
@app.get("/getGroupStudentData/", status_code=200)
def getGroupStudentData(nid: str, token: str, projectUUID: str):
"""get the student list in project
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
Returns:
teacher_list: [
nid: [str] NID
name: [str] name of student
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=projectUUID):
return {
"SQLInjectionCheck": projectUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
student_data = SQLHandler().getGroupStudentData(projectUUID)
student_list = []
for i in student_data:
student_list.append({
"nid": i[0],
"name": i[1],
})
if student_list:
return student_list
else:
return []
@app.get("/getGroupInfo/", status_code=200)
def getGroupInfo(nid: str, token: str, groupUUID: str):
"""get group information
Args:
nid (str): NID
token (str): jwt
groupUUID (str): groupUUID | GID
Returns:
group_info: [
name: [str]
count_member: [int]
student_list: [list]
teacher_list: [list]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=groupUUID):
return {
"SQLInjectionCheck": groupUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
groupInfo = SQLHandler().getGroupInfo(groupUUID)
for i in groupInfo:
if groupInfo[i] == []:
groupInfo[i] = "None"
return groupInfo
@app.delete("/deleteGroup/", status_code=200)
def deleteGroup(nid: str, token: str, groupUUID: str, projectUUID: str):
"""delete target group
Args:
nid (str): NID
token (str): jwt
groupUUID (str): target groupUUID
projectUUID (str): projectUUID of target group
Returns:
_type_: _description_
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.SQLInjectionCheck(prompt=groupUUID):
return {
"SQLInjectionCheck": groupUUID,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
params = {
"groupUUID": groupUUID,
"projectUUID": projectUUID,
}
if SQLHandler().deleteGroup(params):
return {
"status_code": 200
}
else:
return {
"status_code": 403
}
# assignment
@app.get("/getAssignment/", status_code=200)
def getAssignment(nid: str, token: str, projectUUID: str):
"""get assignment list
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
Returns:
assignment_data: [
"assignmentUUID": [str] assignmentUUID
"group": [str] groupUUID
"title": [str] assignment title
"status": [str] assignment status e.g. submitted, not submitted
"date": [datetime] assignment submission date
"uploader": [str] assignment file uploader
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [projectUUID]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
params = {
"nid": nid,
"projectUUID": projectUUID
}
assignment_data = SQLHandler().getAssignment(params)
if assignment_data or assignment_data == []:
return assignment_data
else:
return {
"status_code": 500
}
@app.get("/downloadAssignment/", status_code=200)
def downloadAssignment(
nid: str,
token: str,
projectUUID: str,
taskUUID: str,
fileID: str):
"""download request for assignment
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
taskUUID (str): taskUUID
fileID (str): fileUUID
Returns:
file: [File object] the assignment file
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [taskUUID, fileID]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
params = {
"taskUUID": taskUUID,
"fileID": fileID
}
file_name = SQLHandler().downloadAssignment(params)
file_path = f"assignment/{projectUUID}/{params['taskUUID']}/{params['fileID']}/{file_name}"
return FileResponse(path=file_path)
@app.post("/uploadAssignment/", status_code=200)
def uploadAssignment(
nid: str,
token: str,
projectUUID: str,
taskUUID: str,
filename: str,
file_: UploadFile):
"""assignment upload api
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
taskUUID (str): taskUUID
filename (str): name of the assignment or file
file_ (UploadFile): file object
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [projectUUID, taskUUID, filename]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
file_id = str(uuid.uuid4())
file_path = f"./assignment/{projectUUID}/{taskUUID}/{file_id}/{filename}"
path = f"./assignment/{projectUUID}/{taskUUID}/{file_id}/"
os.makedirs(path)
with open(file_path, "wb+") as f:
copyfileobj(file_.file, f)
params = {
"TASK_ID": taskUUID,
"FILE_ID": file_id,
"FILE_NAME": filename,
"AUTHOR": nid,
"DATE": datetime.date.today(),
"projectUUID": projectUUID,
}
if SQLHandler().uploadAssignment(params):
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.delete("/deleteAssignment/", status_code=200)
def deleteAssignment(nid: str, token: str, assignmentUUID: str, projectUUID: str):
"""delete target assignment not the file
Args:
nid (str): NID
token (str): jwt
assignmentUUID (str): assignmentUUID
projectUUID (str): projectUUID
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [projectUUID]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
params = {
"project_id": projectUUID,
"task_id": assignmentUUID,
}
if SQLHandler().deleteAssignment(params):
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.delete("/deleteAssignmentItem/", status_code=200)
def deleteAssignmentItem(nid: str, token: str, taskUUID: str, fileUUID: str, author: str):
"""delete assignment item aka the file
Args:
nid (str): NID
token (str): jwt
taskUUID (str): taskUUID
fileUUID (str): fileUUID
author (str): the file uploader
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [taskUUID, fileUUID, author]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
params = {
"taskID": taskUUID,
"fileID": fileUUID,
"author": author
}
if SQLHandler().deleteAssignmentItem(params):
return {
"status_code": 200,
}
else:
return {
"status_code": 500
}
@app.post("/markAssignmentScore/", status_code=200)
def markAssignmentScore(nid: str, token: str, projectUUID: str, taskUUID: str, marks: int):
"""mark assignment score
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
taskUUID (str): taskUUID
marks (int): assignment scores
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [projectUUID, taskUUID, marks]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
params = {
"projectUUID": projectUUID,
"taskUUID": taskUUID,
"marks": marks
}
if SQLHandler().markAssignmentScore(params):
return {
"status_code": 200
}
else:
return {
"status_code": 500
}
@app.post("/newAssignment/", status_code=200)
def newAssignment(
nid: str,
token: str,
projectUUID: str,
gid: str,
name: str,
weight: int,
date: str,
allowedFileTypes: str):
"""create a new assignment
Args:
nid (str): NID
token (str): jwt
projectUUID (str): projectUUID
gid (str): groupUUID
name (str): name of the assignment
weight (int): the percentage of the assignment
date (str): the deadline of the assignment
allowedFileTypes (str): allowed file's types
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [projectUUID, gid, name, weight, date]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
params = {
"task_id": str(uuid.uuid4()),
"projectUUID": projectUUID,
"name": name,
"status": "未完成",
"submission_date": date,
"gid": gid,
"uploader": nid,
"weight": weight,
"mark": 0,
"allowedFileTypes": allowedFileTypes
}
if SQLHandler().newAssignment(params):
return {
"status_code": 200,
}
else:
return {
"status_code": 503
}
@app.get("/getAssignmentInfo/", status_code=200)
def getAssignmentInfo(nid: str, token: str, assignmentUUID: str, projectUUID: str):
"""get assignment information
Args:
nid (str): NID
token (str): jwt
assignmentUUID (str): assignmentUUID
projectUUID (str): projectUUID
Returns:
assignment_info: [
"assignment_name": [str] name of the assignment
"group_name": [str] name of the group
"mark": [int] assignment score
"weight": [int] percentage score of assignment
"date": [datetime] deadline
"assignment_file": [
"taskID": [str] taskUUID
"fileID": [str] fileUUID
"filename": [str] name of the assignment file
"author": [str] assignment author
"date": [datetime] date of submission
"allowedFileTypes": [str] allowed file's types
"status": [str] "已繳交" | "未完成" | "已評分"
]
]
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
for i in [projectUUID, assignmentUUID]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
params = {
"task_id": assignmentUUID,
"project_id": projectUUID,
}
info = SQLHandler().getAssignmentInfo(params)
if info and info != ():
return info
else:
return {
"status_code": 500
}
# profile
@app.post("/changeEmail/", status_code=200)
async def changeEmail(nid: str, token: str, newEmail: str):
"""api of for user to change email
Args:
nid (str): NID
token (str): jwt
newEmail (str): user's new email
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
if not AUTHENTICATION().SQLInjectionCheck(prompt=newEmail):
return {
"SQLInjectionCheck": newEmail,
"status_code": 400
}
params = {
"nid": nid,
"new_email": newEmail
}
if SQLHandler().changeEmail(params):
return {
"status_code": 200
}
else:
return {
"status_code": 400
}
@app.post("/changePassword/", status_code=200)
async def changePassword(nid: str, token: str, oldPassword: str, newPassword: str):
"""api of for user to change password
Args:
nid (str): NID
token (str): jwt
oldPassword (str): the old password
newPassword (str): the new password
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
for i in [oldPassword, newPassword]:
if not AUTHENTICATION().SQLInjectionCheck(prompt=i):
return {
"SQLInjectionCheck": i,
"status_code": 400
}
if access.change_password(nid, oldPassword, newPassword):
return {
"status_code": 200
}
else:
return {
"status_code": 400
}
@app.get("/getIconImages/{nid}/", status_code=200)
async def getIconImages(nid: str) -> FileResponse:
"""api of the icon image
Args:
nid (str): NID
Returns:
icon_file: [File Object] the icon file
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if nid == "undefined" or nid == "null":
return FileResponse(f"./icon/default.png")
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
icon_file_name = SQLHandler().getIconImage(nid)
return FileResponse(f"./icon/{icon_file_name}")
@app.post("/changeIcon/", status_code=200)
async def changeIcon(nid: str, token: str, file_: UploadFile, filename: str):
"""api of changing the icon image for user
Args:
nid (str): NID
token (str): jwt
file_ (UploadFile): icon file
filename (str): file name for file type checking
Returns:
status_code: [int] status code
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
if not AUTHENTICATION().SQLInjectionCheck(prompt=filename):
return {
"SQLInjectionCheck": filename,
"status_code": 400
}
file_extension = filename.split(".")[-1]
file_name = str(uuid.uuid4())
path = f"./icon/{nid}/"
file_path = f"./icon/{nid}/{file_name}.{file_extension}"
params = {
"filename": f"{file_name}.{file_extension}",
"nid": nid,
}
if not os.path.exists(path):
os.makedirs(path)
with open(file_path, "wb+") as f:
copyfileobj(file_.file, f)
if SQLHandler().changeIcon(params):
return {
"status_code": 200,
}
else:
return {
"status_code": 500
}
# dashboard
@app.get("/getDeadlineProject/", status_code=200)
def getDeadlineProject(nid: str, token: str):
"""get the deadline project (shown in dashboard page)
Args:
nid (str): NID
token (str): jwt
Returns:
status_code: [int] status code
assignment_data: [
"TASK_ID": [str] taskUUID
"PROJECT_ID": [str] projectUUID
"NAME": [str] name of the project
"SUBMISSION_DATE": [str] deadline
]
assignment_data: None if no deadline assignment
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not AUTHENTICATION().SQLInjectionCheck(prompt=nid):
return {
"SQLInjectionCheck": nid,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
data = SQLHandler().getDeadlineProject(nid)
if data:
return {
"status_code": 200,
"data": data
}
else:
return {
"status_code": 200,
"data": None
}
# about page
@app.get("/getAboutPage/", status_code=200)
def getAboutPage(nid: str, token: str, targetNID: str):
"""the information about the about page
Args:
nid (str): NID
token (str): jwt
targetNID (str): target NID
Returns:
user_info: {
NID: [int] NID,
name: [str] username,
last_login: [datetime] last login,
email: [str] email
}
"""
access = AUTHENTICATION()
func_name = stack()[0][3]
if not AUTHENTICATION().SQLInjectionCheck(prompt=nid):
return {
"SQLInjectionCheck": nid,
"status_code": 400
}
if not access.permission_check(nid, func_name):
return HTTPException(403, "Access denied")
token_validation = access.verify_jwt_token(nid, token)
if not token_validation:
return HTTPException(status_code=403, detail="Token invalid")
user_info = SQLHandler().getAboutPage(targetNID)
return user_info
if __name__ == "__main__":
# development only
# uvicorn main:app --reload --host 0.0.0.0
app.run(debug=DEBUG) |
<div class="navbar m-1 bg-white justify-content-center align-items-center container-fluid border h-100">
<table class="table bg-white table-hover">
<thead class="table-info">
<tr>
<th scope="col">#</th>
<th scope="col" style="width: 15em;">User</th>
<th scope="col" style="width: 10em;">Amount</th>
<th scope="col" style="width: 30em;">Order Date</th>
<th scope="col" style="width: 12em;">Status</th>
<th scope="col" style="width: 15em;">Billing Address</th>
<th scope="col" style="width: 15em;">Shipping Address</th>
<th scope="col" style="width: 5em;">Products</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let order of orders; let i = index" style="font-weight: bold;">
<th scope="row">{{ i+1 }}</th>
<td>{{ order.user.userName }}</td>
<td>${{ order.amount }}</td>
<td>{{ order.orderDate }}</td>
<td (dblclick)="onEdit(order, 'status')" (keypress)="close(order)">
<div class="row" *ngIf="order.editFieldName == 'status'">
<div class="col-9">
<select style="width: 10em; position: absolute;" [(ngModel)]="order.status" class="form-control"
[ngStyle]="{'color': order.status == true ? 'green' : 'red'}">
<option [ngStyle]="{'color': status == true ? 'green' : 'red'}" *ngFor="let status of statuses"
[ngValue]="status">{{ status ? "Shipped" : "In Transit" }}</option>
</select>
</div>
</div>
<div *ngIf="order.editFieldName !== 'status'" [ngStyle]="{'color': order.status ? 'green' : 'red' }">
{{ order.status ? "Shipped" : "In Transit" }}
</div>
</td>
<td (dblclick)="onEdit(order, 'billingAddress')" (keyup.enter)="close(order)">
<div class="row" *ngIf="order.editFieldName == 'billingAddress'">
<div class="col-9">
<input style="width: 10em; position: absolute;" type="text" [(ngModel)]="order.billingAddress" class="form-control" />
</div>
</div>
<div *ngIf="order.editFieldName !== 'billingAddress'">
{{ order.billingAddress }}
</div>
</td>
<td (dblclick)="onEdit(order, 'shippingAddress')" (keyup.enter)="close(order)">
<div class="row" *ngIf="order.editFieldName == 'shippingAddress'">
<div class="col-9">
<input style="width: 10em; position: absolute;" type="text" [(ngModel)]="order.shippingAddress" class="form-control" />
</div>
</div>
<div *ngIf="order.editFieldName !== 'shippingAddress'">
{{ order.shippingAddress }}
</div>
</td>
<td class="">
<div class="d-flex">
<button class="btn bg-light" type="button" (click)="viewOrderItems(items)">Products ({{ orders[i].products.length }})</button>
<button class="btn btn-danger btn-rounded" (click)="verifyDeleteOrder(verifyDelete)"
style="margin-left: 5em;">
<i class="fa-solid fa-trash-can fa-md"></i>
</button>
<!-- Delete Order Modal -->
<ng-template #verifyDelete let-modal>
<div class="modal-body">
<p>Are you sure you want to delete this order?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" (click)="deleteOrder(order)"
(click)="modal.close('Close click')">Delete</button>
<button type="button" class="btn btn-info" (click)="modal.close('Close click')">Cancel</button>
</div>
</ng-template>
<!-- View Order Items Modal -->
<ng-template #items let-modal>
<div class="modal-header">
<h4 class="modal-title">Purchases</h4>
<button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
</div>
<div class="modal-body justify-content-center d-flex">
<div class="card m-2" style="width: 18em;" *ngFor="let product of orderItems(order)">
<img class="card-img-top h-50" style="border-radius: 15px; width: auto; height: auto;"
[src]="product.image" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<h5 class="card-subtitle">${{ product.price }}</h5><br>
<p class="card-text" style="text-overflow: ellipses;">{{ product.description }}</p>
</div>
<div class="d-flex flex-column justify-content-center align-items-center"
style="margin-bottom: 5em; margin-top: 0; padding-top: 0;">
<!-- Able to delete item from order? (click)="updateOrderItems(order, product)" -->
<!-- <button class="btn btn-danger">Delete Item</button> -->
</div>
</div>
</div>
</ng-template>
</div>
</td>
</tr>
</tbody>
</table>
</div> |
# C function and Assmebly:
# Preparing for using C functions in assembly program:
------------------------------------------------------
- Each C function starts with pushing RBX, RSP, RBP, RSI, RDI to stack. Due to their spedial importance these five registers are sometimes
half jokingly called the "Sacred registers" of C.
- C functions return value in RAX register. If the return value is more than 64 bits, its returned in RDX:RAX format. Floating point return
values are returned in floating point stack. Other data structure such as array, structure, object etc are returned as pointer to these data
structures, so they are just 64-bit value.
- Function parameters are pushed to stack in reversed order. So to call a function MyFunc(foo, bar, bas), stack have to be prepared like this:
push bas
push bar
push foo
call MyFunc
- A function doesn't pop the parameters from the stack. So calling procedure must remove them after calling the function. This can be done by
popping or modifying the RSP with appropriate offset.
# glibc stack frame: |_______________________________|
-------------------- | NULL = End of Argument list |
---------------------------------
The stack | - - - |
| _ _ _ | ---------------------------------
| _ _ _ | +24 | Arg 3 |
----------------------------------- ---------------------------------
| RBP+40: | - - - | +16 | Arg 2 |
----------------------------------- ---------------------------------
| RBP+32: |Ptr. to Env. var. tbl. | +8 | Arg 1 |
----------------------------------- ---------------------------------
| RBP+24: | Ptr. to Arg. tbl. | -------------------------> | Arg(0): Invocation text |
----------------------------------- ---------------------------------
| RBP+16: | Argument count |
-----------------------------------
| RBP+08: | Return Address |
-----------------------------------
| RBP+00: | RBP |
-----------------------------------
| RBP-08: | RBX |
-----------------------------------
| RBP-16: | RSI |
-----------------------------------
| RBP-24: | RDI |
-----------------------------------
| RBP-32: | - - - |
-----------------------------------
Thus from a C program, or a assembly program using C functions, command line arguments can be accessed by referencing RBP+24 twice. |
<template>
<div class="main">
<button @click="showDialog">Добавить</button>
<add-user-dialog
v-if="shownDialog"
:inputData="headers"
:users="users"
@createUser="createUser"
@close="closeDialog"
/>
<users-table
:users="groupedUsersToView"
:headers="headers"
:sortAscending = selectedSort.ascending
@sort="sortUsers"
/>
<div v-show="shownSavedUser" class="savedUser">Пользователь успешно создан</div>
</div>
</template>
<script>
import UsersTable from '../components/UsersTable/App.vue'
import AddUserDialog from '../components/AddUserDialog.vue'
export default {
name: 'base-layout',
components: {
UsersTable,
AddUserDialog
},
data () {
return {
users: [],
headers: [{ name: 'name', title: 'Имя' }, { name: 'phone', title: 'Телефон' }],
shownDialog: false,
shownSavedUser: false,
selectedSort: { field: null, ascending: 0 }
}
},
methods: {
createUser (newUser) {
this.users.push(newUser)
localStorage.setItem('users', JSON.stringify(this.users))
this.closeDialog()
this.shownSavedUser = true
setTimeout(() => {
this.shownSavedUser = false
}, 2000)
},
sortUsers (selectedSort) {
if (this.selectedSort.field === selectedSort) {
this.selectedSort.ascending = (this.selectedSort.ascending === -1) ? 1 : -1
} else {
this.selectedSort.ascending = 1
this.selectedSort.field = selectedSort
}
},
showDialog () {
this.shownDialog = true
},
closeDialog () {
this.shownDialog = false
}
},
computed: {
sortUsersByProp () {
return [...this.users].sort((user1, user2) => {
if (user1[this.selectedSort.field] > user2[this.selectedSort.field]) {
return this.selectedSort.ascending
}
if (user1[this.selectedSort] < user2[this.selectedSort]) {
return -this.selectedSort.ascending
}
return 0
})
},
groupedUsersToView () {
let groupedUsers = []
this.sortUsersByProp.forEach((userMaped) => {
userMaped.subordinates = this.sortUsersByProp.filter((userFiltered) => userMaped.id === userFiltered.chiefId) || []
if (userMaped.chiefId == null) {
groupedUsers.push(userMaped)
}
})
return groupedUsers
}
},
mounted () {
this.users = JSON.parse(localStorage.getItem('users')) || []
}
}
</script>
<style scoped>
.main {
display: flex;
flex-direction: column;
width: 500px;
align-items: flex-end;
}
button {
background-color: lightgray;
border: 1px solid black;
border-radius: 13px;
margin: 20px 0;
width: auto;
padding: 5px 20px;
}
.savedUser {
background-color: lightgreen;
border: 1px solid black;
border-radius: 13px;
padding: 20px 20px;
position: absolute;
top: 10px;
right: 10px;
}
</style> |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.0;
contract OperationalOwnable {
// Blocks all state changes throughout the contract if false
bool private operational = true;
// Account used to deploy contract
address payable private contractOwner;
// Define an Event
event UpdateOperationalStatus(bool mode);
// Define an Event
event TransferOwnership(address indexed oldOwner, address indexed newOwner);
// Assign the contract to an owner
constructor() {
contractOwner = payable(msg.sender);
emit TransferOwnership(address(0), contractOwner);
}
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier onlyOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns (bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperationalStatus(bool mode) external onlyOwner {
emit UpdateOperationalStatus(mode);
operational = mode;
}
// Define a function 'kill' if required
function kill() public {
if (msg.sender == contractOwner) {
selfdestruct(contractOwner);
}
}
// Look up the address of the owner
function owner() public view returns (address) {
return contractOwner;
}
// Define a function modifier 'onlyOwner'
modifier onlyOwner() {
require(isOwner(), "Only the owner can perform this operation");
_;
}
// Check if the calling address is the owner of the contract
function isOwner() public view returns (bool) {
return msg.sender == contractOwner;
}
// Check if the passed address is the owner of the contract
function isOwner(address addressToValidate) public view returns (bool) {
return addressToValidate == contractOwner;
}
// Define a function to renounce ownerhip
function renounceOwnership() public onlyOwner {
emit TransferOwnership(contractOwner, address(0));
contractOwner = payable(address(0));
}
// Define a public function to transfer ownership
function transferOwnership(address payable newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
// Define an internal function to transfer ownership
function _transferOwnership(address payable newOwner) internal {
require(newOwner != address(0), "The new Owner cannot be address 0");
contractOwner = newOwner;
emit TransferOwnership(contractOwner, newOwner);
}
} |
module.exports = function(app, passport) {
app.get('/',ifLoggedGotoProfile,function(req, res) {
res.render('index.ejs'); // load the index.ejs file
});
app.get('/login',function(req, res) {
// render the page and pass in any flash data if it exists
res.render('login.ejs', { message: req.flash('loginMessage') });
});
app.get('/signup', function(req, res) {
// render the page and pass in any flash data if it exists
res.render('signup.ejs', { message: req.flash('signupMessage') });
});
/*app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user : req.user
});
});*/
app.get('/dashboard', isLoggedIn, function(req, res) {
res.render('dashboard.ejs', {
user : req.user
});
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/dashboard', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/dashboard', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
};
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
function ifLoggedGotoProfile(req, res, next) {
if (req.user) {
res.redirect('/profile');
}
else next();
} |
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TeamStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'sometimes|string|min:2',
'purpose' => 'sometimes|string|min:2',
'description' => 'string|nullable',
'members' => 'sometimes|array',
'members.*' => 'integer|exists:employees,id',
'roles' => 'sometimes|array',
'roles.*' => 'string|min:2'
];
}
} |
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>STA 235H - Multiple Regression: Interactions & Nonlinearity</title>
<meta charset="utf-8" />
<meta name="author" content="McCombs School of Business, UT Austin" />
<script src="libs/header-attrs/header-attrs.js"></script>
<script src="libs/fabric/fabric.min.js"></script>
<link href="libs/xaringanExtra-scribble/scribble.css" rel="stylesheet" />
<script src="libs/xaringanExtra-scribble/scribble.js"></script>
<script>document.addEventListener('DOMContentLoaded', function() { window.xeScribble = new Scribble({"pen_color":["#FF0000"],"pen_size":3,"eraser_size":30,"palette":[]}) })</script>
<script src="libs/clipboard/clipboard.min.js"></script>
<link href="libs/xaringanExtra-clipboard/xaringanExtra-clipboard.css" rel="stylesheet" />
<script src="libs/xaringanExtra-clipboard/xaringanExtra-clipboard.js"></script>
<script>window.xaringanExtraClipboard(null, {"button":"<i class=\"fa fa-clipboard\"><\/i>","success":"<i class=\"fa fa-check\" style=\"color: #90BE6D\"><\/i>","error":"<i class=\"fa fa-times-circle\" style=\"color: #F94144\"><\/i>"})</script>
<link href="libs/font-awesome/css/all.css" rel="stylesheet" />
<link href="libs/font-awesome/css/v4-shims.css" rel="stylesheet" />
<script src="https://use.fontawesome.com/5235085b15.js"></script>
<link rel="stylesheet" href="xaringan-themer.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
.title[
# STA 235H - Multiple Regression: Interactions & Nonlinearity
]
.subtitle[
## Fall 2023
]
.author[
### McCombs School of Business, UT Austin
]
---
<!-- <script type="text/javascript"> -->
<!-- MathJax.Hub.Config({ -->
<!-- "HTML-CSS": { -->
<!-- preferredFont: null, -->
<!-- webFont: "Neo-Euler" -->
<!-- } -->
<!-- }); -->
<!-- </script> -->
<style type="text/css">
.small .remark-code { /*Change made here*/
font-size: 80% !important;
}
.tiny .remark-code { /*Change made here*/
font-size: 90% !important;
}
</style>
# Before we start...
- Use the **.darkorange[knowledge check]** portion of the JITT to assess your own understanding:
- Be sure to answer the question correctly (look at the feedback provided)
- Feedback are **.darkorange[guidelines]**; Try to use your *own words*.
--
- If you are struggling with material covered in STA 301H: **.darkorange[Check the course website for resources and come to Office Hours]**.
--
- **.darkorange[Office Hours Prof. Bennett]**: Wed 10.30-11.30am and Thu 4.00-5.30pm
--
.box-4trans[No in-person class next week -- Recorded class]
---
# Today
.pull-left[
- Quick **.darkorange[multiple regression]** review:
- Interpreting coefficients
- Interaction models
- **.darkorange[Looking at your data:]**
- Distributions
- **.darkorange[Nonlinear models:]**
- Logarithmic outcomes
- Polynomial terms
]
.pull-right[
.center[
]
]
---
# Remember last week's example? The Bechdel Test
.pull-left[
- **.darkorange[Three criteria:]**
1. At least two named women
2. Who talk to each other
3. About something besides a man
]
.pull-right[
.center[
]
]
---
# Is it convenient for my movie to pass the Bechdel test?
```r
lm(Adj_Revenue ~ bechdel_test + Adj_Budget + Metascore + imdbRating, data=bechdel)
```
```
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -127.0710 17.0563 -7.4501 0.0000
## bechdel_test 11.0009 4.3786 2.5124 0.0121
## Adj_Budget 1.1192 0.0367 30.4866 0.0000
## Metascore 7.0254 1.9058 3.6864 0.0002
## imdbRating 15.4631 3.3914 4.5595 0.0000
```
.box-7trans[What does each column represent?]
---
# Is it convenient for my movie to pass the Bechdel test?
```r
lm(Adj_Revenue ~ bechdel_test + Adj_Budget + Metascore + imdbRating, data=bechdel)
```
```
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -127.0710 17.0563 -7.4501 0.0000
## bechdel_test 11.0009 4.3786 2.5124 0.0121
## Adj_Budget 1.1192 0.0367 30.4866 0.0000
## Metascore 7.0254 1.9058 3.6864 0.0002
## imdbRating 15.4631 3.3914 4.5595 0.0000
```
- **.darkorange["Estimate"]**: Point estimates of our paramters `\(\beta\)`. We call them `\(\hat{\beta}\)`.
--
- **.darkorange["Standard Error"]** (SE): You can think about it as the variability of `\(\hat{\beta}\)`. The smaller, the more precise `\(\hat{\beta}\)` is!
--
- **.darkorange["t-value"]**: A value of the Student distribution that measures how many SE away `\(\hat{\beta}\)` is from 0. You can calculate it as `\(tval = \frac{\hat{\beta}}{SE}\)`. It relates to our null-hypothesis `\(H_0: \beta=0\)`.
--
- **.darkorange["p-value"]**: Probability of rejecting the null hypothesis and being *wrong* (Type I error). You want this to be a small as possible (statistically significant).
---
# Reminder: Null-Hypothesis
We are testing `\(H_0: \beta = 0\)` vs `\(H_1: \beta \neq 0\)`
.pull-left[
- "Reject the null hypothesis"
.center[
]
]
.pull-right[
- "Not reject the null hypothesis"
.center[

]
]
.source[Note: Figures adapted from @AllisonHorst's art]
---
# Reminder: Null-Hypothesis
Reject the null if the t-value falls **outside** the dashed lines.
.center[

]
.source[Note: Figures adapted from @AllisonHorst's art]
---
# One extra dollar in our budget
- Imagine now that you have an hypothesis that Bechdel movies also get more bang for their buck, e.g. they get more revenue for an additional dollar in their budget.
.box-7Trans[How would you test that in an equation?]
--
.box-4[Interactions!]
---
#One extra dollar in our budget
Interaction model:
`$$Revenue = \beta_0 + \beta_1 Bechdel + \beta_3Budget + \color{#db5f12}{\beta_6(Budget \times Bechdel)} + \beta_4IMDB + \beta_5 MetaScore + \varepsilon$$`
--
How should we think about this?
- Write the equation for a movie that **.darkorange[does not pass the Bechdel test]**. How does it look like?
--
`$$Revenue = \beta_0 + \beta_3Budget + \beta_4IMDB + \beta_5 MetaScore + \varepsilon$$`
--
- Now do the same for a movie that **.darkorange[passes the Bechdel test]**. How does it look like?
`$$Revenue = (\beta_0 + \beta_1) + (\beta_3 + \beta_6)Budget + \beta_4IMDB + \beta_5 MetaScore + \varepsilon$$`
---
# One extra dollar in our budget
Now, let's interpret some coefficients:
- If `\(Bechdel = 0\)`, then:
`$$Revenue = \beta_0 + \beta_3Budget + \beta_4IMDB + \beta_5 MetaScore + \varepsilon$$`
--
- If `\(Bechdel = 1\)`, then:
`$$Revenue = (\beta_0 + \beta_1) + (\beta_3 + \beta_6)Budget + \beta_4IMDB + \beta_5 MetaScore + \varepsilon$$`
--
- What is the **.darkorange[difference]** in the association between budget and revenue for movies that pass the Bechdel test vs. those that don't?
---
# Let's put some data into it
```r
lm(Adj_Revenue ~ bechdel_test*Adj_Budget + Metascore + imdbRating, data=bechdel)
```
```
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -124.1997 17.4932 -7.0999 0.0000
## bechdel_test 7.5138 6.4257 1.1693 0.2425
## Adj_Budget 1.0926 0.0513 21.2865 0.0000
## Metascore 7.1424 1.9126 3.7344 0.0002
## imdbRating 15.2268 3.4069 4.4694 0.0000
## bechdel_test:Adj_Budget 0.0546 0.0737 0.7416 0.4585
```
--
- What is the association between budget and revenue for movies that **.darkorange[pass the Bechdel test]**?
- What is the difference in the association between budget and revenue for **.darkorange[movies that pass vs movies that don't pass the Bechdel test]**?
--
- Is that difference **.darkorange[statistically significant]** (at conventional levels)?
---
background-position: 50% 50%
class: center, middle
.box-5Trans[Let's look at another example]
---
# Cars, cars, cars
- Used cars in South California (from this week's JITT)
.small[
```r
cars <- read.csv("https://raw.githubusercontent.com/maibennett/sta235/main/exampleSite/content/Classes/Week2/1_OLS/data/SoCalCars.csv", stringsAsFactors = FALSE)
names(cars)
```
```
## [1] "type" "certified" "body" "make" "model" "trim"
## [7] "mileage" "price" "year" "dealer" "city" "rating"
## [13] "reviews" "badge"
```
]
.source[Data source: "Modern Business Analytics" (Taddy, Hendrix, & Harding, 2018)]
---
# Luxury vs. non-luxury cars?
<br>
<br>
<br>
.box-7trans[Do you think there's a difference between how price changes over time for luxury vs non-luxury cars?]
--
.box-4trans[How would you test this?]
---
background-position: 50% 50%
class: center, middle
.big[
.box-5LA[Let's go to R]
]
---
# Models with interactions
- You include the interaction between two (or more) covariates:
`$$\widehat{Price} = \beta_0 + \hat{\beta}_1 Rating + \hat{\beta}_2 Miles + \hat{\beta}_3 Luxury + \hat{\beta}_4 Year + \hat{\beta}_5 Luxury \times Year$$`
--
- `\(\hat{\beta}_3\)` and `\(\hat{\beta}_4\)` are considered the **.darkorange[main effects]** (no interaction)
--
- The coefficient you are interested in is `\(\hat{\beta}_5\)`:
- Difference in the **.darkorange[price change]** for one additional year between **.darkorange[luxury vs non-luxury cars]**, holding other variables constant.
---
# Now it's your turn
- Looking at this equation:
`$$\widehat{Price} = \beta_0 + \hat{\beta}_1 Rating + \hat{\beta}_2 Miles + \hat{\beta}_3 Luxury + \hat{\beta}_4 Year + \hat{\beta}_5 Luxury \times Year$$`
1) What is the association between price and year for non-luxury cars?
--
2) What is the association between price and year for luxury cars?
---
# Looking at our data
- We have dived into running models head on. **.darkorange[Is that a good idea?]**
--
.center[
]
---
class: center, middle
.box-5Trans[What should we do before we ran any model?]
---
class: center, middle
.box-3Trans[Inspect your data!]
---
# Some ideas:
- Use `vtable`:
```r
library(vtable)
vtable(cars)
```
--
- Use `summary` to see the min, max, mean, and quartile:
```r
cars %>% select(price, mileage, year) %>% summary(.)
```
.small[
```
## price mileage year
## Min. : 1790 Min. : 0 Min. :1966
## 1st Qu.: 16234 1st Qu.: 5 1st Qu.:2017
## Median : 23981 Median : 56 Median :2019
## Mean : 32959 Mean : 21873 Mean :2018
## 3rd Qu.: 36745 3rd Qu.: 36445 3rd Qu.:2020
## Max. :1499000 Max. :292952 Max. :2021
```
]
--
- Plot your data!
---
# Look at the data
<br>
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/cars_inspect-1.svg" style="display: block; margin: auto;" />
---
# Look at the data
What can you say about this variable?
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/cars_inspect2-1.svg" style="display: block; margin: auto;" />
---
# Logarithms to the rescue?
<br>
--
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/cars_inspect_log-1.svg" style="display: block; margin: auto;" />
---
# How would we interpret coefficients now?
- Let's interpret the coefficient for `\(Miles\)` in the following equation:
`$$\log(Price) = \beta_0 + \beta_1 Rating + \beta_2 Miles + \beta_3 Luxury + \beta_4 Year + \varepsilon$$`
--
- Remember: `\(\beta_2\)` represents the average change in the outcome variable, `\(\log(Price)\)`, for a one-unit increase in the independent variable `\(Miles\)`.
- *Think about the units of the dependent and independent variables!*
---
# A side note on log-transformed variables...
.medium30[$$\log(Y) = \hat{\beta}_0 + \hat{\beta}_1 X$$]
We want to compare the outcome for a regression with `\(X = x\)` and `\(X = x+1\)`
--
.medium30[$$\log(y_0) = \hat{\beta}_0 + \hat{\beta}_1 x \ \ \ \ \ \ (1)$$]
and
.medium30[$$\log(y_1) = \hat{\beta}_0 + \hat{\beta}_1 (x+1) \ \ \ \ \ \ (2)$$]
--
- Let's subtract (2) - (1)!
---
# A side note on log-transformed variables...
.medium30[$$\log(y_{1}) - \log(y_0) = \hat{\beta}_0 + \hat{\beta}_1(x+1) - (\hat{\beta}_0 + \hat{\beta}_1 x)$$]
--
.medium30[$$\log(\frac{y_{1}}{y_0}) = \hat{\beta}_1$$]
--
.medium30[$$\log(1+\frac{y_1-y_0}{y_0}) = \hat{\beta}_1$$]
---
# A side note on log-transformed variables...
.medium30[$$\log(y_{1}) - \log(y_0) = \hat{\beta}_0 + \hat{\beta}_1(x+1) - (\hat{\beta}_0 + \hat{\beta}_1 x)$$]
.medium30[$$\log(\frac{y_{1}}{y_0}) = \hat{\beta}_1$$]
.medium30[$$\log(1+\frac{y_1-y_0}{y_0}) = \hat{\beta}_1$$]
.box-7Trans.medium30[$$\rightarrow \frac{\Delta y}{y} = \exp(\hat{\beta}_1)-1$$]
---
# An important approximation
.medium30[$$\log(y_{1}) - \log(y_0) = \hat{\beta}_0 + \hat{\beta}_1(x+1) - (\hat{\beta}_0 + \hat{\beta}_1 x)$$]
.medium30[$$\log(\frac{y_{1}}{y_0}) = \hat{\beta}_1$$]
.medium30[$$\log(1+\frac{y_1-y_0}{y_0}) = \hat{\beta}_1$$]
--
.medium30[$$\approx \frac{y_1-y_0}{y_0} = \hat{\beta}_1$$]
--
.box-4Trans.medium30[$$\rightarrow \% \Delta y = 100\times\hat{\beta}_1$$]
---
# How would we interpret coefficients now?
- Let's interpret the coefficient for `\(Miles\)` in the following equation:
`$$\log(Price) = \beta_0 + \beta_1 Rating + \beta_2 Miles + \beta_3 Luxury + \beta_4 Year + \varepsilon$$`
--
- For an additional 1,000 miles (*Note: Remember Miles is measured in thousands of miles*), the logarithm of the price increases/decreases, on average, by `\(\hat{\beta}_2\)`, holding other variables constant.
--
- For an additional 1,000 miles, the price increases/decreases, on average, by `\(100\times\hat{\beta}_2\)`%, holding other variables constant.
---
# How would we interpret coefficients now?
.small[
```r
summary(lm(log(price) ~ rating + mileage + luxury + year, data = cars))
```
```
##
## Call:
## lm(formula = log(price) ~ rating + mileage + luxury + year, data = cars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.14363 -0.29112 -0.02593 0.26412 2.28855
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.5105164 0.1518312 16.535 < 2e-16 ***
## rating 0.0305782 0.0057680 5.301 1.27e-07 ***
## mileage -0.0098628 0.0004327 -22.792 < 2e-16 ***
## luxury 0.5517712 0.0228132 24.186 < 2e-16 ***
## year 0.0118783 0.0030075 3.950 8.09e-05 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.436 on 2083 degrees of freedom
## Multiple R-squared: 0.4699, Adjusted R-squared: 0.4689
## F-statistic: 461.6 on 4 and 2083 DF, p-value: < 2.2e-16
```
]
---
# Adding polynomial terms
- Another way to capture **.darkorange[nonlinear associations]** between the outcome (Y) and covariates (X) is to include **.darkorange[polynomial terms]**:
- e.g. `\(Y = \beta_0 + \beta_1X + \beta_2X^2 + \varepsilon\)`
--
- Let's look at an example!
---
# Determinants of wages: CPS 1985
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/wages_inspect-1.svg" style="display: block; margin: auto;" />
---
# Determinants of wages: CPS 1985
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/wages_inspect2-1.svg" style="display: block; margin: auto;" />
---
# Experience vs wages: CPS 1985
<br>
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/exp_wages-1.svg" style="display: block; margin: auto;" />
---
# Experience vs wages: CPS 1985
`$$\log(Wage) = \beta_0 + \beta_1 Educ + \beta_2Exp + \varepsilon$$`
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/exp_wages2-1.svg" style="display: block; margin: auto;" />
---
# Experience vs wages: CPS 1985
`$$\log(Wage) = \beta_0 + \beta_1 Educ + \beta_2 Exp + \beta_3 Exp^2 + \varepsilon$$`
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/exp_wages3-1.svg" style="display: block; margin: auto;" />
---
# Mincer equation
`$$\log(Wage) = \beta_0 + \beta_1 Educ + \beta_2 Exp + \beta_3 Exp^2 + \varepsilon$$`
- Interpret the coefficient for **.darkorange[education]**
--
.center[
*One additional year of education is associated, on average, to `\(\hat{\beta}_1\times100\)`% increase in hourly wages, holding experience constant*]
--
- What is the association between experience and wages?
---
# Interpreting coefficients in quadratic equation
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/exp_wages4-1.svg" style="display: block; margin: auto;" />
---
# Interpreting coefficients in quadratic equation
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/exp_wages5-1.svg" style="display: block; margin: auto;" />
---
# Interpreting coefficients in quadratic equation
<img src="f2023_sta235h_3_reg_annotate_files/figure-html/exp_wages6-1.svg" style="display: block; margin: auto;" />
---
# Interpreting coefficients in quadratic equation
`$$\log(Wage) = \beta_0 + \beta_1 Educ + \beta_2 Exp + \beta_3 Exp^2 + \varepsilon$$`
What is the association between experience and wages?
--
- Pick a value for `\(Exp_0\)` (e.g. mean, median, one value of interest)
--
.center[
*Increasing work experience from `\(Exp_0\)` to `\(Exp_0 + 1\)` years is associated, on average, to a `\((\hat{\beta}_2 + 2\hat{\beta}_3\times Exp_0)100\)`% increase on hourly wages, holding education constant*]
--
.center[
*Increasing work experience from 20 to 21 years is associated, on average, to a `\((\hat{\beta}_2 + 2\hat{\beta}_3\times 20)100\)`% increase on hourly wages, holding education constant*]
---
# Let's put some numbers into it
.small[
```r
summary(lm(log(wage) ~ education + experience + I(experience^2), data = CPS1985))
```
```
##
## Call:
## lm(formula = log(wage) ~ education + experience + I(experience^2),
## data = CPS1985)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.12709 -0.31543 0.00671 0.31170 1.98418
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 0.5203218 0.1236163 4.209 3.01e-05 ***
## education 0.0897561 0.0083205 10.787 < 2e-16 ***
## experience 0.0349403 0.0056492 6.185 1.24e-09 ***
## I(experience^2) -0.0005362 0.0001245 -4.307 1.97e-05 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.4619 on 530 degrees of freedom
## Multiple R-squared: 0.2382, Adjusted R-squared: 0.2339
## F-statistic: 55.23 on 3 and 530 DF, p-value: < 2.2e-16
```
]
--
- Increasing experience from 20 to 21 years is associated with an average increase in wages of 1.35%, holding education constant.
---
# Main takeaway points
.pull-left[
- The model you fit **.darkorange[depends on what you want to analyze]**.
- **.darkorange[Plot your data!]**
- Make sure you capture associations that **.darkorange[make sense]**.
]
.pull-right[
.center[
]
]
---
# Next week
.pull-left[
.center[
]
]
.pull-right[
- Issues with regressions and our data:
- Outliers?
- Heteroskedasticity
- Regression models with discrete outcomes:
- Probability linear models
]
---
# References
- Ismay, C. & A. Kim. (2021). “Statistical Inference via Data Science”. Chapter 6 & 10.
- Keegan, B. (2018). "The Need for Openess in Data Journalism". *[Github Repository](https://github.com/brianckeegan/Bechdel/blob/master/Bechdel_test.ipynb)*
<!-- pagedown::chrome_print('C:/Users/mc72574/Dropbox/Hugo/Sites/sta235/exampleSite/content/Classes/Week2/1_OLS/f2021_sta235h_3_reg.html') -->
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script src="macros.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false,
"ratio": "16:9"
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();
// add `data-at-shortcutkeys` attribute to <body> to resolve conflicts with JAWS
// screen reader (see PR #262)
(function(d) {
let res = {};
d.querySelectorAll('.remark-help-content table tr').forEach(tr => {
const t = tr.querySelector('td:nth-child(2)').innerText;
tr.querySelectorAll('td:first-child .key').forEach(key => {
const k = key.innerText;
if (/^[a-z]$/.test(k)) res[k] = t; // must be a single letter (key)
});
});
d.body.setAttribute('data-at-shortcutkeys', JSON.stringify(res));
})(document);
(function() {
"use strict"
// Replace <script> tags in slides area to make them executable
var scripts = document.querySelectorAll(
'.remark-slides-area .remark-slide-container script'
);
if (!scripts.length) return;
for (var i = 0; i < scripts.length; i++) {
var s = document.createElement('script');
var code = document.createTextNode(scripts[i].textContent);
s.appendChild(code);
var scriptAttrs = scripts[i].attributes;
for (var j = 0; j < scriptAttrs.length; j++) {
s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value);
}
scripts[i].parentElement.replaceChild(s, scripts[i]);
}
})();
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
// adds .remark-code-has-line-highlighted class to <pre> parent elements
// of code chunks containing highlighted lines with class .remark-code-line-highlighted
(function(d) {
const hlines = d.querySelectorAll('.remark-code-line-highlighted');
const preParents = [];
const findPreParent = function(line, p = 0) {
if (p > 1) return null; // traverse up no further than grandparent
const el = line.parentElement;
return el.tagName === "PRE" ? el : findPreParent(el, ++p);
};
for (let line of hlines) {
let pre = findPreParent(line);
if (pre && !preParents.includes(pre)) preParents.push(pre);
}
preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted"));
})(document);</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html> |
import React, { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
import bundlesBG from './images/bundles_background.webp';
import {NavBar} from "./components/NavBar"
import {Card} from "./components/Card"
import { BundleCard } from './components/BundleCard';
import { Hero } from './components/Hero';
interface Featured {
bundle: Bundle,
devName: string,
finalPrice: Number,
layout: {
name: string,
category: string,
}
items: Item[],
}
interface Bundle {
name: string,
image: string,
info: string,
}
interface Item {
name: string,
images: {
featured: string,
}
}
function App() {
const [nonBundles, setNonBundles] = useState([])
const [bundles, setBundles] = useState([])
const [heroItem, setHeroItem] = useState<Item>({
name: '',
images: {
featured: ''
}
});
useEffect( () => {
const fetchData = async () => {
try {
const response = await axios('https://fortnite-api.com/v2/shop/br');
const heItem = response.data.data.featured.entries[1].items[0];
const featured = response.data.data.featured.entries;
const featuredBundles = featured.filter((entry: { bundle: Bundle; }) => entry.bundle !== null)
const featuredItems = featured.filter((entry: { bundle: Bundle; }) => entry.bundle == null)
setNonBundles(featuredItems);
setBundles(featuredBundles);
setHeroItem(heItem);
console.log("CONSOLE LOG HERE")
console.log(featuredItems)
} catch (error) {
console.log(error);
}
}
fetchData();
}, [] )
return (
<div className="App">
{/* <NavBar/> */}
{/* HERO */}
<Hero item={heroItem}/>
<div className="bundles-container">
<div className="bundle-cards">
{bundles.map((item: Featured) =>
<BundleCard item={item}/>
)}
</div>
<div className='bundles'>
<img src={bundlesBG} alt="Bundles background" />
<div className='bundles1'>BUNDLES</div>
<div className='bundles2'>BUNDLES</div>
<div className='bundles3'>BUNDLES</div>
</div>
</div>
<div className="cards-container">
<h2>Item Shop</h2>
<div className='cards'>
{nonBundles.map((nonBundle: Featured) =>
<Card item={nonBundle.items[0]}/>
)}
</div>
</div>
</div>
);
}
export default App; |
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn import svm
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier
from collections import Counter
class DiseasePredictor:
def __init__(self, dataset_path, doctor_data_path, description_data_path):
self.dataset_path = dataset_path
self.doctor_data_path = doctor_data_path
self.description_data_path = description_data_path
self.algorithms = {
'Logistic Regression': LogisticRegression(),
'Decision Tree': tree.DecisionTreeClassifier(),
'Random Forest': RandomForestClassifier(),
'SVM': svm.SVC(probability=True),
'NaiveBayes': GaussianNB(),
'K-Nearest Neighbors': KNeighborsClassifier()
}
self.le = LabelEncoder()
self.dis_sym_data = None
self.doc_data = None
self.des_data = None
self.X_train = None
self.y_train = None
def load_data(self):
self.dis_sym_data = pd.read_csv(self.dataset_path)
self.doc_data = pd.read_csv(self.doctor_data_path, encoding='latin1', names=['Disease', 'Specialist'])
self.des_data = pd.read_csv(self.description_data_path)
def preprocess_data(self):
columns_to_check = [col for col in self.dis_sym_data.columns if col != 'Disease']
symptoms = list(set(self.dis_sym_data.iloc[:, 1:].values.flatten()))
for symptom in symptoms:
self.dis_sym_data[symptom] = self.dis_sym_data.iloc[:, 1:].apply(lambda row: int(symptom in row.values), axis=1)
self.dis_sym_data = self.dis_sym_data.drop(columns=columns_to_check)
self.dis_sym_data = self.dis_sym_data.loc[:, self.dis_sym_data.columns.notna()]
self.dis_sym_data.columns = self.dis_sym_data.columns.str.strip()
var_mod = ['Disease']
for i in var_mod:
self.dis_sym_data[i] = self.le.fit_transform(self.dis_sym_data[i])
self.X_train = self.dis_sym_data.drop(columns="Disease")
self.y_train = self.dis_sym_data['Disease']
def train_models(self):
for model_name, model in self.algorithms.items():
model.fit(self.X_train, self.y_train)
def predict_disease(self, symptoms):
test_data = {}
predicted = []
for column in self.X_train.columns:
test_data[column] = 1 if column in symptoms else 0
test_df = pd.DataFrame(test_data, index=[0])
for model_name, model in self.algorithms.items():
predict_disease = model.predict(test_df)
predict_disease = self.le.inverse_transform(predict_disease)
predicted.extend(predict_disease)
disease_counts = Counter(predicted)
percentage_per_disease = {disease: (count / len(self.algorithms)) * 100 for disease, count in disease_counts.items()}
result_df = pd.DataFrame({"Disease": list(percentage_per_disease.keys()),
"Chances": list(percentage_per_disease.values())})
result_df = result_df.merge(self.doc_data, on='Disease', how='left')
result_df = result_df.merge(self.des_data, on='Disease', how='left')
return result_df
def test_input(self):
symptoms = input("Enter Symptoms (comma-separated): ").split(",")
result = self.predict_disease(symptoms)
return result |
<?php
namespace App\Http\Requests\Admin\Tag;
use Illuminate\Foundation\Http\FormRequest;
/**
* @property integer $id
*
* Class DeleteTagRequest
* @package App\Http\Requests\Admin\Tag
*/
class DeleteTagRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'id' => 'required|exists:tags,id',
];
}
public function attributes()
{
return [
'id' => 'Тег',
];
}
} |
import React from "react";
// позволяет более удобно обрабатывать ошибки
// должен быть стейт
export default class ErrorBoundary extends React.Component {
state = {
hasError: false,
};
// оборачивает другие компоненты в себя и красиво их выводит
componentDidCatch(error, info) {
this.setState({
hasError: true,
});
}
render() {
if (this.state.hasError) {
return <h2>Error</h2>;
}
return this.props.children;
}
} |
import json
import re
from moto.core.responses import BaseResponse
from .exceptions import InvalidDomainName
from .models import es_backends
class ElasticsearchServiceResponse(BaseResponse):
"""Handler for ElasticsearchService requests and responses."""
@property
def es_backend(self):
"""Return backend instance specific for this region."""
return es_backends[self.region]
@classmethod
def list_domains(cls, request, full_url, headers):
response = ElasticsearchServiceResponse()
response.setup_class(request, full_url, headers)
if request.method == "GET":
return response.list_domain_names()
@classmethod
def domains(cls, request, full_url, headers):
response = ElasticsearchServiceResponse()
response.setup_class(request, full_url, headers)
if request.method == "POST":
return response.create_elasticsearch_domain()
@classmethod
def domain(cls, request, full_url, headers):
response = ElasticsearchServiceResponse()
response.setup_class(request, full_url, headers)
if request.method == "DELETE":
return response.delete_elasticsearch_domain()
if request.method == "GET":
return response.describe_elasticsearch_domain()
def create_elasticsearch_domain(self):
params = json.loads(self.body)
domain_name = params.get("DomainName")
if not re.match(r"^[a-z][a-z0-9\-]+$", domain_name):
raise InvalidDomainName(domain_name)
elasticsearch_version = params.get("ElasticsearchVersion")
elasticsearch_cluster_config = params.get("ElasticsearchClusterConfig")
ebs_options = params.get("EBSOptions")
access_policies = params.get("AccessPolicies")
snapshot_options = params.get("SnapshotOptions")
vpc_options = params.get("VPCOptions")
cognito_options = params.get("CognitoOptions")
encryption_at_rest_options = params.get("EncryptionAtRestOptions")
node_to_node_encryption_options = params.get("NodeToNodeEncryptionOptions")
advanced_options = params.get("AdvancedOptions")
log_publishing_options = params.get("LogPublishingOptions")
domain_endpoint_options = params.get("DomainEndpointOptions")
advanced_security_options = params.get("AdvancedSecurityOptions")
auto_tune_options = params.get("AutoTuneOptions")
domain_status = self.es_backend.create_elasticsearch_domain(
domain_name=domain_name,
elasticsearch_version=elasticsearch_version,
elasticsearch_cluster_config=elasticsearch_cluster_config,
ebs_options=ebs_options,
access_policies=access_policies,
snapshot_options=snapshot_options,
vpc_options=vpc_options,
cognito_options=cognito_options,
encryption_at_rest_options=encryption_at_rest_options,
node_to_node_encryption_options=node_to_node_encryption_options,
advanced_options=advanced_options,
log_publishing_options=log_publishing_options,
domain_endpoint_options=domain_endpoint_options,
advanced_security_options=advanced_security_options,
auto_tune_options=auto_tune_options,
)
return 200, {}, json.dumps({"DomainStatus": domain_status})
def delete_elasticsearch_domain(self):
domain_name = self.path.split("/")[-1]
self.es_backend.delete_elasticsearch_domain(domain_name=domain_name)
return 200, {}, json.dumps(dict())
def describe_elasticsearch_domain(self):
domain_name = self.path.split("/")[-1]
if not re.match(r"^[a-z][a-z0-9\-]+$", domain_name):
raise InvalidDomainName(domain_name)
domain_status = self.es_backend.describe_elasticsearch_domain(
domain_name=domain_name
)
return 200, {}, json.dumps({"DomainStatus": domain_status})
def list_domain_names(self):
domain_names = self.es_backend.list_domain_names()
return 200, {}, json.dumps({"DomainNames": domain_names}) |
"""
Notochord MIDI co-improviser server.
Notochord plays different instruments along with the player.
Authors:
Victor Shepardson
Intelligent Instruments Lab 2023
"""
# TODO: make key bindings visibly click corresponding buttons
# TODO: make Mute a toggle but Reset a momentary
# TODO: color note by pitch class + register
# TODO: color instrument 1-128, MEL, DRUM, ANON, ANONDRUM
# TODO: color time
# TODO: id prediction as player / noto
# TODO: unify note log / prediction format
# TODO: grey out predictions when player or muted notochord
# TODO: controls display panel
# TODO: MIDI learn
# TODO: held notes display panel
from typing import Optional, Dict
from numbers import Number
from notochord import Notochord, MIDIConfig, NotoPerformance
from iipyper import OSC, MIDI, run, Stopwatch, repeat, cleanup, TUI, profile, lock
from rich.panel import Panel
from rich.pretty import Pretty
from textual.reactive import reactive
from textual.widgets import Header, Footer, Static, Button, RichLog, Switch, Checkbox
### def TUI components ###
class NotoLog(RichLog):
value = reactive('')
def watch_value(self, time: float) -> None:
self.write(self.value)
class NotoPrediction(Static):
value = reactive(None)
def watch_value(self, time: float) -> None:
evt = self.value
if evt is None:
s = ''
else:
s = f"\tinstrument: {evt['inst']:3d} pitch: {evt['pitch']:3d} time: {int(evt['time']*1000):4d} ms velocity:{int(evt['vel']):3d}"
self.update(Panel(s, title='prediction'))
# class NotoToggle(Static):
# def compose(self):
# yield Button("Mute", id="mute", variant="error")
# yield Switch()
class NotoControl(Static):
def compose(self):
# yield NotoToggle()
# yield Checkbox("Mute", id="mute")
yield Button("Mute", id="mute", variant="error")
yield Button("Sustain", id="sustain", variant="primary")
yield Button("Query", id="query")
yield Button("Reset", id="reset", variant='warning')
class NotoTUI(TUI):
CSS_PATH = 'improviser.css'
BINDINGS = [
("m", "mute", "Mute Notochord"),
("s", "sustain", "Mute without ending notes"),
("q", "query", "Re-query Notochord"),
("r", "reset", "Reset Notochord")]
def compose(self):
"""Create child widgets for the app."""
yield Header()
yield self.std_log
yield NotoLog(id='note')
yield NotoPrediction(id='prediction')
yield NotoControl()
yield Footer()
### end def TUI components###
def main(
checkpoint="notochord-latest.ckpt", # Notochord checkpoint
player_config:Dict[int,int]=None, # map MIDI channel : GM instrument
noto_config:Dict[int,int]=None, # map MIDI channel : GM instrument
initial_mute=False, # start with Notochord muted
initial_query=False, # let Notochord start playing immediately
midi_in:Optional[str]=None, # MIDI port for player input
midi_out:Optional[str]=None, # MIDI port for Notochord output
thru=False, # copy player input to output
send_pc=False, # send program change messages
dump_midi=False, # print all incoming MIDI
balance_sample=False, # choose instruments which have played less recently
n_recent=64, # number of recent note-on events to consider for above
n_margin=8, # amount of 'slack' in the balance_sample calculation
max_note_len=5, # in seconds, to auto-release stuck Notochord notes
max_time=None, # max time between events
nominal_time=False, #feed Notochord with nominal dt instead of actual
osc_port=None, # if supplied, listen for OSC to set controls on this port
osc_host='', # leave this as empty string to get all traffic on the port
use_tui=True, # run textual UI
predict_player=True, # forecasted next events can be for player (preserves model distribution, but can lead to Notochord deciding not to play)
auto_query=True, # query notochord whenever it is unmuted and there is no pending event. generally should be True except for testing purposes.
testing=False
):
"""
Args:
checkpoint: path to notochord model checkpoint.
player_config: mapping from MIDI channels to MIDI instruments controlled
by the player.
noto_config: mapping from MIDI channels to MIDI instruments controlled
by notochord. Both indexed from 1.
instruments should be different from the player instruments.
channels should be different unless different ports are used.
MIDI channels and General MIDI instruments are indexed from 1.
initial_mute: start Notochord muted so it won't play with input.
initial_query: query Notochord immediately so it plays even without input.
midi_in: MIDI ports for player input.
default is to use all input ports.
can be comma-separated list of ports.
midi_out: MIDI ports for Notochord output.
default is to use only virtual 'From iipyper' port.
can be comma-separated list of ports.
thru: if True, copy incoming MIDI to output ports.
only makes sense if input and output ports are different.
send_pc: if True, send MIDI program change messages to set the General MIDI
instrument on each channel according to player_config and noto_config.
useful when using a General MIDI synthesizer like fluidsynth.
dump_midi: if True, print all incoming MIDI for debugging purposes
balance_sample: choose instruments which have played less recently
ensures that all configured instruments will play.
n_recent: number of recent note-on events to consider for above
n_margin: amount of 'slack' in the balance_sample calculation
max_note_len: time in seconds after which to force-release sustained
notochord notes.
max_time: maximum time in seconds between predicted events.
default is the Notochord model's maximum (usually 10 seconds).
nominal_time: if True, feed Notochord with its own predicted times
instead of the actual elapsed time.
May make Notochord more likely to play chords.
osc_port: optional. if supplied, listen for OSC to set controls
osc_host: hostname or IP of OSC sender.
leave this as empty string to get all traffic on the port
use_tui: run textual UI.
predict_player: forecasted next events can be for player.
generally should be true, use balance_sample to force Notochord to
play.
auto_query=True, # query notochord whenever it is unmuted and there is no pending event. generally should be True unless debugging.
"""
if osc_port is not None:
osc = OSC(osc_host, osc_port)
midi = MIDI(midi_in, midi_out)
### Textual UI
tui = NotoTUI()
print = tui.print
###
# default channel:instrument mappings
if player_config is None:
player_config = {1:1} # channel 1: grand piano
if noto_config is None:
noto_config = {2:257} # channel 2: anon
# convert 1-indexed MIDI channels to 0-indexed here
player_map = MIDIConfig({k-1:v for k,v in player_config.items()})
noto_map = MIDIConfig({k-1:v for k,v in noto_config.items()})
if len(player_map.insts & noto_map.insts):
print("WARNING: Notochord and Player instruments shouldn't overlap")
print('setting to an anonymous instrument')
# TODO: set to anon insts without changing mel/drum
# respecting anon insts selected for player
raise NotImplementedError
# TODO:
# check for repeated insts/channels
def warn_inst(i):
if i > 128:
if i < 257:
print(f"WARNING: drum instrument {i} selected, be sure to select a drum bank in your synthesizer")
else:
print(f"WARNING: instrument {i} is not General MIDI")
if send_pc:
for c,i in (player_map | noto_map).items():
warn_inst(i)
midi.program_change(channel=c, program=(i-1)%128)
# TODO: add arguments for this,
# and sensible defaults for drums etc
inst_pitch_map = {i: range(128) for i in noto_map.insts | player_map.insts}
# load notochord model
try:
noto = Notochord.from_checkpoint(checkpoint)
noto.eval()
noto.reset()
except Exception:
print("""error loading notochord model""")
raise
# main stopwatch to track time difference between MIDI events
stopwatch = Stopwatch()
# simple class to hold pending event prediction
class Prediction:
def __init__(self):
self.event = None
self.gate = not initial_mute
pending = Prediction()
# query parameters controlled via MIDI / OSC
controls = {}
# tracks held notes, recently played instruments, etc
history = NotoPerformance()
def display_event(tag, memo, inst, pitch, vel, channel, **kw):
"""print an event to the terminal"""
if tag is None:
return
s = f'{tag}:\t {inst=:4d} {pitch=:4d} {vel=:4d} {channel=:3d}'
if memo is not None:
s += f' ({memo})'
tui(note=s)
def play_event(event, channel, feed=True, send=True, tag=None, memo=None):
"""realize an event as MIDI, terminal display, and Notochord update"""
# normalize values
vel = event['vel'] = round(event['vel'])
dt = stopwatch.punch()
if 'time' not in event or not nominal_time:
event['time'] = dt
# send out as MIDI
if send:
midi.send(
'note_on' if vel > 0 else 'note_off',
note=event['pitch'], velocity=vel, channel=channel)
# feed to NotoPerformance
# put a stopwatch in the held_note_data field for tracking note length
history.feed(held_note_data=Stopwatch(), channel=channel, **event)
# print
display_event(tag, memo=memo, channel=channel, **event)
# feed to Notochord
if feed:
noto.feed(**event)
# @lock
def noto_reset():
"""reset Notochord and end all of its held notes"""
print('RESET')
# cancel pending predictions
pending.event = None
tui(prediction=pending.event)
# end Notochord held notes
for (chan,inst,pitch) in history.note_triples:
if inst in noto_map.insts:
play_event(
dict(inst=inst, pitch=pitch, vel=0),
channel=chan,
feed=False, # skip feeding Notochord since we are resetting it
tag='NOTO', memo='reset')
# reset stopwatch
stopwatch.punch()
# reset notochord state
noto.reset()
# reset history
history.push()
# query the fresh notochord for a new prediction
if pending.gate:
noto_query()
# @lock
def noto_mute(sustain=False):
tui.query_one('#mute').label = 'UNMUTE' if pending.gate else 'MUTE'
# if sustain:
tui.query_one('#sustain').label = 'END SUSTAIN' if pending.gate else 'SUSTAIN'
pending.gate = not pending.gate
if sustain:
print('END SUSTAIN' if pending.gate else 'SUSTAIN')
else:
print('UNMUTE' if pending.gate else 'MUTE')
# if unmuting, we're done
if pending.gate:
if sustain:
noto_query()
return
# cancel pending predictions
pending.event = None
tui(prediction=pending.event)
if sustain:
return
# end+feed all held notes
for (chan,inst,pitch) in history.note_triples:
if chan in noto_map:
play_event(
dict(inst=inst, pitch=pitch, vel=0),
channel=chan, tag='NOTO', memo='mute')
# query Notochord for a new next event
# @lock
def noto_query():
# check for stuck notes
# and prioritize ending those
for (_, inst, pitch), sw in history.note_data.items():
if (
inst in noto_map.insts
and sw.read() > max_note_len*(.1+controls.get('steer_duration', 1))
):
# query for the end of a note with flexible timing
# with profile('query', print=print):
t = stopwatch.read()
pending.event = noto.query(
next_inst=inst, next_pitch=pitch,
next_vel=0, min_time=t, max_time=t+0.5)
print(f'END STUCK NOTE {inst=},{pitch=}')
return
counts = history.inst_counts(
n=n_recent, insts=noto_map.insts | player_map.insts)
print(counts)
all_insts = noto_map.insts
if predict_player:
all_insts = all_insts | player_map.insts
held_notes = history.held_inst_pitch_map(all_insts)
steer_time = 1-controls.get('steer_rate', 0.5)
steer_pitch = controls.get('steer_pitch', 0.5)
steer_density = controls.get('steer_density', 0.5)
tqt = (max(0,steer_time-0.5), min(1, steer_time+0.5))
tqp = (max(0,steer_pitch-0.5), min(1, steer_pitch+0.5))
# if using nominal time,
# *subtract* estimated feed latency to min_time; (TODO: really should
# set no min time when querying, use stopwatch when re-querying...)
# if using actual time, *add* estimated query latency
time_offset = -5e-3 if nominal_time else 10e-3
min_time = stopwatch.read()+time_offset
# balance_sample: note-ons only from instruments which have played less
bal_insts = set(counts.index[counts <= counts.min()+n_margin])
if balance_sample and len(bal_insts)>0:
insts = bal_insts
else:
insts = all_insts
# VTIP is better for time interventions,
# VIPT is better for instrument interventions
# could decide probabilistically based on value of controls + insts...
if insts==all_insts:
query_method = noto.query_vtip
else:
query_method = noto.query_vipt
# print(f'considering {insts} for note_on')
# use only currently selected instruments
note_on_map = {
i: set(inst_pitch_map[i])-set(held_notes[i]) # exclude held notes
for i in insts
}
# use any instruments which are currently holding notes
note_off_map = {
i: set(ps)&set(held_notes[i]) # only held notes
for i,ps in inst_pitch_map.items()
}
max_t = None if max_time is None else max(max_time, min_time+0.2)
pending.event = query_method(
note_on_map, note_off_map,
min_time=min_time, max_time=max_t,
truncate_quantile_time=tqt,
truncate_quantile_pitch=tqp,
steer_density=steer_density,
)
# display the predicted event
tui(prediction=pending.event)
#### MIDI handling
# print all incoming MIDI for debugging
if dump_midi:
@midi.handle
def _(msg):
print(msg)
@midi.handle(type='program_change')
def _(msg):
"""Program change events set instruments"""
if msg.channel in player_map:
player_map[msg.channel] = msg.program
if msg.channel in noto_map:
noto_map[msg.channel] = msg.program
@midi.handle(type='pitchwheel')
def _(msg):
controls['steer_pitch'] = (msg.pitch+8192)/16384
# print(controls)
# very basic CC handling for controls
@midi.handle(type='control_change')
def _(msg):
"""CC messages on any channel"""
if msg.control==1:
controls['steer_pitch'] = msg.value/127
print(f"{controls['steer_pitch']=}")
if msg.control==2:
controls['steer_density'] = msg.value/127
print(f"{controls['steer_density']=}")
if msg.control==3:
controls['steer_rate'] = msg.value/127
print(f"{controls['steer_rate']=}")
if msg.control==4:
noto_reset()
if msg.control==5:
noto_query()
if msg.control==6:
noto_mute()
# very basic OSC handling for controls
if osc_port is not None:
@osc.args('/notochord/improviser/*')
def _(route, *a):
print('OSC:', route, *a)
ctrl = route.split['/'][3]
if ctrl=='reset':
noto_reset()
elif ctrl=='query':
noto_query()
elif ctrl=='mute':
noto_mute()
else:
assert len(a)==0
arg = a[0]
assert isinstance(arg, Number)
controls[ctrl] = arg
print(controls)
@midi.handle(type=('note_on', 'note_off'))
def _(msg):
"""MIDI NoteOn events from the player"""
# if thru and msg.channel not in noto_map.channels:
# midi.send(msg)
if msg.channel not in player_map.channels:
return
inst = player_map[msg.channel]
pitch = msg.note
vel = msg.velocity if msg.type=='note_on' else 0
# feed event to Notochord
# with profile('feed', print=print):
play_event(
{'inst':inst, 'pitch':pitch, 'vel':vel},
channel=msg.channel, send=thru, tag='PLAYER')
# query for new prediction
noto_query()
# send a MIDI reply for latency testing purposes:
# if testing: midi.cc(control=3, value=msg.note, channel=15)
def noto_event():
# notochord event happens:
event = pending.event
inst, pitch, vel = event['inst'], event['pitch'], round(event['vel'])
# note on which is already playing or note off which is not
if (vel>0) == ((inst, pitch) in history.note_pairs):
print(f're-query for invalid {vel=}, {inst=}, {pitch=}')
noto_query()
return
chan = noto_map.inv(inst)
play_event(event, channel=chan, tag='NOTO')
@repeat(1e-3, lock=True)
def _():
"""Loop, checking if predicted next event happens"""
# check if current prediction has passed
if (
not testing and
pending.gate and
pending.event is not None and
stopwatch.read() > pending.event['time']
):
# if so, check if it is a notochord-controlled instrument
if pending.event['inst'] in noto_map.insts:
# prediction happens
noto_event()
# query for new prediction
if auto_query:
noto_query()
@cleanup
def _():
"""end any remaining notes"""
# print(f'cleanup: {notes=}')
for (chan,inst,pitch) in history.note_triples:
# for (inst,pitch) in notes:
if inst in noto_map.insts:
midi.note_on(note=pitch, velocity=0, channel=chan)
@tui.set_action
def mute():
noto_mute()
@tui.set_action
def sustain():
noto_mute(sustain=True)
@tui.set_action
def reset():
noto_reset()
@tui.set_action
def query():
noto_query()
if initial_query:
noto_query()
if use_tui:
tui.run()
if __name__=='__main__':
run(main) |
using CustomerPortalApi.Models;
namespace CustomerPortalApi.Data
{
public static class DbInitializer
{
public static void Initialize(AppDbContext context)
{
// Ensure the database is created
context.Database.EnsureCreated();
// Check if there are any customers
if (context.Customers.Any())
{
return; // DB has been seeded
}
var customers = new List<Customer>();
for (int i = 1; i <= 20; i++)
{
customers.Add(new Customer
{
FirstName = $"FirstName{i}",
LastName = $"LastName{i}",
Email = $"customer{i}@example.com",
CreatedDateTime = DateTime.Now,
LastUpdatedDateTime = DateTime.Now
});
}
context.Customers.AddRange(customers);
context.SaveChanges();
}
}
} |
import Alpine from 'alpinejs';
import { resourcePreviewUrl } from '../utils/api';
import { renderMarkdown } from '../utils/markdown';
import { formatDate } from '../utils/date';
import { gravatar_url } from '../utils/gravatar';
import { isStatusUpdate, statusText } from '../utils/taskStatus';
import { truncate } from '../utils/taskStatus';
export default function PreviewModal() {
return {
pendingComment: '',
currentlyEditing: null,
followupsIsLoading: false,
contentIsLoading: false,
showEdition: false,
get index() {
return this.$store.previewModal.index;
},
get taskId() {
return this.$store.previewModal.taskId;
},
get task() {
return this.$store.tasksData.getTaskById(this.taskId);
},
get followups() {
return this.$store.previewModal.followups;
},
get notifications() {
return this.$store.previewModal.notifications;
},
get newTasks() {
return this.$store.tasksData.newTasks;
},
async refresh() {
this.followupScrollToLastMessage();
},
resourcePreviewUrl,
renderMarkdown,
formatDate,
gravatar_url,
isStatusUpdate,
statusText,
truncate,
newTasksNavigationText() {
return `${this.index + 1} sur ${this.newTasks.length} recommandation${this.newTasks.length > 0 ? 's' : ''}`;
},
hasNotification(followupId) {
return (
this.notifications.filter(
(n) => n.action_object.who && n.action_object.id === followupId
).length > 0
);
},
async onSubmitComment(content) {
this.$store.editor.setIsSubmitted(true);
if (!this.currentlyEditing) {
await this.$store.tasksData.issueFollowup(
this.task,
undefined,
content
);
await this.$store.previewModal.loadFollowups();
} else {
const [type, id] = this.currentlyEditing;
if (type === 'followup') {
await this.$store.tasksData.editComment(this.task.id, id, content);
await this.$store.previewModal.loadFollowups();
} else if (type === 'content') {
await this.$store.tasksData.patchTask(this.task.id, {
content: content,
});
await this.$store.tasksView.updateViewWithTask(this.task.id);
}
}
this.pendingComment = '';
this.currentlyEditing = null;
this.$dispatch('set-comment', this.pendingComment);
this.followupScrollToLastMessage();
if (!this.task.public) {
this.showEdition = false;
}
},
onEditComment(followup) {
this.showEdition = true;
this.pendingComment = followup.comment;
this.currentlyEditing = ['followup', followup.id];
document.querySelector('#comment-text-ref .ProseMirror').focus();
this.$dispatch('set-comment', followup.comment);
},
onEditContent() {
this.showEdition = true;
this.pendingComment = this.task.content;
this.currentlyEditing = ['content', this.task.id];
document.querySelector('#comment-text-ref .ProseMirror').focus();
this.$dispatch('set-comment', this.task.content);
},
loadContent() {
this.contentIsLoading = true;
setTimeout(() => {
this.contentIsLoading = false;
}, 300);
},
followupScrollToLastMessage(initPage = false) {
if (initPage) {
this.followupsIsLoading = true;
}
const scrollContainer = document.getElementById(
'followups-scroll-container'
);
if (scrollContainer) {
setTimeout(
() => {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
if (initPage) {
this.followupsIsLoading = false;
}
},
initPage ? 500 : 1
);
}
},
changeShowEdition() {
this.showEdition = false;
},
getTypeOfModalClass(isDocumented) {
let typeOfModalClass = '';
if (this.$store.previewModal.isPaginated) {
typeOfModalClass = 'is-paginated';
}
if (isDocumented) {
typeOfModalClass = 'is-documented';
}
if (this.$store.previewModal.isPaginated && isDocumented) {
typeOfModalClass = 'is-paginated-documented';
}
return typeOfModalClass;
},
};
}
Alpine.data('PreviewModal', PreviewModal); |
package com.example.apricart;
import com.example.apricart.controller.ProductController;
import com.example.apricart.entity.Product;
import com.example.apricart.service.ProductService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class ProductControllerTest {
@Mock
private ProductService productService;
@InjectMocks
private ProductController productController;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(productController).build();
}
@Test
void testCreateProduct() throws Exception {
Product product = new Product();
product.setProductName("Test Product");
when(productService.createProduct(any(Product.class))).thenReturn(product);
mockMvc.perform(post("/products")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"productName\": \"Test Product\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.productName").value("Test Product"));
}
// Similar tests for updateProduct, deleteProduct, getProductById
} |
// Animancer // https://kybernetik.com.au/animancer // Copyright 2020 Kybernetik //
// Compare to the original script: https://github.com/Unity-Technologies/animation-jobs-samples/blob/master/Assets/animation-jobs-samples/Samples/Scripts/TwoBoneIK/TwoBoneIK.cs
#pragma warning disable CS0649 // Field is never assigned to, and will always have its default value.
using UnityEngine;
namespace Animancer.Examples.Jobs
{
/// <summary>
/// An example of how to use Animation Jobs in Animancer to apply simple two bone Inverse Kinematics, even to
/// Generic Rigs which are not supported by Unity's inbuilt IK system.
/// </summary>
///
/// <remarks>
/// This example is based on Unity's
/// <see href="https://github.com/Unity-Technologies/animation-jobs-samples">Animation Jobs Samples</see>.
/// <para></para>
/// This script sets up the job in place of
/// <see href="https://github.com/Unity-Technologies/animation-jobs-samples/blob/master/Assets/animation-jobs-samples/Samples/Scripts/TwoBoneIK/TwoBoneIK.cs">
/// TwoBoneIK.cs</see>.
/// <para></para>
/// The <see cref="TwoBoneIKJob"/> script is almost identical to the original
/// <see href="https://github.com/Unity-Technologies/animation-jobs-samples/blob/master/Assets/animation-jobs-samples/Runtime/AnimationJobs/TwoBoneIKJob.cs">
/// TwoBoneIKJob.cs</see>.
/// <para></para>
/// The <see href="https://learn.unity.com/tutorial/working-with-animation-rigging">Animation Rigging</see> package
/// has an IK system which is much better than this example.
/// </remarks>
///
/// <example><see href="https://kybernetik.com.au/animancer/docs/examples/jobs/two-bone-ik">Two Bone IK</see></example>
///
/// https://kybernetik.com.au/animancer/api/Animancer.Examples.Jobs/TwoBoneIK
///
[AddComponentMenu(Strings.ExamplesMenuPrefix + "Jobs - Two Bone IK")]
[HelpURL(Strings.DocsURLs.ExampleAPIDocumentation + nameof(Jobs) + "/" + nameof(TwoBoneIK))]
public class TwoBoneIK : MonoBehaviour
{
/************************************************************************************************************************/
[SerializeField] private AnimancerComponent _Animancer;
[SerializeField] private Transform _EndBone;
[SerializeField] private Transform _Target;
/************************************************************************************************************************/
private void Awake()
{
// Get the bones we want to affect.
var midBone = _EndBone.parent;
var topBone = midBone.parent;
// Create the job and setup its details.
var twoBoneIKJob = new TwoBoneIKJob();
twoBoneIKJob.Setup(_Animancer.Animator, topBone, midBone, _EndBone, _Target);
// Add it to Animancer's output.
_Animancer.Playable.InsertOutputJob(twoBoneIKJob);
}
/************************************************************************************************************************/
}
} |
package patmat
/**
* A huffman code is represented by a binary tree.
*
* Every `Leaf` node of the tree represents one character of the alphabet that the tree can encode.
* The weight of a `Leaf` is the frequency of appearance of the character.
*
* The branches of the huffman tree, the `Fork` nodes, represent a set containing all the characters
* present in the leaves below it. The weight of a `Fork` node is the sum of the weights of these
* leaves.
*/
abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree
/**
* Assignment 4: Huffman coding
*
*/
trait Huffman extends HuffmanInterface {
// Part 1: Basics
def weight(tree: CodeTree): Int = {
tree match {
case leaf: Leaf => leaf.weight
case fork: Fork => weight(fork.left) + weight(fork.right)
}
}
def chars(tree: CodeTree): List[Char] = {
tree match {
case leaf: Leaf => List(leaf.char)
case fork: Fork => chars(fork.left) ::: chars(fork.right)
}
}
def makeCodeTree(left: CodeTree, right: CodeTree) =
Fork(left, right, chars(left) ::: chars(right), weight(left) + weight(right))
// Part 2: Generating Huffman trees
/**
* In this assignment, we are working with lists of characters. This function allows
* you to easily create a character list from a given string.
*/
def string2Chars(str: String): List[Char] = str.toList
/**
* This function computes for each unique character in the list `chars` the number of
* times it occurs. For example, the invocation
*
* times(List('a', 'b', 'a'))
*
* should return the following (the order of the resulting list is not important):
*
* List(('a', 2), ('b', 1))
*
* The type `List[(Char, Int)]` denotes a list of pairs, where each pair consists of a
* character and an integer. Pairs can be constructed easily using parentheses:
*
* val pair: (Char, Int) = ('c', 1)
*
* In order to access the two elements of a pair, you can use the accessors `_1` and `_2`:
*
* val theChar = pair._1
* val theInt = pair._2
*
* Another way to deconstruct a pair is using pattern matching:
*
* pair match {
* case (theChar, theInt) =>
* println("character is: "+ theChar)
* println("integer is : "+ theInt)
* }
*/
def times(chars: List[Char]): List[(Char, Int)] = {
def charTime(charsList: List[Char], resList: List[(Char, Int)], char: Char, sum: Int): List[(Char, Int)] = {
charsList match {
case Nil => resList :+ (char, sum)
case _ => charsList.head match {
case x if x != char => charTime(charsList.tail, resList :+ (char, sum), charsList.head, 1)
case _ => charTime(charsList.tail, resList, char, sum + 1)
}
}
}
val list = chars.sortWith((s, t) => s < t)
if (list.isEmpty)
Nil
else
charTime(list, List(), list.head, 0)
}
/**
* Returns a list of `Leaf` nodes for a given frequency table `freqs`.
*
* The returned list should be ordered by ascending weights (i.e. the
* head of the list should have the smallest weight), where the weight
* of a leaf is the frequency of the character.
*/
def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = {
def insertLeaf(tuples: (Char, Int), resList: List[Leaf]): List[Leaf] = {
resList match {
case Nil => List(Leaf(tuples._1, tuples._2))
case x :: xs => if (tuples._2 < x.weight) Leaf(tuples._1, tuples._2) :: resList else x :: insertLeaf(tuples, xs)
}
}
def makeLeafList(list: List[(Char, Int)], resList: List[Leaf]): List[Leaf] = {
list match {
case Nil => resList
case _ => makeLeafList(list.tail, insertLeaf(list.head, resList))
}
}
makeLeafList(freqs, List())
}
/**
* Checks whether the list `trees` contains only one single code tree.
*/
def singleton(trees: List[CodeTree]): Boolean = {
trees match {
case Nil => false
case List(x) => true
case x :: xs => false
}
}
/**
* The parameter `trees` of this function is a list of code trees ordered
* by ascending weights.
*
* This function takes the first two elements of the list `trees` and combines
* them into a single `Fork` node. This node is then added back into the
* remaining elements of `trees` at a position such that the ordering by weights
* is preserved.
*
* If `trees` is a list of less than two elements, that list should be returned
* unchanged.
*/
def combine(trees: List[CodeTree]): List[CodeTree] = {
trees match {
case Nil => trees
case x if x.tail.isEmpty => trees
case x :: xs => if (xs.tail.isEmpty) trees else combine(makeCodeTree(x, xs.head) :: xs.tail)
}
}
/**
* This function will be called in the following way:
*
* until(singleton, combine)(trees)
*
* where `trees` is of type `List[CodeTree]`, `singleton` and `combine` refer to
* the two functions defined above.
*
* In such an invocation, `until` should call the two functions until the list of
* code trees contains only one single tree, and then return that singleton list.
*/
def until(done: List[CodeTree] => Boolean, merge: List[CodeTree] => List[CodeTree])(trees: List[CodeTree]): List[CodeTree] = {
trees match {
case Nil => trees
case x if x.tail.isEmpty => trees
case x :: xs => if (done(trees)) until(done, merge)(merge(trees)) else trees
}
}
/**
* This function creates a code tree which is optimal to encode the text `chars`.
*
* The parameter `chars` is an arbitrary text. This function extracts the character
* frequencies from that text and creates a code tree based on them.
*/
def createCodeTree(chars: List[Char]): CodeTree = {
def union(list: List[CodeTree]): List[CodeTree] = {
list match {
case Nil => list
case List(x) => list
case _ =>
val sortedList = list.sortBy(checkLen).sortBy(checkWeight)
val firstEl = sortedList.head
val secondEl = sortedList.tail.head
val tailList = sortedList.tail.tail
makeCodeTree(firstEl, secondEl) :: union(tailList)
}
}
def checkLen(codeTree: CodeTree): Int = {
codeTree match {
case fork: Fork => fork.chars.length
case leaf: Leaf => 1
}
}
def checkWeight(codeTree: CodeTree): Int = {
codeTree match {
case fork: Fork => fork.weight
case leaf: Leaf => leaf.weight
}
}
def unionFork(subtree: List[CodeTree]): CodeTree = {
subtree match {
case Nil => subtree.head
case List(x) => x
case x if x.length == 2 => makeCodeTree(subtree.last, subtree.head)
case x :: xs =>
val (first, second) = subtree span (y => checkWeight(y) <= checkWeight(x))
first.length match {
case len if len == 1 => unionFork(union(xs.tail ::: union(List(first.head, xs.head))))
case len if len > 1 => unionFork(union(first) ::: second)
}
}
}
unionFork(makeOrderedLeafList(times(chars)))
}
// Part 3: Decoding
type Bit = Int
/**
* This function decodes the bit sequence `bits` using the code tree `tree` and returns
* the resulting list of characters.
*/
/*Decoding also starts at the root of the tree. Given a sequence of bits to decode, we successively
read the bits, and for each 0, we choose the left branch, and for each 1 we choose the right branch.
When we reach a leaf, we decode the corresponding character and then start again at the root of the
tree. As an example, given the Huffman tree above, the sequence of bits,10001010 corresponds to BAC.*/
def decode(tree: CodeTree, bits: List[Bit]): List[Char] = {
def foundChar(bit: List[Bit], subTree: CodeTree): (Char, List[Bit]) = {
subTree match {
case fork: Fork => bit match {
case Nil => throw new NoSuchElementException
case _ => bit.head match {
case x if x == 1 => foundChar(bit.tail, fork.right)
case x if x == 0 => foundChar(bit.tail, fork.left)
}
}
case leaf: Leaf => (leaf.char, bit)
}
}
def bitIter(bitsList: List[Bit], resList: List[Char]): List[Char] = {
bitsList match {
case Nil => resList
case _ => bitIter(foundChar(bitsList, tree)._2, resList :+ foundChar(bitsList, tree)._1)
}
}
bitIter(bits, List())
}
/**
* A Huffman coding tree for the French language.
* Generated from the data given at
* http://fr.wikipedia.org/wiki/Fr%C3%A9quence_d%27apparition_des_lettres_en_fran%C3%A7ais
*/
val frenchCode: CodeTree = Fork(Fork(Fork(Leaf('s', 121895), Fork(Leaf('d', 56269), Fork(Fork(Fork(Leaf('x', 5928), Leaf('j', 8351), List('x', 'j'), 14279), Leaf('f', 16351), List('x', 'j', 'f'), 30630), Fork(Fork(Fork(Fork(Leaf('z', 2093), Fork(Leaf('k', 745), Leaf('w', 1747), List('k', 'w'), 2492), List('z', 'k', 'w'), 4585), Leaf('y', 4725), List('z', 'k', 'w', 'y'), 9310), Leaf('h', 11298), List('z', 'k', 'w', 'y', 'h'), 20608), Leaf('q', 20889), List('z', 'k', 'w', 'y', 'h', 'q'), 41497), List('x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q'), 72127), List('d', 'x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q'), 128396), List('s', 'd', 'x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q'), 250291), Fork(Fork(Leaf('o', 82762), Leaf('l', 83668), List('o', 'l'), 166430), Fork(Fork(Leaf('m', 45521), Leaf('p', 46335), List('m', 'p'), 91856), Leaf('u', 96785), List('m', 'p', 'u'), 188641), List('o', 'l', 'm', 'p', 'u'), 355071), List('s', 'd', 'x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q', 'o', 'l', 'm', 'p', 'u'), 605362), Fork(Fork(Fork(Leaf('r', 100500), Fork(Leaf('c', 50003), Fork(Leaf('v', 24975), Fork(Leaf('g', 13288), Leaf('b', 13822), List('g', 'b'), 27110), List('v', 'g', 'b'), 52085), List('c', 'v', 'g', 'b'), 102088), List('r', 'c', 'v', 'g', 'b'), 202588), Fork(Leaf('n', 108812), Leaf('t', 111103), List('n', 't'), 219915), List('r', 'c', 'v', 'g', 'b', 'n', 't'), 422503), Fork(Leaf('e', 225947), Fork(Leaf('i', 115465), Leaf('a', 117110), List('i', 'a'), 232575), List('e', 'i', 'a'), 458522), List('r', 'c', 'v', 'g', 'b', 'n', 't', 'e', 'i', 'a'), 881025), List('s', 'd', 'x', 'j', 'f', 'z', 'k', 'w', 'y', 'h', 'q', 'o', 'l', 'm', 'p', 'u', 'r', 'c', 'v', 'g', 'b', 'n', 't', 'e', 'i', 'a'), 1486387)
/**
* What does the secret message say? Can you decode it?
* For the decoding use the `frenchCode' Huffman tree defined above.
*/
val secret: List[Bit] = List(0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1)
/**
* Write a function that returns the decoded secret
*/
def decodedSecret: List[Char] = {
decode(frenchCode, secret)
}
// Part 4a: Encoding using Huffman tree
/**
* This function encodes `text` using the code tree `tree`
* into a sequence of bits.
*/
/*Encoding
For a given Huffman tree, one can obtain the encoded representation of a character by traversing
from the root of the tree to the leaf containing the character. Along the way, when a left branch
is chosen, a 0 is added to the representation, and when a right branch is chosen, 1 is added to
the representation. Thus, for the Huffman tree above, the character D is encoded as 1011.*/
def encode(tree: CodeTree)(text: List[Char]): List[Bit] = {
def createBitList(char: Char, subTree: CodeTree, bitList: List[Bit]): List[Bit] = {
def check(codeTree: CodeTree): Boolean = {
codeTree match {
case fork: Fork => fork.chars.contains(char)
case leaf: Leaf => leaf.char == char
}
}
subTree match {
case fork: Fork =>
if (check(fork.left))
createBitList(char, fork.left, bitList :+ 0)
else
createBitList(char, fork.right, bitList :+ 1)
case leaf: Leaf => bitList
}
}
def charIter(charList: List[Char], bitList: List[Bit]): List[Bit] = {
charList match {
case Nil => bitList
case _ => charIter(charList.tail, createBitList(charList.head, tree, bitList))
}
}
charIter(text, List())
}
// Part 4b: Encoding using code table
type CodeTable = List[(Char, List[Bit])]
/**
* This function returns the bit sequence that represents the character `char` in
* the code table `table`.
*/
def codeBits(table: CodeTable)(char: Char): List[Bit] = table.filter(s => s._1 == char).head._2
/**
* Given a code tree, create a code table which contains, for every character in the
* code tree, the sequence of bits representing that character.
*
* Hint: think of a recursive solution: every sub-tree of the code tree `tree` is itself
* a valid code tree that can be represented as a code table. Using the code tables of the
* sub-trees, think of how to build the code table for the entire tree.
*/
def convert(tree: CodeTree): CodeTable = {
def converterTree(codeTable: CodeTable, list: List[Char]): CodeTable = {
list match {
case Nil => codeTable
case _ => converterTree(codeTable :+ (list.head, encode(tree)(List(list.head))), list.tail)
}
}
tree match {
case leaf: Leaf => converterTree(List(), List(leaf.char))
case fork: Fork => converterTree(List(), fork.chars)
}
}
/**
* This function takes two code tables and merges them into one. Depending on how you
* use it in the `convert` method above, this merge method might also do some transformations
* on the two parameter code tables.
*/
def mergeCodeTables(a: CodeTable, b: CodeTable): CodeTable = {
def mergerTable(resTable: CodeTable, addedTable: CodeTable): CodeTable = {
addedTable match {
case Nil => resTable
case _ =>
if (resTable.filter(s => s._1 == addedTable.head._1).isEmpty)
mergerTable(resTable :+ addedTable.head, addedTable.tail)
else
mergerTable(resTable, addedTable.tail)
}
}
mergerTable(a, b)
}
/**
* This function encodes `text` according to the code tree `tree`.
*
* To speed up the encoding process, it first converts the code tree to a code table
* and then uses it to perform the actual encoding.
*/
def quickEncode(tree: CodeTree)(text: List[Char]): List[Bit] = {
val codeTable = convert(tree)
def addedBits(first: List[Bit], second: List[Bit]): List[Bit] = {
second match {
case Nil => first
case _ => addedBits(first :+ second.head, second.tail)
}
}
def iterChar(list: List[Char], resList: List[Bit]): List[Bit] = {
list match {
case Nil => resList
case _ => iterChar(list.tail, addedBits(resList, codeBits(codeTable)(list.head)))
}
}
iterChar(text, List())
}
}
object Huffman extends Huffman |
from django.db import models
from economy.models.states import TimeStamp, Simulation
from economy.models.commodity import Commodity
from economy.global_constants import *
from economy.models.report import Trace
class Stock(models.Model): # Base class for IndustryStock and SocialStock
time_stamp = models.ForeignKey(TimeStamp, related_name="%(app_label)s_%(class)s_related", on_delete=models.CASCADE)
commodity = models.ForeignKey(Commodity, null=True, on_delete=models.CASCADE)
usage_type = models.CharField( choices=USAGE_CHOICES, max_length=50, default=UNDEFINED) #! Sales, productive, consumption, money, sales
owner_type = models.CharField(choices=STOCK_OWNER_TYPES, max_length=20,default=UNDEFINED)
size = models.FloatField( default=0)
stock_owner=models.ForeignKey("StockOwner",on_delete=models.CASCADE,null=True)
value = models.FloatField( default=0)
price = models.FloatField( default=0)
demand=models.FloatField( default=0)
supply=models.FloatField( default=0)
monetary_demand=models.FloatField(default=0) #! Convenience field - should normally be simply set to demand * commodity.unit_price
simulation = models.ForeignKey(Simulation, on_delete=models.CASCADE)
@property
def comparator_stock(self):
comparator_time_stamp=self.simulation.comparator_time_stamp
comparator_stocks=Stock.objects.filter(
time_stamp=comparator_time_stamp,
commodity__name=self.commodity.name,
usage_type=self.usage_type,
stock_owner__name=self.stock_owner.name,
)
if comparator_stocks.count()!=1:
return self
else:
return comparator_stocks.get()
@property
def commodity_name(self):
return self.commodity.name
@property
def owner_name(self):
return self.stock_owner.name
@property
def display_order(self):
return self.commodity.display_order
@property
def comparator_size(self):
if self.comparator_stock==None:
return -1
else:
last_size=self.comparator_stock.size
return last_size
@property
def comparator_demand(self):
if self.comparator_stock==None:
return -1
else:
return self.comparator_stock.demand
@property
def comparator_supply(self):
if self.comparator_stock==None:
return -1
else:
return self.comparator_stock.supply
@property
def current_query_set(self):
return Stock.objects.filter(self.simulation.current_time_stamp)
#! TODO had to do this because {self} doesn't return __str__ for reasons I don't follow
@property
def description(self):
return f"stock with owner:{self.stock_owner.name} commodity:{self.commodity.name} usage:{self.usage_type} id:{self.id}"
def change_size(self,quantity):
#! change the size of this stock by 'quantity'
#! change its price using the commodity's unit price
#! change its value using the commodity's unit value
#! save self (NOTE caller does not have to do this) TODO is this the best way?
#! tell the commodity about these changes
logger.info(f"Stock {self.description} is changing its size by {quantity}")
new_size=self.size+quantity
new_price=self.price+quantity*self.commodity.unit_price
new_value=self.value+quantity*self.commodity.unit_value
if new_size<0 or new_value<0 or new_price<0:
Trace.enter(self.simulation,0,f"WARNING: the stock {self.commodity.name} of type {self.usage_type} owned by {self.stock_owner.name} will become negative with size {new_size}, value {new_value} and price {new_price}")
logger.warning(f"the stock {self.commodity.name} of type {self.usage_type} owned by {self.stock_owner.name} will become negative with size {new_size}, value {new_value} and price {new_price}")
logger.warning(f"This took place after it was asked to change its size by {quantity} ")
# raise Exception (f"The stock {self} will become negative with size {new_size}, value {new_value} and price {new_price}")
self.size=new_size
self.price=new_price
self.value=new_value
self.commodity.change_size(quantity)
self.save()
return
def __str__(self):
return f"[Project {self.time_stamp.simulation.project_number}]{self.owner_name}:{self.commodity.name}:{self.usage_type}[{self.id}]"
class IndustryStock(Stock):
industry = models.ForeignKey("Industry", on_delete=models.CASCADE, null=True) #TODO redundant? the base class has stock_owner
production_requirement = models.FloatField( default=0)
class Meta:
verbose_name = 'Industry Stock'
verbose_name_plural = 'Industry Stocks'
class SocialStock(Stock):
social_class = models.ForeignKey("SocialClass", related_name='class_stock', on_delete=models.CASCADE, null=True)
consumption_requirement = models.FloatField(default=0)
#! TODO had to do this because {self} doesn't return __str__ for reasons I don't follow
class Meta:
verbose_name = 'Social Stock'
verbose_name_plural = 'Social Stocks'
ordering = ['commodity__display_order'] |
package SUPERMEGAAWESOMEEBLACKJACK;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
/**
*
* Support custom painting on a panel in the form of
* a) images - that can be scaled, tiled or painted at original size
* b) non solid painting - that can be done by using a Paint object
*
* Also, any component added directly to this panel will be made
* non-opaque so that the custom painting can show through.
*
* @author ytwytw
*/
public class Background extends JPanel {
/**
* Window size is actual value initialization
*/
public static final int SCALED = 0;
private Paint painter;
private Image image;
private int style = SCALED;
private float alignmentX = 0.5f;
private float alignmentY = 0.5f;
private boolean isTransparentAdd = true;
/**
* Set image as the background with the SCALED style
* @param image
*/
public Background(Image image) {
this(image, SCALED);
}
/**
* Set image as the background with the specified style
* @param image
* @param style
*/
public Background(Image image, int style) {
setImage(image);
setStyle(style);
setLayout(new BorderLayout());
}
/**
* Set image as the backround with the specified style and alignment
* @param image
* @param style
* @param alignmentX
* @param alignmentY
*/
public Background(Image image, int style, float alignmentX, float alignmentY) {
setImage(image);
setStyle(style);
setImageAlignmentX(alignmentX);
setImageAlignmentY(alignmentY);
setLayout(new BorderLayout());
}
/**
* Use the Paint interface to paint a background
* @param painter
*/
public Background(Paint painter) {
setPaint(painter);
setLayout(new BorderLayout());
}
/**
* Set the image used as the background
* @param image
*/
public void setImage(Image image) {
this.image = image;
repaint();
}
/**
* Set the style used to paint the background image
* @param style
*/
public void setStyle(int style) {
this.style = style;
repaint();
}
/**
* Set the Paint object used to paint the background
* @param painter
*/
public void setPaint(Paint painter) {
this.painter = painter;
repaint();
}
/**
* Specify the horizontal alignment of the image when using ACTUAL style
* @param alignmentX
*/
public void setImageAlignmentX(float alignmentX) {
this.alignmentX = alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX;
repaint();
}
/**
* Specify the horizontal alignment of the image when using ACTUAL style
* @param alignmentY
*/
public void setImageAlignmentY(float alignmentY) {
this.alignmentY = alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY;
repaint();
}
/**
* Override method so we can make the component transparent
* @param component
*/
public void add(JComponent component) {
add(component, null);
}
/**
* Override method so we can make the component transparent
* @param component
* @param constraints
*/
public void add(JComponent component, Object constraints) {
if (isTransparentAdd) {
makeComponentTransparent(component);
}
super.add(component, constraints);
}
/**
* Controls whether components added to this panel should automatically
* be made transparent. That is, setOpaque(false) will be invoked.
* The default is set to true.
* @param isTransparentAdd
*/
public void setTransparentAdd(boolean isTransparentAdd) {
this.isTransparentAdd = isTransparentAdd;
}
/**
* Try to make the component transparent.
* For components that use renderers, like JTable, you will also need to
* change the renderer to be transparent. An easy way to do this it to
* set the background of the table to a Color using an alpha value of 0.
*/
private void makeComponentTransparent(JComponent component) {
component.setOpaque(false);
if (component instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane) component;
JViewport viewport = scrollPane.getViewport();
viewport.setOpaque(false);
Component c = viewport.getView();
if (c instanceof JComponent) {
((JComponent) c).setOpaque(false);
}
}
}
/**
* Add custom painting
* @param g
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Invoke the painter for the background
if (painter != null) {
Dimension d = getSize();
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(painter);
g2.fill(new Rectangle(0, 0, d.width, d.height));
}
// Draw the image
if (image == null) {
return;
}
switch (style) {
case SCALED:
drawScaled(g);
break;
default:
drawScaled(g);
}
}
/**
* Custom painting code for drawing a SCALED image as the background
*/
private void drawScaled(Graphics g) {
Dimension d = getSize();
g.drawImage(image, 0, 0, d.width, d.height, null);
}
/**
* Custom painting code for drawing TILED images as the background
*/
} |
#pragma warning disable CA2201 // Do not raise reserved exception types
namespace Exos.Platform.Persistence.Policies
{
using System;
using Exos.Platform.AspNetCore.Resiliency.Policies;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Polly.Registry;
/// <summary>
/// Defines the <see cref="ExosRetrySqlPolicyConfigurationExtension" />.
/// </summary>
public static class ExosRetrySqlPolicyConfigurationExtension
{
/// <summary>
/// Configure Exos Retry Sql Policy.
/// </summary>
/// <param name="services"><see cref="IServiceCollection"/>.</param>
/// <param name="configuration"><see cref="IConfiguration"/>.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddExosRetrySqlPolicy(this IServiceCollection services, IConfiguration configuration)
{
if (configuration != null)
{
if (configuration.GetSection("ResiliencyPolicy:SqlRetryPolicyOptions").Exists())
{
services.Configure<SqlRetryPolicyOptions>(configuration.GetSection("ResiliencyPolicy:SqlRetryPolicyOptions"));
if (configuration.GetSection("ResiliencyPolicy:SqlRetryPolicyOptions:CommandTimeout").Exists())
{
DapperExtensions.SetCommandTimeout(configuration.GetValue<int>("ResiliencyPolicy:SqlRetryPolicyOptions:CommandTimeout"));
}
else
{
DapperExtensions.SetCommandTimeout(30);
}
}
else
{
services.Configure<SqlRetryPolicyOptions>(options =>
{
options.MaxRetries = 5;
options.MaxRetryDelay = 15;
options.CommandTimeout = 30;
});
DapperExtensions.SetCommandTimeout(30);
}
}
else
{
services.Configure<SqlRetryPolicyOptions>(options =>
{
options.MaxRetries = 5;
options.MaxRetryDelay = 15;
options.CommandTimeout = 30;
});
DapperExtensions.SetCommandTimeout(30);
}
services.AddSingleton<IExosRetrySqlPolicy, ExosRetrySqlPolicy>();
return services;
}
/// <summary>
/// Configure Exos Retry Sql Policy.
/// </summary>
/// <param name="serviceProvider"><see cref="IServiceProvider"/>.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static IServiceProvider AddExosRetrySqlPolicy(this IServiceProvider serviceProvider)
{
var policyRegistry = serviceProvider.GetService<IPolicyRegistry<string>>();
if (policyRegistry == null)
{
throw new NullReferenceException("AddExosPlatformDefaults() is mandatory in ConfigureServices method.");
}
if (!policyRegistry.ContainsKey(PolicyRegistryKeys.SqlResiliencyPolicy))
{
var exosRetrySqlPolicy = serviceProvider.GetService<IExosRetrySqlPolicy>();
if (exosRetrySqlPolicy != null)
{
policyRegistry.Add(PolicyRegistryKeys.SqlResiliencyPolicy, exosRetrySqlPolicy.ResilientPolicy);
}
}
// Configure Dapper Extensions
DapperExtensions.SetExosRetrySqlPolicy(policyRegistry);
return serviceProvider;
}
/// <summary>
/// Configure Exos Retry Sql Policy.
/// </summary>
/// <param name="app"><see cref="IApplicationBuilder"/>.</param>
/// <returns>The <see cref="IApplicationBuilder"/>.</returns>
public static IApplicationBuilder AddExosRetrySqlPolicy(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
AddExosRetrySqlPolicy(app.ApplicationServices);
return app;
}
}
}
#pragma warning restore CA2201 // Do not raise reserved exception types |
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './auth.entity';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule,
PassportModule.register({defaultStrategy:'jwt'}),
JwtModule.registerAsync({
imports:[ConfigModule],
inject:[ConfigService],
useFactory: async(configService: ConfigService)=>({
secret: configService.get('JWT_SECRET'),
signOptions:{
expiresIn: 3600,
}
})
}),
// JwtModule.register({
// secret:'topSecret',
// signOptions:{
// expiresIn: 3600,
// }
// }),
TypeOrmModule.forFeature([User])],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [JwtStrategy, PassportModule],
})
export class AuthModule {} |
"""Implements a singleton class for the state of the annotation tools.
The singleton is implemented following the metaclass design described here:
https://itnext.io/deciding-the-best-singleton-approach-in-python-65c61e90cdc4
"""
from dataclasses import dataclass, field
from functools import partial
from typing import Dict, List, Optional, Tuple
import numpy as np
import torch.nn as nn
import zarr
import micro_sam.util as util
from micro_sam.instance_segmentation import AMGBase, get_decoder
from micro_sam.precompute_state import cache_amg_state, cache_is_state
from qtpy.QtWidgets import QWidget
from segment_anything import SamPredictor
try:
from napari.utils import progress as tqdm
except ImportError:
from tqdm import tqdm
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
@dataclass
class AnnotatorState(metaclass=Singleton):
# predictor, image_embeddings and image_shape:
# This needs to be initialized for the interactive segmentation fucntionality.
image_embeddings: Optional[util.ImageEmbeddings] = None
predictor: Optional[SamPredictor] = None
image_shape: Optional[Tuple[int, int]] = None
embedding_path: Optional[str] = None
data_signature: Optional[str] = None
# amg: needs to be initialized for the automatic segmentation functionality.
# amg_state: for storing the instance segmentation state for the 3d segmentation tool.
# decoder: for direct prediction of instance segmentation
amg: Optional[AMGBase] = None
amg_state: Optional[Dict] = None
decoder: Optional[nn.Module] = None
# current_track_id, lineage, committed_lineages:
# State for the tracking annotator to keep track of lineage information.
current_track_id: Optional[int] = None
lineage: Optional[Dict] = None
committed_lineages: Optional[List[Dict]] = None
# Dict to keep track of all widgets, so that we can update their states.
widgets: Dict[str, QWidget] = field(default_factory=dict)
# z-range to limit the data being committed in 3d / tracking.
z_range: Optional[Tuple[int, int]] = None
def initialize_predictor(
self,
image_data,
model_type,
ndim,
save_path=None,
device=None,
predictor=None,
decoder=None,
checkpoint_path=None,
tile_shape=None,
halo=None,
precompute_amg_state=False,
prefer_decoder=True,
pbar_init=None,
pbar_update=None,
):
assert ndim in (2, 3)
# Initialize the model if necessary.
if predictor is None:
self.predictor, state = util.get_sam_model(
device=device, model_type=model_type,
checkpoint_path=checkpoint_path, return_state=True
)
if prefer_decoder and "decoder_state" in state:
self.decoder = get_decoder(
image_encoder=self.predictor.model.image_encoder,
decoder_state=state["decoder_state"],
device=device,
)
else:
self.predictor = predictor
self.decoder = decoder
# Compute the image embeddings.
self.image_embeddings = util.precompute_image_embeddings(
predictor=self.predictor,
input_=image_data,
save_path=save_path,
ndim=ndim,
tile_shape=tile_shape,
halo=halo,
verbose=True,
pbar_init=pbar_init,
pbar_update=pbar_update,
)
self.embedding_path = save_path
# If we have an embedding path the data signature has already been computed,
# and we can read it from there.
if save_path is not None:
with zarr.open(save_path, "r") as f:
self.data_signature = f.attrs["data_signature"]
# Otherwise we compute it here.
else:
self.data_signature = util._compute_data_signature(image_data)
# Precompute the amg state (if specified).
if precompute_amg_state:
if save_path is None:
raise RuntimeError("Require a save path to precompute the amg state")
cache_state = cache_amg_state if self.decoder is None else partial(
cache_is_state, decoder=self.decoder, skip_load=True,
)
if ndim == 2:
self.amg = cache_state(
predictor=self.predictor,
raw=image_data,
image_embeddings=self.image_embeddings,
save_path=save_path
)
else:
n_slices = image_data.shape[0] if image_data.ndim == 3 else image_data.shape[1]
for i in tqdm(range(n_slices), desc="Precompute amg state"):
slice_ = np.s_[i] if image_data.ndim == 3 else np.s_[:, i]
cache_state(
predictor=self.predictor,
raw=image_data[slice_],
image_embeddings=self.image_embeddings,
save_path=save_path, i=i, verbose=False,
)
def initialized_for_interactive_segmentation(self):
have_image_embeddings = self.image_embeddings is not None
have_predictor = self.predictor is not None
have_image_shape = self.image_shape is not None
init_sum = sum((have_image_embeddings, have_predictor, have_image_shape))
if init_sum == 3:
return True
elif init_sum == 0:
return False
else:
miss_vars = [
name for name, have_name in zip(
["image_embeddings", "predictor", "image_shape"],
[have_image_embeddings, have_predictor, have_image_shape]
)
if not have_name
]
miss_vars = ", ".join(miss_vars)
raise RuntimeError(
f"Invalid state: the variables {miss_vars} have to be initialized for interactive segmentation."
)
def initialized_for_tracking(self):
have_current_track_id = self.current_track_id is not None
have_lineage = self.lineage is not None
have_committed_lineages = self.committed_lineages is not None
have_tracking_widget = "tracking" in self.widgets
init_sum = sum((have_current_track_id, have_lineage, have_committed_lineages, have_tracking_widget))
if init_sum == 4:
return True
elif init_sum == 0:
return False
else:
miss_vars = [
name for name, have_name in zip(
["current_track_id", "lineage", "committed_lineages", "widgets['tracking']"],
[have_current_track_id, have_lineage, have_committed_lineages, have_tracking_widget]
)
if not have_name
]
miss_vars = ", ".join(miss_vars)
raise RuntimeError(f"Invalid state: the variables {miss_vars} have to be initialized for tracking.")
def reset_state(self):
"""Reset state, clear all attributes."""
self.image_embeddings = None
self.predictor = None
self.image_shape = None
self.embedding_path = None
self.amg = None
self.amg_state = None
self.decoder = None
self.current_track_id = None
self.lineage = None
self.committed_lineages = None
self.z_range = None
self.data_signature = None
# Note: we don't clear the widgets here, because they are fixed for a viewer session. |
import { cn } from "@/utils";
import { HTMLAttributes, forwardRef } from "react";
export type HeadingProps = HTMLAttributes<HTMLHeadingElement>;
export const H1 = forwardRef<HTMLHeadingElement, HeadingProps>(
({ className, ...props }, ref) => (
<h1
className={cn(
"scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",
className
)}
ref={ref}
{...props}
/>
)
);
H1.displayName = "H1";
export const H2 = forwardRef<HTMLHeadingElement, HeadingProps>(
({ className, ...props }, ref) => (
<h2
className={cn(
"scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight transition-colors first:mt-0",
className
)}
ref={ref}
{...props}
/>
)
);
H2.displayName = "H2";
export const H3 = forwardRef<HTMLHeadingElement, HeadingProps>(
({ className, ...props }, ref) => (
<h3
className={cn(
"scroll-m-20 text-2xl font-semibold tracking-tight",
className
)}
ref={ref}
{...props}
/>
)
);
H3.displayName = "H3";
export const H4 = forwardRef<HTMLHeadingElement, HeadingProps>(
({ className, ...props }, ref) => (
<h4
className={cn(
"scroll-m-20 text-xl font-semibold tracking-tight",
className
)}
ref={ref}
{...props}
/>
)
);
H4.displayName = "H4"; |
const express = require('express');
const axios = require('axios');
const router = express.Router();
// Route för att söka efter böcker
router.get('/search', async (req, res) => {
// Destrukturera query-parametrar och sätt ett standardvärde på limit till 5
const { q, author, title, isbn, limit = 5 } = req.query;
// Skapa en array för att bygga upp query-strängen
const query = [];
if (q) query.push(`q=${q}`);
if (author) query.push(`author=${author}`);
if (title) query.push(`title=${title}`);
if (isbn) query.push(`isbn=${isbn}`);
query.push(`limit=${limit}`);
// Sammanfoga query-parametrarna till en sträng
const queryString = query.join('&');
try {
// Skicka en GET-förfrågan till Open Library API med den byggda query-strängen
const response = await axios.get(`https://openlibrary.org/search.json?${queryString}`);
const books = response.data.docs.map(book => ({
key: book.key,
title: book.title,
author_name: book.author_name,
first_publish_year: book.first_publish_year,
cover_id: book.cover_i
}));
// Skicka tillbaka svaret som JSON
res.json({ docs: books })
} catch (error) {
// Logga eventuella fel och skicka ett felmeddelande till klienten
if (error.response && error.response.status === 503) {
console.error(error.response.statusText);
} else {
console.error('Error fetching books:', error);
}
}
});
// Route för att hämta detaljer om en specifik bok
router.get('/book/:id', async (req, res) => {
// Hämta bok-ID från URL-parametrarna
const { id } = req.params;
try {
// Skicka en GET-förfrågan till Open Library API för att hämta bokdetaljer
const response = await axios.get(`https://openlibrary.org/works/${id}.json`);
const bookDetails = response.data;
console.log('Book details:', bookDetails)
// Dra ut det första ID:et ur arrayn "covers"
const coverId = bookDetails.covers && bookDetails.covers.length > 0 ? bookDetails.covers[0] : null;
// Hämta information om författare
let authorDetails = []; // Tom array för att lagra information om författare
if (bookDetails.authors && bookDetails.authors.length > 0) {
authorDetails = await Promise.all(
// Använd map över authors-arrayn för att skapa en lista över promises för varje författare
bookDetails.authors.map(async author => {
// API-request för att hämta info om varje författare baserat på author.key
const authorRes = await axios.get(`https://openlibrary.org${author.author.key}.json`);
// Extrahera och returnera författares namn
return authorRes.data.name;
})
);
}
// Hämta utgivningsår via Search-API:et
const searchResponse = await axios.get(`https://openlibrary.org/search.json?q=${encodeURIComponent(bookDetails.title)}&author=${encodeURIComponent(authorDetails.join(','))}`);
// Filtrera sökresultat för att hitta boken som matchar id:et
const searchResults = searchResponse.data.docs.filter(book => book.key === `/works/${id}`);
// Extrahera utgivningsår från sökresultat
const publishDetails = searchResults.length > 0 && searchResults[0].first_publish_year ? searchResults[0].first_publish_year : null;
// Skicka tillbaka svaret som JSON
res.json({
...bookDetails,
author_names: authorDetails,
first_published_year: publishDetails,
cover_id: coverId
})
} catch (error) {
// Logga eventuella fel och skicka ett felmeddelande till klienten
if (error.response && error.response.status === 503) {
console.error(error.response.statusText);
} else {
console.error('Error fetching book details:', error);
}
}
});
module.exports = router; |
import sinon from 'sinon';
import fs from 'fs';
import { multerFile } from '../mocks/multerFile';
import { FileHandlingService } from '../../../main/service/fileHandlingService';
import { uploadType } from '../../../main/models/consts';
const { redisClient } = require('../../../main/cacheManager');
const fileHandlingService = new FileHandlingService();
const validFileCase = multerFile('testFile.HtMl', 1000);
const largeFile = multerFile('testFile.docx', 3000000);
const validFile = multerFile('testFile.pdf', 1000);
const validImage = multerFile('testImage.png', 1000);
const largeImage = multerFile('testFile.png', 3000000);
const dotSeparatedFile = multerFile('t.e.s.t.f.i.l.e.png', 1000);
const invalidFileType = multerFile('testFile.xyz', 1000);
const noFileType = multerFile('testFile', 1000);
const userId = '1234';
const base64FileContent = 'VGhpcyBpcyBiYXNlIDY0';
const jsonContent = '{"TestContent": "TestValue"}';
const stub = sinon.stub(fs, 'unlinkSync');
const englishLanguage = 'en';
const createMediaAccountLanguageFile = 'create-media-account';
const manualUploadLanguageFile = 'manual-upload';
describe('File handling service', () => {
describe('validateImage', () => {
it('should return null if valid image is provided', () => {
expect(fileHandlingService.validateImage(validImage, englishLanguage, createMediaAccountLanguageFile)).toBe(
null
);
});
it('should return null if a dot-separated image is provided', () => {
expect(
fileHandlingService.validateImage(dotSeparatedFile, englishLanguage, createMediaAccountLanguageFile)
).toBe(null);
});
it('should return error message if image is not provided', () => {
expect(fileHandlingService.validateImage(null, englishLanguage, createMediaAccountLanguageFile)).toBe(
'There is a problem - We will need ID evidence to support your application for an account'
);
});
it('should return error message if unsupported format image is provided', () => {
expect(
fileHandlingService.validateImage(invalidFileType, englishLanguage, createMediaAccountLanguageFile)
).toBe('There is a problem - ID evidence must be a JPG, PDF or PNG');
});
it('should return error message if image is over 2MB', () => {
expect(fileHandlingService.validateImage(largeImage, englishLanguage, createMediaAccountLanguageFile)).toBe(
'There is a problem - ID evidence needs to be less than 2Mbs'
);
});
});
describe('validateFileUpload', () => {
it('should return null when checking a valid file', () => {
expect(
fileHandlingService.validateFileUpload(
validFile,
englishLanguage,
manualUploadLanguageFile,
uploadType.FILE
)
).toBe(null);
});
it('should return null when checking file type in different case sensitivity', () => {
expect(
fileHandlingService.validateFileUpload(
validFileCase,
englishLanguage,
manualUploadLanguageFile,
uploadType.FILE
)
).toBe(null);
});
it('should return error message if file greater than 2MB', () => {
expect(
fileHandlingService.validateFileUpload(
largeFile,
englishLanguage,
manualUploadLanguageFile,
uploadType.FILE
)
).toEqual('File too large, please upload file smaller than 2MB');
});
it('should return error message if invalid file type', () => {
expect(
fileHandlingService.validateFileUpload(
invalidFileType,
englishLanguage,
manualUploadLanguageFile,
uploadType.FILE
)
).toEqual('Please upload a valid file format');
});
it('should return error message if missing file type', () => {
expect(
fileHandlingService.validateFileUpload(
noFileType,
englishLanguage,
manualUploadLanguageFile,
uploadType.FILE
)
).toEqual('Please upload a valid file format');
});
it('should return error message if no file passed', () => {
expect(
fileHandlingService.validateFileUpload(null, englishLanguage, manualUploadLanguageFile, uploadType.FILE)
).toEqual('Please provide a file');
});
});
describe('readFile', () => {
it('should read a pdf file successfully', () => {
const file = fileHandlingService.readFile('validationFile.pdf');
expect(file).toBeInstanceOf(Buffer);
});
it('should read a json file successfully', () => {
const file = fileHandlingService.readFile('validationJson.json');
expect(file).toEqual({ name: 'this is valid json file' });
});
it('should return null if there is an error in reading a file', () => {
const file = fileHandlingService.readFile('foo.pdf');
expect(file).toEqual(null);
});
});
describe('readCsvToArray', () => {
it('should read a csv file successfully', () => {
const file = fs.readFileSync('./manualUpload/tmp/bulkMediaUploadValidationFile.csv', 'utf-8');
const rows = fileHandlingService.readCsvToArray(file);
expect(rows).toHaveLength(4);
const header = rows[0];
expect(header).toHaveLength(3);
expect(header).toStrictEqual(['column1', 'column2', 'column3']);
});
});
describe('readFile from redis', () => {
const getStub = sinon.stub(redisClient, 'get');
it('should read a pdf file successfully', async () => {
getStub.withArgs('1234-validationFile.pdf').resolves(base64FileContent);
const fileBuffer = await fileHandlingService.readFileFromRedis(userId, 'validationFile.pdf');
expect(fileBuffer.toString()).toEqual('This is base 64');
});
it('should read a json file successfully', async () => {
getStub.withArgs('1234-validationJson.json').resolves(jsonContent);
const file = await fileHandlingService.readFileFromRedis(userId, 'validationJson.json');
expect(file).toEqual(JSON.parse(jsonContent));
});
});
describe('storeFile in redis', () => {
const setStub = sinon.stub(redisClient, 'set');
it('should store a pdf file succesfully in redis', async () => {
setStub.resolves('');
await fileHandlingService.storeFileIntoRedis(userId, 'validationFile.pdf', 'validation.pdf');
sinon.assert.calledWith(setStub, '1234-validation.pdf', sinon.match.any, 'EX', sinon.match.any);
});
it('should store a JSON file succesfully', async () => {
setStub.resolves('');
await fileHandlingService.storeFileIntoRedis(userId, 'validationJson.json', 'validation.json');
sinon.assert.calledWith(setStub, '1234-validation.json', sinon.match.any, 'EX', sinon.match.any);
});
});
describe('removeFile from redis', () => {
it('should remove a file successfully', async () => {
const deleteStub = sinon.stub(redisClient, 'del');
deleteStub.withArgs('1234-validationFile.pdf').returns();
await fileHandlingService.removeFileFromRedis(userId, 'validationFile.pdf');
sinon.assert.calledWith(deleteStub, '1234-validationFile.pdf');
});
});
describe('isValidFileType', () => {
it('should return true for valid image type', () => {
expect(fileHandlingService.isValidFileType('foo.jpg', uploadType.IMAGE)).toBe(true);
});
it('should return false for invalid image type', () => {
expect(fileHandlingService.isValidFileType('bar.gif', uploadType.IMAGE)).toBe(false);
});
it('should return false for no image type', () => {
expect(fileHandlingService.isValidFileType('buzz', uploadType.IMAGE)).toBe(false);
});
it('should return true for valid file type', () => {
expect(fileHandlingService.isValidFileType('foo.pdf', uploadType.FILE)).toBe(true);
});
it('should return false for invalid image type', () => {
expect(fileHandlingService.isValidFileType('bar.gif', uploadType.IMAGE)).toBe(false);
});
it('should return false for no file type', () => {
expect(fileHandlingService.isValidFileType('pop', uploadType.FILE)).toBe(false);
});
it('should return true for dot separated image file', () => {
expect(fileHandlingService.isValidFileType('f.i.l.e.png', uploadType.IMAGE)).toBe(true);
});
});
describe('isFileCorrectSize', () => {
it('should return true if file is less than 2MB', () => {
expect(fileHandlingService.isFileCorrectSize(1000)).toEqual(true);
});
it('should return false if file is greater than 2MB', () => {
expect(fileHandlingService.isFileCorrectSize(3000000)).toEqual(false);
});
});
describe('removeFile', () => {
it('should remove a file', () => {
expect(fileHandlingService.removeFile(validImage)).toEqual(void 0);
stub.restore();
});
it('should error when failing to delete a file', () => {
stub.restore();
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {
('');
});
fileHandlingService.removeFile(invalidFileType);
expect(consoleSpy).toHaveBeenCalledTimes(1);
});
});
describe('getFileExtension', () => {
it('should return file type', () => {
const fileType = fileHandlingService.getFileExtension('demo.pdf');
expect(fileType).toEqual('pdf');
});
it('should return file type even if dot-separated filename', () => {
const fileType = fileHandlingService.getFileExtension('f.i.l.e.n.a.m.e.png');
expect(fileType).toEqual('png');
});
});
describe('Test sanitise file name', () => {
it('should santise the filename', () => {
const fileName = fileHandlingService.sanitiseFileName('ThisIs—AFile');
expect(fileName).toEqual('ThisIsAFile');
});
});
}); |
function solve() {
document.querySelector("#btnSend").addEventListener("click", onClick);
function onClick() {
let restaurant = {};
let input = document.querySelector("#inputs textarea");
let bestRestaurantOutput = document.querySelector('#bestRestaurant p');
let bestWorkersOutput = document.querySelector('#workers p');
let newInput = JSON.parse(input.value);
for (let index = 0; index < newInput.length; index++) {
let [restaurantName, workers] = newInput[index].split(" - ");
let splitInput = newInput[index].split("-");
let nameOfRestaurant = splitInput[0];
let arrayOfWorkers = [];
workers = workers.split(" ");
for (let i = 0; i < workers.length; i += 2) {
let nameOfWorker = workers[i];
let currentSalary = Number(workers[i + 1].split(",")[0]);
if (!restaurant.hasOwnProperty(restaurantName)) {
restaurant[restaurantName] = [];
}
restaurant[restaurantName].push({
name: nameOfWorker,
salary: currentSalary,
});
}
const currentRestaurantValues = Object.values(restaurant[restaurantName]);
let size = currentRestaurantValues.length;
let sum = 0;
for (const worker of currentRestaurantValues) {
let type = typeof worker.salary;
if (type === "number") {
sum += worker.salary;
}else {
size--
}
}
restaurant[restaurantName].average = (sum / size).toFixed(2);
}
const values = Object.values(restaurant);
let bestAverage = values.sort((a, b) => b.average - a.average)[0];
let bestSalary = bestAverage.sort((a, b) => b.salary - a.salary)[0];
const entries = Object.entries(restaurant);
let name = entries.sort((a, b) => b[1].average - a[1].average)[0][0];
let average = bestAverage.average;
let highestSalary = Number(bestSalary.salary).toFixed(2);
const outputBestRestaurant = `Name: ${name} Average Salary: ${average} Best Salary: ${highestSalary}`;
let outputBestWorkers = [];
for (const key in bestAverage) {
let type = typeof bestAverage[key].salary;
if (type === "number") {
const currentName = bestAverage[key].name;
const currentSalary = Number(bestAverage[key].salary).toFixed(0);
let currentResult = `Name: ${currentName} With Salary: ${currentSalary}`;
outputBestWorkers.push(currentResult);
}
}
bestRestaurantOutput.textContent = outputBestRestaurant;
bestWorkersOutput.textContent = outputBestWorkers.join(' ');
}
}
//second solution
// function solve() {
// document.querySelector('#btnSend').addEventListener('click', onClick);
// const inputTextarea = document.querySelector("#inputs > textarea")
// const outputP = document.querySelectorAll("#outputs p")
// function onClick () {
// let restaurantsInfo = {};
// for (let restaurant of JSON.parse(inputTextarea.value)) {
// let [restaurantName, workersList] = restaurant.split(" - ");
// workersList = workersList.split(", ");
// if (!(restaurantName in restaurantsInfo)) {
// restaurantsInfo[restaurantName] = {}
// }
// for (let worker of workersList) {
// let [workerName, salary] = worker.split(" ");
// restaurantsInfo[restaurantName][workerName] = parseInt(salary);
// }
// }
// let bestRestaurant = ''
// let bestAverageSalary = 0
// let bestMaxSalary = 0
// for (let[ restaurant, workersInfo] of Object.entries(restaurantsInfo)) {
// let salariesList = Object.values(workersInfo);
// let averageSalary = salariesList.reduce((a, b) => a + b, 0) / salariesList.length;
// if (averageSalary > bestAverageSalary) {
// bestAverageSalary = averageSalary;
// bestRestaurant = restaurant;
// bestMaxSalary = salariesList.reduce((a, b) => Math.max(a, b));
// }
// }
// let result = `Name: ${bestRestaurant} Average Salary: ${bestAverageSalary.toFixed(2)} Best Salary: ${bestMaxSalary.toFixed(2)}`
// outputP[0].textContent = result
// let workersSorted = Object.entries(restaurantsInfo[bestRestaurant]).sort((a, b) => b[1] - a[1]);
// result = workersSorted.reduce((result, worker) => result + `Name: ${worker[0]} With Salary: ${worker[1]} `, '');
// outputP[1].textContent = result
// inputTextarea.value = ''
// }
// } |
import React, { ReactNode, createContext, useContext, useEffect, useState } from 'react'
import { getObject, storeData, storeObject } from '../helpers/storage'
import { TViewPoint } from '../helpers/types/ViewPoint'
import { storageKeys } from '../helpers/constants'
const ObservationSpotContext = createContext<any>({})
export const useSpot = () => {
return useContext(ObservationSpotContext)
}
interface ObservationSpotProviderProps {
children: ReactNode
}
export function ObservationSpotProvider({ children }: ObservationSpotProviderProps) {
const [currentSpotElevation, setCurrentSpotElevation] = useState<number>(0)
const [viewPoints, setViewPoints] = useState<TViewPoint[]>([])
const [selectedSpot, setSelectedSpot] = useState<TViewPoint | null>(null)
const defaultAltitude: string = "+341m"
useEffect(() => {
(async () => {
const spots = await getObject(storageKeys.viewPoints)
const spot = await getObject(storageKeys.selectedSpot)
if (spots) setViewPoints(spots)
if (spot) setSelectedSpot(spot)
})()
}, [])
const handleCurrentSpotElevation = (newElevation: number) => {
setCurrentSpotElevation(newElevation)
storeData(storageKeys.hasChangedCurrentSpotElevation, 'true')
}
const addNewSpot = async (newSpot: TViewPoint) => {
const temp = await getObject(storageKeys.viewPoints)
console.log(temp);
if (temp) {
temp.push(newSpot)
storeObject(storageKeys.viewPoints, temp)
} else {
storeObject(storageKeys.viewPoints, [newSpot])
}
storeData(storageKeys.hasAddedSpot, 'true')
refreshViewPoints()
}
const refreshViewPoints = async () => {
const temp = await getObject(storageKeys.viewPoints)
if (temp) {
setViewPoints(temp)
}
}
const deleteSpot = async (spotTitle: string) => {
const temp = await getObject(storageKeys.viewPoints)
if (temp) {
const newSpots = temp.filter((spot: TViewPoint) => spot.title !== spotTitle)
storeObject(storageKeys.viewPoints, newSpots)
}
refreshViewPoints()
}
const changeSelectedSpot = (spot: TViewPoint) => {
setSelectedSpot(spot)
storeObject(storageKeys.selectedSpot, spot)
}
const values = {
currentSpotElevation,
handleCurrentSpotElevation,
addNewSpot,
deleteSpot,
viewPoints,
refreshViewPoints,
changeSelectedSpot,
selectedSpot,
defaultAltitude,
}
return (
<ObservationSpotContext.Provider value={values}>
{children}
</ObservationSpotContext.Provider>
)
} |
package com.quaap.primary.C6;
import android.support.test.espresso.ViewInteraction;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import com.quaap.primary.MainActivity;
import com.quaap.primary.R;
import org.hamcrest.core.IsInstanceOf;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.replaceText;
import static android.support.test.espresso.action.ViewActions.scrollTo;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withClassName;
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class AddDeleteUserC6 {
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void addDeleteUserC6() {
ViewInteraction linearLayout = onView(
withClassName(is("android.widget.LinearLayout")));
linearLayout.perform(scrollTo(), click());
ViewInteraction appCompatImageView = onView(
allOf(ViewMatchers.withId(R.id.add_list_item_button), withContentDescription("Add Item")));
appCompatImageView.perform(scrollTo(), click());
ViewInteraction appCompatEditText = onView(
withId(R.id.username_input));
appCompatEditText.perform(scrollTo(), replaceText("user"), closeSoftKeyboard());
ViewInteraction appCompatButton = onView(
allOf(withId(R.id.user_added_button), withText("Add")));
appCompatButton.perform(scrollTo(), click());
ViewInteraction linearLayout2 = onView(
allOf(IsInstanceOf.<View>instanceOf(android.widget.LinearLayout.class), isDisplayed()));
linearLayout2.check(matches(isDisplayed()));
ViewInteraction appCompatTextView = onView(
allOf(withId(R.id.delete_user_link), withText("Delete User")));
appCompatTextView.perform(scrollTo(), click());
ViewInteraction appCompatButton2 = onView(
allOf(withId(android.R.id.button1), withText("Delete")));
appCompatButton2.perform(scrollTo(), click());
ViewInteraction linearLayout3 = onView(
allOf(withId(R.id.items_list_area), isDisplayed()));
linearLayout3.check(matches(isDisplayed()));
}
} |
//
// DRStringTable.swift
// SwiftNetrek
//
// Created by Darrell Root on 2/25/19.
//
import Cocoa
class DRStringTable: NSView {
override var isOpaque: Bool {
return true
}
var hasChangedVal: Bool = false
var columns: [DRStringList] = []
let notificationCenter = LLNotificationCenter.default()
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
var aRect = self.bounds
let columnWidth = self.bounds.size.width / CGFloat(columns.count)
aRect.size.width = columnWidth
for column in columns {
column.bounds = aRect
column.draw(aRect)
aRect.origin.x = aRect.origin.x + columnWidth
}
hasChangedVal = false
super.draw(aRect)
}
override func awakeFromNib() {
let list = DRStringList()
list.frame = self.frame
list.bounds = self.bounds
list.awakeFromNib()
columns.append(list)
}
@objc func disableSelection() {
hasChangedVal = true
}
override var isFlipped: Bool {
return true
}
@objc func hasChanged() -> Bool {
return hasChangedVal
}
func mousePos() -> NSPoint {
let mouseBase = self.window?.mouseLocationOutsideOfEventStream
let mouseLocation = self.convert(mouseBase ?? NSPoint.zero, from: nil)
if mouseLocation == NSPoint.zero {
debugPrint("Warning: DRStringTable: mousePosition is nil")
}
return mouseLocation
}
override func mouseDown(with event: NSEvent) {
//TODO shouldnt we get mouse position from event?
let mousePosition = self.mousePos()
let columnWidth = self.bounds.size.width / CGFloat(columns.count)
let selectedColumn: Int = Int(mousePosition.x) / Int(columnWidth)
for (index,column) in columns.enumerated() {
if index == selectedColumn {
let row = Int(mousePosition.y) / Int(column.rowHeight)
column.setSelectedRow(row: row)
self.newStringSelected(column.selectedString())
} else {
column.disableSelection()
}
}
hasChangedVal = true
}
func newStringSelected(_ str: NSString) {
notificationCenter?.postNotificationName("LL_STRING_TABLE_SELECTION", object: self, userInfo: str)
}
func emptyAllColumns() {
for column in columns {
column.emptyAllRows()
}
}
func maxNrOfRows() -> Int {
if let column = columns.first {
return column.maxNrOfStrings()
} else {
debugPrint("Error: DRStringTable no columns, unable to calculate maxNrOfRows")
return 0
}
}
func setNrOfColumns(_ newNrOfColumns: Int) {
guard newNrOfColumns > 0 else { return }
var listBounds = self.bounds
listBounds.size.width = CGFloat(Int(listBounds.size.width) / newNrOfColumns)
// delete
if newNrOfColumns < columns.count {
for _ in newNrOfColumns ..< columns.count {
columns.removeLast()
}
}
// add
if columns.count < newNrOfColumns {
for _ in columns.count ..< newNrOfColumns {
let newColumn = DRStringList()
columns.append(newColumn)
}
}
// set bounds of all
for column in columns {
column.frame = listBounds
column.bounds = listBounds
column.awakeFromNib()
listBounds.origin.x = listBounds.origin.x + listBounds.size.width
}
hasChangedVal = true
}
func removeString(_ str: NSString,fromColumn column: Int) {
guard column < columns.count && column > -1 else {
debugPrint("Error: DRStringTable:removeString column \(column) does not exist")
return
}
columns[column].removeString(str)
hasChangedVal = true
}
func addString(_ str: NSString,toColumn column: Int) {
guard column < columns.count && column > -1 else {
debugPrint("Error: DRStringTable:addString column \(column) does not exist")
return
}
columns[column].addString(str: str)
hasChangedVal = true
}
func addString(_ str: NSString, withColor color: NSColor, toColumn column: Int) {
guard column < columns.count && column > -1 else {
debugPrint("Error: DRStringTable:addString column \(column) does not exist")
return
}
columns[column].addString(str: str, withColor: color)
hasChangedVal = true
}
} |
//
// Created by aojoie on 6/23/2023.
//
#pragma once
#include <ojoie/Allocator/MemoryDefines.h>
#include <cstddef>
namespace AN {
template<typename T, int align = kDefaultMemoryAlignment>
class STLAllocator {
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
STLAllocator() {}
template <typename U, int _align>
STLAllocator(const STLAllocator<U, _align>& alloc) noexcept {}
template<typename U>
struct rebind {
typedef STLAllocator<U, align> other;
};
pointer address (reference x) const { return &x; }
const_pointer address (const_reference x) const { return &x; }
pointer allocate (size_type count, void const* /*hint*/ = 0) {
return (pointer)AN_MALLOC_ALIGNED(count * sizeof(T), align);
}
void deallocate (pointer p, size_type /*n*/) {
AN_FREE(p);
}
size_type max_size() const noexcept { return 0x7fffffff; }
void construct(pointer p, const T& val) { new (p) T(val); }
void destroy(pointer p) { p->~T(); }
};
} |
import { openExternalUrl } from "@padloc/core/src/platform";
import { sanitize } from "dompurify";
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators.js";
import { unsafeHTML } from "lit/directives/unsafe-html.js";
import { markdownToLitTemplate } from "../lib/markdown";
import { content, shared } from "../styles";
import { icons } from "../styles/icons";
@customElement("pl-rich-content")
export class RichContent extends LitElement {
@property()
content = "";
@property()
type: "plain" | "markdown" | "html" = "markdown";
@property({ type: Boolean })
sanitize = true;
static styles = [shared, icons, content];
updated() {
for (const anchor of [...this.renderRoot.querySelectorAll("a[href]")] as HTMLAnchorElement[]) {
anchor.addEventListener("click", (e) => {
e.preventDefault();
if (anchor.getAttribute("href")?.startsWith("#")) {
const el = this.renderRoot.querySelector(anchor.getAttribute("href")!);
el?.scrollIntoView();
} else {
openExternalUrl(anchor.href);
}
});
}
}
render() {
switch (this.type) {
case "markdown":
return markdownToLitTemplate(this.content, this.sanitize);
case "html":
const content = this.sanitize
? sanitize(this.content, { ADD_TAGS: ["pl-icon"], ADD_ATTR: ["icon"] })
: this.content;
return html`${unsafeHTML(content)}`;
default:
return html`${this.content}`;
}
}
} |
import { Button } from '../Button';
import { SubTitle } from '../SubTitle';
import { ContactFuncionality } from './contact';
import styles from './styles.module.scss';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import { FaPhone, FaEnvelope, FaMapMarkedAlt, FaPaperPlane } from 'react-icons/fa';
import { LatLngExpression } from 'leaflet';
import L from 'leaflet';
import customIconUrl from '../../../public/map-marker.png';
const customIcon = new L.Icon({
iconUrl: customIconUrl,
iconSize: [32, 32],
iconAnchor: [16, 32],
popupAnchor: [0, -32],
});
export function Contact() {
const { form, sendEmail, error, isLoading, handlePhone } = ContactFuncionality();
const position: LatLngExpression = [-22.77709907415005, -42.967335232971834];
return (
<div id='contact'>
<SubTitle title="Contato" subtitle="Entre em contato" />
<div data-aos="zoom-out-left" className={`container m-auto row ${styles.contact}`} id='contact'>
<div className='col-md-6 d-flex flex-column gap-5 m-auto container mt-5'>
<div className={`mb-4 d-flex wrap justify-content-center gap-4 ${styles.contactContainer}`}>
<div className='d-flex gap-3'>
<FaPhone className={styles.icon} />
<div>
<h5 className='fw-bold'>Número</h5>
<h6>21 9 6475-7806</h6>
</div>
</div>
<div className='d-flex gap-3'>
<FaEnvelope className={styles.icon} />
<div>
<h5 className='fw-bold'>Email</h5>
<h6>danteopzz@hotmail.com</h6>
</div>
</div>
<div className='d-flex gap-3'>
<FaMapMarkedAlt className={styles.icon} />
<div>
<h5 className='fw-bold'>Localização</h5>
<h6>Brasil - Rio de Janeiro</h6>
</div>
</div>
</div>
<form ref={form} onSubmit={sendEmail} className='d-flex flex-column gap-4'>
<div className='row'>
<div className={`col-md-6 ${styles.inputBox}`}>
<input type="text" placeholder='Nome' name='nome' />
{error.nome && <span className='text-danger mt-2'>Preencha este campo</span>}
</div>
<div className={`col-md-6 ${styles.inputBox}`}>
<input type="email" placeholder='Email' name='email' />
{error.email && <span className='text-danger mt-2'>Preencha este campo</span>}
</div>
</div>
<div className={styles.inputBox}>
<input type="tel" placeholder='Número' name='numero' onKeyUp={(e) => handlePhone(e)} maxLength={15} />
{error.numero && <span className='text-danger mt-2'>Preencha este campo</span>}
</div>
<div className={styles.inputBox}>
<textarea placeholder='Mensagem' name='mensagem' />
{error.mensagem && <span className='text-danger mt-2'>Preencha este campo</span>}
</div>
<div className='m-auto'>
<Button type='submit'>
{isLoading ?
<div className="spinner-border text-light" role="status">
</div>
: <span>Enviar <FaPaperPlane className="text-light ms-1" /></span>}
</Button>
</div>
</form>
</div>
<div className={`${styles.map} col-md-6 m-auto`}>
<MapContainer center={position} zoom={12} style={{ height: "400px" }}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={position} icon={customIcon}>
<Popup>Localização</Popup>
</Marker>
</MapContainer>
</div>
</div>
</div>
);
} |
import { PushBack } from "./generics";
export type WeaponType = "sword" | "spear" | "rod" | "shield";
export type WeaponLevel = "1" | "2" | "3";
export interface BaseWeaponType {
name: string;
assetName: string;
level: WeaponLevel;
type: WeaponType;
}
export const isSword = (weaponType: PlayerWeapon): weaponType is Sword => {
return weaponType.type === "sword";
};
export const isSpear = (weaponType: PlayerWeapon): weaponType is Spear => {
return weaponType.type === "spear";
};
export const isRod = (weaponType: PlayerWeapon): weaponType is Rod => {
return weaponType.type === "rod";
};
export const isShield = (weaponType: PlayerWeapon): weaponType is Shield => {
return weaponType.type === "shield";
};
export interface SwordAttackAttributes {
damage: number;
pushBack: PushBack;
}
export interface Sword extends BaseWeaponType {
attributes: SwordAttackAttributes;
type: "sword";
}
export interface SpearAttackAttributes {
damage: number;
range: number;
velocity: number;
pushBack: PushBack;
}
export interface Spear extends BaseWeaponType {
attributes: SpearAttackAttributes;
type: "spear";
}
export interface RodAttackAttributes {
damage: number;
pushBack: PushBack;
}
export interface Rod extends BaseWeaponType {
attributes: RodAttackAttributes;
type: "rod";
}
export interface ShieldAttributes {
duration: number;
direction: "left" | "right";
pushBack: PushBack;
scale: number;
}
export interface Shield extends BaseWeaponType {
attributes: ShieldAttributes;
type: "shield";
}
export type PlayerWeapon = Sword | Spear | Rod | Shield; |
import "./styles.css"
import "./App.css"
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Header from "./components/Header";
import Home from "./Home";
import About from "./components/About";
import Contact from "./components/Contact";
import Products from "./components/Products";
import Footer from "./components/Footer";
import NoPage from "./NoPage";
import Careers from "./components/Careers";
import Starters from "./Products/Starters";
import ControlSwitches from "./Products/ControlSwitches";
import LimitSwitches from "./Products/LimitSwitches";
import SubmersiblePanels from "./Products/SubmersiblePanels";
import Contactors from "./Products/Contactors";
import PlugsSockets from "./Products/PlugsSockets";
import PanelAccessories from "./Products/PanelAccessories";
import DirectOnlineStarters from "./Products/DirectOnlineStarters";
import StarDeltaStarters from "./Products/StarDeltaStarters";
import ReverseForwardStarters from "./Products/ReverseForwardStarters";
import { useEffect } from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import ProductDetail from "./components/ProductDetail";
export function useTitle(title) {
useEffect(() => {
const prevTitle = document.title
document.title = title
return () => {
document.title = prevTitle
}
})
}
export default function App() {
return (
<BrowserRouter>
< Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/Contact" element={<Contact />} />
<Route path="/About" element={<About />} />
<Route path="/Products" element={<Products />} />
<Route path="/Careers" element={<Careers />} />
<Route path="/Product/Starters" element={<Starters />} />
<Route path="/Product/ControlSwitches" element={< ControlSwitches />} />
<Route path="/Product/SubmersiblePanels" element={< SubmersiblePanels />} />
<Route path="/Product/PanelAccessories" element={<PanelAccessories />} />
<Route path="/Product/LimitSwitches" element={<LimitSwitches />} />
<Route path="/Product/PlugsSockets" element={<PlugsSockets />} />
<Route path="/Product/Contactors" element={<Contactors />} />
<Route path="/ProductDetail/:id" element={<ProductDetail />} />
<Route path="/Product/Starters/DirectOnlineStarters" element={<DirectOnlineStarters />} />
<Route path="/Product/Starters/StarDeltaStarters" element={<StarDeltaStarters />} />
<Route path="/Product/Starters/ReverseForwardStarters" element={<ReverseForwardStarters />} />
<Route path="*" element={<NoPage />} />
</Routes>
<Footer />
</BrowserRouter>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />); |
<?xml version="1.0" encoding="utf-8"?>
<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" xmlns:ui="http://projectmallard.org/ui/1.0/" type="topic" style="task" id="net-install-flash" xml:lang="ca">
<info>
<link type="guide" xref="net-browser"/>
<revision pkgversion="3.4.0" date="2012-02-20" status="final"/>
<revision version="18.04" date="2018-01-23" status="review"/>
<credit type="author">
<name>Phil Bull</name>
<email>philbull@gmail.com</email>
</credit>
<credit type="editor">
<name>Equip de documentació de l'Ubuntu</name>
</credit>
<desc>Us caldrà instal·lar el Flash per poder visualitzar correctament alguns llocs web, aquells que mostrin vídeos i pàgines web interactives.</desc>
<include xmlns="http://www.w3.org/2001/XInclude" href="legal.xml"/>
</info>
<title>Instal·leu el connector Flash</title>
<p>El Flash és un <em>connector</em> per al vostre navegador que us permet veure vídeos i fer ús de pàgines web interactives en alguns llocs webs. Tot i que cada vegada l'HTML5, que és una solució més moderna, és més present, encara hi ha alguns llocs webs que no funcionen sense Flash.</p>
<p>Si no teniu instal·lat el Flash, molt probablement veureu un missatge informant-vos que el necessiteu quan visiteu algun lloc web. El Flash està disponible en descàrrega gratuïta (però no és codi obert) per a la majoria de navegadors web.</p>
<note style="warning">
<p>Adobe va anunciar que deixarien d'actualitzar i distribuir el Flash Player a finals de 2020. Per aquesta raó, per motius de seguretat, no hauríeu d'utilitzar el connector de Flash passat 2020.</p>
</note>
<p>Hi ha dues classes de connectors disponibles:</p>
<list>
<item>
<p><em>NPAPI</em> per al <app>Firefox</app> i d'altres navegadors web basats en Gecko</p>
</item>
<item>
<p><em>PPAPI</em> per a <app>Chromium</app> i altres navegadors web basat en Blink, incloent-hi l'<app>Opera</app> i el <app>Vivaldi</app></p>
</item>
</list>
<note>
<p>El navegador <app>Google Chrome</app> ja incorpora el Flash i no cal instal·lar-hi cap connector.</p>
</note>
<section id="flashplugin-installer">
<title>flashplugin-installer</title>
<p>El paquet <app>flashplugin-installer</app> proveeix el connector NPAPI per al Firefox. <link href="apt:flashplugin-installer">Instaŀleu el paquet</link> i reinicieu el vostre navegador.</p>
</section>
<section id="adobe-flashplugin">
<title>adobe-flashplugin</title>
<p>El paquet <app>adobe-flashplugin</app> proveeix els connectors NPAPI i PPAPI, és a dir, que proveeix el Flash per navegadors web tant de tipus Firefox com per tipus Chromium.</p>
<steps>
<item>
<p>Assegureu-vos que <link xref="addremove-sources#canonical-partner"> està activat el repositori Canonical Partner</link>.</p>
</item>
<item>
<p>Instaŀla el paquet <link href="apt:adobe-flashplugin">adobe-flashplugin</link>.</p>
</item>
<item>
<p>Reinicieu el vostre navegador.</p>
</item>
</steps>
</section>
<section id="browser-plugin-freshplayer-pepperflash">
<title>browser-plugin-freshplayer-pepperflash</title>
<p>Algunes característiques del connector PPAPI, com l'acceleració 3D i el video premium DRM, no estan disponibles el connector NPAPI. Si useu el Firefox o algun altre navegador basat en Gecko i us cal usar aquestes caractewrístiques, podeu instaŀŀar el paquet <app>browser-plugin-freshplayer-pepperflash</app>. És un adaptador que fa que el Firefox usi el connector PPAPI.</p>
<steps>
<item>
<p>Assegureu-vos que <app>adobe-flashplugin</app> està instal·lat.</p>
</item>
<item>
<p>Obriu una finestra de terminal prement <keyseq><key>Ctrl</key><key>Alt</key><key>T</key></keyseq> i instal·leu el paquet <app>browser-plugin-freshplayer-pepperflash</app>:</p>
<p><cmd its:translate="no">sudo apt install browser-plugin-freshplayer-pepperflash</cmd></p>
</item>
<item>
<p>Reinicieu el vostre navegador.</p>
</item>
</steps>
</section>
<section id="snap">
<title>El navegador web proveït per un paquet snap</title>
<p>Si useu el <app>Firefox</app> o el <app>Chromium</app> com a snap, els paquets descrits abans no us seran d'ajuda. En el seu lloc, us suggerim a continuació les passes per tenir disponible el Flash.</p>
<p>Si us plau, teniu en compte que se suposa que sempre teniu la darrera versió de Flash. Això vol dir que us cal repetir els punts 2 - 7 de tant en tant per continuar accedint als serveis web que requereixen el Flash.</p>
<steps ui:expanded="false">
<title>Firefox com a snap</title>
<item>
<p its:locNote="Translators: Don't translate 'plugins' - it's the name of a folder on the file system.">Crea una carpeta a <sys>plugins</sys>:</p>
<p><cmd its:translate="no">mkdir ~/snap/firefox/common/.mozilla/plugins</cmd></p>
</item>
<item>
<p>Vés a <link href="https://get.adobe.com/flashplayer/">https://get.adobe.com/flashplayer/</link>.</p>
</item>
<item>
<p>Descarregueu el fitxer <sys>.tar.gz</sys> per a Linux.</p>
</item>
<item>
<p>Aneu a la carpeta de baixades</p>
</item>
<item>
<p>Extraieu els arxius del fitxer baixat:</p>
<p><cmd its:translate="no">tar xf flash_player*</cmd></p>
</item>
<item>
<p>Copia <sys>libflashplayer.so</sys> a la carpeta <sys>plugins</sys>:</p>
<p><cmd its:translate="no">cp libflashplayer.so ~/snap/firefox/common/.mozilla/plugins</cmd></p>
</item>
<item>
<p>Reinicieu el vostre navegador.</p>
</item>
</steps>
<steps ui:expanded="false">
<title>Chromium com a snap</title>
<item>
<p its:locNote="Translators: Don't translate 'lib' - it's the name of a folder on the file system.">Crea la carpeta <sys>lib</sys>:</p>
<p><cmd its:translate="no">mkdir ~/snap/chromium/current/.local/lib</cmd></p>
</item>
<item>
<p>Vés a <link href="https://get.adobe.com/flashplayer/">https://get.adobe.com/flashplayer/</link>.</p>
</item>
<item>
<p>Descarregueu el fitxer <sys>.tar.gz</sys> per a Linux.</p>
</item>
<item>
<p>Aneu a la carpeta de baixades</p>
</item>
<item>
<p>Extraieu els arxius del fitxer baixat:</p>
<p><cmd its:translate="no">tar xf flash_player*</cmd></p>
</item>
<item>
<p>Copia <sys>libpepflashplayer.so</sys> a la carpeta <sys>lib</sys>:</p>
<p><cmd its:translate="no">cp libpepflashplayer.so ~/snap/chromium/current/.local/lib</cmd></p>
</item>
<item>
<p>Reinicieu el vostre navegador.</p>
</item>
</steps>
</section>
</page> |
class_name RstyVector2
var x: float
var y: float
func _init(x: float = 0, y: float = 0) -> void:
self.x = x
self.y = y
func distance(x1: float, y1: float, x2: float, y2: float) -> float:
var a = x2 - x1
var b = y2 - y1
return sqrt(pow(a, 2) + pow(b, 2))
func get_x() -> float:
return self.x
func set_x(value: float) -> void:
self.x = value
func get_y() -> float:
return self.y
func set_y(value: float) -> void:
self.y = value
func set_angle(angle: float) -> void:
var length = self.get_length()
self.x = cos(angle) * length
self.y = sin(angle) * length
func get_angle() -> float:
return atan2(self.y, self.x)
func get_length() -> float:
return sqrt(pow(self.x, 2) + pow(self.y, 2))
func set_length(length: float) -> void:
var angle = self.get_angle()
self.x = cos(angle) * length
self.y = sin(angle) * length
func add(v2: RstyVector2) -> RstyVector2:
return RstyVector2.new(self.get_x() + v2.get_x(), self.get_y() + v2.get_y())
func subtract(v2: RstyVector2) -> RstyVector2:
return RstyVector2.new(self.get_x() - v2.get_x(), self.get_y() - v2.get_y())
func multiply(scalar: float) -> RstyVector2:
return RstyVector2.new(self.get_x() * scalar, self.get_y() * scalar)
func divide(scalar: float) -> RstyVector2:
return RstyVector2.new(self.get_x() / scalar, self.get_y() / scalar)
func add_to(v2: RstyVector2) -> void:
self.x += v2.get_x()
self.y += v2.get_y()
func subtract_from(v2: RstyVector2) -> void:
self.x -= v2.get_x()
self.y -= v2.get_y()
func multiply_by(value: float) -> void:
self.x *= value
self.y *= value
func divide_by(value: float) -> void:
self.x /= value
self.y /= value
func get_godot_vector() -> Vector2:
return Vector2(self.x, self.y) |
# Apache SeaTunnel
<img src="https://seatunnel.apache.org/image/logo.png" alt="seatunnel logo" height="200px" align="right" />
[](https://github.com/apache/seatunnel/actions/workflows/backend.yml)
[](https://join.slack.com/t/apacheseatunnel/shared_invite/zt-123jmewxe-RjB_DW3M3gV~xL91pZ0oVQ)
[](https://twitter.com/ASFSeaTunnel)
---
[](README.md)
SeaTunnel was formerly named Waterdrop , and renamed SeaTunnel since October 12, 2021.
---
So, What we are?
An open-source web console to manage your seatunnel-script, and would push them to any scheduling-system easily.
Click it if your want to know more about our design. 👉🏻[Design](https://github.com/apache/seatunnel/issues/1947)
## How to start
Notice: Some details please refer to the docs/QuickStart.md
### 1 Preparing the Apache SeaTunnel environment
Because SeaTunnel Web uses the SeaTunnel Java Client to submit jobs, running SeaTunnel Web requires preparing a SeaTunnel Zeta Engine service first.
Based on the usage requirements of SeaTunnel Zeta Engine, the SeaTunnel Client node that submits the job must have the same operating system and installation directory structure as the SeaTunnel Server node that runs the job. Therefore, if you want to run SeaTunnel Web in IDEA, you must install and run a SeaTunnel Zeta Engine Server on the same machine as the IDEA.
Don't worry, the next steps will tell you how to correctly install SeaTunnel Zeta Engine Server in different situations.
### 2 Run SeaTunnel Web in IDEA
If you want to deploy and run SeaTunnel Web, Please turn to [3 Run SeaTunnel Web In Server](#3 Run SeaTunnel Web In Server)
#### 2.1 Install SeaTunnel Zeta Engine Server
You have two ways to get the SeaTunnel installer package. Build from source code or download from the SeaTunnel website.
**The SeaTunnel version used here is only for writing this document to show you the process used, and does not necessarily represent the correct version. SeaTunnel Web and SeaTunnel Engine have strict version dependencies, and you can confirm the specific version mapping through xxx. Now only support build SeaTunnel Web and Seatunnel Zeta Engine in local, Because it is necessary to ensure that the seatunnel-api in SeaTunnel Web and the version in SeaTunnel Zeta Engine are the same.**
##### 2.1.1 Build from source code and deploy
* Get the source package from https://seatunnel.apache.org/download or https://github.com/apache/seatunnel.git
* Build installer package use maven command `./mvnw -U -T 1C clean install -DskipTests -D"maven.test.skip"=true -D"maven.javadoc.skip"=true -D"checkstyle.skip"=true -D"license.skipAddThirdParty" `
* After building, it is necessary to set an environment variable `ST_WEB_BASEDIR_PATH` to represent the location of the data source shade package. A custom class loader will be used to load the data source shade package based on this. For example: `ST_WEB_BASEDIR_PATH=/seatunnel-web-dist/target/apache-seatunnel-web-1.0.0-SNAPSHOT/`
* Then you can get the installer package in `${Your_code_dir}/seatunnel-dist/target`, For example:`apache-seatunnel-2.3.3-SNAPSHOT-bin.tar.gz`
* Run `tar -zxvf apache-seatunnel-2.3.3-SNAPSHOT-bin.tar.gz` to unzip the installer package.
* Run `cd apache-seatunnel-2.3.3-SNAPSHOT & sh bin/seatunnel-cluster.sh -d` to run the SeaTunnel Zeta Engine Server.
* Please confirm that port 5801 is being monitored by the SeaTunnelServer process.
##### 2.1.2 Download installer package and deploy
The other way to install SeaTunnel Zeta Engine Server is download the installer package from https://seatunnel.apache.org/download and deploy.
* Download and install connector plugin(Some third-party dependency packages will also be automatically downloaded and installed during this process, such as hadoop jar). You can get the step from https://seatunnel.apache.org/docs/2.3.2/start-v2/locally/deployment.
* Run `cd apache-seatunnel-2.3.2 & sh bin/seatunnel-cluster.sh -d` to run the SeaTunnel Zeta Engine Server.
#### 2.2 Init database
1. Edit `seatunnel-server/seatunnel-app/src/main/resources/script/seatunnel_server_env.sh` file, Complete the installed database address, port, username, and password. Here is an example:
```
export HOSTNAME="localhost"
export PORT="3306"
export USERNAME="root"
export PASSWORD="123456"
```
2. Run init shell `sh seatunnel-server/seatunnel-app/src/main/resources/script/init_sql.sh` If there are no errors during operation, it indicates successful initialization.
#### 2.3 Build the project
```shell
sh build.sh code
```
#### 2.4 Config application and Run SeaTunnel Web Backend Server
1. Edit `seatunnel-server/seatunnel-app/src/main/resources/application.yml` Fill in the database connection information

2. Copy `apache-seatunnel-2.3.3-SNAPSHOT/connectors/plugin-mapping.properties` file to `seatunnel-web/seatunnel-server/seatunnel-app/src/main/resources` dir.
3. Run `seatunnel-server/seatunnel-app/src/main/java/org/apache/seatunnel/app/SeatunnelApplication.java` If there are no errors reported, the seatunnel web backend service is successfully started. Notice that, you must set `-DSEATUNNEL_HOME=${your_seatunnel_install_path}` like this:

Because the data source plugin is dynamically loaded, it is necessary to set relevant environment variables:

#### 2.3 Run SeaTunnel Web Front End
```
cd seatunnel-ui
npm install
npm run dev
```
If there are no issues with the operation, the following information will be displayed:
```
➜ Local: http://127.0.0.1:5173/
➜ Network: use --host to expose
➜ press h to show help
```
Accessing in a browser http://127.0.0.1:5173/login Okay, the default username and password are admin/admin.
### 3 Run SeaTunnel Web In Server
To run SeaTunnel Web on the server, you need to first have a SeaTunnel Zeta Engine Server environment. If you do not already have one, you can refer to the following steps for deployment.
#### 3.1 Deploy SeaTunnel Zeta Engine Server In Server Node
You have two ways to get the SeaTunnel installer package. Build from source code or download from the SeaTunnel website.
**The SeaTunnel version used here is only for writing this document to show you the process used, and does not necessarily represent the correct version. SeaTunnel Web and SeaTunnel Engine have strict version dependencies, and you can confirm the specific version mapping through xxx**
##### 3.1.1 Build from source code
* Get the source package from https://seatunnel.apache.org/download or https://github.com/apache/seatunnel.git
* Build installer package use maven command `./mvnw -U -T 1C clean install -DskipTests -D"maven.test.skip"=true -D"maven.javadoc.skip"=true -D"checkstyle.skip"=true -D"license.skipAddThirdParty" `
* Then you can get the installer package in `${Your_code_dir}/seatunnel-dist/target`, For example:`apache-seatunnel-2.3.3-SNAPSHOT-bin.tar.gz`
##### 3.1.2 Download installer package
The other way to get SeaTunnel Zeta Engine Server installer package is download the installer package from https://seatunnel.apache.org/download and install plugins online.
* Download and install connector plugin(Some third-party dependency packages will also be automatically downloaded and installed during this process, such as hadoop jar). You can get the step from https://seatunnel.apache.org/docs/2.3.2/start-v2/locally/deployment.
* After completing the previous step, you will receive an installation package that can be used to install SeaTunnel Zeta Engine Server on the server. Run `tar -zcvf apache-seatunnel-2.3.3-SNAPSHOT-bin.tar.gz apache-seatunnel-2.3.3-SNAPSHOT`
##### 3.1.3 Deploy SeaTunnel Zeta Server
After 3.1.1 or 3.1.2 you can get an installer package `apache-seatunnel-2.3.3-SNAPSHOT-bin.tar.gz`, Then you can copy it to you server node and deploy reference https://seatunnel.apache.org/docs/seatunnel-engine/deployment.
##### 3.1.4 Deploy SeaTunnel Zeta Client In SeaTunnel Web Run Node
If you use SeaTunnel Web, you need deploy a SeaTunnel Zeta Client in the SeaTunnel Web run Node. **If you run SeaTunnel Zeta Server and SeaTunnel Web in same node, you can skip this step**.
* Copy `apache-seatunnel-2.3.3-SNAPSHOT-bin.tar.gz` to the SeaTunnel Web node and unzip it **in the same path of SeaTunnel Zeta Server node**.
* Set `SEATUNNEL_HOME` to environment variable like SeaTunnel Zeta Server node.
* Config `hazelcast-client.yaml` reference https://seatunnel.apache.org/docs/seatunnel-engine/deployment#6-config-seatunnel-engine-client
* Run `$SEATUNNEL_HOME/bin/seatunnel.sh --config $SEATUNNEL_HOME/config/v2.batch.config.template`, If this job run finished, it indicates successful client deployment.
#### 3.2 Build SeaTunnel Web Install Package From Code
```
cd seatunnel-web
sh build.sh code
```
Then you can find the installer package in dir `seatunnel-web/seatunnel-web-dist/target/apache-seatunnel-web-${project.version}.tar.gz`.
#### 3.3 Install
Copy the `apache-seatunnel-web-${project.version}.tar.gz` to your server node and unzip it.
```shell
tar -zxvf apache-seatunnel-web-${project.version}.tar.gz
```
#### 3.4 Init database
1. Edit `apache-seatunnel-web-${project.version}/script/seatunnel_server_env.sh` file, Complete the installed database address, port, username, and password. Here is an example:
```
export HOSTNAME="localhost"
export PORT="3306"
export USERNAME="root"
export PASSWORD="123456"
```
2. Run init shell `sh apache-seatunnel-web-${project.version}/script/init_sql.sh` If there are no errors during operation, it indicates successful initialization.
#### 3.5 Config application and Run SeaTunnel Web Backend Server
* Edit `apache-seatunnel-web-${project.version}/conf/application.yml` Fill in the database connection information and DS interface related information in the file.

* Copy `$SEATUNNEL_HOME/config/hazelcast-client.yaml` to `apache-seatunnel-web-${project.version}/conf/`
* Copy `apache-seatunnel-2.3.3-SNAPSHOT/connectors/plugin-mapping.properties` file to `apache-seatunnel-web-${project.version}/conf/` dir.
#### 3.6 Start SeaTunnel Web
```shell
cd apache-seatunnel-web-${project.version}
sh bin/seatunnel-backend-daemon.sh start
```
Accessing in a browser http://127.0.0.1:8801/ui/ Okay, the default username and password are admin/admin.
### How to use it
After all the pre-work is done, we can open the following URL: 127.0.0.1:7890(please replace it according to your configuration) to use it.
Now ,let me show you how to use it.
#### User manage

#### Task manage

#### Datasource manage

#### Virtual Tables manage
 |
//
// Repository.swift
// EmployerSearch
//
// Created by rinto.andrews on 26/01/2024.
//
import CoreData
protocol RepositoryProtocol {
func getEmployers(with query: String) async throws -> [Employer]
}
final class Repository: RepositoryProtocol {
let database: DataBaseRepositoryProtocol
let webservice: WebServiceRepositoryProtocol
init(database: DataBaseRepositoryProtocol,
webservice: WebServiceRepositoryProtocol ) {
self.database = database
self.webservice = webservice
}
func getEmployers(with query: String) async throws -> [Employer] {
if let query = try loadFromDatabase(query: query) {
if let response = try isQueryNotExpiredThenUseSavedResponse(query: query) {
return response
} else {
return try await fetchAndSaveToDatabase(query: query.query)
}
} else {
return try await fetchAndSaveToDatabase(query: query)
}
}
private func isQueryNotExpiredThenUseSavedResponse(query: QueryModel) throws -> [Employer]? {
if Date() < query.expiryDate {
let employers = try JSONDecoder().decode([Employer].self, from: query.response)
return employers
}
return nil
}
private func loadFromDatabase(query: String) throws -> QueryModel? {
guard let query: Query = try database.fetchQuery(with: query.lowercased()),
let text: String = query.query,
let expieryDate = query.timestamp,
let response = query.response else { return nil }
return QueryModel(query: text, expiryDate: expieryDate, response: response)
}
private func fetchAndSaveToDatabase(query: String) async throws -> [Employer] {
let response = try await webservice.getEmployersApi(with: query)
let employers = try JSONDecoder().decode([Employer].self, from: response)
try database.save(queryModel: QueryModel(query: query, expiryDate: Date().addingTimeInterval(7*24*60*60), response: response))
return employers
}
} |
{% load get_group %}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'main/styles.css' %}">
<title>RIET eCanteen | Dishes</title>
</head>
<body style="background-image: url('https://media.istockphoto.com/photos/hexagonal-honeycomb-abstract-3d-background-picture-id905438692?b=1&k=20&m=905438692&s=170667a&w=0&h=pTjmS2z305vjoU2j-yWgUwEK_mdK-F8IH5yGtVsbDAY=');background-size: cover;background-repeat: no-repeat;">
<nav class="navbar fixed-top navbar-expand-lg navbar-dark " style="background-color: black;">
<a class="navbar-brand" href="#">
<img src="https://riet.net.in/wp-content/uploads/2019/03/Logo-RIET-1024x155.png" width="280" height="30" class="d-inline-block align-top" alt="">
</a>
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav mr-auto">
</ul>
<ul class="navbar-nav ml-auto">
<li><a href="{% url 'main:home' %}" class="btn mr-2 text-light">Home</a></li>
{% if user.is_authenticated %}
{% if request.user|has_group:"admin_owner" %}
<li><a href="{% url 'main:admin_dashboard' %}" class="btn mr-2 text-light">DashBoard</a></li>
<li>
<form class="logout-link" action="{% url 'accounts:logout' %}" method="post">
{% csrf_token %}
<button type="submit" class="btn mr-2">Logout</button>
</form>
</li>
{% else %}
<li><a href="{% url 'main:cart' %}" class="btn mr-2 text-light">My Cart🛒</a></li>
<li><a href="{% url 'main:order_details' %}" class="btn mr-2 text-light">Your Orders</a></li>
<li>
<form class="logout-link" action="{% url 'accounts:logout' %}" method="post">
{% csrf_token %}
<button type="submit" class=" btn btn-outline-success mr-2">Logout</button>
</form>
</li>
{% endif %}
{% else %}
<li><a href="{% url 'accounts:login' %}" class="btn mr-2 text-light">Login</a></li>
<li><a href="{% url 'accounts:signup' %}" class="btn mr-2 text-light">SignUp</a></li>
{% endif %}
</ul>
</div>
</nav>
<div class="dishes" style="background-image: url('https://media.istockphoto.com/photos/hexagonal-honeycomb-abstract-3d-background-picture-id905438692?b=1&k=20&m=905438692&s=170667a&w=0&h=pTjmS2z305vjoU2j-yWgUwEK_mdK-F8IH5yGtVsbDAY=');">
<!--Main layout-->
<main class="mt-3 pt-4 main">
<div class="container dark-grey-text">
<div class="row wow fadeIn">
<div class="col-sm-4">
<img src="{{ item.image.url }}" style="height: 250px; width:350px; display: block; margin-left: auto; margin-right: auto;" class="img-fluid mt-4" alt="" >
</div>
<div class="col-md-6 mb-4 information">
<!--Content-->
<div class="p-4 content">
<div class="mt-0">
<h2>{{ item.title }}</h2>
</div>
<div class="lead">
{% if item.description %}
<h5>{{ item.description }}<span class="badge badge-{{ item.label_colour }} ml-2">{{ item.labels }}</span></h5>
{% endif %}
<h3>₹{{ item.price }} per order of {{ item.pieces}} pieces</h3>
<h4>{{ item.instructions }}</h4>
</div>
<a href="{% url 'main:add-to-cart' item.slug %}" class="btn btn-primary btn-md my-0 p">Add to cart</a>
</div>
</div>
</div>
<hr>
</div>
</main>
<div class="container">
<h1 class="text-center">Reviews</h1>
<form action="{% url 'main:add_reviews' %}" method="POST" class="mb-3">
{% csrf_token %}
<div class="row">
<div class="col-sm-11">
<input type="text" name="review" class="form-control" placeholder="Enter Your Review">
<input type="hidden" name="rslug" class="form-control" value="{{item.slug}}">
</div>
<div class="col-sm-1">
<button type="submit" class="btn btn-danger">Submit</button>
</div>
</div>
</form>
{% for review in reviews %}
<div style="height:100px;" class="main-reviews card bg-light mb-3">
<div style="padding:1.0rem;" class="card-body">
<div class="user_details" style="display: flex; border-bottom: 1px solid rgb(31, 30, 30);align-items: baseline;justify-content: space-between;flex-direction: row;">
<p class="mr-3">{{ review.user.username }} </p>
<h8 class="mt-2">{{ review.posted_on }}</h8>
</div>
<h5>{{ review.review }}</h5>
</div>
</div>
{% endfor %}
</div >
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
$('.carousel').carousel();
</script>
<footer style="margin-top: 190px;" class="text-center text-lg-start">
<!-- Copyright -->
<div class="text-light text-center p-2 bg-dark">
© 2022 Copyright:
<a style="text-decoration:none;" class="text-light" href="https://riet.edu.in/">Rajadhani Institute of Engineering & Technology</a>
</div>
<!-- Copyright -->
</footer> |
from django.test import TestCase
from django.contrib.auth.hashers import check_password
from django.db import IntegrityError
from ..models import User, Team
from .factories.user_factories import *
# Create your tests here.
class UserModelTest(TestCase):
def test_user_exist(self):
user = User.objects.all()
self.assertEqual(user.count(), 0)
def test_create_new_user(self):
user = UserFactory(email='probe@mail.com')
nickname = 'probe'
users_from_db = User.objects.all()
self.assertEqual(len(users_from_db), 1)
user_created = users_from_db[0]
self.assertEqual(user.email, user_created.email)
self.assertEqual(user.team.id, user_created.team.id)
self.assertEqual(nickname, user_created.nickname)
self.assertTrue(check_password('1234', user_created.password))
def test_create_new_superuser(self):
user = User.objects.create_superuser(email='super@mail.com', password='1234')
users_from_db = User.objects.all()
self.assertEqual(len(users_from_db), 1)
user_created = users_from_db[0]
self.assertEqual(user.email, user_created.email)
self.assertEqual(user.team.id, user_created.team.id)
self.assertTrue(user_created.is_superuser)
self.assertTrue(user_created.is_staff)
self.assertTrue(check_password('1234', user_created.password))
def test_validate_unique_fields(self):
UserFactory(email='probe@mail.com')
with self.assertRaises(IntegrityError):
user2 = User()
user2.email = 'probe@mail.com'
user2.set_password('1234')
user2.save()
def test_required_team_fields(self):
with self.assertRaises(IntegrityError):
team = Team()
team.save()
def test_delete_team(self):
team = TeamFactory(id=2)
UserFactory(team=team)
default_team = Team.objects.get(pk=1)
user_from_db = User.objects.first()
self.assertEqual(user_from_db.team.id, team.id)
team.delete()
user_from_db = User.objects.first()
self.assertEqual(user_from_db.team, default_team) |
import React from 'react';
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { ThemeDecorator } from 'shared/config/storybook/ThemeDecorator/ThemeDecorator';
import { Theme } from 'app/providers/ThemeProvider';
import { Avatar } from './Avatar';
import AvatarImg from './storybook.jpg';
export default {
title: 'shared/Avatar',
component: Avatar,
argTypes: {
backgroundColor: { control: 'color' },
},
} as ComponentMeta<typeof Avatar>;
const Template: ComponentStory<typeof Avatar> = (args) => <Avatar {...args} />;
export const Primary = Template.bind({});
Primary.args = {
src: AvatarImg,
alt: 'Avatar',
};
export const PrimarySmall = Template.bind({});
PrimarySmall.args = {
size: 50,
src: AvatarImg,
alt: 'Avatar',
};
export const Dark = Template.bind({});
Dark.args = {
src: AvatarImg,
alt: 'Avatar',
};
export const DarkSmall = Template.bind({});
DarkSmall.args = {
size: 50,
src: AvatarImg,
alt: 'Avatar',
};
Dark.decorators = [ThemeDecorator(Theme.DARK)]; |
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="autor" content="Dayane">
<meta name="description" content="Revisão de HTML">
<meta name="Keywords" content="Sites, Web, Tags, HTML">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Primeira Página</title>
<style>
body {
background: linear-gradient(rgba(255, 255, 255, 0.879), rgba(255, 255, 255, 0.879)), url("bootstrap.jpg");
color: black;
}
</style>
</head>
<body link="#00ff00" vlink="#8a2be2" alink="#dc143c">
<header>
<h1 id="titulo1">Pesquisa sobre Design Responsivo: Técnicas e Frameworks</h1>
<br>
<nav>
<ul>
<li><a href="#introducao">INTRODUÇÃO</a></li>
<li><a href="#titulo2">CONCEITO DE DESIGN RESPONSIVO</a></li>
<li><a href="#titulo3">TÉCNICAS DE DESIGN RESPONSIVO</a></li>
<li><a href="#titulo4">FRAMEWORKS PARA DESIGN RESPONSIVO</a></li>
<li><a href="#titulo5">CONCLUSÃO</a></li>
<li><a href="#titulo6">REFERÊNCIAS</a></li>
</ul>
</nav>
<h3 id="introducao">INTRODUÇÃO</h3>
<br>
<p>
O design responsivo é uma abordagem crucial no desenvolvimento web moderno,
permitindo que sites e aplicativos se adaptem de forma fluida a uma variedade de dispositivos
e tamanhos de tela. Nesta pesquisa, exploramos as técnicas
e frameworks utilizados no design responsivo, examinando sua importância,
benefícios e impacto na experiência do usuário.
</p>
</header>
<section>
<h3 id="titulo2">CONCEITO DE DESIGN RESPONSIVO</h3>
<ol>
<li>
<h3>Definição e objetivos.</h3>
</li>
<p>
Uma das técnicas fundamentais do design responsivo é a criação de layouts flexíveis e fluidos. Essa
abordagem permite que os elementos da interface se ajustem automaticamente às diferentes dimensões da
tela, proporcionando uma experiência de usuário consistente e agradável em uma variedade de
dispositivos. Os layouts flexíveis e fluidos são a base sobre a qual muitos outros aspectos do design
responsivo são construídos. Vamos explorar em mais detalhes essa técnica:O design responsivo é uma
abordagem no desenvolvimento web que visa criar interfaces digitais que se adaptem de maneira fluida e
eficaz a uma ampla variedade de dispositivos e tamanhos de tela, incluindo desktops, laptops, tablets e
smartphones. Em outras palavras, um design responsivo permite que um site ou aplicativo se ajuste
automaticamente às dimensões da tela do dispositivo em que está sendo visualizado, garantindo uma
experiência de usuário consistente e agradável.
</p>
<p>
Objetivos do Design Responsivo: Consistência da Experiência do Usuário; Acessibilidade; Melhoria na Taxa
de Rejeição; SEO Aprimorado; Economia de Tempo e Recursos e Acompanhamento das Tendências Tecnológicas.
</p>
<li>
<h3>Necessidade de adaptação a dispositivos diversos.</h3>
</li>
<p>
Uma das técnicas fundamentais do design responsivo é a criação de layouts flexíveis e fluidos. Essa
abordagem permite que os elementos da interface se ajustem automaticamente às diferentes dimensões da
tela, proporcionando uma experiência de usuário consistente e agradável em uma variedade de
dispositivos. Os layouts flexíveis e fluidos são a base sobre a qual muitos outros aspectos do design
responsivo são construídos. Vamos explorar em mais detalhes essa técnica:O conceito de design responsivo
emerge da necessidade fundamental de proporcionar uma experiência de usuário consistente e otimizada em
uma ampla gama de dispositivos e tamanhos de tela. Com a proliferação de dispositivos móveis, tablets,
laptops, desktops e até mesmo dispositivos vestíveis, a criação de interfaces que se adaptem de forma
inteligente e harmoniosa se tornou uma prioridade para os desenvolvedores e designers de hoje.
</p>
<tag><img src="design-responsivo.png"></tag>
<li>
<h3>Importância na era mobile-first.</h3>
</li>
<p>
O conceito de design responsivo se tornou ainda mais relevante na era "mobile-first", que é uma
abordagem estratégica em que o design e desenvolvimento de uma interface começam pelo foco nos
dispositivos móveis, priorizando a experiência do usuário nesses dispositivos e expandindo para telas
maiores. Essa abordagem reflete a crescente importância dos dispositivos móveis na forma como as pessoas
acessam informações, serviços e interagem com a web.
</p>
</ol>
</section>
<br>
<section>
<h3 id="titulo3">TÉCNICAS DE DESIGN RESPONSIVO</h3>
<ol>
<li>
<h3>Layouts flexíveis e fluídos. </h3>
</li>
<p>
Uma das técnicas fundamentais do design responsivo é a criação de layouts flexíveis e fluidos. Essa
abordagem permite que os elementos da interface se ajustem automaticamente às diferentes dimensões da
tela, proporcionando uma experiência de usuário consistente e agradável em uma variedade de
dispositivos. Os layouts flexíveis e fluidos são a base sobre a qual muitos outros aspectos do design
responsivo são construídos. Vamos explorar em mais detalhes essa técnica:
</p>
<p>
Layouts flexíveis e fluidos referem-se ao uso de unidades de medida relativas e proporções flexíveis em
vez de medidas fixas (como pixels) para dimensionar elementos da interface. Isso permite que os
elementos se estendam e contraiam de acordo com o tamanho da tela do dispositivo, criando uma adaptação
suave e sem quebras.
</p>
<li>
<h3>Uso de unidades relativas (em, rem).</h3>
</li>
<p>
No design responsivo, o uso de unidades de medida relativas desempenha um papel fundamental na criação
de layouts flexíveis e adaptáveis a diferentes tamanhos de tela. Duas das unidades de medida relativas
mais comuns são "em" e "rem". Essas unidades permitem que os elementos da interface se dimensionem de
acordo com o contexto, proporcionando uma adaptação suave e consistente em dispositivos diversos. Vamos
explorar mais detalhadamente o uso dessas unidades relativas: Unidade "em" (em): A unidade "em" (em) é
relativa ao tamanho da fonte do elemento pai. Isso significa que 1 "em" é igual ao tamanho da fonte
definido para o elemento pai. Por exemplo, se o tamanho da fonte do elemento pai for 16 pixels, 1em será
igual a 16 pixels.
</p>
<li>
<h3>Media queries: breakpoints e adaptação condicional.</h3>
</li>
<p>
Media queries são uma técnica crucial no design responsivo, permitindo que os desenvolvedores e
designers criem layouts que se adaptem de forma específica a diferentes tamanhos de tela e dispositivos.
Os breakpoints em media queries indicam os pontos em que um design deve ser adaptado para acomodar
diferentes contextos de exibição. A adaptação condicional ocorre dentro desses breakpoints, permitindo
ajustes precisos na apresentação do conteúdo. Vamos explorar mais detalhadamente essas técnicas:
</p>
<ul>
<li>
Breakpoints: são pontos de interrupção definidos nas media queries, indicando quando um layout deve
ser adaptado para tamanhos de tela específicos. Eles são definidos em larguras de tela específicas e
são usados para modificar a apresentação do conteúdo, como reorganizar elementos, ajustar tamanhos
de fonte e alterar a disposição dos componentes.
</li>
<li>
Adaptação Condicional: Dentro de um breakpoint, ocorre a adaptação condicional, que envolve a
aplicação de regras CSS específicas para otimizar o layout para o tamanho de tela em questão. Isso
pode incluir reorganização de elementos, ocultação de conteúdo menos relevante, ajuste de tamanhos
de fonte e outros ajustes para garantir uma experiência de usuário ideal.
</li>
</ul>
<br>
<tag><img src="media.png"></tag>
<li>
<h3>Imagens responsivas e otimização.</h3>
</li>
<p>
A otimização de imagens e a implementação de imagens responsivas são aspectos cruciais do design
responsivo, uma vez que as imagens frequentemente compõem grande parte do conteúdo visual de um site ou
aplicativo. Garantir que as imagens se adaptem bem a diferentes dispositivos e resoluções é essencial
para proporcionar uma experiência de usuário consistente e de alto desempenho. Vamos explorar mais
detalhadamente essas técnicas:
</p>
<ul>
<li>
Imagens Responsivas: Imagens responsivas são imagens que se ajustam automaticamente ao tamanho da
tela do dispositivo em que estão sendo exibidas, sem perder qualidade ou causar problemas de layout.
Essa adaptação é alcançada por meio de regras CSS e, muitas vezes, do uso da propriedade max-width:
100%;
</li>
<li>
Otimização de Imagens: A otimização de imagens é o processo de reduzir o tamanho do arquivo de uma
imagem sem comprometer significativamente sua qualidade visual. Isso é crucial para garantir que as
páginas carreguem rapidamente, especialmente em conexões de internet mais lentas ou dispositivos
móveis.
</li>
</ul>
</ol>
</section>
<br>
<section>
<h3 id="titulo4">FRAMEWORKS PARA DESIGN RESPONSIVO</h3>
<ol>
<li>
<h3>Bootstrap.</h3>
</li>
<p>
O Bootstrap é um dos frameworks mais populares para o desenvolvimento de design responsivo e interfaces
web modernas. Desenvolvido pelo Twitter, o Bootstrap fornece uma base sólida de componentes e estilos
pré-construídos, facilitando a criação de layouts flexíveis e adaptáveis a diferentes tamanhos de tela.
</p>
<p>
O Bootstrap é um framework front-end de código aberto que oferece uma coleção de componentes, estilos e
utilitários CSS, juntamente com bibliotecas JavaScript, para acelerar o desenvolvimento web. Ele permite
que os desenvolvedores criem rapidamente layouts responsivos e atraentes sem a necessidade de escrever
código CSS personalizado do zero.
</p>
<br>
<!--<tag><img src="bootstrap.jpg"></tag>-->
<p>Recursos e Características do Bootstrap:</p>
<ul>
<li>
Grid System Responsivo: O sistema de grid do Bootstrap é a base para criar layouts responsivos. Ele
permite a divisão da tela em colunas, facilitando a criação de layouts flexíveis que se adaptam a
diferentes dispositivos.
</li>
<li>
Componentes Pré-Construídos: O Bootstrap oferece uma ampla gama de componentes prontos para uso,
como navegações, botões, formulários, modais, carrosséis, entre outros. Isso economiza tempo e
esforço no desenvolvimento.
</li>
<li>
Tipografia e Estilos de Base: O Bootstrap fornece estilos consistentes para tipografia, cores,
espaçamentos e outros elementos visuais, garantindo uma aparência coesa em toda a aplicação.
</li>
<li>
Responsividade Incorporada: O design responsivo está integrado ao DNA do Bootstrap. Os componentes e
o grid system são desenvolvidos para se ajustar naturalmente a diferentes tamanhos de tela.
</li>
<li>
Media Queries e Breakpoints: O Bootstrap usa breakpoints padrão para adaptar os layouts a diferentes
dispositivos, permitindo um design responsivo eficaz.
</li>
<li>
Flexbox e CSS Grid: Versões mais recentes do Bootstrap incorporaram Flexbox e CSS Grid, melhorando
ainda mais a flexibilidade do layout e a criação de designs responsivos.
</li>
<li>
Customização: Embora venha com estilos predefinidos, o Bootstrap é altamente customizável. Os
desenvolvedores podem escolher quais componentes e estilos usar e ajustá-los conforme necessário.
</li>
<li>
Suporte a JavaScript: Além do CSS, o Bootstrap inclui bibliotecas JavaScript que podem ser usadas
para criar interações e funcionalidades avançadas.
</li>
</ul>
<li>
<h3>Foundation.</h3>
</li>
<p>
Foundation é outro framework front-end popular para o desenvolvimento de design responsivo e criação de
interfaces web modernas. Assim como o Bootstrap, o Foundation oferece uma série de recursos
pré-construídos e estilos que facilitam a criação de layouts adaptáveis a diferentes dispositivos e
tamanhos de tela. O Foundation é um framework front-end de código aberto desenvolvido pela ZURB,
projetado para facilitar o desenvolvimento web responsivo e rápido. Ele oferece um conjunto de
ferramentas e componentes que ajudam os desenvolvedores a criar interfaces consistentes e atraentes em
diversos dispositivos.
</p>
<li>
<h3>Vantagens e Desvantagens dos frameworks.</h3>
</li>
<p>
O conceito de design responsivo se tornou ainda mais relevante na era "mobile-first", que é uma
abordagem estratégica em que o design e desenvolvimento de uma interface começam pelo foco nos
dispositivos móveis, priorizando a experiência do usuário nesses dispositivos e expandindo para telas
maiores. Essa abordagem reflete a crescente importância dos dispositivos móveis na forma como as pessoas
acessam informações, serviços e interagem com a web.
</p>
<p>
A escolha de usar um framework para design responsivo depende das necessidades do
projeto, das habilidades da equipe e das prioridades de desenvolvimento. Embora os frameworks
ofereçam benefícios significativos em termos de velocidade de desenvolvimento, consistência
visual e criação de layouts adaptáveis, eles também têm desvantagens potenciais em termos de
controle criativo, curva de aprendizado e desempenho. Ao escolher um framework, é importante
avaliar cuidadosamente as vantagens e desvantagens em relação aos objetivos e requisitos
específicos do projeto.
</p>
</ol>
</section>
<section>
<h3 id="titulo5">CONCLUSÃO</h3>
<p>
O design responsivo é essencial para oferecer uma experiência de usuário consistente e
agradável em dispositivos variados. As técnicas como layouts flexíveis, media queries e
otimização de imagens permitem que os websites se adaptem de maneira eficaz. Além disso, os
frameworks de design responsivo, como o Bootstrap e o Foundation, simplificam o processo de
desenvolvimento, agilizando a criação de interfaces adaptáveis. Com o aumento contínuo do uso
de dispositivos móveis, o design responsivo permanece como uma prática fundamental para
garantir a acessibilidade e usabilidade dos produtos digitais.
</p>
</section>
<section>
<h3 id="titulo6">REFERÊNCIAS</h3>
<p>
W3Schools. "Responsive Web Design - Introduction." Disponível em:
https://www.w3schools.com/css/css_rwd_intro.asp
</p>
<p>
MDN Web Docs. "Responsive Web Design Basics." Disponível em:
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design
</p>
<p>
Bootstrap. "The most popular HTML, CSS, and JS library in the world." Disponível em:
https://getbootstrap.com/
</p>
<p>
Foundation. "The most advanced responsive front-end framework in the world." Disponível em:
https://foundation.zurb.com/
</p>
<p>
Materialize. "A modern responsive front-end framework based on Material Design." Disponível
em: https://materializecss.com/
</p>
<p>
Bulma. "Modern CSS framework based on Flexbox." Disponível em: https://bulma.io
</p>
</section>
</body>
</html> |
<div id="wrapper">
<!-- Sidebar -->
<ul
class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion"
id="accordionSidebar"
>
<!-- Sidebar - Brand -->
<a
class="sidebar-brand d-flex align-items-center justify-content-center"
[routerLink]="['/main/home']"
>
<div class="sidebar-brand-text mx-3">Quản lý thu chi</div>
</a>
<!-- Divider -->
<hr class="sidebar-divider my-0" />
<li class="nav-item" [ngClass]="{ active: currentUrl == '/main/home' }">
<a class="nav-link" [routerLink]="['/main/home']">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span></a
>
</li>
<li
*ngFor="let i of menus"
class="nav-item"
[ngClass]="{
active:
currentUrl.split('/').slice(1, 3).join('') ==
i.route.split('/').slice(1, 3).join('')
}"
>
<a
class="nav-link collapsed"
href=""
data-toggle="collapse"
[attr.data-target]="'#' + i.route.split('/').join('')"
>
<i [class]="i.icon"></i>
<span>{{ i.name }}</span>
</a>
<div [id]="i.route.split('/').join('')" class="collapse">
<div class="bg-white py-2 collapse-inner rounded">
<a
*ngFor="let j of i.children"
class="collapse-item"
[routerLink]="[j.route]"
>{{ j.name }}</a
>
</div>
</div>
</li>
<!-- Sidebar Toggler (Sidebar) -->
<div class="text-center d-none d-md-inline">
<button class="rounded-circle border-0" id="sidebarToggle"></button>
</div>
<!-- Sidebar Message -->
</ul>
<!-- End of Sidebar -->
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<nav
class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow"
>
<!-- Sidebar Toggle (Topbar) -->
<button
id="sidebarToggleTop"
class="btn btn-link d-md-none rounded-circle mr-3"
>
<i class="fa fa-bars"></i>
</button>
<!-- Topbar Search -->
<form
class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search"
>
<!-- <div class="input-group">
<input type="text" class="form-control bg-light border-0 small" placeholder="Search for..."
aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" type="button">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div> -->
</form>
<!-- Topbar Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Nav Item - Search Dropdown (Visible Only XS) -->
<li class="nav-item dropdown no-arrow d-sm-none">
<a
class="nav-link dropdown-toggle"
href="#"
id="searchDropdown"
role="button"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
>
<i class="fas fa-search fa-fw"></i>
</a>
<!-- Dropdown - Messages -->
<div
class="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in"
aria-labelledby="searchDropdown"
>
<form class="form-inline mr-auto w-100 navbar-search">
<div class="input-group">
<input
type="text"
class="form-control bg-light border-0 small"
placeholder="Search for..."
aria-label="Search"
aria-describedby="basic-addon2"
/>
<div class="input-group-append">
<button class="btn btn-primary" type="button">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
</div>
</li>
<!-- Nav Item - Alerts -->
<div class="topbar-divider d-none d-sm-block"></div>
<!-- Nav Item - User Information -->
<li class="nav-item dropdown no-arrow">
<a
class="nav-link dropdown-toggle"
href="#"
id="userDropdown"
role="button"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
>
<span class="mr-2 d-none d-lg-inline text-gray-600 small">{{
User.Name
}}</span>
<img
class="img-profile rounded-circle"
src="assets/img/undraw_profile.svg"
/>
</a>
<!-- Dropdown - User Information -->
<div
class="dropdown-menu dropdown-menu-right shadow animated--grow-in"
aria-labelledby="userDropdown"
>
<a
class="dropdown-item"
href="#"
data-toggle="modal"
data-target="#logoutModal"
>
<i
class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"
></i>
Logout
</a>
</div>
</li>
</ul>
</nav>
<!-- End of Topbar -->
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<router-outlet></router-outlet>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<!-- Footer -->
<footer class="sticky-footer bg-white">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<span>Copyright © Your Website 2021</span>
</div>
</div>
</footer>
<!-- End of Footer -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" routerLink="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div
class="modal fade"
id="logoutModal"
tabindex="-1"
role="dialog"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">
Bạn có muốn thoát không?
</h5>
<button
class="close"
type="button"
data-dismiss="modal"
aria-label="Close"
>
<span aria-hidden="true"></span>
</button>
</div>
<div class="modal-body">
Chọn "Đăng xuất" bên dưới nếu bạn đã sẵn sàng kết thúc phiên hiện tại
của mình.
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">
Đóng
</button>
<a class="btn btn-primary" href="/auth/login">Đăng xuất</a>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin-2.min.js"></script>
<!-- Page level plugins -->
<script src="vendor/chart.js/Chart.min.js"></script>
<!-- Page level custom scripts -->
<script src="js/demo/chart-area-demo.js"></script>
<script src="js/demo/chart-pie-demo.js"></script>
<script>
function checking(a, b) {
console.log(a + b);
}
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(1);
resolve(checking(1, 4));
}, 3000);
});
promise
.then((res) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(2);
resolve(checking(1, 4));
}, 1000);
});
})
.then((res) => {
console.log(3);
});
</script> |
import { useState, useEffect } from 'react';
import './App.css';
import axios from 'axios';
import { FaGithub } from 'react-icons/fa';
import { UserInfo } from './UserInfo';
import { UserNotFound } from './UserNotFound';
import './index.css';
import { HistoryUser } from './HistoryUser';
function App() {
useEffect(() => {
document.title = 'GITHUB USER';
}, []);
const [user, setUser] = useState('');
const [gitUser, setGitUser] = useState({});
const [searching, setSearching] = useState(null);
const [searched, setSearched] = useState(false);
const [userNotFound, setUserNotFound] = useState(true);
const [pass, setPass] = useState('');
const [show, setShow] = useState(false);
const [historyList, setHistoryList] = useState([]); // State to store the list of searched users
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const submit = (e) => {
e.preventDefault();
setSearching(true);
if (user.trim() === '') {
setSearching(false);
return;
}
axios
.get(`https://api.github.com/users/${user}`)
.then((response) => {
setGitUser(response.data);
setUserNotFound(true);
setPass(user);
// Add the user to the history list
if (!historyList.some((historyUser) => historyUser.id === response.data.id)) {
setHistoryList((prevList) => [
...prevList,
{ id: response.data.id, login: response.data.login, link: response.data.html_url },
]);
}
})
.catch(() => {
setUserNotFound(false);
})
.finally(() => {
setUser('');
setSearching(false);
setSearched(true);
});
};
const deleteFromHistory = (userId) => {
setHistoryList((prevList) => prevList.filter((user) => user.id !== userId));
};
return (
<>
<HistoryUser handleClose={handleClose} show={show} historyList={historyList} deleteFromHistory={deleteFromHistory} />
<UserNotFound userNotFound={userNotFound} />
<div style={{ display: 'flex', alignContent: 'center' }} className='outter-div'>
<div className='rht-section'>
<FaGithub size={50} />
<h1 style={{ marginLeft: '10px' }} className='header-title'>
Github
</h1>
</div>
<div className='mdl-section'>
<form className='my-form' onSubmit={submit}>
<input
type='search'
value={user}
onChange={(e) => setUser(e.target.value)}
placeholder='Search user'
className='search-bar'
/>
<button>Search</button>
</form>
</div>
<div className='lft-section'>
<button style={{ height: '50px' }} onClick={handleShow}>
Search history
</button>
</div>
</div>
{searching ? (
<div>LOADING.....</div>
) : (
<UserInfo gitUser={gitUser} searched={searched} userNotFound={userNotFound} />
)}
</>
);
}
export default App; |
import pandas as pd
# Instead of uploading, directly read from your local directory
# Replace 'path_to_file' with the local path where your file is stored
df_dict = {
"paylocity_df": pd.read_csv('path_to_paylocity_file.csv'),
"q1_df": pd.read_csv('path_to_q1_file.csv'),
"q2_df": pd.read_csv('path_to_q2_file.csv')
}
paylocity_df = df_dict.get("paylocity_df")
q1_df = df_dict.get("q1_df")
q2_df = df_dict.get("q2_df")
# q1_df['Survey Metadata - End Date (+00:00 GMT)'] = pd.to_datetime(q1_df['Survey Metadata - End Date (+00:00 GMT)'])
# # Determine the most recent month
# latest_month = q1_df['Survey Metadata - End Date (+00:00 GMT)'].dt.to_period('M').max()
# # Filter the data to only include rows from the most recent month
# latest_data = q1_df[q1_df['Survey Metadata - End Date (+00:00 GMT)'].dt.to_period('M') == latest_month]
# latest_data
# Merge the dataframes on the specified columns
paylocity_df.rename(columns={'CostCenter1': 'LocCode'}, inplace=True)
merged_df = q2_df.merge(paylocity_df[['EmployeeID', 'LocCode']],
left_on='External Data Reference',
right_on='EmployeeID',
how='left')
# Drop the 'EmployeeID' column after merging as it's redundant
merged_df.drop('EmployeeID', axis=1, inplace=True)
print()
# Now, group by "External Data Reference" and "CostCenter2"
grouped = merged_df.groupby(['External Data Reference', 'LocCode']).size().reset_index(name='count')
# Group by community and then aggregate to get the sum
sum_counts_by_community = merged_df.groupby('LocCode').size().reset_index(name='sum_counts')
print(sum_counts_by_community)
q1_df
# Duplicate the column
q1_df['LocCode'] = q1_df['Embedded Data - Community']
# Now, group by 'LocCode' and aggregate
aggregated = q1_df.groupby('LocCode').agg({
'Q1 - On a scale of 0-10 how satisfied are you working for Morning Pointe?': 'mean',
'Q2 - What can we do better?': 'count',
'Embedded Data - Community': 'size'
}).reset_index()
# Round the Q1 average score to 1 decimal place
aggregated['Q1 - On a scale of 0-10 how satisfied are you working for Morning Pointe?'] = aggregated['Q1 - On a scale of 0-10 how satisfied are you working for Morning Pointe?'].round(1)
# Rename the columns for clarity
aggregated.columns = ['LocCode', 'Average Q1 Score', 'Count of Q2 Entries', 'Count of Community Entries']
print(aggregated)
# # Group by 'Embedded Data - Community' and aggregate
# aggregated = q1_df.groupby('Embedded Data - Community').agg({
# 'Q1 - On a scale of 0-10 how satisfied are you working for Morning Pointe?': 'mean',
# 'Q2 - What can we do better?': 'count'
# }).reset_index()
# # Round the Q1 average score to 1 decimal place
# aggregated['Q1 - On a scale of 0-10 how satisfied are you working for Morning Pointe?'] = aggregated['Q1 - On a scale of 0-10 how satisfied are you working for Morning Pointe?'].round(1)
# # Rename the columns for clarity
# aggregated.columns = ['Embedded Data - Community', 'Average Q1 Score', 'Count of Q2 Entries']
# print(aggregated)
# Assuming the 'sum_counts_by_community' DataFrame has a column named 'community' for the community names.
combined = pd.merge(aggregated, sum_counts_by_community, left_on='LocCode', right_on='LocCode', how='left')
print(combined)
# Assuming you've already calculated sum_counts for each community
# and it's present in the 'sum_counts_by_community' DataFrame.
# Merge the two dataframes on 'LocCode' (or community name)
merged_results = aggregated.merge(sum_counts_by_community, on='LocCode', how='left')
# Calculate the % of completion and round to 2 decimals
merged_results['% Completion'] = ((merged_results['Count of Community Entries'] / merged_results['sum_counts']) * 100).round(2)
print(merged_results)
merged_results.to_csv('filename.csv') |
import React from "react";
import cn from "classnames";
class TweetImage extends React.Component<{
src: string;
}> {
render() {
const { src } = this.props;
return (
<div className="column col-6">
<img src={src} style={{ width: "100%" }} />
</div>
);
}
}
export default class TweetModal extends React.Component<{
images: () => string[];
tweet: (text: string, indices: number[]) => Promise<string>;
done: () => void;
open: boolean;
}, {
sending: boolean;
images: string[];
text?: string;
}> {
constructor(props) {
super(props);
this.state = {
sending: false,
images: [...this.props.images()],
};
}
render() {
const { done, open } = this.props;
const { images, sending } = this.state;
return (
<div className={cn("modal", { active: open })}>
<a className="modal-overlay" onClick={() => done()} />
<div className="modal-container">
<div className="modal-body container">
<div className="columns">
<div className="column col-12 form-group">
<textarea
onChange={ev => this.setState({ text: ev.currentTarget.value })}
className="form-input"
id="input-example-3"
placeholder="Textarea"
rows={2}
style={{ resize: "none", marginBottom: "12px" }}
/>
</div>
</div>
<div className="columns">
{images.map((src, i) => <TweetImage key={i} src={src} />)}
</div>
</div>
<div className="modal-footer">
<button className={cn("btn", { disabled: sending })} style={{ marginRight: "4px" }}>キャンセル</button>
<button className={cn("btn", "btn-primary", { disabled: sending })} onClick={async () => {
this.setState({ sending: true });
await this.props.tweet(this.state.text, [0]);
this.setState({ sending: false });
done();
}}>Tweet</button>
</div>
</div>
</div>
);
}
} |
#include <map>
#include <print>
int main()
{
std::map<std::string, std::string> m;
m.emplace("sun", "일요일");
// # bad. 새로운 항목을 추가하는 코드
if ( m["mon"] != "") { }
// # good. C++20 ~
if ( m.contains("tue") ) { }
// # good. ~ C++17
if ( m.find("wed") != m.end() ) { }
for (const auto& [key, value] : m)
std::println("{}, {}", key, value);
} |
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { AuthService } from '../../services/authService';
import { FilterStatus, INITIAL_FILTER_STATUS, selectedFields } from './../../types';
import { ITickets } from '../../interface/ITickets';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ModalContentComponent } from '../../component/tickets/ModalContentComponent';
@Component({
selector: 'app-tickets',
templateUrl: './tickets.component.html',
styleUrls: ['tickets.component.css'],
})
export class TicketsComponent implements OnInit {
uniqueUsers: string[] = [];
filter: FilterStatus = INITIAL_FILTER_STATUS;
filteredTickets: ITickets[] = [];
viewingTicketId: number | null = null;
isDesc = false;
column = '';
uniqueIds: number[] = [];
selectedFields = selectedFields;
p: number = 1;
optionsNota: string[] = ['Ruim', 'Regular', 'Bom', 'Ótimo', 'Sem Avaliação'];
optionsSituacao: string[] = ['Em andamento', 'Fechada', 'Cancelada'];
optionsOrigemAtendimento: string[] = [
'2º Nível',
'3º Nivel',
'E-mail',
'Facebook',
'Internet',
'Portal de Serviços',
'Service Desk',
'Twitter',
];
showLogoutButton: boolean = false;
get itemsPerPage(): number {
return this.filter.itemsPerPage;
}
get filterSituacao(): string {
return this.filter.filterSituacao;
}
set filterSituacao(value: string) {
this.filter.filterSituacao = value;
}
get filterUsuario(): string {
return this.filter.filterUsuario;
}
set filterUsuario(value: string) {
this.filter.filterUsuario = value;
}
get filteridPrioridade(): string {
return this.filter.filteridPrioridade;
}
set filteridPrioridade(value: string) {
this.filter.filteridPrioridade = value;
}
get filterOrigemAtendimento(): string {
return this.filter.filterOrigemAtendimento;
}
set filterOrigemAtendimento(value: string) {
this.filter.filterOrigemAtendimento = value;
}
get filterIdSolicitacao(): string {
return this.filter.filterIdSolicitacao;
}
set filterIdSolicitacao(value: string) {
this.filter.filterIdSolicitacao = value;
}
get filterNota(): string {
return this.filter.filterNota;
}
set filterNota(value: string) {
this.filter.filterNota = value;
}
url = 'https://gsm-hmg.centralitcloud.com.br/citsmart/services/data/query';
constructor(private http: HttpClient, private authService: AuthService,
private modalService: NgbModal
) {}
ngOnInit() {
const sessionToken = this.authService.getSessionToken();
if (sessionToken) {
this.loadUniqueUsers(sessionToken);
}
this.showLogoutButton = true;
}
openModal(ticket: ITickets) {
const modalRef = this.modalService.open(ModalContentComponent, { size: 'lg' });
modalRef.componentInstance.ticket = ticket;
}
resetFilters(): void {
this.filter = { ...INITIAL_FILTER_STATUS };
this.filterUsuario = '';
this.filteredTickets = [];
}
toggleView(ticketId: number): void {
this.viewingTicketId = this.viewingTicketId === ticketId ? null : ticketId;
}
toggleDetails(ticket: ITickets): void {
this.openModal(ticket);
}
sortTable(property: string): void {
this.isDesc = !this.isDesc;
this.column = property;
let direction = this.isDesc ? 1 : -1;
this.filteredTickets.sort((a: any, b: any) => {
if (a[property] < b[property]) {
return -1 * direction;
} else if (a[property] > b[property]) {
return 1 * direction;
} else {
return 0;
}
});
}
loadUniqueUsers(sessionToken: string) {
const body = {
sessionID: sessionToken,
queryName: 'DESAFIODEV',
fields: ['Usuario'],
};
const headers = new HttpHeaders({
'Content-Type': 'application/json',
});
this.http.post(this.url, body, { headers }).subscribe(
(response: any) => {
if (response && response.result && Array.isArray(response.result)) {
const uniqueUserSet = new Set(
response.result.map((ticket: any) => ticket.Usuario)
);
this.uniqueUsers = Array.from(uniqueUserSet) as string[];
}
},
(error: any) => {
console.log('Erro ao carregar usuários únicos: ', error);
}
);
}
postRequest() {
const sessionToken = this.authService.getSessionToken();
if (!sessionToken) {
return;
}
const selectedFields = Object.keys(this.selectedFields).filter(
(key: string) => this.selectedFields[key]
);
const body = {
sessionID: sessionToken,
queryName: 'DESAFIODEV',
fields: selectedFields,
};
const headers = new HttpHeaders({
'Content-Type': 'application/json',
});
this.http.post(this.url, body, { headers }).subscribe(
(response: any) => {
this.filteredTickets = response.result;
this.applyFilters();
},
(error: any) => {
console.log('Erro ao fazer requisição POST: ', error);
}
);
}
applyFilters(): void {
const filters = [
{ property: 'situacao', value: this.filterSituacao },
{ property: 'idprioridade', value: this.filteridPrioridade },
{ property: 'Usuario', value: this.filterUsuario },
{ property: 'OrigemAtendimento', value: this.filterOrigemAtendimento },
{ property: 'idsolicitacaoservico', value: this.filterIdSolicitacao },
{ property: 'nota', value: this.filterNota },
];
this.filteredTickets = this.filteredTickets.filter((ticket: any) => {
return filters.every(filter => {
if (filter.value) {
if (filter.property === 'idprioridade' || filter.property === 'idsolicitacaoservico') {
return ticket[filter.property] === parseInt(filter.value);
}
return ticket[filter.property] === filter.value;
}
return true;
});
});
}
} |
import React from 'react';
export default class Home extends React.Component {
componentDidMount = () => {
document.title = "Welcome to Chat Battler Dungeons";
}
render() {
return (
<div style={{paddingBottom: "10px"}}>
<h1>Welcome to Chat Battler Dungeons</h1>
<p>THIS IS STILL IN EARLY ACCESS!</p>
<p>Welcome to what I hope is a new experience in the game-ification of Twitch chat to increase interaction with followers. Currently this bot is only used for https://twitch.tv/thetruekingofspace, but as soon as it's finished it will be available to whoever desires to use it and characters will be accessible cross-channel.</p>
<h1>Getting Started</h1>
<p>First you need to create a battler through the Twitch extension under the video. Once you do this, you can check out and manage your profile here: https://deusprogrammer.com/cbd/battlers/~self</p>
<h1>How Does it Work?</h1>
<p>Well, as soon as you create your battler as layed out above, you will become visible to other players as soon as you perform any of the below actions.</p>
<p>The bot or a mod will spawn monsters during the duration of the chat. They will attack a random person or whoever has the most aggro based on who has done the most damage. Once defeated, they will drop loot for a random participant.</p>
<h1>User Commands</h1>
<p>You can use these commands in chat, or you can use the extension for a push button interface.</p>
<div className="command-grid">
<div className="command-grid-item">
<h2>Ready yourself for battle</h2>
<p>Mark yourself as available for battle with monsters or other players. This state will end after 10 minutes of inactivity.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!ready<br/>
<br/>
Example:<br/>
!ready
</div>
</div>
<div className="command-grid-item">
<h2>Attack an Enemy</h2>
<p>Attack a given target with your currently equipped weapon. Monsters are prefixed with a ~ and use a special target identifier like ~M1 instead of a name.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!attack TARGET<br/>
<br/>
Example:<br/>
!attack thetruekingofspace<br/>
!attack ~M1
</div>
</div>
<div className="command-grid-item">
<h2>Use an Ability</h2>
<p>Use an ability with a given name on a target. If an ability targets all monsters, you may leave the target off. Also if the ability targets a friendly target, you can leave the target off as a shortcut for yourself.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!use ABILITY_NAME [TARGET]<br/>
<br/>
Examples:<br/>
// Heal yourself<br/>
!use HEAL<br/>
// Heal 'other_player'<br/>
!use HEAL other_player<br/>
// Heal all other players<br/>
!use RESTA<br/>
// Tackle 'other_player'<br/>
!use TACKLE other_player<br/>
// Tackle monster identified by ~M1<br/>
!use TACKLE ~M1<br/>
// Rocket blast all monsters<br/>
!use ROCKET_BLAST
</div>
</div>
<div className="command-grid-item">
<h2>Use an Item</h2>
<p>Use an item with a given name on a target. If an item targets all monsters, you may leave the target off. Also if the item targets a friendly target, you can leave the target off as a shortcut for yourself. Items are prefixed with a #.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!user ABILITY_NAME [TARGET]<br/>
<br/>
Examples:<br/>
// Use potion on yourself<br/>
!use #POTION<br/>
// Use potion on 'other_player'<br/>
!use #POTION other_player<br/>
// Use mega potion on all players <br/>
!use #MEGA_POTION
</div>
</div>
<div className="command-grid-item">
<h2>Look at Stats</h2>
<p>This will show your stats or the stats of a user if you provide a target.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!stats [TARGET]<br/>
<br/>
Example:<br/>
!stats thetruekingofspace
</div>
</div>
<div className="command-grid-item">
<h2>Show Targets</h2>
<p>This will show all available targets in chat. Monsters will be denoted with a ~.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!targets<br/>
<br/>
Example:<br/>
!targets
</div>
</div>
<div className="command-grid-item">
<h2>Show Abilities</h2>
<p>This will show a link to go view your abilities.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!abilities<br/>
<br/>
Example:<br/>
!abilities
</div>
</div>
<div className="command-grid-item">
<h2>Give an Item to another Character</h2>
<p>This will give an item to a user. You must have it in your inventory however.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!give ITEM_ID TARGET<br/>
<br/>
Example:<br/>
!give POTION thetruekingospace
</div>
</div>
<div className="command-grid-item">
<h2>Explore</h2>
<p>Explore the dungeon and find monsters to fight and occasional treasure and gold. If you specify a dungeon id, you can hunt specific and rarer monsters for their loot. Exploring costs 5AP and exploring a specific dungeon costs 10AP.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!explore [DUNGEON_ID]<br/>
<br/>
Example:<br/>
!explore<br/>
OR<br/>
!explore PSO
</div>
</div>
</div>
<h1>Mod Commands</h1>
<div className="command-grid">
<div className="command-grid-item">
<h2>Spawn a Monster</h2>
<p>Spawns a monster with a given id. If an id isn't provided, a random monster will be spawned for whatever the currently configured dungeon is.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!spawn [MONSTER_ID]<br/>
<br/>
Example:<br/>
!spawn SLIME<br/>
OR<br/>
!spawn
</div>
</div>
<div className="command-grid-item">
<h2>Turn an Annoying Chatter into a Slime</h2>
<p>Converts a chat user into a slime who is banned once they die.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!transmog TARGET<br/>
<br/>
Example:<br/>
!transmog get_affiliated_now
</div>
</div>
<div className="command-grid-item">
<h2>Turn a Chatter back into a Human</h2>
<p>Converts a chat user back into a chatter from a slime.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!untransmog TARGET<br/>
<br/>
Example:<br/>
!untransmog get_affiliated_now
</div>
</div>
<div className="command-grid-item">
<h2>Gift an Item to a User</h2>
<p>Gift any item to a user even if you don't have it in your inventory.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!gift ITEM_ID TARGET<br/>
<br/>
Example:<br/>
!gift VIRTUOUS_CONTRACT thetruekingospace
</div>
</div>
<div className="command-grid-item">
<h2>Refresh Cache</h2>
<p>After updating the database, use this command to refresh the cache on the bot.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!refresh<br/>
<br/>
Example:<br/>
!refresh
</div>
</div>
<div className="command-grid-item">
<h2>Reset Encounters</h2>
<p>Reset the encounter table to clear all monsters in case of a malfunction.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!reset<br/>
<br/>
Example:<br/>
!reset
</div>
</div>
<div className="command-grid-item">
<h2>Change Bot Configuration</h2>
<p>Change a config value on the bot. Currently the two config items are 'verbosity', 'currentDungeon' and 'maxEncounters'</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!config CONFIG_KEY CONFIG_VALUE<br/>
<br/>
Example:<br/>
!config verbosity verbose<br/>
!config verbosity simple<br/>
!config currentDungeon PSO<br/>
!config maxEncounters 4
</div>
</div>
<div className="command-grid-item">
<h2>Shut Down Bot</h2>
<p>Turn off the bot.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!shutdown<br/>
<br/>
Example:<br/>
!shutdown
</div>
</div>
<div className="command-grid-item">
<h2>Restart Bot</h2>
<p>Restart the bot.</p>
<div style={{background: "gray", color: "white", paddingLeft: "5px", marginLeft: "10px"}}>
!restart<br/>
<br/>
Example:<br/>
!restart
</div>
</div>
</div>
<h1>Game Play Features</h1>
<h2>Your Stats and What they Mean</h2>
<div className="command-grid">
<div className="command-grid-item">
<h3>HP</h3>
<p>Hit points are how much damage your character can take until you are dead. Simple enough.</p>
</div>
<div className="command-grid-item">
<h3>AP</h3>
<p>Action points are used everytime you perform an action like attacking, using abilities, or exploring.</p>
</div>
<div className="command-grid-item">
<h3>STR</h3>
<p>Strength is how hard you hit with your weapon. This stat adds damage each attack you perform.</p>
</div>
<div className="command-grid-item">
<h3>DEX</h3>
<p>How quickly you can attack. If you have a DEX of 0 your cooldown time is 25 seconds. At the maximum value of +5 your cool down times are 5 seconds, and negative DEX has no limit on how much it can slow you down. In the future, DEX beyond +5 will allow for multiple attacks in one cool down period.</p>
</div>
<div className="command-grid-item">
<h3>INT</h3>
<p>This stat is how well you can cast magic. Abilities can use any of these stats to specify if an ability hits or not, but magic type abilities will always rely on intelligence.</p>
</div>
<div className="command-grid-item">
<h3>HIT</h3>
<p>This stat is how well you can aim your attacks. The higher this is, the more likely you are to hit your target with an attack or a non-magic ability.</p>
</div>
<div className="command-grid-item">
<h3>AC</h3>
<p>This stat represents how hard you are to damage. This is generally due to how well you armor protects you.</p>
</div>
</div>
<h2>Special Effects</h2>
<div className="command-grid">
<div className="command-grid-item">
<h3>Damage Area/Target Types</h3>
<p>Some abilities can target more than one enemy, and some can only target monsters or only players in chat.</p>
</div>
<div className="command-grid-item">
<h3>Damage Types</h3>
<p>Weapons and abilities can damage more than just your HP. They can also damage (or heal) your AP or Gold.</p>
</div>
<div className="command-grid-item">
<h3>Buffs/Debuffs</h3>
<p>Some abilities will temporarily increase your stats and make it easier/harder to damage targets, do more/less damage to targets, act faster/slower, or be harder/easier hit.</p>
</div>
<div className="command-grid-item">
<h3>Status Effects</h3>
<p>Some attacks and abilities will harm your HP/AP/Gold over time. An example of this is the poison spell that deals 1d4 every 10 seconds.</p>
</div>
<div className="command-grid-item">
<h3>Triggered Effects</h3>
<p>Some weapons are able to trigger abilities. The Poop Knife for example has a 50% chance of inflicting poison. Triggered abilities are used for free.</p>
</div>
</div>
</div>
);
}
} |
package main
import "fmt"
func main() {
var t [5]float64 = [5]float64{24.0, 25.9, 27.8, 26.9, 26.2}
// range를 이용하여 배열 요소 전체 순회(Java 의 for-each처럼)
// for 인덱스값 요소값 := range 배열
for i, v := range t {
fmt.Println(i, v)
}
// 만약 요소만 필요하면 인덱스 변수는 _를 이용해 무효화할 수 있음
// Go 에서는 변수를 선언했으면 사용해야 하기 때문(안할 시 에러)
for _, v := range t {
fmt.Println(v)
}
} |
# 方法一
在package.json中追加如下配置:
```
"proxy": "http://localhost:5000"
```
说明:
1. 优点:配置简单,前端请求资源时,可以不加任何前缀
2. 缺点:不能配置多个代理
3. 工作方式:当请求了3000不存在的资源时,那么该请求会转发给5000
# 方法二
1.第一步:创建代理配置文件
在src下创建配置文件:
```
src/setupProxy.js
```
2.编写setupProxy配置具体代理规则:
```
const {createProxyMiddleware} = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
createProxyMiddleware('/api1', { // api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000)
target: "http://localhost:5000", // 配置转发目标地址(能返回数据的服务器地址)即:请求转发给谁
changeOrigin: true, // 控制服务器收到的请求头中Host的值(host:服务器可以通过这个字段知道请求是从哪来的)
/**
* changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
* changeOrigin设置为false时(默认),服务器收到的请求头中的host为: localhost:3000
*/
pathRewrite: {'^/api1': ''} // 重写请求路径(必须)--去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
}),
createProxyMiddleware('/api2', {
target: "http://localhost:5001",
changeOrigin: true,
pathRewrite: {'^/api2': ''}
}),
);
}
```
说明:
1. 优点:可以配置多个代理,可以灵活控制请求是否走代理(即:配置了一定会走代理,即使本地开发服务器有匹配的资源,也不会由本地响应数据,仍然会将请求发给代理的目标服务器)
2. 缺点:配置繁琐,前端请求资源时必须加前缀 |
import 'package:flutter/material.dart';
import 'package:sizer/sizer.dart';
import '../../widgets/home-page-widgets/announcements_widget.dart';
import '../../widgets/home-page-widgets/church_today_grid_view.dart';
import '../../widgets/home-page-widgets/exhortation_container.dart';
import '../../widgets/home-page-widgets/home_page_app_bar.dart';
import '../../widgets/home-page-widgets/home_page_title_subtitle.dart';
import '../../widgets/home-page-widgets/upcoming_service_widget.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key, required this.scrollController});
final ScrollController scrollController;
@override
Widget build(BuildContext context) {
var sizedBox = SizedBox(
height: 2.h,
);
return SingleChildScrollView(
controller: scrollController,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 2.h,
),
// custom app bar
const HomePageAppBar(),
sizedBox,
HomePageTitleSubtitle(
title: "Upcoming service",
subtitle:
"Discover the heart of our next service as we explore an uplifting message together.",
sizedBox: sizedBox,
),
const UpcomingServiceWidget(),
sizedBox,
sizedBox,
HomePageTitleSubtitle(
title: "Announcement",
subtitle:
"Discover the latest updates, sermons, and activities happening in our church community.",
sizedBox: sizedBox,
),
const AnnouncemenstsWidget(),
sizedBox,
sizedBox,
HomePageTitleSubtitle(
title: "Church today",
subtitle:
"Experience the joy of community and spiritual nourishment at Church today!",
sizedBox: sizedBox,
),
const ChurchTodayGridView(),
sizedBox,
sizedBox,
HomePageTitleSubtitle(
title: "This weeks exhortation",
subtitle:
"Find inspiration and encouragement for the week ahead through our weekly exhortation.",
sizedBox: sizedBox,
),
const ExhortationContainer(),
SizedBox(
height: 15.h,
),
],
),
);
}
} |
package com.backend.tjtablepartyspringboot.dto;
import com.backend.tjtablepartyspringboot.entity.PublicSiteTime;
import com.backend.tjtablepartyspringboot.entity.TrpgPublic;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.List;
/**
* @Author 2051196 刘一飞
* @Date 2023/4/17
* @JDKVersion 17.0.4
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PublicSiteDto {
Long publicSiteId;
String creatorId;
String name;
String city;
String location;
String picture;
String introduction;
float avgCost;
int capacity;
int gameNum;
String phone;
@DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss")
@JsonFormat(shape = JsonFormat.Shape.STRING , pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
Date uploadTime;
@DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss")
@JsonFormat(shape = JsonFormat.Shape.STRING , pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
Date checkTime;
String[] type;
String[] tag;
int status;
List<PublicSiteTimeDto> openTime;
float latitude;
float longitude;
String locationTitle;
List<TrpgPublic> games;
} |
from typing import List
from pydantic import BaseModel, Field, validator
class SectionConclusion(BaseModel):
section_name: str = Field(description='Name or main topic of the article section', default="")
conclusion: str = Field(description='Summary or conclusion of the section.', default="")
class Config:
validate_assignment = True
@validator('section_name')
def set_name(cls, value):
return value or 'Not Available'
@validator('conclusion')
def set_conclusion(cls, value):
return value or 'Not Available'
class MainConclusion(BaseModel):
conclusion: str = Field(description='Main conclusion of the whole article', default="")
justification: str = Field(description='Justification or quote from the article to justify how the conclusion is derived.', default="")
class Config:
validate_assignment = True
@validator('justification')
def set_justification(cls, value):
return value or 'Not Available'
@validator('conclusion')
def set_conclusion(cls, value):
return value or 'Not Available'
class Conclusions(BaseModel):
sections: List[SectionConclusion] = []
main_conclusion: MainConclusion = MainConclusion() |
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Buyer, BuyerDocument } from './buyer.schema';
import { IAuthBuyerMessageDetails, IBuyerDocument } from '@freedome/common';
@Injectable()
export class BuyerService {
constructor(
@InjectModel(Buyer.name) private readonly buyerModel: Model<BuyerDocument>,
) {}
async getBuyerByEmail(email: string): Promise<BuyerDocument | null> {
return this.buyerModel.findOne({ email }).exec();
}
async getBuyerByUsername(username: string): Promise<BuyerDocument | null> {
return this.buyerModel.findOne({ username }).exec();
}
async getRandomBuyers(count: number): Promise<BuyerDocument[]> {
return this.buyerModel.aggregate([{ $sample: { size: count } }]);
}
async createBuyer(buyerData: IAuthBuyerMessageDetails): Promise<void> {
const { username, email, profilePublicId, country, createdAt } = buyerData;
const buyer: IBuyerDocument = {
username,
email,
profilePublicId,
country,
purchasedGigs: [],
createdAt,
};
await this.buyerModel.create(buyer);
}
async updateBuyerIsSellerProp(email: string): Promise<void> {
await this.buyerModel
.updateOne(
{ email },
{
$set: {
isSeller: true,
},
},
)
.exec();
}
async updateBuyerPurchasedGigsProp(
buyerId: string,
purchasedGigId: string,
type: string,
): Promise<void> {
const updateOperation =
type === 'purchased-gigs'
? { $push: { purchasedGigs: purchasedGigId } }
: { $pull: { purchasedGigs: purchasedGigId } };
await this.buyerModel.updateOne({ _id: buyerId }, updateOperation).exec();
}
} |
/**
******************************************************************************
* @file Project/STM32F10x_StdPeriph_Template/stm32f10x_it.c
* @author MCD Application Team
* @version V3.5.0
* @date 08-April-2011
* @brief Main Interrupt Service Routines.
* This file provides template for all exceptions handler and
* peripherals interrupt service routine.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
#include "stm32f10x_it.h"
#include "stm32f10x_conf.h"
#include "stm32f10x_system.h"
#include "mdindly.h"
#include "mdintype.h"
/** @addtogroup STM32F10x_StdPeriph_Template
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
BYTE TxBuffer[30];
BYTE RxBuffer[RxBufferSize];
BYTE TxCounter = 0;
WORD RxCounter = 0;
BYTE NbrOfDataToTransfer = TxBufferSize;
BYTE NbrOfDataToRead = RxBufferSize;
BYTE usart_receive_end = 0;
WORD Ir_Execute_Delay = 0;
extern WORD Ir_Timer_Count;
extern DWORD TimeDisplay;
extern BYTE RTC_Display_Enable;
/******************************************************************************/
/* Cortex-M3 Processor Exceptions Handlers */
/******************************************************************************/
/**
* @brief This function handles NMI exception.
* @param None
* @retval None
*/
void NMI_Handler(void)
{
}
/**
* @brief This function handles Hard Fault exception.
* @param None
* @retval None
*/
void HardFault_Handler(void)
{
/* Go to infinite loop when Hard Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Memory Manage exception.
* @param None
* @retval None
*/
void MemManage_Handler(void)
{
/* Go to infinite loop when Memory Manage exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Bus Fault exception.
* @param None
* @retval None
*/
void BusFault_Handler(void)
{
/* Go to infinite loop when Bus Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Usage Fault exception.
* @param None
* @retval None
*/
void UsageFault_Handler(void)
{
/* Go to infinite loop when Usage Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles SVCall exception.
* @param None
* @retval None
*/
void SVC_Handler(void)
{
}
/**
* @brief This function handles Debug Monitor exception.
* @param None
* @retval None
*/
void DebugMon_Handler(void)
{
}
/**
* @brief This function handles PendSVC exception.
* @param None
* @retval None
*/
void PendSV_Handler(void)
{
}
/**
* @brief This function handles SysTick Handler.
* @param None
* @retval None
*/
void SysTick_Handler(void)
{
TimingDelay_Decrement();
}
void USART3_IRQHandler(void)
{
if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)
{
BYTE RxCounter_old;
/* Clear the USART1 Receive interrupt */
USART_ClearITPendingBit(USART3, USART_IT_RXNE);
if(USART_ReceiveData(USART3) != 0xd){
/* Read one byte from the receive data register */
RxBuffer[RxCounter++] = USART_ReceiveData(USART3) & 0xFF;
if(RxCounter == RxBufferSize-1){
RxCounter = 0;
}
}else if(USART_ReceiveData(USART3) == 0xd){
usart_receive_end = 1;
}
/* Disable the USART3 Receive interrupt */
USART_ITConfig(USART3, USART_IT_RXNE, DISABLE);
}
if(USART_GetITStatus(USART3, USART_IT_TXE) != RESET)
{
USART_ClearITPendingBit(USART3, USART_IT_TXE);
/* Write one byte to the transmit data register */
USART_SendData(USART3, TxBuffer[TxCounter++]);
if(TxCounter == NbrOfDataToTransfer)
{
/* Disable the USART3 Transmit interrupt */
USART_ITConfig(USART3, USART_IT_TXE, DISABLE);
TxCounter = 0;
}
}
}
void EXTI15_10_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line13) != RESET)
{
Ir_Receive_code();
EXTI_ClearITPendingBit(EXTI_Line13);
}
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2,TIM_IT_Update) != RESET)
{
Ir_Timer_Count++;
TIM_ClearITPendingBit(TIM2, TIM_IT_Update); // Clear the interrupt flag
}
}
void WWDG_IRQHandler(void)
{
/* Update WWDG counter */
WWDG_SetCounter(0x7F);
RTC_Display_Enable = 0;
TimeDisplay = 0;
/* Clear EWI flag */
WWDG_ClearFlag();
}
void RTC_IRQHandler(void)
{
if (RTC_GetITStatus(RTC_IT_SEC) != RESET)
{
/* Enable time update */
TimeDisplay = 1;
//if(RTC_Display_Enable) Time_Show();
/* Clear the RTC Second interrupt */
RTC_ClearITPendingBit(RTC_IT_SEC);
}
/* Wait until last write operation on RTC registers has finished */
RTC_WaitForLastTask();
/* Reset RTC Counter when Time is 23:59:59 */
if (RTC_GetCounter() == 0x00015180)
{
RTC_SetCounter(0x0);
/* Wait until last write operation on RTC registers has finished */
RTC_WaitForLastTask();
}
}
/******************************************************************************/
/* STM32F10x Peripherals Interrupt Handlers */
/* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */
/* available peripheral interrupt handler's name please refer to the startup */
/* file (startup_stm32f10x_xx.s). */
/******************************************************************************/
/**
* @brief This function handles PPP interrupt request.
* @param None
* @retval None
*/
/*void PPP_IRQHandler(void)
{
}*/
/**
* @}
*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/ |
package main
import "fmt"
func Add(a, b int) int {
return a + b
}
func Minus(a, b int) int {
return a - b
}
// 函数也是一种数据类型,同故宫type给一个函数类型起名
// My_FuncType它是一个函数类型
type My_FuncType func(int, int) int
func main() {
var res int
res = Add(2, 3)
fmt.Printf("res =%d\n", res)
//声明一个函数类型的变量
var test1 My_FuncType = Add
res = test1(4, 5)
fmt.Printf("res =%d\n", res)
test1 = Minus
res = test1(6, 2)
fmt.Printf("res =%d\n", res)
} |
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"runtime/debug"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/redis/go-redis/v9"
)
////// Authentication //////
func createAuthToken(userId int) string {
key := make([]byte, 64)
retry:
if _, err := rand.Read(key); err != nil {
panic(err)
}
keyStr := base64.StdEncoding.EncodeToString(key)
val, err := rcli.SetNX(context.Background(),
"auth-key:"+keyStr, userId, 7*24*time.Hour).Result()
if !val {
// Collision is almost impossible
// but handle anyway to stay theoretically sound
goto retry
}
if err != nil {
panic(err)
}
return keyStr
}
func validateAuthToken(token string) int {
if Config.Debug && token[0] == '!' {
userId, err := strconv.Atoi(token[1:])
if err == nil {
return userId
}
}
val, err := rcli.GetEx(context.Background(),
"auth-key:"+token, 7*24*time.Hour).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return 0
}
panic(err)
}
userId, err := strconv.Atoi(val)
if err != nil {
panic(err)
}
return userId
}
func auth(w http.ResponseWriter, r *http.Request) User {
cookies := r.Cookies()
var cookieValue string
for _, cookie := range cookies {
if cookie.Name == "auth" {
cookieValue = cookie.Value
break
}
}
if cookieValue == "" {
// Try Authorization header
authHeader := r.Header.Get("Authorization")
if len(authHeader) >= 7 && authHeader[0:7] == "Bearer " {
cookieValue = authHeader[7:]
}
}
if cookieValue == "" {
panic("401 Authentication required")
}
userId := validateAuthToken(cookieValue)
if userId == 0 {
panic("401 Authentication required")
}
user := User{Id: userId}
if !user.LoadById() {
panic("500 Inconsistent databases")
}
return user
}
////// Miscellaneous communication //////
func parseIntFromPathValue(r *http.Request, key string) int {
n, err := strconv.Atoi(r.PathValue(key))
if err != nil {
panic("400 Incorrect `" + key + "`")
}
return n
}
func postFormValue(r *http.Request, key string, mandatory bool) (string, bool) {
value, ok := r.PostForm[key]
if mandatory && !ok {
panic("400 Missing `" + key + "`")
}
if ok {
return value[0], true
} else {
return "", false
}
}
func parseIntFromPostFormValue(r *http.Request, key string) int {
value, _ := postFormValue(r, key, true)
n, err := strconv.Atoi(value)
if err != nil {
panic("400 Incorrect `" + key + "`")
}
return n
}
type JsonMessage map[string]interface{}
func (obj JsonMessage) String() string {
b, err := json.Marshal(obj)
if err != nil {
panic(err)
}
return string(b)
}
func write(w http.ResponseWriter, status int, p interface{}) {
bytes, err := json.Marshal(p)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write(bytes)
}
////// Handlers //////
func signUpHandler(w http.ResponseWriter, r *http.Request) {
nickname := r.PostFormValue("nickname")
password := r.PostFormValue("password")
if nickname == "" {
panic("400 Missing nickname")
}
if password == "" {
panic("400 Missing password")
}
user := User{
Nickname: nickname,
Password: password,
}
user.Save()
write(w, 200, user.Repr())
}
func logInHandler(w http.ResponseWriter, r *http.Request) {
id := r.PostFormValue("id")
password := r.PostFormValue("password")
if id == "" {
panic("400 Missing id")
}
idN, err := strconv.Atoi(id)
if err != nil {
panic("400 Incorrect id format")
}
if password == "" {
panic("400 Missing password")
}
user := User{Id: idN}
if !user.LoadById() {
panic("401 No such user")
}
if !user.VerifyPassword(password) {
panic("401 Incorrect password")
}
token := createAuthToken(idN)
w.Header().Add("Set-Cookie",
"auth="+token+"; SameSite=Strict; Path=/; Secure; Max-Age=604800")
write(w, 200, user.Repr())
}
func meHandler(w http.ResponseWriter, r *http.Request) {
user := auth(w, r)
write(w, 200, user.Repr())
}
func profileCUHandler(w http.ResponseWriter, r *http.Request, createNew bool) {
user := auth(w, r)
if err := r.ParseForm(); err != nil {
panic("400 Incorrect form format")
}
profile := Profile{Id: 0}
if createNew {
profile.Creator = user.Id
} else {
profile.Id = parseIntFromPathValue(r, "profile_id")
if !profile.Load() {
panic("404 No such profile")
}
if profile.Creator != user.Id {
panic("403 Not creator")
}
}
if details, has := postFormValue(r, "details", createNew); has {
if !json.Valid([]byte(details)) {
panic("400 `details` is not a valid JSON encoding")
}
profile.Details = details
}
if stats, has := postFormValue(r, "stats", createNew); has {
var err error
profile.Stats, err = parseProfileStats(stats)
if err != nil {
panic("400 " + err.Error())
}
}
if traits, has := postFormValue(r, "traits", createNew); has {
profile.Traits = parseProfileTraits(traits)
}
profile.Save()
write(w, 200, profile.Repr())
}
func profileCreateHandler(w http.ResponseWriter, r *http.Request) {
profileCUHandler(w, r, true)
}
func profileUpdateHandler(w http.ResponseWriter, r *http.Request) {
profileCUHandler(w, r, false)
}
func profileDeleteHandler(w http.ResponseWriter, r *http.Request) {
user := auth(w, r)
profileId := parseIntFromPathValue(r, "profile_id")
profile := Profile{Id: profileId}
if !profile.Load() {
panic("404 No such profile")
}
if profile.Creator != user.Id {
panic("403 Not creator")
}
profile.Delete()
write(w, 200, JsonMessage{})
}
func profileGetHandler(w http.ResponseWriter, r *http.Request) {
_ = auth(w, r)
profileId := parseIntFromPathValue(r, "profile_id")
profile := Profile{Id: profileId}
if !profile.Load() {
panic("404 No such profile")
}
/* if profile.Creator != user.Id {
panic("403 Not creator")
} */
write(w, 200, profile.Repr())
}
func avatarHandler(w http.ResponseWriter, r *http.Request) {
handle := r.PathValue("profile_id")
fmt.Fprintln(w, "avatar "+handle)
}
func profileListMyHandler(w http.ResponseWriter, r *http.Request) {
user := auth(w, r)
write(w, 200, ProfileListByCreatorRepr(user.Id))
}
func roomCUHandler(w http.ResponseWriter, r *http.Request, createNew bool) {
user := auth(w, r)
if err := r.ParseForm(); err != nil {
panic("400 Incorrect form format")
}
room := Room{Id: 0}
if createNew {
room.Creator = user.Id
room.CreatedAt = time.Now().Unix()
} else {
room.Id = parseIntFromPathValue(r, "room_id")
if !room.Load() {
panic("404 No such room")
}
if room.Creator != user.Id {
panic("403 Not creator")
}
}
if title, has := postFormValue(r, "title", createNew); has {
room.Title = title
}
if tags, has := postFormValue(r, "tags", createNew); has {
room.Tags = tags
}
if description, has := postFormValue(r, "description", createNew); has {
room.Description = description
}
room.Save()
if createNew {
go GameRoomRun(room, nil)
if Config.Debug {
log.Printf("Visit http://localhost:%d/test/%d/%d for testing\n", Config.Port, room.Id, user.Id)
}
}
write(w, 200, room.Repr())
}
func roomCreateHandler(w http.ResponseWriter, r *http.Request) {
roomCUHandler(w, r, true)
}
func roomUpdateHandler(w http.ResponseWriter, r *http.Request) {
roomCUHandler(w, r, false)
}
func roomGetHandler(w http.ResponseWriter, r *http.Request) {
room := Room{
Id: parseIntFromPathValue(r, "room_id"),
}
if !room.Load() {
panic("404 No such room")
}
write(w, 200, room.Repr())
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func roomChannelHandler(w http.ResponseWriter, r *http.Request) {
user := auth(w, r)
room := Room{Id: parseIntFromPathValue(r, "room_id")}
if !room.Load() {
panic("404 No such room")
}
gameRoom := GameRoomFind(room.Id)
if gameRoom == nil {
if room.Creator == user.Id {
// Reopen room
createdSignal := make(chan *GameRoom)
go GameRoomRun(room, createdSignal)
gameRoom = <-createdSignal
} else {
panic("404 Room closed")
}
}
// Establish the WebSocket connection
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
panic(err)
}
// Set read limit and timeouts
c.SetReadLimit(4096)
c.SetReadDeadline(time.Now().Add(10 * time.Second))
c.SetPongHandler(func(string) error {
c.SetReadDeadline(time.Now().Add(10 * time.Second))
return nil
})
// `outChannel`: messages to be sent to the client
outChannel := make(chan interface{}, 4)
// Add to the room
gameRoom.Join(user, outChannel)
// Goroutine that keeps reading JSON from the WebSocket connection
// and pushes them to `inChannel`
go func(c *websocket.Conn) {
var object map[string]interface{}
for {
if err := c.ReadJSON(&object); err != nil {
if !websocket.IsCloseError(err,
websocket.CloseNormalClosure,
websocket.CloseGoingAway,
websocket.CloseNoStatusReceived,
) && !errors.Is(err, net.ErrClosed) {
log.Printf("%T %v\n", err, err)
}
if _, ok := err.(*json.SyntaxError); ok {
continue
}
break
}
gameRoom.InChannel <- GameRoomInMessage{
UserId: user.Id,
Message: object,
}
}
}(c)
go func(c *websocket.Conn, outChannel chan interface{}) {
pingTicker := time.NewTicker(5 * time.Second)
defer pingTicker.Stop()
messageLoop:
for {
select {
case object := <-outChannel:
if object == nil {
// Signal to close connection
break messageLoop
}
if err := c.WriteJSON(object); err != nil {
log.Println(err)
break messageLoop
}
case <-pingTicker.C:
if err := c.WriteMessage(websocket.PingMessage, nil); err != nil {
log.Println(err)
break messageLoop
}
}
}
gameRoom.Lost(user.Id, outChannel)
c.Close()
close(outChannel)
}(c, outChannel)
}
func versionInfoHandler(w http.ResponseWriter, r *http.Request) {
var vcsRev string
var vcsTime string
if info, ok := debug.ReadBuildInfo(); ok {
for _, s := range info.Settings {
if s.Key == "vcs.revision" {
vcsRev = s.Value
} else if s.Key == "vcs.time" {
vcsTime = s.Value
}
}
}
GameRoomMapMutex.Lock()
roomsCount := len(GameRoomMap)
var roomsStr strings.Builder
if roomsCount > 0 {
roomsStr.WriteString(" (")
i := 0
for roomId, _ := range GameRoomMap {
if i > 0 {
roomsStr.WriteString(", ")
}
roomsStr.WriteString(strconv.Itoa(roomId))
i += 1
if i >= 5 {
break
}
}
if roomsCount > i {
roomsStr.WriteString(", etc.")
}
roomsStr.WriteString(")")
}
GameRoomMapMutex.Unlock()
fmt.Fprintf(w, "#Rooms %d%s\nPID %d\n\nTime %s\nHash %s\n",
roomsCount, roomsStr.String(), os.Getpid(),
vcsTime, vcsRev)
}
func testHandler(w http.ResponseWriter, r *http.Request) {
content, err := os.ReadFile("test.html")
if err != nil {
panic("404 Cannot read page content")
}
s := string(content)
s = strings.Replace(s, "~ room ~", r.PathValue("room_id"), 1)
s = strings.Replace(s, "~ id ~", r.PathValue("player_id"), 1)
userId, _ := strconv.Atoi(r.PathValue("player_id"))
s = strings.Replace(s, "~ profile ~",
strconv.Itoa(ProfileAnyByCreator(userId)), 1)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(s))
}
func dataInspectionHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
ReadEverything(w)
}
// A handler that captures panics and return the error message as 500
type errCaptureHandler struct {
Handler http.Handler
}
func (h *errCaptureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if obj := recover(); obj != nil {
if err, ok := obj.(error); ok {
http.Error(w, err.Error(), 500)
} else if str, ok := obj.(string); ok {
status := 500
message := str
// Try parsing the string `str` into status + message
index := strings.Index(str, " ")
if index != -1 {
if n, err := strconv.Atoi(str[:index]); err == nil {
status = n
message = str[(index + 1):]
}
}
http.Error(w, message, status)
} else {
message := fmt.Sprintf("%v", obj)
http.Error(w, message, 500)
}
}
}()
h.Handler.ServeHTTP(w, r)
}
// A handler that allows all cross-origin requests
type corsAllowAllHandler struct {
Handler http.Handler
StaticServer http.Handler
}
func (h *corsAllowAllHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Upgrade")
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == "OPTIONS" {
// Intercept OPTIONS requests
w.Write([]byte{})
} else if r.URL.Path == "/play" {
w.Header().Set("Location", "/play/")
w.WriteHeader(302)
w.Write([]byte("Redirecting to /play/"))
} else if strings.HasPrefix(r.URL.Path, "/play/") {
h.StaticServer.ServeHTTP(w, r)
} else {
h.Handler.ServeHTTP(w, r)
}
}
func ServerListen() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", versionInfoHandler)
mux.HandleFunc("POST /sign-up", signUpHandler)
mux.HandleFunc("POST /log-in", logInHandler)
mux.HandleFunc("GET /me", meHandler)
mux.HandleFunc("POST /profile/create", profileCreateHandler)
mux.HandleFunc("POST /profile/{profile_id}/update", profileUpdateHandler)
mux.HandleFunc("POST /profile/{profile_id}/delete", profileDeleteHandler)
mux.HandleFunc("GET /profile/{profile_id}", profileGetHandler)
mux.HandleFunc("GET /profile/{profile_id}/avatar", avatarHandler)
mux.HandleFunc("GET /profile/my", profileListMyHandler)
mux.HandleFunc("POST /room/create", roomCreateHandler)
mux.HandleFunc("POST /room/{room_id}/update", roomUpdateHandler)
mux.HandleFunc("GET /room/{room_id}", roomGetHandler)
mux.HandleFunc("GET /room/{room_id}/channel", roomChannelHandler)
var handler http.Handler
handler = &errCaptureHandler{Handler: mux}
if Config.Debug {
mux.HandleFunc("GET /test", testHandler)
mux.HandleFunc("GET /test/{room_id}", testHandler)
mux.HandleFunc("GET /test/{room_id}/{player_id}", testHandler)
mux.HandleFunc("GET /debug/pprof/", pprof.Index)
mux.HandleFunc("GET /data", dataInspectionHandler)
staticHandler := http.StripPrefix("/play",
http.FileServer(http.Dir("../client")))
handler = &corsAllowAllHandler{
Handler: handler,
StaticServer: staticHandler,
}
}
port := Config.Port
log.Printf("Listening on http://localhost:%d/\n", port)
if Config.Debug {
log.Printf("Visit http://localhost:%d/play to play", port)
log.Printf("Visit http://localhost:%d/debug/pprof/ for profiling stats\n", port)
}
server := &http.Server{
Handler: handler,
Addr: fmt.Sprintf("localhost:%d", port),
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Print(err)
}
}()
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
<-ch
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Print(err)
}
log.Print("Shutting down")
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.