text
stringlengths 184
4.48M
|
|---|
import streamlit as st
import subprocess
import concurrent.futures
def display_iframe(url):
iframe_html = f'<iframe src="{url}" width="800" height="600"></iframe>'
st.write(iframe_html, unsafe_allow_html=True)
def run_catboost(url):
cmd_catboost = ["python3", "Catboost_prediction.py", '"' + url + '"']
process_catboost = subprocess.run(cmd_catboost, capture_output=True, text=True)
return process_catboost.stdout.strip(), process_catboost.stderr.strip()
def run_bert(url):
cmd_bert = ["python3", "bert.py", '"' + url + '"']
process_bert = subprocess.run(cmd_bert, capture_output=True, text=True)
return process_bert.stdout.strip(), process_bert.stderr.strip()
def run_app():
st.title("Website Analysis App")
url = st.text_input("Enter the website URL")
if st.button("Analyze"):
with concurrent.futures.ThreadPoolExecutor() as executor:
# Submit the tasks to the executor
future_catboost = executor.submit(run_catboost, url)
future_bert = executor.submit(run_bert, url)
output1, error1 = future_catboost.result()
output2, error2 = future_bert.result()
# Display the outputs or error messages
st.write("CatBoost Output:", output1)
st.write("BERT Output:", output2)
display_iframe(url)
if __name__ == "__main__":
run_app()
|
import React, { useEffect, useState } from 'react';
import styles from './Profile.module.scss';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch } from '../../app/store';
import { useForm, SubmitHandler } from 'react-hook-form';
import { Avatar, IconButton } from '@material-ui/core';
import AccountCircleIcon from '@material-ui/icons/AccountCircle';
import {
updateProfile,
selectProfile,
getMyProfile,
getUser,
selectUserId,
createProfile,
isSignIn,
} from '../../features/auth/authSlice';
import { useHistory } from 'react-router-dom';
import { useCookies } from 'react-cookie';
import { job as jobs, incomes, compositions } from '../../data/data';
import Alert from '../../components/message/alert/Alert';
import {
isLoadingEnd,
isLoadingStart,
selectIsLoading,
} from '../../features/layout/layoutSlice';
import Loading from '../../components/loading/Loading';
interface INPUTS {
name: string;
age: number;
job: string;
income: string;
composition: string;
body: string;
}
const Profile: React.FC = () => {
const [avatarImage, setAvatarImage] = useState<any>(null),
[validError, setValidError] = useState(false),
[image, setImage] = useState<any>(null);
const dispatch: AppDispatch = useDispatch();
const userId = useSelector(selectUserId),
profile = useSelector(selectProfile),
isLoading = useSelector(selectIsLoading);
const history = useHistory();
const [cookies, setCookie] = useCookies();
let id = window.location.pathname.split('/profile')[1];
if (id !== '') {
id = id?.split('/')[1];
}
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<INPUTS>({
shouldUnregister: false,
});
const handlerEditPicture = (e: any) => {
setImage(e.target.files![0]);
if (e.target.files && e.target.files[0]) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (e: any) => {
setAvatarImage(e.target.result);
};
reader.readAsDataURL(file);
}
};
const clickPicture = (e: any) => {
const fileInput = document.getElementById('imageInput');
fileInput?.click();
};
const getUserProfile = async () => {
await dispatch(getUser(cookies));
await dispatch(getMyProfile(cookies));
};
useEffect(() => {
const fetchBootLoader = async () => {
if (id) {
await dispatch(isLoadingStart());
await dispatch(isSignIn());
await getUserProfile();
await dispatch(isLoadingEnd());
} else if (cookies) {
await dispatch(isSignIn());
await dispatch(getUser(cookies));
}
};
fetchBootLoader();
}, []);
useEffect(() => {
if (id) {
reset(profile);
}
setAvatarImage(profile?.img);
}, [reset, profile]);
const onSubmit: SubmitHandler<INPUTS> = async (data) => {
if (id) {
const packet = {
id: profile.id,
name: data.name,
age: data.age,
job: data.job,
income: data.income,
composition: data.composition,
body: data.body,
img: image,
user_id: userId,
cookie: cookies,
};
const result = await dispatch(updateProfile(packet));
if (updateProfile.rejected.match(result)) {
setValidError(true);
} else {
await history.push('/mypage');
await reset();
}
} else {
const packet = {
name: data.name,
age: data.age,
job: data.job,
income: data.income,
composition: data.composition,
body: data.body,
img: image,
user_id: userId,
cookie: cookies,
};
const result = await dispatch(createProfile(packet));
if (createProfile.rejected.match(result)) {
setValidError(true);
} else {
await history.push('/mypage');
await reset();
}
}
};
return (
<>
{isLoading ? (
<div className="h-screen">
<Loading title={'Loading...'} />
</div>
) : (
<form onSubmit={handleSubmit(onSubmit)}>
<div className="w-full py-8 mb-12 md:mb-1">
<div className="w-9/12 md:w-4/12 mx-auto pt-14 text-center text-silver h-auto bg-stone-100 bg-white rounded">
<h2
className="mb-10 text-black text-xl font-bold"
data-testid="title"
>
ใใญใใฃใผใซ่จญๅฎ
</h2>
{validError && (
<Alert
title={'็ป้ฒใจใฉใผ'}
message={
'็ปๅใตใคใบใ500KBไปฅไธใใใใใฏๅนด้ฝขใ0~100ใพใงใฎๆดๆฐๅคใงใชใๅฏ่ฝๆงใใใใใพใใ'
}
/>
)}
<input
type="file"
id="imageInput"
hidden={true}
multiple
onChange={handlerEditPicture}
/>
<br />
{avatarImage ? (
<Avatar
src={avatarImage}
style={{
width: 110,
height: 110,
}}
className="text-center mx-auto"
/>
) : (
<AccountCircleIcon
style={{ fontSize: 120 }}
className={avatarImage ? styles.addIcon : styles.normal}
/>
)}
<br />
<IconButton onClick={clickPicture}>
<span className="text-base text-blue-600 mb-4">
ใใญใใฃใผใซๅ็ใๅคๆด
</span>
</IconButton>
<div className="mb-4">
<div className="text-left ml-6 sm:ml-10 md:ml-9 text-gray-700 mb-1 pl-1">
<label htmlFor="name" data-testid="label-name">
ๅๅ
</label>
</div>
<input
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 w-10/12 py-2 px-3 mb-5"
id="name"
type="text"
data-testid="input-name"
placeholder="ๅๅใๅ
ฅๅ"
{...register('name', {
required: {
value: true,
message: 'โปๅๅใฎๅ
ฅๅใฏๅฟ
้ ใงใ',
},
})}
/>
{errors.name && (
<p className="text-red-500 text-xs italic" role="alert">
{errors.name.message}
</p>
)}
</div>
<div className="mb-4">
<div className="text-left ml-6 sm:ml-10 md:ml-9 text-gray-700 mb-1 pl-1">
<label htmlFor="age" data-testid="label-age">
ๅนด้ฝข
</label>
</div>
<input
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 w-10/12 py-2 px-3 mb-5"
id="age"
type="number"
data-testid="input-age"
placeholder="ๅนด้ฝขใๅ
ฅๅ"
{...register('age', {
required: {
value: true,
message: 'โปๅนด้ฝขใฎๅ
ฅๅใฏๅฟ
้ ใงใ',
},
pattern: {
value: /^[0-9]+$/,
message: 'ๅนด้ฝขใฏๆดๆฐใงๅ
ฅๅใใฆใใ ใใ',
},
})}
/>
{errors.age && (
<p className="text-red-500 text-xs italic" role="alert">
{errors.age.message}
</p>
)}
</div>
<div className="mb-6">
<div className="text-left ml-6 sm:ml-10 md:ml-9 text-gray-700 mb-1 pl-1">
<label htmlFor="job" data-testid="label-job">
่ทๆฅญ
</label>
</div>
<select
className={`${styles.select_placeholder} bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 w-10/12 py-2 px-3 mb-5`}
id="job"
data-testid="select-job"
required
{...register('job', {
required: {
value: true,
message: 'โป่ทๆฅญใฎ้ธๆใฏๅฟ
้ ใงใ',
},
})}
>
<option className="hidden" value="">
่ทๆฅญใ้ธๆใใฆใใ ใใ
</option>
{jobs?.map((job) => (
<option key={job.id}>{job.name}</option>
))}
</select>
{errors.job && (
<p className="text-red-500 text-xs mt-3 italic" role="alert">
{errors.job.message}
</p>
)}
</div>
<div className="mb-6">
<div className="text-left ml-6 sm:ml-10 md:ml-9 text-gray-700 mb-1 pl-1">
<label htmlFor="income" data-testid="label-income">
ๅนดๅ
</label>
</div>
<select
className={`${styles.select_placeholder} bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 w-10/12 py-2 px-3 mb-5`}
id="income"
data-testid="select-income"
required
{...register('income', {
required: {
value: true,
message: 'โปๅนดๅใฎ้ธๆใฏๅฟ
้ ใงใ',
},
})}
>
<option className="hidden" value="">
ๅนดๅใ้ธๆใใฆใใ ใใ
</option>
{incomes?.map((income) => (
<option key={income.id}>{income.name}</option>
))}
</select>
{errors.income && (
<p className="text-red-500 text-xs mt-3 italic" role="alert">
{errors.income.message}
</p>
)}
</div>
<div className="mb-6">
<div className="text-left ml-6 sm:ml-10 md:ml-9 text-gray-700 mb-1 pl-1">
<label htmlFor="composition" data-testid="label-composition">
ไธๅธฏ
</label>
</div>
<select
className={`${styles.select_placeholder} bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 w-10/12 py-2 px-3 mb-5`}
id="composition"
data-testid="select-composition"
required
{...register('composition', {
required: {
value: true,
message: 'โปไธๅธฏใฎ้ธๆใฏๅฟ
้ ใงใ',
},
})}
>
<option className="hidden" value="">
ไธๅธฏใ้ธๆใใฆใใ ใใ
</option>
{compositions?.map((composition) => (
<option key={composition.id}>{composition.name}</option>
))}
</select>
{errors.composition && (
<p className="text-red-500 text-xs mt-3 italic" role="alert">
{errors.composition.message}
</p>
)}
</div>
<div className="mb-6">
<div className="text-left ml-6 sm:ml-10 md:ml-9 text-gray-700 mb-1 pl-1">
<label htmlFor="body" data-testid="label-body">
่ชๅทฑ็ดนไป
</label>
</div>
<textarea
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 w-10/12 py-2 px-3 mb-5"
rows={6}
id="body"
data-testid="input-body"
placeholder="่ชๅทฑ็ดนไปๆใฏ150ๆๅญไปฅๅ
ใงๅ
ฅๅ"
{...register('body', {
maxLength: {
value: 150,
message: '่ชๅทฑ็ดนไปๆใฏ150ๆๅญไปฅๅ
ใงๅ
ฅๅใใฆใใ ใใ',
},
})}
/>
{errors.body && (
<p className="text-red-500 text-xs italic">
{errors.body.message}
</p>
)}
</div>
<div className="mb-6 pb-6 md:mb-0">
<button
type="submit"
className="px-20 py-2.5 relative rounded group font-medium text-white inline-block"
data-testid="button-submit"
>
<span className="absolute top-0 left-0 w-full h-full rounded opacity-50 filter blur-sm bg-gradient-to-br from-button-color-orange-hover to-yellow-200"></span>
<span className="h-full w-full inset-0 absolute mt-0.5 ml-0.5 bg-gradient-to-br filter group-active:opacity-0 rounded opacity-50 from-button-color-orange-hover to-yellow-200"></span>
<span className="absolute inset-0 w-full h-full transition-all duration-200 ease-out rounded shadow-xl bg-gradient-to-br filter group-active:opacity-0 group-hover:blur-sm from-button-color-orange-hover to-yellow-200"></span>
<span className="absolute inset-0 w-full h-full transition duration-200 ease-out rounded bg-gradient-to-br to-button-color-orange-hover from-yellow-200"></span>
<span className="relative">็ป้ฒ</span>
</button>
</div>
</div>
</div>
</form>
)}
</>
);
};
export default Profile;
|
import React, { useEffect, useState } from "react";
import Lottie from "react-lottie";
import * as location from "./load.json";
import * as success from "./1127-success.json";
const defaultOptions1 = {
loop: true,
autoplay: true,
animationData: location.default,
rendererSettings: {
preserveAspectRatio: "xMidYMid slice",
},
};
const defaultOptions2 = {
loop: true,
autoplay: true,
animationData: success.default,
rendererSettings: {
preserveAspectRatio: "xMidYMid slice",
},
};
function PreLoader2() {
const [data, setData] = useState([]);
const [loading, setloading] = useState(undefined);
const [completed, setcompleted] = useState(undefined);
useEffect(() => {
setTimeout(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((json) => {
setData(json);
setloading(true);
setTimeout(() => {
setcompleted(true);
}, 2000);
});
}, 50000);
}, []);
return (
<>
{!completed ? (
<>
{!loading ? (
<Lottie options={defaultOptions1} height={200} width={200} />
) : (
<Lottie options={defaultOptions2} height={100} width={100} />
)}
</>
) : (
<>
<br />
<h6 style={{ position: "Absolute", right: "5rem", bottom: "0" }}>
<a
style={{ color: "white" }}
href="https://lottiefiles.com/chrisgannon"
>
</a>
<br />
<a style={{ color: "white" }} href="https://lottiefiles.com/darius">
</a>
</h6>
</>
)}
</>
);
}
export default PreLoader2;
|
# create a workbook
wb = xlsx_package.workbook
wb.styles do |style|
project_heading = style.add_style(b: true, sz: 14)
heading = style.add_style(b: true)
# add a worksheet
wb.add_worksheet(name: "Items") do |sheet|
# Add a title row
sheet.add_row ["Inventory Item"], style: project_heading
# Add the date this was downloaded
sheet.add_row ["Download At", Time.now.strftime("%b %-d, %Y")]
# Add a blank row
sheet.add_row []
# Create the header row
sheet.add_row ["Item Name", "Quantity"], style: heading
# Create the database reference row
sheet.add_row ["id", "name", "quantity"], style: heading
# Create entries for each item
@items.each do |item|
sheet.add_row [item.name, item.quantity]
end
end
end
|
vue + interia
1. composer create-project laravel/laravel laravel-inertia-crud
2. cd laravel-inertia-crud
3. composer require inertiajs/inertia-laravel
4. composer require tightenco/ziggy
5. resources/views/app.blade.php=>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Laravel Inertia CRUD</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link href="{{ asset('/css/app.css') }}" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
@routes
<script src="{{ asset('/js/app.js') }}" defer></script>
</head>
<body>
<div class="container">
@inertia
</div>
</body>
</html>
6. php artisan inertia:middleware
7. app/Http/Kernel.php=>
'web' => [
// ...
\App\Http\Middleware\HandleInertiaRequests::class,
],
8. npm install
9. npm install @inertiajs/inertia @inertiajs/inertia-vue3
10. npm install vue@next vue-loader@^16.2.0 @vue/compiler-sfc
11. npm install @inertiajs/progress
12. .env=>
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_inertia_crud
DB_USERNAME=<DB username>
DB_PASSWORD=<DB password>
13. php artisan make:migration create_posts_table
14. php artisan migrate
15. app/Http/Controllers/Auth/LoginController.php=>
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
class LoginController extends Controller
{
public function showLoginForm()
{
return Inertia::render('Auth/Login'); // Vue component
}
public function authenticate(Request $request)
{
}
public function logout(Request $request)
{
}
}
16. app/Http/Controllers/Auth/RegisterController.php=>
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Inertia\Inertia;
class RegisterController extends Controller
{
public function showRegisterForm()
{
return Inertia::render('Auth/Register');
}
public function register(Request $request)
{
}
}
17. php artisan make:controller PostsController --resource
18. PostsController.php=>
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Inertia\Inertia;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware("auth")->except(["index"]);
}
public function index()
{
return Inertia::render('Posts/Index', [
"posts" => Post::orderBy('id', 'DESC')->paginate(10)
]);
}
public function create()
{
return Inertia::render('Posts/Create');
}
public function store(Request $request)
{
}
public function edit($id)
{
return Inertia::render('Posts/Edit', [
'post' => Post::findOrFail($id)
]);
}
public function update(Request $request, $id)
{
}
public function destroy(Request $request, $id)
{
}
}
19. routes/web.php=>
<?php
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\PostsController;
use Illuminate\Support\Facades\Route;
Route::get('login', [LoginController::class, 'showLoginForm'])->name('showLoginForm')->middleware('guest');
Route::get('register', [RegisterController::class, 'showRegisterForm'])->name('showRegisterForm')->middleware('guest');
Route::post('login', [LoginController::class, 'authenticate'])->name('login');
Route::post('register', [RegisterController::class, 'register'])->name('register');
Route::post('logout', [LoginController::class, 'logout'])->name('logout');
Route::resource('post', PostsController::class);
Route::redirect('/', 'post');
20.
|
//https://docs.oracle.com/javase/tutorial/uiswing/painting/step1.html
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class SwingPaintDemo {
public static void createAndShowGUI() {
System.out.println("Created GUI on EDT? " + SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(250, 250);
f.setVisible(true);
}
}
class SwingPaintDemo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel {
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
}
public Dimension getPreferredSize() {
return new Dimension(250,200);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw Text
g.drawString("Welcoming everyone to this Java Session",10,20);
}
}
public class SwingDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SwingPaintDemo2.createAndShowGUI();
}
});
}
}
|
import React, { useEffect, useRef, useState } from "react";
import Image from "next/image";
import arrowDown from "../../Images/arrowdown.png";
import Link from "next/link";
import { Url } from "next/dist/shared/lib/router/router";
type DropDownMenuListProps = {
staticNames: {
ulName: string;
linkone?: string;
linkOneHref?: Url;
linktwo?: string;
linkTwoHref?: Url;
linkthree?: string;
linkThreeHref?: Url;
linkfour?: string;
linkFourHref?: Url;
linkfive?: string;
linkFiveHref?: Url;
linksix?: string;
linkSixHref?: Url;
linkseven?: string;
linkSevenHref?: Url;
};
};
const DropDownMenuList = ({ staticNames }: DropDownMenuListProps) => {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
const toggleDropdown = () => {
setIsOpen(!isOpen);
};
const handleOutsideClick = (event: MouseEvent) => {
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node)
) {
setIsOpen(false);
}
};
useEffect(() => {
document.addEventListener("mousedown", handleOutsideClick);
return () => {
document.removeEventListener("mousedown", handleOutsideClick);
};
}, [isOpen]);
return (
<div ref={dropdownRef} className="dropdown ">
<button onClick={toggleDropdown} className="flex items-center ">
{staticNames.ulName}
<span className=" ml-1 relative top-1">
<Image
src={arrowDown}
alt="Location pin"
width={12}
height={12}
className="items-end"
/>
</span>
</button>
{isOpen && (
<ul
className="absolute flex flex-col items-start px-2 py-3 gap-3 bg-white w-60 z-50"
style={{
borderRadius: "0px 20px 20px 20px",
boxShadow: "0px 4px 4px 0px rgba(0, 0, 0, 0.25)",
color: "rgba(0, 0, 0, 0.50)",
}}
>
{staticNames.linkone && (
<li>
<Link
href={staticNames.linkOneHref || "#"}
onClick={() => {
setIsOpen(false);
}}
>
{staticNames.linkone}
</Link>
</li>
)}
{staticNames.linktwo && (
<li>
<Link
href={staticNames.linkTwoHref || "#"}
onClick={() => {
setIsOpen(false);
}}
>
{staticNames.linktwo}
</Link>
</li>
)}
{staticNames.linkthree && (
<li>
<Link
href={staticNames.linkThreeHref || "#"}
onClick={() => {
setIsOpen(false);
}}
>
{staticNames.linkthree}
</Link>
</li>
)}
{staticNames.linkfour && (
<li>
<Link
href={staticNames.linkFourHref || "#"}
onClick={() => {
setIsOpen(false);
}}
>
{staticNames.linkfour}
</Link>
</li>
)}
{staticNames.linkfive && (
<li>
<Link
href={staticNames.linkFiveHref || "#"}
onClick={() => {
setIsOpen(false);
}}
>
{staticNames.linkfive}
</Link>
</li>
)}
{staticNames.linksix && (
<li>
<Link
href={staticNames.linkSixHref || "#"}
onClick={() => {
setIsOpen(false);
}}
>
{staticNames.linksix}
</Link>
</li>
)}
{staticNames.linkseven && (
<li>
<Link
href={staticNames.linkSevenHref || "#"}
onClick={() => {
setIsOpen(false);
}}
>
{staticNames.linkseven}
</Link>
</li>
)}
</ul>
)}
</div>
);
};
export default DropDownMenuList;
|
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.
Example 1:
Input: s = "hello"
Output: "holle"
Example 2:
Input: s = "leetcode"
Output: "leotcede"
s = "elapqoruse"
a = []
v = "aeiouAEIOU"
s.chars.each do |item|
a << item if v.include?(item)
end
s.chars.each_with_index do |item, index|
s[index] = a.pop if v.include?(item)
end
# def reverse_string(s)
# vowels = "aeiouAEIOU"
# left, right = 0, s.length - 1
# while left < right
# while left < right && !vowels.include?(s[left])
# left += 1
# end
# while left < right && !vowels.include?(s[right])
# right -= 1
# end
# s[left], s[right] = s[right], s[left] if left < right
# left += 1
# right -= 1
# end
# s
# end
# puts reverse_string("hello") #holle
# def reverse_vowels(s, left = 0, right = s.length - 1)
# vowels = "aeiouAEIOU"
# return s if left >= right
# while left < right && !vowels.include?(s[left])
# left += 1
# end
# while left < right && !vowels.include?(s[right])
# right -= 1
# end
# s[left], s[right] = s[right], s[left] if left < right
# reverse_vowels(s, left + 1, right - 1)
# end
# puts reverse_vowels("hello") # Output: "holle"
# puts reverse_vowels("leetcodeo") # Output: "leotcedoe"
# puts reverse_vowels("world") # Output: "world"
# def reverse_vovel(str)
# chars_arr = str.chars
# left = chars_arr.length - 1
# vowels = "aeiouAEIOU"
# chars_arr.each_with_index do |char, index|
# if vowels.include?(char)
# while(left >= 0)
# if vowels.include?(chars_arr[left]) && left >= index
# temp = chars_arr[index]
# chars_arr[index] = chars_arr[left]
# chars_arr[left] = temp
# left -= 1
# break
# end
# left -= 1
# end
# end
# end
# chars_arr.join('')
# end
# p reverse_vovel("hello")
|
<?php
namespace App\Http\Controllers\User;
use App\Models\Appointment;
use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyAppointmentRequest;
use App\Http\Requests\StoreAppointmentRequest;
use App\Http\Requests\UpdateAppointmentRequest;
use App\Models\Doctor;
use App\Models\User;
use DateInterval;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
use Yajra\DataTables\Facades\DataTables;
class AppointmentsController extends Controller
{
public function index(Request $request)
{
if ($request->ajax()) {
$query = Appointment::with(['user', 'doctor'])->select(sprintf('%s.*', (new Appointment)->table));
$table = Datatables::of($query);
$table->addColumn('placeholder', ' ');
$table->addColumn('actions', ' ');
$table->editColumn('actions', function ($row) {
$viewGate = 'appointment_show';
$editGate = 'appointment_edit';
$deleteGate = 'appointment_delete';
$crudRoutePart = 'appointments';
return view('partials.datatablesActions', compact(
'viewGate',
'editGate',
'deleteGate',
'crudRoutePart',
'row'
));
});
$table->editColumn('id', function ($row) {
return $row->id ? $row->id : "";
});
$table->addColumn('user_name', function ($row) {
return $row->client ? $row->client->name : '';
});
$table->addColumn('doctor_name', function ($row) {
return $row->employee ? $row->employee->name : '';
});
$table->editColumn('comments', function ($row) {
return $row->comments ? $row->comments : "";
});
$table->rawColumns(['actions', 'placeholder', 'user', 'doctor']);
return $table->make(true);
}
return redirect()->route('user.systemCalendar');
}
// public function create()
// {
// //abort_if(Gate::denies('appointment_create'), Response::HTTP_FORBIDDEN, '403 Forbidden');
//
// $users = User::all()->pluck('name', 'id')->prepend(__('Select User'), '');
//
// $doctors = Doctor::all()->pluck('name', 'id')->prepend(__('Select Doctor'), '');
//
//
//
// return view('user.appointments.create', compact('users', 'doctors'));
// }
public function store(StoreAppointmentRequest $request)
{
$minutes_to_add = 45;
$date = $request['start_time'];
$request['finish_time'] = new DateTime($request['start_time']) ;
// 45 lepta to rantevou
$request['finish_time']->add(new DateInterval('PT' . $minutes_to_add . 'M'))->format('Y-m-d H:i');
// Tsekarw an uparxei idi rantevou konta sautin tin wra
$alreadyBooked = DB::table('appointments')
->whereRaw('ABS(TIMESTAMPDIFF(MINUTE, start_time, ?)) <= 30', [$date])
->where('user_id',Auth::id())
->exists();
if($alreadyBooked){
echo '<script>alert("Appointment time already exists")</script>';
return redirect()->route('user.systemCalendar');
}
Appointment::create($request->all());
return redirect()->route('user.systemCalendar');
}
// public function update(UpdateAppointmentRequest $request, Appointment $appointment)
// {
// $appointment->update($request->all());
//
// //gurnaei sto callendar
// return redirect()->route('user.calendar.calendar');
// }
// public function show(Appointment $appointment)
// {
// //abort_if(Gate::denies('appointment_show'), Response::HTTP_FORBIDDEN, '403 Forbidden');
//
// $appointment->load('user', 'doctor');
//
// return view('user.appointments.show', compact('appointment'));
// }
// public function destroy(Appointment $appointment)
// {
// // abort_if(Gate::denies('appointment_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden');
//
// $appointment->delete();
//
// return back();
// }
}
|
Dubstep
''ํ์ฌ'' [[์ผ๋ ํธ๋ก๋์นด]]์ ํ์ ์ฅ๋ฅด.[* ๋ฅ์คํ
์ ์ ๊ตฌ๊ฐ๋ฑ ๋ฌธ๋จ ์ฐธ๊ณ ]
[[๋ชฉ์ฐจ]]
{{{#!html
<iframe width="560" height="315" src="http://www.youtube.com/embed/C46PEbXLYCs" frameborder="0" allowfullscreen></iframe>}}}
Dave Crowe ์ ๋์ฌ ๊ณต์ฐ.~~[[ํ๋ชจ๋์นด]] ํฅํ๋ค~~
{{{#!html
<iframe width="560" height="315" src="http://www.youtube.com/embed/n1htNKK_6hQ" frameborder="0" allowfullscreen></iframe>}}}
Mount Kimbie์ ๋ฅ์คํ
๋ผ์ด๋ธ. ~~๋ฅ์คํ
์ด๋ผ๋ฉด์ ์ฐ๋ธ๋ฒ ์ด์ค๋ ์ด๋ฐ ํ์๋จน์๊ฑฐ์ผ?~~ ~~[[wiki:"๊ฒ์๋ชป"๋ฅ์คํ
์์ง๋ ๋ชปํ๋ ๋๋ค์]] Brostep Sucks!!~~ ๋ฐ์์ ์ค๋ช
.
== ๊ฐ์ ==
[[UK ๊ฑฐ๋ผ์ง]], [[ํฌ์คํ
]] ๋ฑ ํ์ฐ์ค ์์
์ ๋ฆฌ๋ฌ์ [[์๋ฉ์ด์นด]]์์ ๋ฐ์ํ [[๋ฅ]] ์์
์ ์์๋ฅผ ์น์ ์์
์ด์, ํ์ฌ๋ [[์ผ๋ ํธ๋ก๋์นด]] ์์
์ ํ ๋ถํ๋ก ๋ณํ๋ค.
๊ธฐ์กด ํด๋ฝ ๋์ค๋ฎค์ง๊ณผ ๊ถค๋ฅผ ๋ฌ๋ฆฌํ๋ [BPM]๊ณผ ๋ฆฌ๋ฌ๊ตฌ์กฐ์ ์กฐํฉ์ผ๋ก ์ธํด ํน์ ์ ๊ฐ๋ ฌํ ์พ๊ฐ๊ณผ ํ๋ก์ฐ๊ฐ์ ์์๋ด๋ ๋์ ๋น์ฃผ๋ฅ ์ฅ๋ฅด์ ์ํ์ง๋ง, ์ฐ๋ธ๋ฒ ์ด์ค ์์์ ๊ฐ๋ ฅํ ๋ฒ ์ด์ค ๋ฆฌ๋ฌ์ ๊ฐ๋ฏธํ ์ ์ข
๋ฅ์คํ
์ด ๋ฑ์ฅํ ์ดํ ์ ์ธ๊ณ ๋์ค ์์
์
๊ณ์์ ์ฃผ๋ฅ ์ฅ๋ฅด๋ก ์๋ฆฌ์ก์๋ค.
๋ฅ์คํ
์ดํ์ ์ต์ ์ฑ๊ธฐ๋ 2012๋
์ด์๊ณ , ๊ทธ ์ดํ๋ก๋ ๋ถ์ ์ฌ๊ทธ๋ผ๋ ์ํ.
== ๋ฅ์คํ
์ ์ ๊ตฌ(ๆฐ่) ๊ฐ๋ฑ ==
ํํ ์
์
๊ฑฐ๋ฆฌ๋ ์ฐ๋ธ๋ฒ ์ด์ค๊ฐ ๋ค์ด๊ฐ ์์
์ผ๋ก ์๋ ค์ ธ ์์ง๋ง ์๋๋ ์ฐ๋ธ๋ฒ ์ด์ค๊ฐ ์ฃผ๊ฐ ๋๋ ์์
๋ ์๋์๊ณ ๋ฅ์คํ
์ ํฌ์คํ
๋ฆฌ๋ฌ์ด ์ฃผ ์์์ด์ง ์ฐ๋ธ๋ฒ ์ด์ค๋ ์๋
์ ๋ถ๊ณผํ๋ค. ์ด๊ธฐ ๋ฅ์คํ
์ ํฌ์คํ
๋ฆฌ๋ฌ์ [[๋ฅ]] ์์
์ ๊ณต๊ฐ๊ฐ์ ์น์ ์คํ์ ์ธ ์ฅ๋ฅด์๋ค. ๋ฅ์คํ
์ 180๋ ๋ฐ๊ฟ๋์ ๊ฒ์ ํ์ฑ๊ณผ๋ ๊ฐ์ด ๋ฑ์ฅํ ์คํฌ๋ฆด๋ ์ค๋ผ๋ ์ธ๋ฌผ์ ๊ณต์ด ํฌ๋ค๊ณ ํ ์ ์๋ค. ๊ทธ๋ ์์ ํ ๋ฅ ์์
๋ด์ง๋ [ํธ๋ฆฝ ํฉ]๊ณผ ์ ์ฌํ ๋ฉด๋ชจ๋ฅผ ๋ณด์ด๋ ๋ฅ์คํ
์ ์ ์ฒด์ฑ์ ์ฐ๋ธ๋ฒ ์ด์ค[* ๋ฒ ์ด์ค๊ฐ ๋ง์น ์ฌ๋์ด ๋งํ๋ ๊ฒ์ฒ๋ผ ์ธ๋ ๋๋ ๊ฒ์ ๋ปํ๋ฉฐ, ๊ฐ์ ๋งฅ๋ฝ์์ yai ๋๋ yoi๋ผ๊ณ ๋ ๋ถ๋ฆฌ์ด๋ค. ๋ณดํต ๋์ค๋ฎค์ง์ด๋ ๋ฐด๋์์
์์ ๋ฒ ์ด์ค๊ธฐํ ๋๋ ๋ฒ ์ด์ค์ ์ค๊ฐ ์ ํ๋ ์์ญ์ด ๋๋ต 300Hz๋ณด๋ค๋ ๋ฎ์ ํธ์ด๊ณ ์์๋ ๋ถ๋๋ฝ๊ณ ์จ๊ฑดํ ํธ์ธ๋ฐ, ์ผ๋ ํธ๋ก ํ์ฐ์ค๊ฐ ๋ฐ์ ํ๋ ์์ค์ ๋ณด๋ค ๊ฒฉ๋ ฌํ๊ณ ๋ํญํ ์์์ ์กฐ์ฑํ๊ธฐ ์ํด ๋ฒ ์ด์ค์ ๋์ ์ฐจ์์ ๋ฐฐ์์ ์ฒจ๊ฐํ๊ธฐ ์์ํ๊ฒ ์์ด์ด๋ค. ๊ทธ๋ฆฌ๊ณ ๋น๊ต์ ๋๋ฆฐ BPM์ผ๋ก ์ธํด ๋ง๋ ์์ ๋ณด๋ค ๋ค์ํ ํธ๋ฆญ์ ๋ฐ์ด๋ฃ์ ์ ์๋ ๋ฅ์คํ
์์๋ ๋ฒ ์ด์ค์ ๋ด๊ธด ๋ฐฐ์์ ๋น์ค์ ๋๋ฆฌ๊ณ ์ฐจ์๋ฅผ ๋์ด๋ ๋์ ์ฌ๋์ด ์์์ ์ฐจ์ด๋ฅผ ์ธ์ํ๋ 3000~5000Hz์ ๋ฌํ๋ ๋์ ์ฃผํ์๊น์ง ๊ฑด๋ค๊ฒ ๋์๊ณ ์ด๊ฒ์ด ์ฐ๋ธ๋ฒ ์ด์ค๋ผ๋ ์ด๋ฆ์ผ๋ก ์ ์ฐฉ๋์๋ค.]์ ๋
ธ๊ณจ์ ์ธ ์ผ๋ ํธ๋ก ์ฌ์ด๋, ์ฌํ๋ค ์ถ์ ์ ๋๋ก ๊ณผ๋ํ ๊ธ๋ฆฟ์น์ ๋์คํ ์
์ผ๋ก ์์ ํ ๋ฐ๊พธ์ด ๋์๋ค.
์๋ ๋ฅ์คํ
์ ๋ฐฉ๊ตฌ์ [[ํ์คํฐ]]๋ค์ด๋ ์ฐพ์๋ฃ๋, ๊ตณ์ด ํํํ๋ฉด [[Nerd]]๊ฐ์ ์ฅ๋ฅด์๋๋ฐ ์คํฌ๋ฆด๋ ์ค๋ฅ์ ์ฐ๋ธ๋ฒ ์ด์ค๋ฅผ ํ์ฉํ ๋ฅ์คํ
์ด ์ฃผ๋ฅ๊ฐ ๋๋ฉด์ 'ํํฐ์ฉ ์์
'์ด ๋๊ณ ๋ง์๋ค. ๊ทธ๋์ ์ด๋ฅผ ์กฐ๋กฑํ๊ธฐ ์ํด ์ด๋ฐ ์งค๋ฐฉ๋ ๋์ค๋ ๊ฒ์ด๋ค.
http://i.imgur.com/XZjj8.jpg
๋๋ฌธ์ ๋ฅ๊ณผ ํฌ์คํ
์ ์ตํฉ์ผ๋ก์จ ๋ฐ์ํ๋ ์์กฐ ๋ฅ์คํ
์ ๋๋ฆฌ์ด ๊ตฌ์ง๊ตฌ์งํ ์๋ฅ ๋ด์ง๋ ๋ฃจ์ ๋ค์ ์๊ธฐ์์ ์ ๋๋ก ํ๊ฐํ๋ ๋ฆ๊น์ด ์
๋ฌธ์์ ์ด ๋ฐ์ธ์ ๋ด์ง๋ฅผ ๊ฑฐ๋ ์ข ์ค๋๋ ์ ํธ๊ฐ๊ฐ์ ํค๋ฐฐ๊ฐ ์ธ๊ณ ๋์ฒ์์ ์ค๋๋ ๋ถ์ง๋ฐํ ๋ฒ์ด์ง๋ ์ค์ด๋ค. ๋๊ฐ ์คํฌ๋ฆด๋ ์ค๋ฅ์ ์ฐ๋ธ ๋ฒ ์ด์ค ์๋ฉ ๋ค์ด๊ฐ ๋ฅ์คํ
๋ง ์๋ ์ฌ๋๋ค์ด Burial์ด๋ Kode9๋ฅ์ ์ฌ๋์ค์ฟจ ๋ฅ์คํ
์ ๋ฃ๊ณ "[[wiki:"๋ด๋น" ์์ด ์ด๊ฒ ๋ฌด์จ ๋ฅ์คํ
์ด์์ฌ? wobwob๋๋ ์๋ ์๊ณ ๋นํธ๋ ์ฝํ๋ฐ ใ
กใ
ก;; ์ญ์ ๋ฅ์คํ
์ ์คํฌ๋ฆด๋ ์ค๊ฐ ์งฑ์ธ๋ฏ ^-^]]" ์์ผ๋ก ๋์ค๋ฉด ๊ฑฐ๊ธฐ์ ๋ํญํด์ ์ฌ๋์ค์ฟจ ๋ฅ์คํ
๋ฆฌ์ค๋๋ค์ด ๋ฐ๋ํ๋ ๋ฐฉ์์ผ๋ก ์งํ๋๋ค.(โฆ) ๋ค์ผ๋ก [[๋๋ผ ์ค ๋ฒ ์ด์ค]]๋ฅผ ๊ฐ์ง๊ณ "์ด๊ฑด ๋ ๋ฌด์จ ๋ฅ์คํ
์ธ๊ฐ์? 'Fast Dubstep'์ธ๊ฐ์? ์คํฌ๋ฆด๋ ์ค๋ณด๋ค ๋ชปํ๋ค?" ๋ผ๋ ์ด๊ทธ๋ก๋ฅผ ๋์ด์ ์ ๊ธ๋ฆฌ์คํธ๋ค์๊ฒ๋ ๊ต์ฅํ ๋นก์นจ์ ์ ๋ํ๊ณ ๊ทธ๊ฒ ์๋ ์ค๋ช
ํ๋ฏ, ๋ฉ์ด์ ์ฅ๋ฅด DJ๋ค์ด ๊น๊ฒ ๋๋ ๊ณ๊ธฐ๊ฐ ๋๊ธฐ๋ ํ๋ค.
์ ๊ตฌ ๋ฅ์คํ
์ ์ผ๋ฐ์ธ์ด ๊ทธ๋ฅ ๋ค์ด๋ '์ด ๋ ์์
์ ๊ฐ์ ์ฅ๋ฅด๋ก ๋ฌถ๋ ๊ฒ์ด ์ ์ ํ๊ฐ?' ์ถ์ ์๊ฐ์ด ๋ค ์ ๋๋ก ์ฐจ์ด๊ฐ ํฌ๋ค. ํ์ ํ ๊ฐ์ฃผ์ฒ๋ผ, ๊ฐ์ [[์ถ๊ตฌ]]์ง๋ง ์ผ๋ฐ์ ์ธ ์ ๋ฝ์ [[์ถ๊ตฌ]]์ [[๋ฏธ์์ถ๊ตฌ]] ์ ๋์ ์ฐจ์ด๋ผ๊ณ ๋ด์ผ ํ ๋ฏ.~~์์ด ์ด๊ฒ ๋ฌด์จ ์ถ๊ตฌ์์ฌ? ์๋ ์ ์ฐ๊ณ ๋ชธ์ธ์๋ ์๋๋ฐ ใ
กใ
ก;; ์ญ์ ์ถ๊ตฌ๋ ์ํผ๋ณผ์ด ์งฑ์ธ๋ฏ ^-^~~ ํ ์์
์ ์กฐ๋ฅ ๋ด์์ ์ ๋ฝ๊ณผ ๋ฏธ๊ตญ์ ๋ถ๋ช
ํ ์์
์ฑ ์ฐจ์ด์ ๋ฐ์์ด [[๊ฐ๋ฒ]]์ ์ด์ด์ ๋ฅ์คํ
์์๋ ๋ํ๋๋ ์
.[* ์ ๋ฝ์ชฝ์์๋ ๋์คํ์ผ ๊ณ์ด์ 12๋นํธ, ์ ๋นํ ๋น ๋ฅธ ํ
ํฌ์ ๊ฐ๋ฒ๊ฐ ๊ฐ์ธ์ด๋ฉฐ, ๋ถ๋ฏธ์์๋ ์ฐ์งํ๊ฒ ๋น ๋ฅธ ํ
ํฌ์ [[four-on-the-floor]]๋ก ๋ฌด์ํ๊ฒ ๋ฐ์ด๋ถ์ด๋ ๊ฐ๋ฒ๊ฐ ๊ฐ์ธ๋ผ๊ณ ํ๋ค. ์ด๊ธฐ ๊ฐ๋ฒ๋ ์์ชฝ์ด ํผ์ฌ๋ ๋ชจ์ต์ด์ง๋ง ์ธ์์ด ์ง๋๋ฉด์ ์์
์ฑ ์ฐจ์ด๊ฐ ๋ฐ์ํ๋ฏ. EDM ๊ฐ์ด๋๋ฅผ ํธ์ฐฌํ ishkur์ ๋ฐ๋ฅด๋ฉด '์ด๊ฒ์ ๋ง์น ์ ๋ฝ์ [[์ถ๊ตฌ]]์ [[๋ฏธ์์ถ๊ตฌ]]์ ์ฐจ์ด ๊ฐ์๊ฒ'์ด๋ผ๊ณ ํ๋ค. ๋ณธ ๊ฐ์ฃผ๋ EDM ๊ฐ์ด๋ 2.5์ '''์ฃผ๊ด์ ์ธ ๋ถ์'''์ ๊ธฐ๋ฐํ [[๋
์์ฐ๊ตฌ]]์์ ๋ฐํ.] ์ด ๋ฌธ์์์๋ ๊ฐ๊ฐ UK ๋ฅ์คํ
, US ๋ฅ์คํ
์ผ๋ก ๋ถ๋ฅํ๋ค.
* UK ๋ฅ์คํ
์๊ตญ ์ธ๋๊ทธ๋ผ์ด๋ ํด๋ฝ์ฌ์์ ๋ฐ๋ฌ์์ผ์จ [UK ๊ฐ๋ฌ์ง][* garage๋ ์ฐจ๊ณ ๋ฅผ ๋ปํ๋๋ฐ, ์ฐจ๊ณ ์ ๋ชจ์ฌ์ ๊ฐ์ด ์ฆ๊ธฐ๋ ์์
์ด๋ผ๋ ์๋ฏธ์ด๋ค. ์ด๊ฒ์ ์ฐฝ๊ณ (warehouse)์ ๋ชจ์ฌ์ ๋ฃ๋ ๊ฒ์ด๋ผ๋ ์๋ฏธ์์ ์ ์์ ๊ธฐ๋ฐ์ 4๋ฐ์ ๋์ค๋ฎค์ง์ house๋ผ๋ ์ฅ๋ฅด๋ก ๊ท์ ํ ๋ฏธ๊ตญ์ ์ฌ๋ก์ ์ ํํ ์ผ์นํ๋ค.]์ ์ฃผ๋ ํน์ง์ธ 2 Step[* ์ฌ๊ธฐ์์ ์คํ
์๋ ์ถค์ ์ถ๋ฉด์ ๋ฐ๋ฅ์ ๋๋ ๊ฒ๊ณผ ํฅ๋๋ผ์ ์น ๋ ํฅํจ๋๋ฅผ ๋ฐ๋ ๋๊ฐ์ง์ ์๋ฏธ๊ฐ ์๋ค. ์ฆ 2์คํ
์ 1๋ง๋ 4๋ฐ์์ ์คํ
(ํฅ๋๋ผ)์ด 2๋ฒ๋ง ๋์จ๋ค๋ ์๋ฏธ์ธ ์
์ด๋ค. ์ด์ ๋ฌ๋ฆฌ ํ์ฐ์ค, ๋์ค์ฝ, ๋ฝ ๋ฑ์ ๋ฆฌ๋ฌ์๋ ์ง์๋ฐ์๋ ํฅ์ด ์ฐํ๋ค.]๋ฆฌ๋ฌ์ ๋ผ๋๋ก ์ผ๊ณ , [์๋ฉ์ด์นด]์ ๋ฅ ์์
์ ์์๋ฅผ ๊ทธ ์์ ์น์ด์ฌ๋ฆฐ ์คํ์ ์ธ ํผํฉ์ฅ๋ฅด์ด๋ค.
2000๋
๋ ํ๋ฐ์ ๊ฐ์๊ธฐ ํญ๋ฐํด์ ์ธ๋ ์ผ๋ ํธ๋ก๋์นด์ ๋ฉ์ด์ ์ฅ๋ฅด๊ฐ ๋์์ง๋ง, ์ฐ๋ธ๋ฒ ์ด์ค๊ฐ ์ฃผ๋ฅ๊ฐ ๋๋ US ๋ฅ์คํ
์ด ๋ฑ์ฅํ 2010๋
๋ ์ด๋ฐ ํ์ฌ์๋ ๋ค์ ์ผ๋ถ ์ ํธ๊ฐ๋ค๋ง์ ์ฅ๋ฅด๋ก ๋์๊ฐ๋ค.
* US ๋ฅ์คํ
๋ฏธ๊ตญ์์ ๊ฐ๋๋ ์ ์ข
๋ฅ์คํ
. ๋ฆฌ๋ฌ๊ณผ ์๋๋ง ํฌ๊ฒ ์ฐจ์ด๋ ๋ฟ ์ฃผ๋ก ์ฐ์ด๋ ์ ์์ฌ์ด์ ๋ ํผ์ปค์
์ ์์์ [[์ผ๋ ํธ๋ก ํ์ฐ์ค]]์ ๋๊ฐ๋ค๊ณ ํด๋ ๋ฌด๋ฐฉํ๋ค. UK ๋ฅ์คํ
์ด UK ๊ฑฐ๋ผ์ง์ ์ฐจ๋ถํ ๋ฆฌ๋ฌ์ ๊ธฐ๋ฐํ ๊ฒ์ ๋นํด
์ฐ๋ธ๋ฒ ์ด์ค๋ฅผ ๋ก์น ์์ค์ผ๋ก ๋จ์ฉํ๋ ๋ฅ์คํ
์ ๋ธ๋ก์คํ
[* BroStep. Bro๋ค์ด๋ ๋ฃ๋ ์คํ
์ด๋ผ๋ ์๋ฏธ์ธ๋ฐ, ์์ด๊ถ์์ Bro๋ ๋๋ต ๋ถ์์ ๋ง์ง ์๊ฒ ๋ช
ํ์ท์ผ๋ก ๋๋ฐฐํ๊ณ ๋ค๋๋(Chav์ ๋น์ท), ๊ต์์๊ณ ๋ฌด๋กํ, ์ฌ์ ๊ผฌ์๋๋ฐ ํ์์ด ๋, ํนํ ์ถ๊ตฌ์ ํ์ฅํ, ๋จ์ฑ์ฑ์ ๊ณผ์ํ๋ ค ๋ค๊ณ ๊ฒ์ด๋ฑ์ ์์์์๊ฒ ์ ๋์ ์ธ, ํ์ธ์ค๋ฝ๊ฒ ํ๊ณ ๋ค๋์ง๋ ์์ง๋ง ๋งํฌ๋ ์ ์ค์ณ์์ ํ์ธ ํํฉ๋ฌธํ์ ์ํฅ์ ๋ง์ด ๋ฐ์(์น๊ตฌ๋ผ๋ฆฌ "hey bro"๋ผ๊ณ ๋ถ๋ฅด๋ ๋ฑ) ์ ์ ๋ฐฑ์ธ๋จ์ฑ์ ์ง์นญํ๋ ๋ง์ด๋ค. ์ฆ ์ ๋ฐ ๋๋ค๊ฐ์ ์์
์ด๋ผ๋ ๋ฉธ์์ ์ธ ์๋ฏธ.]์ด๋ผ๊ณ ๋ถ๋ฅด๊ธฐ๋ ํ๋ค. ์์ ๋ฏธ๊ตญ์ ๋ฅ์คํ
์ ์ธ์ก์์ ๋ธ๋ก์คํ
์ด๋ผ๊ณ ๋ถ๋ฅด๋ ์ฌ๋๋ ์๋ค.
์ด ๋ฌธ์์๋ ์ฐ๋ธ๋ฒ ์ด์ค ์ฌ์ด๋๊ฐ ์ค์ฌ์ด ๋๋ ๋ฅ์คํ
์ ๋ํ ์๊ฐ๊ฐ ์ฃผ๋ฅ๋ฅผ ์ด๋ฃจ๊ณ ์๋ ์ ์ ์ ๋
ํ์.
== ํ ์ฅ๋ฅด์์ ๊ฒฐํฉ ==
2010๋
๋๋ถํฐ ํ ์ฅ๋ฅด์ ์ฌ๋ฌ ์ํฐ์คํธ๋ค์ด ๋ฅ์คํ
์ฌ์ด๋๋ฅผ ๋์
ํ๊ณ ์๋ค. [[์คํฌ๋ฆด๋ ์ค]]๋ณธ์ธ์ Cat rats๋ผ๋ ๊ณก์ผ๋ก ๋์ค์ฝ์์ ๊ฒฐํฉ[* ์ฌ์ด๋ํด๋ผ์ฐ๋์์ ๋ณธ ๊ณก์ ํ๊ทธ๋ฅผ ๊ณต์์ผ๋ก Discostep(LOL)์ด๋ผ๊ณ ๋ถ์๋ค(...)]์ ์๋ํ๋ฐ๊ฐ ์์ผ๋ฉฐ
์๋ฅผ๋ค๋ฉด, [[๋ธ๋ฆฌํธ๋ ์คํผ์ด์ค]]์ ํ๋ฏํํ์ ์๋ก๊ณก Hold It Against Me์ ๋์
ํ ๋ฅ์คํ
์ด๋ผ๋ ์ง, ์ ์์ค ๋ธ๋ ์ดํฌ์ ์จ๋ฒ ์ ์์ค ๋ธ๋ ์ดํฌ์์๋ ์์ธ์ ๋ฅ์คํ
์ฌ์ด๋๋ฅผ ์ ๋ฒ๋ฌด๋ ค์ UK์ฐจํธ 9์ ํซ์ท ๋ฐ๋ทํ๋ ๊ธฐ์ผ์ ํ ํ๋ ๋ฑ ๋์ธ ์ธ์ฆ์ ํ๊ณ ์๋ ์
์ด๋ค. ๊ฐ๊น๊ฒ๋ [[ํ์]]์ ๋ฒ๋ธํ์ 2๋ถ 20์ด๋ถํฐ ์ฝ 28์ด๊ฐ, [[์ ํํฐ ์ค์ฟจ]]์ ํ๋์๋ฐฑ์์๋ 2๋ถ 25์ด๋ถํฐ ์ฝ 10์ด๊ฐ ์ง์๋๋ค๊ณ ํ๋, ๊ถ๊ธํ๋ค๋ฉด ๋ค์ด๋ณด๋๋ก ํ์.[* ๋ธ๋ฆฌํธ๋ ์คํผ์ด์ค, ํ์, ์ ํํฐ ์ค์ฟจ์ ๋
ธ๋๋ค์ ์
๊ณก ๊ตฌ์กฐ์ ๋ธ๋ฆฟ์ง์ ํด๋นํ๋ ์ ์ ์ฌ๋ ๊ตฌ๊ฐ์ ๋ฅ์คํ
๋ฆฌ๋ฌํจํด์ ๊ธฐ๊ณ์ ์ผ๋ก ์ค์
๋ฃ์ ๊ฒ์ผ๋ก ๋ณผ ์ ์๋ค.] --์ด๋ฅผ ๋ณด๋ฉด ๋ฅ์คํ
์ ๋ฃ๋๋ค๊ณ ๋ค ํฅํ์ง๋ ์๋ ๋ฏํ๋ค.-- --๋ฅ์คํ
์ด ๋์ง ๊ฐ์ด๋ฆ์ด๋?!?!?-- New F O ๋ผ๋ ํ๊ตญ ๊ฑธ๊ทธ๋ฃน์ด ๋ฅ์คํ
์์ด๋์ ํ๋ฐฉํ๊ณ ๋์๋ค. ํธ๋ ๋๋ ํธ๋ ๋์ธ์ง [[SMP]]๋ฅผ ๊ณ ์ํ๋ [[๋๋ฐฉ์ ๊ธฐ]] ์ญ์ 6์ง์์ ๋ฅ์คํ
์ ์๋ํ๋ค.[* ํ์ง๋ง ๋ค์ด๋ณด๋ฉด ๋ํ์ ์ธ SMP ๊ณก์ธ 'Rising Sun' ๊ณผ ์
๊ณก ๊ตฌ์กฐ๊ฐ ๊ฑฐ์ ๋น์ทํ๋ค(...)] ์ดํ SM์ [[EXO]]์ ์ ๊ท 1์ง์์ ๋ณธ๊ฒฉ์ ์ผ๋ก ๋ฅ์คํ
์ ์๋ํ๋ค.[* ์์ ์ธ๊ธํ ํ์๋ ์ ํํฐ์ค์ฟจ, ๋๋ฐฉ์ ๊ธฐ๊ฐ ๋ฅ์คํ
์ ์ ๋ชฉํ ๊ณก ์์ค์ด๋ผ๋ฉด ์ด์ชฝ์ ์ผ๋ถ๋ฅผ ๋นผ๊ณ ์์ ํ ๋ฅ์คํ
์ด๋ค.] ๋ํ ์ต๊ทผ f(x)์ ์ ๊ท 2์ง ์๋ก๊ณก ์ค ํ๋์ธ 'toy'์์๋ 2๋ถ 4์ด๋ถํฐ 30์ด๊น์ง ๋ฅ์คํ
์ ์ฌ์ฉํ๊ธฐ๋ ํ์๋ค. 2011๋
์ '''[[๋ผ๋์คํค๋]]'''๊ฐ [[The King of Limbs]]์์ ๋ฅ์คํ
์ ์ํฅ์ ๋ฐ์๋ฏํ ์ฌ์ด๋๋ฅผ ์ ๋ณด์๋ค. ๋๋
์ [[๋ด๋ฉํ]]์ ๋๋ถ์๋ '''[[Korn]]'''์ด ์์ ๋ค์ ์จ๋ฒ The Path of Totality์ '''[[์คํฌ๋ฆด๋ ์ค]]'''๋ฑ ์ฌ๋ฌ ๋ฅ์คํ
๋ฎค์ง์
๊ณผ ์์
ํ๋ฉด์ ๋ฉํ๊ณผ ๋ฅ์คํ
์ ์์ด [์ ์ ]ํ ๋ถ๋ฐฐํ์ฌ ํ๋จ์ ํธํ์ ๋ฐ์๋ค. '''[[3OH!3]]'''๋ํ Do or die๋ผ๋ ์ฑ๊ธ์ ํตํด ๋ฅ์คํ
์ ๋ณด์ฌ์ฃผ์๋ค. '''[[Muse]]'''๋ 2012๋
๋ ์ ๋ณด์ '''๋ฌ๊ธ์์ด''' ๋ฅ์คํ
์ ์๋ํ๋ค. --๋ฌผ๋ก ์ฃ๋ค ๋ธ๋ก์คํ
์ด๋ค.-- --[[wiki:"๋ด๋น" ๋น์ฐํ์ง, ์ฐ๋ธ๋ ์๋๊ฒ ๋ฌด์จ ๋ฅ์คํ
์ด๋?]]--
๋ํ ๋๋ฆด ์ค ๋ฒ ์ด์ค/[[IDM]] ์ํฐ์คํธ์ธ Warp Records ์์์ธ [์คํ์ดํธ์
]๊ฐ 2012๋
๋ฐํํ ์ ๊ณก
{{{#!html
<iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/XvLAKrVbCBM" frameborder="0" allowfullscreen></iframe>}}}
์์๋ ์์ ์ ์ฃผ ์ฅ๋ฅด์ธ ๋๋ฆด ์ค ๋ฒ ์ด์ค์ ๋ฅ์คํ
์ ๊ฒฐํฉ์ ์๋ํ๋ค. ๋ฌผ๋ก ์์
ํน์ฑ์ ๋ธ๋ก์คํ
์ ์ธ ์์๋ ๊ฝค๋ ํฌ์๋๋ฏ ํ์ง๋ง, ์คํ์ดํธ์
๊ฐ ๋ฅ์คํ
์ ๊ฒฐํฉ์ ์๋ํ๋ค๋ ์ ์์ฒด๋ง์ผ๋ก๋ "์ ์ ํ ์๋๋ค" vs "์๋ ์ด๊ฒ ๋ฌด์จ์๋ฆฌ์ผ ๋๋ฆด ์ค ๋ฒ ์ด์ค์ ์์กด์ฌ ์คํ์ดํธ์
์๋ฐ์ด ๋ฅ์คํ
์ ํ๋ค๋"๋ก ํธ๋ถํธ๊ฐ ๊ฐ๋ฆฌ๊ณ ์๋ค.
== ํน์ง ==
๋ฆฌ๋ฒ๋ธ, ์์ฝ, ๋๋ ์ด๋ฑ์ ์ฌ์ฉํ์ฌ ๋์ ๊ณต๊ฐ๊ฐ์ ํ์ฑํ๊ณ , ๋ฒ ์ด์ค๋ฅผ ๋ฌต์งํ๊ฒ ๊น์ 90Hz ์ดํ์ ์๋ธ ๋ฒ ์ด์ค๊ฐ ๋งค์ฐ ๋๋๋ผ์ง๋ค. ์ต๊ทผ ๋ค์ด์๋ ๋ฒ ์ด์ค์ ๋ฌด๊ฒ๊ฐ์ด๋ ์๊ฐ ๋ณด๋ค๋ ์๋ธ๋ง์ ๊ธฐ๊ต์ ์ฃผ๋ชฉํ๋ ๊ฒฝํฅ์ด ๋ ๊ฐํด์ ์๋ธ ๋ฒ ์ด์ค๋ณด๋ค๋ ์ดํผ ๋ฒ ์ด์ค ํน์ ๊ทธ ์ด์์ ์ฌ์ด๋๊ฐ ๋ ๋๋๋ผ์ง๋ ๊ฒฝ์ฐ๋ ๋ง๋ค. ๋นํธ์ ํน์ง์ผ๋ก๋ ํฅ๊ณผ ์ค๋ค์ด๋ฅผ ํฌ ์คํ
๋นํธ๋ก '''์ฟต! ์ฐฉ! ์ฟต! ์ฐฉ!''' ๋๋ ์[* ์ง์๋ฐ์ ํฅ์ด ์ ๋๋ก ๋ค์ด๊ฐ์ง ์์.] ์น๊ณ ์ฌ์ด์ฌ์ด ๋ฎคํธ[* ๋ฐ์์ ๋ง๋๋ณด๋ค ํฐ ๋จ์์ธ ํ๋ ์ด์ฆ์ ์ฌ์ด๋ฅผ ์งง์ ์ ์ ๊ณผ ๋ค์ด์ ํฐ ์๋ฆฌ๋ก ์ฅ์ํ๋ ๊ธฐ๋ฒ์ด ์๋๋ฐ, ์ฌ์ด๋์ ๊ฐ์ฅ ํฐ ๋ถ๋ถ์ ์ฐจ์งํ๋ ๋ฒ ์ด์ค๊ฐ ์๊ฐ ์์์ง๋ค๋ ์๋ฏธ์์ ๋ฒ ์ด์ค๋๋(Bass Drop)์ด๋ผ๊ณ ๋ถ๋ฅธ๋ค.]๋ฅผ ๋ฃ์ด ์ฃผ๋ ๊ฒ์ด ํน์ง์ด๋ค. ์ข
์ข
๋ ๊ฒ ๋ฆฌ๋ฌ๋ ์ฐพ์๋ณผ ์ ์์ผ๋ฉฐ, ๊ฐ๋์ฉ ์๊ทน ์ฅ๋ฅด์ธ [[ํ๋์ฝ์ด ํ
ํฌ๋
ธ]][[wiki:"four-on-the-floor" ์ ๋ฆฌ๋ฌ]]๊ณผ๋ ๊ฒฐํฉ๋๋ค. BPM์ ๋๋ถ๋ถ์ ๊ฒฝ์ฐ 110-140์ฌ์ด๋ฉฐ, ๋ณดํต์ ๊ฒฝ์ฐ์๋ 140(70)์ด ์ฃผ๋ฅผ ์ด๋ฃฌ๋ค. [[๋๋ผ ์ค ๋ฒ ์ด์ค]]์ ๋๋ผ ๋นํธ๊ฐ ๋ณธ๋์ ์ ์ ๋ ์คํ์ผ์ ๋๋ผ ๋นํธ๋ฅผ ๊ฐ์ง ๋ฅ์คํ
๊ณผ ํฉ์ณ์ง ๋๋ผ์คํ
๋ฅ์ ๊ฒฝ์ฐ 85(170) ์ ํ์ BPM์ ๊ฐ์ง๋ค.
[[๋ธ๋ ์ดํฌ๋นํธ]]์ ์ํฅ์ ๋ฐ์ ๋ณต์กํ ๋ฆฌ๋ฌ์ ๋ถ์ , ๋ฒ ์ด์ค๊ฐ ์ ๋ํ ๊ฐ๋ ฅํ ์ฅ๋ฅด์ ํน์ฑ์ [[๋๋ผ ์ค ๋ฒ ์ด์ค]]๋ฆฌ์ค๋๊ฐ ๋ค์ด๋ ๊ฑฐ๋ถ๊ฐ์ด ์๊ณ , ์ฌ์ง์ด ๋ฏน์ค์์ ๋ฅ์คํ
์ ๊ฐ๊ฐํ ๋ผ์๋ฃ๋ [[DJ]]๋ ์๋ค.[* ๋ฐ์ง๊ณ ๋ค์๋ฉด ๋ฅ์คํ
์ ๋๋ผ์ค๋ฒ ์ด์ค์ ๋์์ด๋ ์กฐ์นด๊ฒฉ์ธ ์ฅ๋ฅด์ด๋ฉฐ, ๋ฆฌ๋ฌ๊ตฌ์กฐ๊ฐ ๋์ผํ ํฌ์คํ
์ด๊ธฐ ๋๋ฌธ์ BPM๋ง ์ญ ๋ฐ์ด์ฃผ๋ฉด ๋นํธ๋งค์นญ์ผ๋ก ์ด์ด๋ถ์ฌ๋ ์ํ๊ฐ์ด ์๋ค.]
๋ฅ์คํ
์ ํฌ๊ฒ [[Skrillex]] ์ด์ ๊ณผ ์ดํ๋ก ๋๋๋๋ฐ, Skrillex๊ฐ ์ธ๊ธฐ DJ๊ฐ ๋ ์ดํ, ์๋นํ ํค๋นํ ๋ถ๋ฏธ๊ณ์ด ๋ฅ์คํ
๋ฆฌ์ค๋/์ํฐ์คํธ๋ค์ด ์๊ตญ ๋ฅ์คํ
, ๊ทธ๋ฌ๋๊น ์์ ์ ์๋ฐํ ๋ฅ์คํ
์ ๋ฌด์ํ๊ธฐ ์์ํ๋ค. ๊ทธ๋์ ์ ์ ์๊ตญ๊ณผ ๋ถ๋ฏธ ๋ฅ์คํ
์ผ๋ก ๋๋๋ ์ค.
์๊ทผํ ํ๋์ฝ์ด ํ
ํฌ๋
ธ ๋ฆฌ์ค๋/์ ๊ธ๋ฆฌ์คํธ๋ค์ด ๊ต์ฅํ ์ซ์ดํ๋ค. ์ ํ๋ธ์์ ํ๋์ฝ์ด ๋ฏน์ค์
์ด๋ ๋๋ผ ์ค ๋ฒ ์ด์ค ๊ด๋ จ ๋์์๋ค์ ์ข ์ฐพ์๋ณด๋ฉด ๋๊ธ์ฐฝ์์ ๋ฅ์คํ
์ ๊น๋ ๋๊ธ์ ์ฌ์ฌ ์ฐฎ๊ฒ ์ฐพ์๋ณผ์ ์๋ค. Headhunterz๋ "๋ฅ์คํ
๊ณผ [[ํ๋์คํ์ผ]]์ ์๊ทน"์ด๋ผ๊ณ ๋งํ๊ธฐ๋[* ๋ฌผ๋ก ์ ๋ถ๊ฐ ๊ทธ๋ ๋ค๊ณ ํ๊ธฐ๋ ์ด๋ ต๋ค. Headhunterz ๋ณธ์ธ์ ์ ์ ํ๋์คํ์ผ๊ณผ ๋ฅ์คํ
์ ํฉ์น '[["ํ๋์ฝ์ด ํ
ํฌ๋
ธ" ๋ฅ์คํ์ผ]]'์ด๋ผ๋ ์ฅ๋ฅด๋ฅผ ๋ง๋ค์ด๋๊ณ , J-์ฝ์ด๊ณ์์ ์ ๋ช
ํ [[DJ TECHNORCH]]์ญ์ ๊ฐ๋ฒ์คํ
์ด๋ผ๋ ํน์ดํ ์ฅ๋ฅด๋ฅผ ๋ง๋ค์ด ๋ด๊ธฐ๋ ํ๋ค. ์ด์ ๋น์ทํ๊ฒ ๋ฅ์ฝ์ด๋ผ๋ ์ฅ๋ฅด๋ ์กด์ฌ.] ๋๋ผ ์ค ๋ฒ ์ด์ค ์ชฝ์ผ๋ก๋ [[RAM Records]]์์ [[Chase & Status]]๋ [[DC Breaks]]๊ฐ ๋๋ผ ์ค ๋ฒ ์ด์ค๊ฐ ์๋๋ผ ๋ฅ์คํ
์ ์๋ํ๋ค ํฌ๋ค์๊ฒ ๋ชป๋งค๋ฅผ ๋ง๊ณ DC Breaks ๋ ๋ฅ์คํ
์ ๋์ด์ ๋ด์ง ์๊ณ CnS๋ ์์ ๋ ์ด๋ธ์ ๋์ค๊ฒ ๋๊ณ , [[John B]]๋ [[Sigma]], [[Friction]], [[Andy C]], [[DJ Hype]] ์ ๊ฒฝ์ฐ [[ํ์ด์ค๋ถ]]๊ณผ [[ํธ์ํฐ]]๋ฑ์ ํตํด "Dubstep Sucks"์ ๊ดํ ๋ด์ฉ๋ค์ '''๊ณต์์ ์ผ๋ก "๊ฝค ์์ฃผ"'''์ฌ๋ฆฌ๊ณ ์๋ค. ์ฌ์ค์ UK ๋๋ผ ์ค ๋ฒ ์ด์ค์ ์ค๊ฒฌ๊ธ ์ํฐ์คํธ๊ฐ ์ด๋ฐ ๋ฐ์์ ๋ณด์ผ ์ ๋๋ฉด ์ด๋ค์ด '๋ธ๋ก์คํ
'์ ๊ฐ์ง ๊ฐ์ ์ ๊ณจ์ด ์ด๋ ์ ๋์ธ์ง ์ง์ ๊ฐ๋ฅํ ๋ฏ. ~~๊ทธ๋ฆฌ๊ณ ์ด ๋จ๋ ์ฅ๋ฅด ๊น๊ธฐ๋ [wiki:"ํ์ฐ์ค(์์
)#s-2.12"๋น
๋ฃธ ํ์ฐ์ค]๋ก ์ด์ด์ง๋ค~~
== ๋ฅ์คํ
์ฅ๋ฅด ์ ๋ช
DJ ==
[wiki:"DJ/๋ชฉ๋ก#s-1.5" ํญ๋ชฉ ์ฐธ์กฐ]
== ๋ํ ๋ ์ด๋ธ ==
* Tempa
* Hyperdub[* ๋ฅ์คํ
๋ ์ด๋ธ๋ก ๋ง์ด ์๋ ค์ ธ ์์ผ๋ ์ ์คํ, ๊ฐ๋ฌ์ง, ๊ทธ๋ผ์๋ ํผ์ฌ๋์ด ์๋ค.]
* Deep Medi Musik
* Tectonic
* Firepower Records[* Datsik์ด ์ค๋ฆฝํ ๋ ์ด๋ธ๋ก, AFK, Must Die!, Getter, Barely Alive๋ฑ์ด ์์๋์ด ์๋ค.]
* Planet Mu[* ๋ณธ๋ ๋ฎค์งํฌ(ฮผ-Ziq)๋ฅผ ํ๋๋ก ํ IDM ๋ ์ด๋ธ๋ก ์ถ๋ฐํ์ผ๋ ํ์ฌ๋ ๊ฑฐ์ง๋ฐ ๋ฅ์คํ
๋ ์ด๋ธํ๋์๋ค.(...) ํ๋ ์ดํ์ ์์นด๊ณ ํ์ฐ์ค๋ฅผ ๋ฐ๋ค๊ฐ ํญ๋งํ ๋ค๋ก ์ด๋์ ๋ ์๋๊ฒ ๋์ด๋ฒ๋ ธ์ผ๋ [[์์ต]]. ๊ฒ๋ค๊ฐ ์ฌ๊ธฐ์ ์จ๋ฒ์ ๋๋ ๋ฅ์คํ
๋ฎค์ง์
๋ค์ด ๋์ํ ๋ฑ ํ ์ผ๋ ํธ๋ก๋์นด ๋ ์ด๋ธ๋ก ์ ๊ฐ๊ธฐ ํฉ์ด์ ธ๋ฒ๋ ธ๋ค...]
* Punch Drunk
* [Monstercat Media][http://www.youtube.com/user/MonstercatMedia ์ ํฌ๋ธ ์ฑ๋][* ๋ฅ์คํ
์ธ์๋ ์ผ๋ ํธ๋ก ํ์ฐ์ค, ๋๋ผ์คํ
, ๋๋ผ์ค ๋ฒ ์ด์ค, ํ
ํฌ๋
ธ ๋ฑ ์ฌ๋ฌ ์ผ๋ ํธ๋ก๋์นด ์ฅ๋ฅด๋ฅผ ์ญ๋ ตํ๋ ๋ ์ด๋ธ์ด๋ค. ์ ํฌ๋ธ ์ฑ๋์์ ๋งค์ฃผ ์, ์, ๊ธ๋ง๋ค ์๋ก์ด ๊ณก๋ค์ ์
๋ก๋ํ๊ณ ์๋ค.]
* [OWSLA][* [Skrillex]๊ฐ [Deadmau5]์ ๋ ์ด๋ธ์ธ Mau5trap์ ๋์์ ๋ง๋ ๋ ์ด๋ธ.[Skrillex], [Porter Robinson] ๋ฑ์ ์ ๋ช
ํ ๋ฅ์คํ
, [๋๋ผ ์ค ๋ฒ ์ด์ค], [ํ์ฐ์ค] ํ๋ก๋์๋ค์ด ์ํด์๋ค.]
* MTA Records[* Chase and Status, Nero, 16bit ๋ฑ์ด ์ํด์๋ ๋ ์ด๋ธ์ด๋ค.]
* Never Say Die Records[* SKiSM, 501, Dodge & Fuski, Zomboy ๋ฑ์ด ์ํด์๋ ๋ ์ด๋ธ์ด๋ค. UKF Dubstep ์ฑ๋์์ ๋ฐ์ด์ฃผ๊ณ ์๋ ๋ ์ด๋ธ.]
* Circus Records
== ์ ๋ฌธ [[์ ํฌ๋ธ]] ์ฑ๋ ==
* [http://www.youtube.com/user/MonstercatMedia Monstercat Media][* ๋ ์ด๋ธ์ด๋ฉด์ 1์ฃผ์ 3๋ฒ์ฉ ์ข์ ํ๋ฆฌํฐ์ ๊ณก์ ์์๋ด๋ ๋์ธ๋ฐฐ์ ์ธ ๋ ์ด๋ธ. ์์ ์ธ์์ mainstream ํ ์ฌ๋๋ค๊ณผ๋ ๊ฑฐ๋ฆฌ๊ฐ ์์ผ๋ ์ค๋ ฅ์ด ์ถ์คํ๋ค.]
* [http://www.youtube.com/user/UKFDubstep UKF Dubstep][* ์
๋ฌธ์ฉ์ผ๋ก ์ข์ ์ฑ๋. ์ฃผ๊ธฐ์ ์ผ๋ก ๋ฅ์คํ
๊ณก์ ์
๋ก๋ํ๋, Skrillex ์คํ์ผ๊ณผ ๊ฐ์ ๊ธฐ์กด ๋ฅ์คํ
๊ณผ๋ ๊ฑฐ๋ฆฌ๊ฐ ๋จผ ๊ณก๋ค์ ์์ฃผ ์
๋ก๋ํ๊ณ ํ๋ณด์ฑ์ด ์ง์ด ์ข์ ํ๊ฐ๋ ๋ฐ์ง ๋ชปํ๋ค. ์์ฒด์ ์ผ๋ก ํ๋ ๋ฆฌ๋ฏน์ค๊ฐ ํ๋ฆฌํฐ๊ฐ ์ข๋ค.]
* [http://www.youtube.com/user/OWSLAOfficial OWSLA][* Skrillex์ ๋ ์ด๋ธ์ ์ฑ๋. OWSLA ์์ ์ํฐ์คํธ๋ค์ ๊ณก์ ์์ฃผ ์
๋ก๋ํ๋ค.]
== ์ํ ==
=== UK ๋ฅ์คํ
===
{{{#!html
<iframe width="560" height="315" src="//www.youtube.com/embed/gDU1Cy152S4" frameborder="0" allowfullscreen></iframe>}}}
Skream - Midnight Request Line
์ต์ด๋ก ์์
์ ์ธ ์ฑ๊ณต์ ๊ฑฐ๋ UK ๋ฅ์คํ
๊ณก์ด๋ค.
{{{#!html
<iframe width="480" height="360" src="//www.youtube-nocookie.com/embed/QlEyR27fvGc" frameborder="0" allowfullscreen></iframe>}}}
Coki - Spongebob
๊ธฐ์กด์ ์๋ธ ๋ฒ ์ด์ค ์์ฃผ์ ๋ฅ์คํ
์์ ๋ฒ์ด๋ ์ค์์ญ๋์ ์ฐ๋ธ ๋ฒ ์ด์ค๋ฅผ ์ฒ์์ผ๋ก ์๋ํ ์ต์ด์ UK ๋ฅ์คํ
๊ณก์ด๋ค.
{{{#!html
<iframe width="480" height="360" src="//www.youtube-nocookie.com/embed/eHjxJItKbLQ" frameborder="0" allowfullscreen></iframe>}}}
Burial - Near Dark
์๋ฐํ ์ฌ๋์ค์ฟจ ๋ฅ์คํ
์ ์ ์๋ฅผ ๋ณด์ฌ์ค๋ค. ~~์ ์๋ฐํ๋ค.~~
=== US ๋ฅ์คํ
===
{{{#!html
<iframe width="480" height="360" src="//www.youtube-nocookie.com/embed/3pDKFLEvd3o" frameborder="0" allowfullscreen></iframe>}}}
Excision - Execute ~~์๋นํ ํฅํ๋ค~~
{{{#!html
<iframe width="560" height="315" src="//www.youtube-nocookie.com/embed/WSeNSzJ2-Jw" frameborder="0" allowfullscreen></iframe>}}}
Skrillex - Scary Monsters And Nice Sprites
์คํฌ๋ฆด๋ ์ค์ ๋ฅ์คํ
์ ํ๋๋ฅผ ๋ค์์ด๋ฒ๋ฆฐ ์ธ์์ฑ๊ธ์ด๋ค. ์กฐํ์๋ 2015๋
4์ ๊ธฐ์ค 1์ต 9์ฒ๋ง์ ๋๊ฒผ์ผ๋ฉฐ 2012๋
๊ทธ๋๋ฏธ๋ ์น์ธ์ด๊ฐ๋ค.
== ํฌ์คํธ๋ฅ์คํ
==
ํฌ์คํธ๋ฅ์คํ
์ด๋ ๋ฅ์คํ
์ ์ํฅ์ ๋ฐ๊ฑฐ๋ ๋ฅ์คํ
์ ์์๋ฅผ ์ฝ์
ํ ์์
์ ๋งํ๋ค. ํฐ ๊ด์ฌ์ ๋์ง๋ ๋ชปํ๊ณ ์์ง๋ง ํ์คํฐ๋ค์ด๋ ์ธ๋ํฌ๋ค์ค ์์๋ ๊ฝค ์ธ๊ธฐ๊ฐ ์๋ ๋ฏ.
๊ฐ์ฅ ๋ํ์ ์ธ ์๋ก ๋ฅ์คํ
๋ฆฌ๋ฌ์ ์์ธ ๋ฉ๋ก๋๋ฅผ ์น์ด์ ๋
ํนํ ๋ถ์๊ธฐ๋ฅผ ์ฐ์ถํ ์๊ตญ์ ์์
๊ฐ [[์ ์์ค ๋ธ๋ ์ดํฌ]]๊ฐ ์๋ค. ์ ์์ค ๋ธ๋ ์ดํฌ๋ 2011๋
์ต๊ณ ์ ์ ์ธ์ผ๋ก ๊ผฝํ์ผ๋ฉฐ, 2012๋
[[์ง์ฐ ๋ฐธ๋ฆฌ ๋ก ํ์คํฐ๋ฒ]] ์ฐธ๊ฐ๋ฅผ ์ํด ๋ดํํ๋ค. ๋ํ ๋ฅ์คํ
๊ณผ R&B๋ฅผ ํผํฉํ ์ญํธ๋ํธ๋ ํฌ์คํธ ๋ฅ์คํ
์ํฐ์คํธ๋ก ๊ผฝํ๋ค.
{{{#!html
<object width="560" height="349"><param name="movie" value="http://www.youtube.com/v/oOT2-OTebx0?version=3&hl=ko_KR"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/oOT2-OTebx0?version=3&hl=ko_KR" type="application/x-shockwave-flash" width="560" height="349" allowscriptaccess="always" allowfullscreen="true"></embed></object>}}}
์ ์์ค ๋ธ๋ ์ดํฌ์ ๋ํ๊ณก Limit to Your Love.
๋ํ ์์ ์ธ๊ธํ Starkey ์ญ์ ์ต๊ทผ ์๊ตญ ๊ตด์ง์ ๋ค์ดํ
ํฌ ๋ ์ด๋ธ์ธ Ninja Tune ๋ ์ด๋ธ ์
์ฑ ์ดํ ํฌ์คํธ๋ฅ์คํ
๊ฒฝํฅ์ ๋ณด์ฌ์ค๋ค. ๋ํ ๊ฐ์ ๋ ์ด๋ธ์ ์์๋ Emika๋ผ๋ ์ง, ๊ทธ์ธ Magnetic Man์ ๋ช๋ช ํธ๋์์ ๋ณด์ปฌ๋ก ์ฐธ์ฌํ๋ Katy B๋ ํฌ์คํธ๋ฅ์คํ
์ผ๋ก ์๊ฐํด๋ณผ ์ ์๊ฒ ๋ค.
== ๋ฆฌ๋ฌ๊ฒ์์์์ ๋ฅ์คํ
==
[[ํธ๋ฆฝ ํฉ]]๋งํผ์ ์๋๋๋ผ๋ ์ฅ๋ฅด ํน์ ์ ๋์ด์ง๋ ํน์ฑ ๋๋ฌธ์ธ์ง [[๋ฆฌ๋ฌ๊ฒ์]]์์ ์ด ์ฅ๋ฅด์ ๊ณก์ด ๋ฑ์ฅํ ์ฌ๋ก๋ ์์์ง๋ง ์๋์ [[๋นํธ๋งค๋์ IIDX 20 tricoro]]์์ ๋ฅ์คํ
์ผ๋ก ์ฅ๋ฅดํ๊ธฐ๋ฅผ ํ ๊ณก์ด ๋ฑ์ฅํ๋ค[* ๊ทธ๋ฌ๋ ์ผ๋ฐ์ ์ธ ๋ฅ์คํ
์ bpm์ ๊ฐ๋ณ๊ฒ ๋ฐ์ด๋๋ ๋น ๋ฅธ ๊ณก์ด๋ค]. ๋ํ [[ํธ๋์ค]], [[ํ์ฐ์ค]] ๋ฑ ๋ค๋ฅธ ์ฅ๋ฅด์ ๋ฐํ์์ ๋ฅ์คํ
์ ๊ฐ์ฅ ํน์ง์ ์ธ ์์์ธ ์ฐ๋ธ ๋ฒ ์ด์ค๋ฅผ ๊น์๋ ๊ณก์ ๋ง์ด ๋์๋ค. ๊ทธ๋ฆฌ๊ณ DJMAX ์๋ฆฌ์ฆ๋ [[DJMAX RAY]]์์ ๊ฐ์๊ธฐ ์ด ์ฅ๋ฅด๋ฅผ ํ๋ฐฉํ๊ณ ์๊ฑฐ๋ ๋ค๋ฅธ ์ฅ๋ฅด์ ํฉ์ฑ์ ์๋ํ ๊ณก๋ค์ด ๋์ค๊ธฐ ์์ํ๋ค. [[BEMANI ์๋ฆฌ์ฆ]]์์ [[kors k]]์ [[ํ์ง๋ชจ๋ฆฌ ์ํ]]๊ฐ ๋ฅ์คํ
ํํธ๊ฐ ๋ค์ด๊ฐ ๊ณก์ ๋ง์ด ๋ง๋๋ ํธ์ด๋ค. ํ์ง๋ง ์ด๋ฏธ ๋ฅ์คํ
์ ํ์ด ์ง๋ ๋๋ก ์ง๋ฌ๋ค๋ ๊ฒ์ ๋ฌธ์ . ๊ฒ๋ค๊ฐ BEMANI์์ ๋ฅ์คํ
์ ์ฒ์ ์๋ํ๋ kors k ๋ง์ ๋ [Monkey Business|์ด๋ฏธ ๋ฑ์ ๋๋ ธ๋ค.]
* [[Noiseproof]] ([[Tone Sphere]])
* [[Remain]] ([[ํํ๋ฎค์ง]] 19 TUNE STREET)
* Der Wald (kors k Remix) ([[ํํ๋ฎค์ง 20 fantasia]])
* [[ใณใใขใฉใคใ]] ([[ํํ๋ฎค์ง Sunny Park]])
* [[Star Trail]] ([[๋นํธ๋งค๋์ IIDX 19 Lincle]])
* [[ZED]] ([[๋นํธ๋งค๋์ IIDX 20 tricoro]]) [* ์ต์ด๋ก ์ฅ๋ฅด๋ช
์ด '''๋ฅ์คํ
'''์ผ๋ก ํ๊ธฐ๋ ๊ณก. ํ์ง๋ง ๊ฒ์์ด ๊ฒ์์ด๋ค๋ณด๋ ์ผ๋ฐ์ ์ธ ๋ฅ์คํ
๊ณผ๋ ๋ฌ๋ฆฌ BPM์ด ๋น ๋ฅด๋ค.]
* [[VOLTEXES]] ([[์ฌ์ด๋ ๋ณผํ
์ค]]์ ์์คํ
BGM, [[๋ฆฌํ๋ ๋นํธ ์ฝ๋ ํธ]])
* [[GirlZ]] ([[DJMAX RAY]])
* [[SINister Evolution]] ([[DJMAX RAY]])
* [[OrBiTal]] ([[DJMAX RAY]])
* [[wiki:"pandora#s-2" pandora Maozon Remix]] ([[์ฌ์ด๋ ๋ณผํ
์ค]])
* [[Catadioptric]] ([[์ฌ์ด๋ ๋ณผํ
์ค]])
* [[DINO]] ([[Cytus]])
* [[wiki:"Qualia(Rayark)" Qualia]] ([[Cytus]])
* [[CODE NAME : ZERO]] ([[Cytus]])
* [[Magnolia]] ([[Deemo]])
* [[Extreme Fantasy]] ([[์คํฌ์ผ ์๋ ๋ก๊ทธ]], [[์คํฌ์ผ S]], [[์คํฌ์ผ U]])
* [[Dual Racing <RED vs BLUE>]] ([[์คํฌ์ผ ์๋ ๋ก๊ทธ]], [[์คํฌ์ผ U]])
* [[Sky of the Ocean]] ([[์คํฌ์ผ ์๋ ๋ก๊ทธ]], [[์คํฌ์ผ U]])
* [[BSPower Bigbang]] ([[์คํฌ์ผ ์๋ ๋ก๊ทธ]], [[์คํฌ์ผ U]])
* [[Jam on the Breaks]] ([[์คํฌ์ผ ์๋ ๋ก๊ทธ]], [[์คํฌ์ผ U]])
* [[Agony]] ([[์คํฌ์ผ U]])
* [[DEBSTEP!]] ([[ๆฐ ํ๊ณ ์ ๋ฌ์ธ]])
* SkyScraper ([[GROOVE COASTER]])
== ํ๊ตญ ๋์ค์์
์์์ ๋ฅ์คํ
==
์ผ๋ ํธ๋ก๋ ์์
์ ์ธ์ง๋๊ฐ ์๋ง์ธ๋ฐ๋ค, ์ ์์์ ๋ํด ๋ถ์ ์ ์ธ ์์ ์ ๊ฐ์ง ํ๊ตญ์๋ ๊ฑฐ์ ์๋ ค์ ธ ์์ง ์์ ์ฅ๋ฅด์ด๋ค. ๋ค๋ง, ์์
์ ๊ด์ฌ์ด ์๋ค๋ฉด ์๊ณ ์์ ํ๋ฅ ์ด ๋์ ์ฅ๋ฅด์ด๊ธฐ๋ ํ๋ค. ์คํฌ๋ฆด๋ ์ค ํจ๊ณผ๋ก ๋ฅ์คํ
์ด ๋ญ์ง ๋ชฐ๋ผ๋ ๋ค์ด๋ณธ ์ ์ด ์๋ค๋ ์ฌ๋์ ๊ต์ฅํ ๋ง์์ก๋ค.
๋์ค์์
์์์ ๋ฅ์คํ
์ ์์ ๋ถํฐ [[์ผ๋]]์ ๊ฐ์ ์ธ๋ ์ํฐ์คํธ๋ค์ด ์๋ํ๊ณ ์์ผ๋ฉฐ, ์ต๊ทผ์๋ K-POP์๋ ์ ๋ชฉ๋๊ณ ์๋ค. ์ค์ปฌ๊ณผ ํํ์ ํฉ์์จ๋ฒ์์๋ ์ผ๋ถ ์๋๋์์ผ๋ฉฐ, ํ์์ Bubble Pop๊ณผ ์ ํํฐ์ค์ฟจ์ Flashback ๋ํ ~~์
์
๋๋ ๋์ค ๋ธ๋ ์ดํฌ~~ ๋ฅ์คํ
์ ํน์ง์ ์ผ๋ถ ์ฐจ์ฉํ๊ณ ์๋ค. ๊ตญ๋ด์์ ๋ฅ์คํ
๋ง์ผ๋ก ์ด๋ฃจ์ด์ง ์ต์ด์ ์จ๋ฒ์ Potlatch์ The Sign. [[SM์ํฐํ
์ธ๋จผํธ]]์์๋ [[SMP]]์ ๋ณํ์ผ๋ก ๋ฐ์ด์ฃผ๊ณ ์์ผ๋ฉฐ, [[์ค์ด๋]]์ Everybody์์๋ ๋ฅ์คํ
์ฌ์ด๋๋ฅผ ๊ฒฐํฉํ ์ปดํ๋ ์คํธ๋ก๋ฅผ ์ ๋ณด์ด๋ฉฐ, ๋์ค์์
์ ๋๋ค๋ฅธ ๊ฐ๋ฅ์ฑ์ ๋ณด์ฌ์ฃผ์๋ค.
๊ทธ๋ฆฌ๊ณ ~~ํ๊ตญ์ ์คํฌ๋ฆด๋ ์ค๋ผ ์ ๊ณ ํ์ ์ด๋ผ ๋ถ๋ฅด๋~~ DJ Driller๋ ๋ฅ์คํ
์จ๋ฒ(Rage Against)์ ํ๊ตญ ์ต์ด๋ก ๋ฐ๋งคํ๋ค.~~First of the Year์ด๋ ๋ฎค๋น ๋ด์ฉ์ด ๋๋ฌด๋ ํก์ฌํ๋ค~~
~~ํจ๋ฌ๋๋ผ์์~~
|
#include "apue.h"
#include <pthread.h>
// ไฝฟ็จpthread_mutex_timedlock้ฟๅ
ๆฐธไน
้ปๅก
int
main(void)
{
int err;
struct timespec tout;
struct tm *tmp;
char buf[64];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
// ๅฏนไบๆฅ้ๅ้่ก้ๅฎ
pthread_mutex_lock(&lock);
printf("mutex is locked\n");
// ่ทๅๆถ้ด
clock_gettime(CLOCK_REALTIME, &tout);
tmp = localtime(&tout.tv_sec);
strftime(buf, sizeof(buf), "%r", tmp);
printf("current time is %s\n", buf);
// ็ญๅพ
็็ปๅฏนๆถ้ด
tout.tv_sec += 10; /* 10 seconds from now */
/* caution: this could lead to deadlock */
// ่ฎพๅฎlockๆฟๆ็ญๅพ
้ปๅก็ๆถ้ด
err = pthread_mutex_timedlock(&lock, &tout);
// ็ญๅพ
ไปฅๅ็ๆ
ๅต
clock_gettime(CLOCK_REALTIME, &tout);
tmp = localtime(&tout.tv_sec);
strftime(buf, sizeof(buf), "%r", tmp);
printf("the time is now %s\n", buf);
if (err == 0)
printf("mutex locked again!\n");
else
printf("can't lock mutex again: %s\n", strerror(err));
exit(0);
}
|
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
//import { FormsModule } from '@angular/forms';
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {HttpModule} from '@angular/http';
import {FlexLayoutModule} from "@angular/flex-layout";
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {NavbarComponent} from './navbar/navbar.component';
import {HomeComponent} from './home/home.component';
import {DatabaseComponent} from './database/database.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatSliderModule} from '@angular/material/slider';
import {CurrencyPipe} from "@angular/common";
//import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import {HttpClientModule, HTTP_INTERCEPTORS} from "@angular/common/http";
//import { NgxWebstorageModule } from "ngx-webstorage";
//import { AppComponent } from "./app.component";
//import { HelloComponent } from "./hello.component";
//import { ErrorIntercept } from "./error.interceptor";
import {A11yModule} from "@angular/cdk/a11y";
import {BidiModule} from "@angular/cdk/bidi";
import {ObserversModule} from "@angular/cdk/observers";
import {OverlayModule} from "@angular/cdk/overlay";
import {PlatformModule} from "@angular/cdk/platform";
import {PortalModule} from "@angular/cdk/portal";
import {CdkStepperModule} from "@angular/cdk/stepper";
import {CdkTableModule} from "@angular/cdk/table";
import {MatCardModule} from "@angular/material/card";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatDividerModule} from "@angular/material/divider";
import {MatIconModule} from "@angular/material/icon";
import {MatToolbarModule} from "@angular/material/toolbar";
import {MatInputModule} from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
@NgModule({
exports: [
// CDK
A11yModule,
BidiModule,
ObserversModule,
OverlayModule,
PlatformModule,
PortalModule,
CdkStepperModule,
CdkTableModule,
MatCardModule,
MatFormFieldModule,
MatDividerModule,
MatIconModule,
MatToolbarModule,
MatInputModule,
MatButtonModule
]
})
export class MaterialModule {
}
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
HomeComponent,
DatabaseComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpModule,
BrowserAnimationsModule,
MatSliderModule,
ReactiveFormsModule,
MaterialModule,
FlexLayoutModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
|
import React from "react";
import Post from "./Post/Post";
import { useSelector } from "react-redux";
import { Grid, CircularProgress, Card, Typography, Container } from "@material-ui/core";
import useStyles from "./styles.js";
const Posts = ({ setCurrentId }) => {
const classes = useStyles();
const {posts, isLoading} = useSelector((state) => state.posts);
// console.log(posts, isLoading);
if(!posts.length && !isLoading) return(
<Card className={classes.card} raised elevation={6}>
<div className={classes.cardBody}>
<Typography className={classes.title} color="primary" variant="h5" gutterBottom align="center">
Sorry No Post Found !!
</Typography>
</div>
</Card>
);
return (
<>
{isLoading ? (
<Container align="center"><CircularProgress size="7rem" variant="indeterminate" /></Container>
) : (
<Grid
className={classes.mainContainer}
container
alignItems="stretch"
spacing={3}
>
{posts.map((post) => (
<Grid key={post._id} item xs={12} sm={12} md={6} lg={4}>
<Post post={post} setCurrentId={setCurrentId} />
</Grid>
))}
</Grid>
)}
</>
);
};
export default Posts;
|
package max.shop.domain.time;
import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDateTime;
@Getter
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class BaseTimeEntity {
@CreatedDate
@Column(nullable = false, updatable = false)
@CreationTimestamp
private LocalDateTime createdAt;
@LastModifiedDate
@Column(nullable = false)
@UpdateTimestamp
private LocalDateTime updatedAt;
}
|
/** @jsxImportSource @emotion/react */
import { Upload as AntUpload } from "antd";
import { RcFile } from "antd/lib/upload";
import React, { useCallback } from "react";
interface UploadProps {
children?: React.ReactNode;
onChange?: (file: File) => void;
accept?: string;
className?: string;
}
export default React.memo(function Upload(props: UploadProps) {
const { children, accept, className, onChange } = props;
const beforUpload = useCallback(
(file: RcFile) => {
onChange?.(file);
return false;
},
[onChange]
);
const emptyCallback = useCallback(() => {
// hop
}, []);
return (
<AntUpload
accept={accept}
beforeUpload={beforUpload}
customRequest={emptyCallback}
showUploadList={false}
className={className}
>
{children}
</AntUpload>
);
});
|
import { useMemo } from "react"
import { v4 as uuidv4 } from "uuid"
import useDataTableContext from "../../../hooks/useDataTableContext/useDataTableContext"
import type { Entry } from "../../../models"
import { filterEntries, sortEntries } from "../../../utilities/helpers"
import Row from "./row/row"
function Body() {
const { state } = useDataTableContext()
const { currentPage, pageSize, entries, filter, sortBy, sortDirection } = state
const filtredEntries = useMemo(() => filterEntries({ entries, filter }), [entries, filter])
const sortedEntries = useMemo(() => sortEntries({ entries: filtredEntries, sortBy, sortDirection }), [filtredEntries, sortBy, sortDirection])
const paginatedEntries = sortedEntries.slice((currentPage - 1) * pageSize, currentPage * pageSize)
return (
<tbody className="table-group-divider">
{paginatedEntries.map((entry: Entry) => (
<Row key={`row-${uuidv4()}`} entry={entry} />
))}
</tbody>
)
}
export default Body
|
class Node {
constructor(value) {
this.value = value
this.left = null
this.right = null
}
}
// a
// / \
// b c
// / \ \
// d e f
const a = new Node(20)
const b = new Node(15)
const c = new Node(25)
const d = new Node(10)
const e = new Node(16)
const f = new Node(28)
a.left = b
a.right = c
b.left = d
b.right = e
c.right = f
const treeInclude = (root, value) => {
if (root === null) {
return false
}
if (root.value === value) {
return true
}
const leftInclude = treeInclude(root.left, value)
const rightInclude = treeInclude(root.right, value)
return leftInclude || rightInclude
// return false;
}
console.log(treeInclude(a, 25))
|
// Minimum window substring - hard - 31/08/2023
// CodeStoryWithMIK
class Solution {
public String minWindow(String s, String t) {
if(s.length() < t.length()){
return "";
}
Map<Character, Integer> map = new HashMap<>();
for(int i=0; i<t.length(); i++){
map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0)+1);
}
int count = 0, start=0, min_length=Integer.MAX_VALUE, min_start = 0;
for(int end=0; end<s.length(); end++){
if(map.containsKey(s.charAt(end))){
if(map.get(s.charAt(end))>0){
count++;
}
map.put(s.charAt(end), map.get(s.charAt(end))-1);
}
if(count == t.length()){
while(start < end && (!map.containsKey(s.charAt(start)) || map.get(s.charAt(start))<0)){
if(map.containsKey(s.charAt(start))){
map.put(s.charAt(start), map.get(s.charAt(start))+1);
} start++;
}
if(min_length > end-start+1){
min_length = end-(min_start=start)+1;
}
if(map.containsKey(s.charAt(start))){
map.put(s.charAt(start), map.get(s.charAt(start))+1);
}
count--;
start++;
}
}
return min_length == Integer.MAX_VALUE?"":s.substring(min_start, min_start+min_length);
}
}
// Looks good
public String minWindow(String s, String t) {
if (s == null || t == null || s.length() ==0 || t.length() == 0 ||
s.length() < t.length()) {
return new String();
}
int[] map = new int[128];
int count = t.length();
int start = 0, end = 0, minLen = Integer.MAX_VALUE,startIndex =0;
for (char c :t.toCharArray()) {
map[c]++;
}
char[] chS = s.toCharArray();
while (end < chS.length) {
if (map[chS[end++]]-- >0) {
count--;
}
while (count == 0) {
if (end - start < minLen) {
startIndex = start;
minLen = end - start;
}
if (map[chS[start++]]++ == 0) {
count++;
}
}
}
return minLen == Integer.MAX_VALUE? new String():
new String(chS,startIndex,minLen);
}
|
#ifndef POINT_H_
#define POINT_H_
#include <cmath>
using namespace std;
struct Point{
double x ,y;
Point(const Point& p){
*this = p;
}
Point(double x = 0, double y = 0){
this->x = x;
this->y = y;
}
Point& operator= (const Point& p){
x = p.x;
y = p.y;
return *this;
}
double distance(Point p){
return sqrt(pow(x - p.x, 2) + pow(y - p.y, 2));
}
};
#endif
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\RegisterRequest;
use App\Http\Requests\LoginRequest;
use App\Services\AuthService;
use App\Http\Resources\RegisterResource;
use App\Http\Resources\TokenResource;
use App\Http\Resources\UserResource;
use App\Http\Resources\MessageResource;
use Illuminate\Support\Facades\Log;
class AuthController extends Controller
{
private AuthService $authService;
public function __construct(AuthService $authService)
{
$this->authService = $authService;
}
public function register(RegisterRequest $request)
{
try {
$response = $this->authService->register($request->validated());
return (new MessageResource([
'message' => 'User registered successfully',
'data' => new RegisterResource($response),
'status' => 'success'
]))->response()->setStatusCode(201);
}catch (\Exception $e) {
Log::error($e->getMessage());
return (new MessageResource([
'message' => $e->getMessage(),
'status' => 'error'
]))->response()->setStatusCode(400);
}
}
public function login(LoginRequest $request)
{
try {
$response = $this->authService->login($request->validated());
if(isset($response['status'])) {
throw new \Exception($response['message'], $response['code']);
}
return (new MessageResource([
'message' => 'Login successful',
'data' => new TokenResource($response),
'status' => 'success'
]))->response()->setStatusCode(200);
} catch (\Exception $e) {
return (new MessageResource([
'message' => $e->getMessage(),
'status' => 'error'
]))->response()->setStatusCode($e->getCode() ?: 400);
}
}
public function refresh(Request $request)
{
try {
$response = $this->authService->refresh();
return (new MessageResource([
'message' => 'Token refreshed successfully',
'data' => new TokenResource($response),
'status' => 'success'
]))->response()->setStatusCode(200);
} catch (\Exception $e) {
return (new MessageResource([
'message' => $e->getMessage(),
'status' => 'error',
]))->response()->setStatusCode(400);
}
}
public function user(Request $request)
{
try {
$user = $this->authService->user();
return (new MessageResource([
'message' => 'User data retrieved successfully',
'data' => new UserResource($user),
'status' => 'success'
]))->response()->setStatusCode(200);
} catch (\Exception $e) {
Log::error($e->getMessage());
return (new MessageResource([
'message' => $e->getMessage(),
'status' => 'error'
]))->response()->setStatusCode(400);
}
}
public function logout(Request $request)
{
try {
$this->authService->logout();
return (new MessageResource([
'message' => 'Logout successful',
'data' => null,
'status' => 'success'
]))->response()->setStatusCode(200);
} catch (\Exception $e) {
Log::error($e->getMessage());
return (new MessageResource([
'message' => $e->getMessage(),
'status' => 'error'
]))->response()->setStatusCode(400);
}
}
}
|
import React, { useState } from 'react';
import { View, TextInput, Button, Alert } from 'react-native';
import { initializeApp } from 'firebase/app';
import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth';
import { firebaseConfig } from './firebaseConfig'; // Firebase yapฤฑlandฤฑrma dosyasฤฑnฤฑ iรงe aktar
import { initializeAuth, getReactNativePersistence } from 'firebase/auth';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';
const app = initializeApp(firebaseConfig);
const auth = initializeAuth(app, {
persistence: getReactNativePersistence(ReactNativeAsyncStorage)
});
// auth nesnesini kullanarak kimlik doฤrulama iลlemlerini gerรงekleลtirebilirsiniz
const RegisterScreen = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleRegister = () => {
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Kullanฤฑcฤฑ baลarฤฑyla kaydedildi
const user = userCredential.user;
Alert.alert('Success', 'Account created successfully!');
// ฤฐstediฤiniz yรถnlendirmeyi burada yapabilirsiniz
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
Alert.alert('Error', errorMessage);
});
};
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<TextInput
placeholder="Email"
onChangeText={(text) => setEmail(text)}
value={email}
style={{ width: '80%', marginBottom: 10, borderBottomWidth: 1 }}
/>
<TextInput
placeholder="Password"
onChangeText={(text) => setPassword(text)}
value={password}
secureTextEntry
style={{ width: '80%', marginBottom: 20, borderBottomWidth: 1 }}
/>
<Button title="Register" onPress={handleRegister} />
</View>
);
};
export default RegisterScreen;
|
// import { Metadata } from "next";
import { siteConfig } from "@/config/site"
import { absoluteUrl } from "@/lib/utils"
import type { Metadata } from "next"
const metadata: Metadata = {
// title: "ScriptGen | Home",
title: {
default: siteConfig.name,
template: `%s | ${siteConfig.name}`,
},
description: siteConfig.description,
keywords: siteConfig.keywords,
authors: siteConfig.authors,
creator: siteConfig.creator,
themeColor: siteConfig.theme_color,
openGraph: {
title: siteConfig.title,
description: siteConfig.description,
// type: siteConfig.type,
url: siteConfig.url,
siteName: siteConfig.name,
images: [
{
url: absoluteUrl("/og.jpg"),
width: 1200,
height: 630,
alt: siteConfig.name,
},
{
url: "/assets/img-2.png",
width: 800,
height: 600,
alt: `${siteConfig.name}`,
},
{
url: "/assets/img-2.png",
width: 1800,
height: 1600,
alt: `${siteConfig.name}`,
},
],
locale: siteConfig.locale,
authors: ["Amin Benz"],
// publishedTime: '2023-01-01T00:00:00.000Z',
},
twitter: {
card: "summary_large_image",
title: siteConfig.name,
siteId: siteConfig.name,
description: siteConfig.description,
images: [`${siteConfig.url}/og.jpg`],
creator: siteConfig.creator,
},
icons: {
icon: "/icons/favicon.ico",
shortcut: "/icons/favicon-16x16.png",
apple: "/icons/apple-touch-icon.png",
other: {
rel: "/icons/apple-touch-icon",
url: "/icons/apple-touch-icon.png",
},
},
manifest: `${siteConfig.url}/site.webmanifest`,
generator: siteConfig.name,
applicationName: siteConfig.name,
category: siteConfig.category,
publisher: siteConfig.publisher,
// colorScheme: siteConfig.color_scheme,
// referrer: "origin-when-cross-origin",
// formatDetection: {
// email: false,
// address: false,
// telephone: false,
// },
// robots: {
// index: false,
// follow: true,
// nocache: true,
// googleBot: {
// index: true,
// follow: false,
// noimageindex: true,
// "max-video-preview": -1,
// "max-image-preview": "large",
// "max-snippet": -1,
// },
// },
}
export default metadata
|
package com.todo;
import com.coreoz.plume.jersey.guice.JerseyGuiceFeature;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Stage;
import com.todo.guice.ApplicationModule;
import com.todo.jersey.GrizzlySetup;
import org.glassfish.grizzly.GrizzlyFuture;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.server.ResourceConfig;
import org.h2.tools.Server;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
/**
* The application entry point, where it all begins.
*/
public class WebApplication {
// maximal waiting time for the last process to execute after the JVM received a kill signal
public static final Duration GRACEFUL_SHUTDOWN_TIMEOUT = Duration.ofSeconds(60);
public static void main(String[] args) {
try {
Server.createTcpServer("-tcpPort", "9092").start();
long startTimestamp = System.currentTimeMillis();
// initialize all application objects with Guice
Injector injector = Guice.createInjector(Stage.PRODUCTION, new ApplicationModule());
ResourceConfig jerseyResourceConfig = injector.getInstance(ResourceConfig.class);
// enable Jersey to create objects through Guice Injector instance
jerseyResourceConfig.register(new JerseyGuiceFeature(injector));
// starts the server
HttpServer httpServer = GrizzlySetup.start(
jerseyResourceConfig,
System.getProperty("http.port"),
System.getProperty("http.address")
);
// Add a shutdown hook to execute some code when the JVM receive a kill signal before it stops
addShutDownListener(httpServer);
// If Plume Scheduler / Wisp is used, uncomment next line
// addShutDownListerner(httpServer, injector.getInstance(Scheduler.class));
System.out.println("Server started in {} ms" + (System.currentTimeMillis() - startTimestamp));
} catch (Throwable e) {
System.out.println("Failed to start server" + e);
// This line is important, because during initialization some libraries change the main thread type
// to daemon, which mean that even if the project is completely down, the JVM is not stopped.
// Stopping the JVM is important to enable production supervision tools to detect and restart the project.
System.exit(1);
}
}
private static void addShutDownListener(HttpServer httpServer) { // If scheduler is used, add arg: Scheduler scheduler
Runtime.getRuntime().addShutdownHook(new Thread(
() -> {
System.out.println("Stopping signal received, shutting down server and scheduler...");
GrizzlyFuture<HttpServer> grizzlyServerShutdownFuture = httpServer.shutdown(GRACEFUL_SHUTDOWN_TIMEOUT.toSeconds(), TimeUnit.SECONDS);
try {
System.out.println("Waiting for server to shut down... Shutdown timeout is {} seconds" + GRACEFUL_SHUTDOWN_TIMEOUT.toSeconds());
// If scheduler is used, uncomment next line
// scheduler.gracefullyShutdown(GRACEFUL_SHUTDOWN_TIMEOUT);
grizzlyServerShutdownFuture.get();
} catch (Exception e) {
System.out.println("Error while shutting down server." + e);
}
},
"shutdownHook"
));
}
}
|
<template>
<div class="ๅนด้พๆฎต-ๅพ1">
<div class="chart">
<div class="main" ref="divRef" />
</div>
</div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts';
import { createEchartsOptions } from '../shared/create-echarts-options';
import { onMounted, ref } from 'vue'
import { px } from '../shared/px';
const divRef = ref<HTMLDivElement>()
const colors = ['#F46064', '#F38E1C', '#1CDB7C', '#8D70F8', '#33A4FA'];
const data = [
{ value: 0.08, name: 'ไธๅฒ่ทฏ' },
{ value: 0.06, name: 'ๆฎตๅฎถๆปฉ' },
{ value: 0.11, name: '้ๅ' },
{ value: 0.09, name: 'ไบๆณๅฑฑ' },
{ value: 0.12, name: 'ไธญๅฑฑ่ทฏ' },
{ value: 0.06, name: 'ๅบ้ณ่ทฏ' },
{ value: 0.08, name: 'ๆญฆ้ฝ่ทฏ' },
{ value: 0.08, name: '้
ๆณ่ทฏ' },
{ value: 0.08, name: 'ๅคฉๆฐด่ทฏ' },
];
onMounted(() => {
if (!divRef.value) return
var myChart = echarts.init(divRef.value)
myChart.setOption(createEchartsOptions({
xAxis: { show: false },
yAxis: { show: false },
grid: { x: 0, x2: 0, y: 0, y2: 0, containLabel: true },
legend: {
orient: 'vertical',
left: 'left',
top: 'center',
textStyle: { color: 'white' },
itemWidth: px(10),
itemHeight: px(10),
formatter(name) {
const value = data.find(i => i.name === name)?.value * 100 + '%';
return name + ' ' + value;
}
},
series: [
{
center: ['60%', '50%'],
type: 'pie',
radius: '80%',
label: { show: false },
labelLine: { show: false },
data: data,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
}));
})
</script>
<style lang="scss" scoped>
@import '../assets/css/home.scss';
</style>
|
import Empirica from "meteor/empirica:core"
import "./callbacks.js"
import "./bots.js"
import { independentData, groupData, ItemList, classData } from "./constants"
import { getGroupTags } from "../shared/helpers.js"
// gameInit is where the structure of a game is defined.
// Just before every game starts, once all the players needed are ready, this
// function is called with the treatment and the list of players.
// You must then add rounds and stages to the game, depending on the treatment
// and the players. You can also get/set initial values on your game, players,
// rounds and stages (with get/set methods), that will be able to use later in
// the game.
Empirica.gameInit((game, treatment) => {
console.log(
"Game with a treatment: ",
treatment,
" will start, with workers",
_.pluck(game.players, "id")
)
//initiate the cumulative score for this game (because everyone will have the same score, we can save it at the game object
game.set("cumulativeScore", 0) // the total score at the end of the game
game.set("nOptimalSolutions", 0) // will count how many times they've got the optimal answer
game.set("showStartAlert", true)
let playerRoles = ["Leader", "Follower", "Follower"]
playerRoles = shuffle(playerRoles)
game.players.forEach((player, i) => {
player.set("cumulativeScore", 0)
player.set("nOptimalSolutions", 0)
player.set("personalisedInstructionsPage", 1)
})
const groupTags = getGroupTags(game.players)
console.log("----TAGS HERE")
console.log(groupTags)
groupTags.forEach((tag) => {
const _players = game.players.filter((_p) => _p.get("groupIdTag") === tag)
_players.forEach((player, i) => {
player.set("role", playerRoles[i])
})
})
game.set("justStarted", true) // I use this to play the sound on the UI when the game starts
//we don't know the sequence yet
// let taskSequence1 = independentData
let taskSequence = classData
console.log(taskSequence)
if (game.treatment.shuffleTaskOrder) {
//TODO: I need to make sure that I keep the first task fixed (if it has training)
//taskSequence = _.shuffle(taskSequence); //this is full shuffle
// taskSequence1 = customShuffle(taskSequence1)
taskSequence = customShuffle(taskSequence) //this is with keeping the first practice round fixed
}
// const roundMoonLanding = game.addRound()
// _.times(2, (i) => {
// const stage = roundMoonLanding.addStage({
// name: i ? "Group" : "Independent",
// displayName: `Moon Landing - ${i ? "Group" : "Independent"}`,
// durationInSeconds: 9999999, //game.treatment.stageDuration,
// })
// stage.set("items", ItemList)
// stage.set("type", "moon")
// })
//we'll have 2 rounds, each task is one stage. Round 1 is independent, round2 is grouped
// const round1 = game.addRound()
// _.times(taskSequence1.length, (i) => {
// const stage = round1.addStage({
// name: "Independent_" + i,
// displayName: taskSequence1[i].difficulty,
// durationInSeconds: game.treatment.stageDuration,
// })
// stage.set("task", taskSequence1[i])
// stage.set("type", "room")
// })
const round2 = game.addRound()
const testEnv = game.treatment.isTest === "yes"
if (!testEnv) {
round2.addStage({
name: "personalised_instructions",
displayName: "Instructions",
durationInSeconds: testEnv ? 9999 : game.treatment.instructionsDuration,
})
}
_.times(taskSequence.length, (i) => {
// 2*taskSequence.length ==> if (i % 2) {
// const stage = round2.addStage({
// name: "Quiz_" + i,
// displayName: "Quiz",
// durationInSeconds: game.treatment.stageDuration,
// pauseDuration: game.treatment.pauseDuration,
// })
const stage = round2.addStage({
name: "Group_" + i,
displayName: taskSequence[i].difficulty,
durationInSeconds: testEnv ? 9999 : game.treatment.stageDuration,
pauseDuration: game.treatment.pauseDuration,
})
const pauseStart =
game.treatment.stageDuration - game.treatment.leaderDecisionDuration
const pauseEnd = pauseStart - game.treatment.pauseDuration
stage.set("pauseEnd", pauseEnd)
stage.set("pauseStart", pauseStart)
stage.set("task", taskSequence[i])
stage.set("type", "room")
stage.set("paused", false)
stage.set("isPractice", i === 0)
stage.set("stageNum", i)
})
})
// fix the first practice task and shuffle the rest
//to learn more:
//https://stackoverflow.com/questions/50536044/swapping-all-elements-of-an-array-except-for-first-and-last
function customShuffle(taskSequence) {
// Find and remove first and last:
const practiceTask = taskSequence[0]
const firstIndex = taskSequence.indexOf(practiceTask)
if (firstIndex !== -1) {
taskSequence.splice(firstIndex, 1)
}
// Normal shuffle with the remaining elements using ES6:
for (let i = taskSequence.length - 1; i > 0; --i) {
const j = Math.floor(Math.random() * (i + 1))
;[taskSequence[i], taskSequence[j]] = [taskSequence[j], taskSequence[i]]
}
// Add them back in their new position:
if (firstIndex !== -1) {
taskSequence.unshift(practiceTask)
}
return taskSequence
}
// shuffle(): Fisher-Yates shuffle from https://www.frankmitchell.org/2015/01/fisher-yates/
function shuffle(array) {
var i = 0,
j = 0,
temp = null
//Start with i one less than the array size, and decrement i everytime
for (i = array.length - 1; i > 0; i -= 1) {
//Math.random() returns a random number between 0 (inclusive) and 1 (exclusive)
//Math.floor() function returns the largest integer less than or equal to a given number.
//This will return an integer that is a possible index of the array
j = Math.floor(Math.random() * (i + 1))
//Swap the last element of the array (index i) with the element at index j (randomly generated:
temp = array[i]
array[i] = array[j]
array[j] = temp
}
//return the shuffled array
return array
}
|
package com.udacity.jdnd.course3.critter.schedule;
import com.udacity.jdnd.course3.critter.pet.Pet;
import com.udacity.jdnd.course3.critter.pet.PetService;
import com.udacity.jdnd.course3.critter.user.Employee;
import com.udacity.jdnd.course3.critter.user.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* Handles web requests related to Schedules.
*/
@RestController
@RequestMapping("/schedule")
public class ScheduleController {
@Autowired
private ScheduleService scheduleService;
@Autowired
private EmployeeService employeeService;
@Autowired
private PetService petService;
@PostMapping
public ScheduleDTO createSchedule(@RequestBody ScheduleDTO scheduleDTO) {
Schedule s1=convertfromDTO(scheduleDTO);
Schedule s2=scheduleService.create_schedule(s1);
return(convertToDTO(s2));
}
@GetMapping
public List<ScheduleDTO> getAllSchedules() {
List<Schedule> schedules = scheduleService.get_list();
return convertListToDTO(schedules);
}
@GetMapping("/pet/{petId}")
public List<ScheduleDTO> getScheduleForPet(@PathVariable long petId) {
List<Schedule> schedules = scheduleService.getSchedulesForPet(petId);
return convertListToDTO(schedules);
}
@GetMapping("/employee/{employeeId}")
public List<ScheduleDTO> getScheduleForEmployee(@PathVariable long employeeId) {
List<Schedule> schedules = scheduleService.get_schedule_for_emp(employeeId);
return convertListToDTO(schedules);
}
@GetMapping("/customer/{customerId}")
public List<ScheduleDTO> getScheduleForCustomer(@PathVariable long customerId) {
List<Schedule> schedules = scheduleService.getScheduleForCustomer(customerId);
return convertListToDTO(schedules);
}
private Schedule convertfromDTO(ScheduleDTO dto_schedule)
{
Schedule schedule = new Schedule();
BeanUtils.copyProperties(dto_schedule, schedule);
schedule.setEmployees(getEmployeesFromIds(dto_schedule.getEmployeeIds()));
schedule.setPets(getPetsFromIds(dto_schedule.getPetIds()));
return schedule;
}
private List<Employee> getEmployeesFromIds(List<Long> empIds) {
if(empIds == null) return null;
List<Employee> employees = new ArrayList<>();
for (Long id : empIds)
employees.add(employeeService.getEmployeeById(id));
return employees;
}
private List<Pet> getPetsFromIds(List<Long> petIds) {
if(petIds == null) return null;
List<Pet> pets = new ArrayList<>();
for (Long id : petIds)
pets.add(petService.getPetbyId(id));
return pets;
}
private ScheduleDTO convertToDTO(Schedule schedule) {
ScheduleDTO scheduleDTO = new ScheduleDTO();
BeanUtils.copyProperties(schedule, scheduleDTO);
scheduleDTO.setEmployeeIds(getIdsFromEmp(schedule.getEmployees()));
scheduleDTO.setPetIds(getIdsFromPets(schedule.getPets()));
return scheduleDTO;
}
List<Long> getIdsFromEmp(List<Employee> employees) {
if(employees == null) return null;
List<Long> ids = new ArrayList<>();
for( Employee employee: employees)
ids.add(employee.getId());
return ids;
}
List<Long> getIdsFromPets(List<Pet> pets) {
if(pets == null) return null;
List<Long> ids = new ArrayList<>();
for( Pet pet: pets)
ids.add(pet.getId());
return ids;
}
private List<ScheduleDTO> convertListToDTO(List<Schedule> schedules) {
ArrayList<ScheduleDTO> scheduleDTOs = new ArrayList<>();
for (Schedule schedule : schedules)
scheduleDTOs.add(convertToDTO(schedule));
return scheduleDTOs;
}
}
|
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
console.log("hello");
}
state = {
count: 0,
};
add = () => {
this.setState((current) => ({
count: current.count + 1,
}));
};
minus = () => {
this.setState((current) => ({
count: current.count - 1,
}));
};
componentDidMount() {
console.log("component rendered");
}
componentDidUpdate() {
console.log("I just updated");
}
componentWillUnmount() {
console.log("Goodbye, cruel world");
}
render() {
console.log("I'm rendering");
return (
<div>
{/*this๋ฅผ ์ฐ๋ ์ด์ ๋ ํด๋์ค๋ด์ ๋ณ์์ ํด๋์ค ๋ฐ์ ๋ณ์๊ฐ ์ด๋ฆ์ด
๊ฐ์ ๊ฒฝ์ฐ, ๊ทธ๊ฒ์ ๋ฆฌ์กํธ๊ฐ ์๋ณํ๊ธฐ ์ํด*/}
<h1>return The number is: {this.state.count} </h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
);
}
}
export default App;
|
import { Enemy } from "../Enemy";
import EnemyTypes from "../../enums/EnemyTypes"
import { ZombieEnemy } from "../ZombieEnemy";
import SwordDecorator from "../decorators/SwordDecorator";
import HammerDecorator from "../decorators/HammerDecorator";
export class generateEnemyFactory {
static getEnemy(type: EnemyTypes): Enemy {
const randomZombie = new ZombieEnemy("Pepe", 100, 5);
if(type === EnemyTypes.Zombie){
return randomZombie;
}
if(type === EnemyTypes.ZombieWithHammer){
return new SwordDecorator(randomZombie);
}
if(type === EnemyTypes.ZombieWithSword){
return new HammerDecorator(randomZombie);
}
throw new Error("Invalid Zombie Type")
}
}
|
package com.tour_it.features.searchScreen.ui
import android.annotation.SuppressLint
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FabPosition
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavController
import com.example.b_features.R
import com.tour_it.features.homepage.ui.compose.ProductHome
import com.tour_it.features.productScreen.ProductViewModel
import com.tour_it.features.productScreen.ui.ShowProduct
import com.tour_it.producer.components.GABottomBarNavigation
import com.tour_it.producer.components.GAProfileCircle
import com.tour_it.producer.lists.items
import com.tour_it.producer.models.products.Event
import com.tour_it.producer.models.products.Hotel
import com.tour_it.producer.models.products.Restaurant
import com.tour_it.producer.navigation.NavigationItem
import org.koin.androidx.compose.getViewModel
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchScreen(
navController: NavController,
backStackEntry: NavBackStackEntry
) {
val productVM: ProductViewModel = getViewModel()
val mixedProducts by productVM.mixedProductsList.collectAsState()
val dateTimeString = "2024-05-24T23:30"
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm")
val localDateTime = LocalDateTime.parse(dateTimeString, formatter)
val pointsValue = localDateTime.toString()
Scaffold(
containerColor = Color(0xFF313131),
topBar = {
CenterAlignedTopAppBar(
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
containerColor = Color(0xFF313131)
),
title = {
Image(
painter = painterResource(id = com.example.e_producer.R.drawable.logo_tour_it),
contentDescription = null,
modifier = Modifier
.size(170.dp)
.padding(top = 16.dp, start = 16.dp)
)
},
navigationIcon = {},
actions = {
IconButton(onClick = { navController.navigate(NavigationItem.ProfileScreen.route) }) {
GAProfileCircle(
navController = navController,
image = com.example.e_producer.R.drawable.sem_t_tulo,
modifier = Modifier
.padding(16.dp)
)
}
},
)
},
content = {
Column(
modifier = Modifier.padding(top = 100.dp, start = 16.dp, end = 16.dp)
) {
Column(modifier = Modifier.padding(end = 100.dp)) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Icon(
imageVector = Icons.Default.Search, contentDescription = null,
tint = Color.White,
modifier = Modifier.size(30.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = buildAnnotatedString {
withStyle(
style = SpanStyle(
fontWeight = FontWeight.Bold,
fontSize = 30.sp
)
) {
append("Search")
}
},
fontSize = 40.sp,
color = Color.White
)
}
Spacer(modifier = Modifier.height(8.dp))
Divider(
thickness = 4.dp,
color = Color(0xFFB5B5B5),
modifier = Modifier.padding(end = 130.dp)
)
}
Spacer(modifier = Modifier.height(28.dp))
LazyVerticalGrid(
columns = GridCells.Fixed(3),
) {
items(mixedProducts) { product ->
when(product){
is Hotel -> ShowProduct(
image = product.image,
productName = product.name,
pointsValue = product.rating.toString(),
price = product.priceRange.toString(),
product = product,
navController = navController
)
is Event -> ShowProduct(
image = product.image,
productName = product.name,
pointsValue = pointsValue,
price = product.priceRange.toString(),
product = product,
navController = navController
)
is Restaurant -> ShowProduct(
image = product.image,
productName = product.name,
pointsValue = product.rating.toString(),
price = product.priceRange.toString(),
product = product,
navController = navController
)
}
}
}
}
},
floatingActionButtonPosition = FabPosition.Center,
floatingActionButton = {
FloatingActionButton(
shape = CircleShape,
onClick = { navController.navigate(NavigationItem.MapScreen.route) },
containerColor = Color(0xFFB5B5B5),
modifier = Modifier
.size(90.dp)
.offset(x = 0.dp, y = 50.dp)
) {
Box(
modifier = Modifier
.size(75.dp)
.background(Color(0xFF313131), shape = CircleShape),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Default.LocationOn, contentDescription = "Add", tint = Color(0xFFFF9000))
}
}
},
bottomBar = {
Surface(shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp)) {
GABottomBarNavigation(
navController = navController,
items = items,
selectedIndex = 0,
onItemSelected = {},
)
}
},
)
}
|
$(function() {
'use strict';
var dtTable = $('.donations-list-table'),
isRtl = $('html').attr('data-textdirection') === 'rtl',
API_URL = '/api/donations';
// datatable
if (dtTable.length) {
var dt = dtTable.DataTable({
ajax: API_URL, // JSON file to add data
autoWidth: true,
processing: true,
serverSide: true,
columns: [
// columns according to JSON
{ data: 'id' },
{ data: 'donation_id' },
{ data: 'backer_firstname' },
{ data: 'backer_lastname' },
{ data: 'backer_email' },
{ data: 'message' },
{ data: 'amount' },
{ data: 'date' },
{ data: 'status' },
],
columnDefs: [{
// For Responsive
className: 'control',
responsivePriority: 2,
targets: 0,
render: function() {
return '';
}
},
{
targets: 5,
render: function(data, type, row) {
if(row.message != null && row.message != ''){
if (row.message.length > 20) {
return row.message.substring(0, 20) + '...';
} else {
return row.message;
}
}else{
return '';
}
}
},
{
// Actions
targets: -1,
width: '80px',
orderable: false,
render: function(data, type, full, meta) {
return (
`<div class="d-flex align-items-center col-actions">
<a class="mr-1 btn-edit" href="/admin/donations/${full.id}" data-toggle="tooltip" data-placement="top" title="Details">${feather.icons['eye'].toSvg({ class: 'font-medium-2' })}</a>
</div>
`
);
}
}
],
buttons: [],
order: [
[1, 'desc']
],
dom: '<"row d-flex justify-content-between align-items-center m-1"' +
'<"col-lg-6 d-flex align-items-center"l<"dt-action-buttons text-xl-right text-lg-left text-lg-right text-left "B>>' +
'<"col-lg-6 d-flex align-items-center justify-content-lg-end flex-lg-nowrap flex-wrap pr-lg-1 p-0"f<"invoice_status ml-sm-2">>' +
'>t' +
'<"d-flex justify-content-between mx-2 row"' +
'<"col-sm-12 col-md-6"i>' +
'<"col-sm-12 col-md-6"p>' +
'>',
language: {
sLengthMenu: 'Show _MENU_',
search: 'Search',
searchPlaceholder: 'Search for Donations',
paginate: {
// remove previous & next text from pagination
previous: ' ',
next: ' '
}
},
// For responsive popup
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal({
header: function(row) {
var data = row.data();
return 'Details of Campaign Donation #' + data.id;
}
}),
type: 'column',
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'table',
columnDefs: [{
targets: 1,
visible: false
}, {
targets: 2,
visible: false
}]
})
}
},
initComplete: function() {
$(document).find('[data-toggle="tooltip"]').tooltip();
// Adding role filter once table initialized
},
drawCallback: function() {
$(document).find('[data-toggle="tooltip"]').tooltip();
}
});
}
});
|
---
product: campaign
solution: Campaign
title: ใณใณใใญใผใซใใใซใฏใAdobe Campaign Standard ใ Classic ใฎ่ฃฝๅ็ฎก็่
ใจใใฆใฎไฝๆฅญใฎๅน็ใ้ซใใใฎใซๅฝน็ซใกใพใใ
description: ใณใณใใญใผใซใใใซใธใฎใขใฏใปในๆนๆณใฎ่ฉณ็ดฐ
feature: Control Panel, Overview
role: Admin
level: Experienced
exl-id: cb6cc63b-d6cc-4c8b-870f-e108d05aa740
source-git-commit: a3485766791387bd9422b4f29daf86296efafb98
workflow-type: ht
source-wordcount: '295'
ht-degree: 100%
---
# ไธปใชๆฉ่ฝ {#key-features}
ใณใณใใญใผใซใใใซใไฝฟ็จใใใจใๅใคใณในใฟใณในใฎ่จญๅฎใ็ฎก็ใใใไฝฟ็จ็ถๆณใ่ฟฝ่ทกใใใใงใใใฎใงใAdobe Campaign Standard ใใใณ Classic ใฎ่ฃฝๅ็ฎก็่
ใจใใฆใฎไฝๆฅญใฎๅน็ใๅไธใงใใพใใ็ดๆ็ใชใคใณใฟใผใใงใคในใซใใใไธป่ฆใชใขใปใใใฎไฝฟ็จ็ถๆณใ็ฐกๅใซ็ฃ่ฆใงใใใใใIP ใขใใฌในใฎ่จฑๅฏใชในใ็ป้ฒใSFTP ในใใฌใผใธใฎ็ฃ่ฆใ้ตใฎ็ฎก็ใชใฉใฎ็ฎก็ใฟในใฏใๅฎ่กใงใใพใใ
ไธปใชๅฉ็น๏ผ
* ใซในใฟใใผใฑใขใซ้ฃ็ตกใใใใจใชใใ่ชๅใงใใฐใใ่จญๅฎใซๅคๆดใๅ ใใใใจใใงใใพใใ
* ๆงใ
ใชใฟใคใใณใฐใงๆงใ
ใชใใธใในใใผใบใซๅบใฅใใฆ่จญๅฎใงใใพใใ
* ใใผใบใใจใซใขใฏใปใน่จญๅฎใๅถๅพกใใใใจใงใปใญใฅใชใใฃใๅผทๅใงใใพใใ
>[!NOTE]
>
>ใณใณใใญใผใซใใใซใฏใ็ฎก็่
ใฆใผใถใผใซ้ๅฎใใใฆใใพใใใฆใผใถใผใซ็ฎก็่
ใขใฏใปในๆจฉใไปไธใใๆ้ ใซใคใใฆใฏใ[ใใฎ็ฏ](managing-permissions.md)ใๅ็
งใใฆใใ ใใใ
>
>Campaign v7๏ผv8 ใฎๅ ดๅใฏใใคใณในใฟใณในใ Amazon Web Services๏ผAWS๏ผใงใในใใใๆๆฐใฎ [Campaign ๅฎๅฎใใซใ](https://experienceleague.adobe.com/docs/campaign-classic/using/release-notes/rn-overview.html?lang=ja#rn-statuses)ใพใใฏใใซใ 9032 ไปฅ้ใซใขใใใฐใฌใผใใใๅฟ
่ฆใใใใพใใใใผใธใงใณใ็ขบ่ชใใๆนๆณใซใคใใฆใฏใ[ใใฎ็ฏ](https://experienceleague.adobe.com/docs/campaign-classic/using/getting-started/starting-with-adobe-campaign/launching-adobe-campaign.html?lang=ja#getting-your-campaign-version)ใๅ็
งใใฆใใ ใใใใคใณในใฟใณในใ AWS ใงใในใใใใฆใใใใฉใใใ็ขบ่ชใใใซใฏใ[ใใฎใใผใธ](../../faq.md#hosted-aws)ใง่ฉณใใ่ชฌๆใใใฆใใๆ้ ใซๅพใฃใฆใใ ใใใ
<table style="table-layout:fixed">
<tr>
<td>
<a href="../../discover/using/accessing-control-panel.md"><img alt="conditions" src="assets/do-not-localize/discover.png"/></a>
<div><a href="../../discover/using/accessing-control-panel.md"><strong>ใณใณใใญใผใซใใใซใฎ็่งฃ</strong></a></div>
<em>ใณใณใใญใผใซใใใซใใใณใขใฏใปในๆนๆณใฎ่ฉณ็ดฐ</em>
</td>
<td>
<a href="../../sftp/using/about-sftp-management.md"><img alt="conditions" src="assets/do-not-localize/sftp.png"/></a>
<div><a href="../../sftp/using/about-sftp-management.md"><strong>SFTP ใตใผใใผใฎ็ฃ่ฆ</strong></a></div>
<em>SFTP ใตใผใใผใฎ็ฎก็ๆนๆณใฎ่ฉณ็ดฐ</em>
</td>
<td>
<a href="../../subdomains-certificates/using/subdomains-branding.md"><img alt="conditions" src="assets/do-not-localize/subdomains.png"/></a>
<div><a href="../../subdomains-certificates/using/subdomains-branding.md"><strong>ใตใใใกใคใณใฎ็ฃ่ฆ</strong></a></div>
<em>ใตใใใกใคใณใจใใฎ่จผๆๆธใฎ็ฃ่ฆๆนๆณใฎ่ฉณ็ดฐ</em>
</td>
<td>
<a href="../../instances-settings/using/ip-allow-listing-instance-access.md"><img alt="conditions" src="assets/do-not-localize/instance_settings.png"/></a>
<div><a href="../../instances-settings/using/ip-allow-listing-instance-access.md"><strong>ใคใณในใฟใณใน่จญๅฎใฎ็ฎก็</strong></a></div>
<em>ใคใณในใฟใณใน่จญๅฎ๏ผCampaign v7๏ผv8 ใฎใฟ๏ผใฎ็ฎก็ๆนๆณใฎ่ฉณ็ดฐ</em>
</td>
<td>
<a href="../../performance-monitoring/using/about-performance-monitoring.md"><img alt="ๆกไปถ" src="assets/do-not-localize/monitoring-performance.png"/></a>
<div><a href="../../performance-monitoring/using/about-performance-monitoring.md"><strong>ใใใฉใผใใณในใฎ็ฃ่ฆ</strong></a></div>
<em>ใคใณในใฟใณในใฎไธป่ฆใชใฝใผในใฎไฝฟ็จ็ใ็ฃ่ฆใใๆนๆณใฎ่ฉณ็ดฐ</em>
</td>
</tr>
</table>
|
import { Button, Input, MenuItem, Stack, TextField, Typography } from '@mui/material'
import React from 'react'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import Topbar from '../../components/Topbar'
import ArrowBackIosIcon from '@mui/icons-material/ArrowBackIos';
import { Create } from '@mui/icons-material'
import { apiUrl } from '../../utils/constant'
const initialValues = {
title: '',
content: '',
commitee: ''
}
const commitee = [
{
value: "aaroha",
label: "Aaroha"
},
{
value: "pixel",
label: "Pixel"
},
{
value: 'iste',
label: 'Iste'
},
{
value: 'tooryanaad',
label: 'Tooryanaad'
},
{
value: 'robaroo',
label: 'Robaroo'
},
{
value: "quizzers",
label: "Quizzers"
},
{
value: "ieee",
label: "IEEE"
},
{
value: "vision",
label: "Vision"
},
{
value: "zenith",
label: "Zenith"
},
{
value: "aeseaenak",
label: "Ae se aenak"
},
{
value: "rotaract",
label: "Rotaract"
},
]
const CreatePost = () => {
const [values, setValues] = useState(initialValues);
const navigate = useNavigate();
const createPost = () => {
fetch(`${apiUrl}/posts/create`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: values.title,
content: values.content,
commitee: values.commitee,
createdAt: new Date().toLocaleDateString()
})
}).then(res => res.json())
.then(data => {
if (data) {
navigate('/home')
}
})
.catch(err => console.log(err))
}
const handleCancel = () => {
navigate('/home')
}
return (
<div className="create-post">
<Topbar />
<div className="create-inputs">
<Typography variant="h3" component="div" gutterBottom>
Create a Post
</Typography>
<TextField
fullWidth
id="outlined-basic"
label="Title"
variant="outlined"
value={values.title}
margin="normal"
onChange={(e) => setValues({ ...values, title: e.target.value })}
/>
<TextField
fullWidth
margin="normal"
id="outlined-basic"
label="Description"
variant="outlined"
multiline
rows={4}
values={values.content}
onChange={(e) => setValues({ ...values, content: e.target.value })}
/>
<Stack direction="row" alignItems="center" spacing={2}>
<label htmlFor="contained-button-file">
<Input accept="image/*" id="contained-button-file" multiple type="file" />
<Button variant="contained" component="span">
Upload
</Button>
</label>
</Stack>
<TextField
id="outlined-select-currency"
select
fullWidth
label="Select"
value={values.commitee}
margin="normal"
onChange={(e) => setValues({ ...values, commitee: e.target.value })}
helperText="Please select your commitee"
>
{commitee.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
<div className='create-buttons'>
<Button
variant="contained"
onClick={createPost}
>
<Create />
Create Post
</Button>
<Button
variant="outlined"
onClick={handleCancel}
>
<ArrowBackIosIcon />
Cancel
</Button>
</div>
</div>
</div>
)
}
export default CreatePost
|
import React from "react";
import { Typography } from "@material-ui/core";
import { useStore } from "@store/store";
import { EditBlockStyle } from "./style";
function EditBlock() {
const classes = EditBlockStyle();
const [state] = useStore();
return (
<div className={classes.EditBlockWrapper}>
<div className="white-card edit-block">
<div className="edit-block-header">
<div className="inner-heading">
<p>Online Request Number</p>
<span>
{state.onlineRequest?.getOnlineRequestById?.id
? state.onlineRequest?.getOnlineRequestById?.id
: "-"}
</span>
</div>
</div>
{state.onlineRequest?.getOnlineRequestById?.description && (
<div className="edit-block-content">
<Typography variant="h6">Description:</Typography>
<p>{state.onlineRequest?.getOnlineRequestById?.description}</p>
</div>
)}
<div className="edit-block-list">
<ul>
<li>
<Typography variant="h6">Ref No</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.referenceNo
? state.onlineRequest?.getOnlineRequestById?.referenceNo
: "-"}
</p>
</div>
</li>
<li>
<Typography variant="h6">Job type</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.jobTypes
? state.onlineRequest?.getOnlineRequestById?.jobTypes?.name
: "-"}
</p>
</div>
</li>
<li>
<Typography variant="h6">Cargo type</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.cargoTypes
? state.onlineRequest?.getOnlineRequestById?.cargoTypes
?.name
: "-"}
</p>
</div>
</li>
<li>
<Typography variant="h6">Requester</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.requesterName
? state.onlineRequest?.getOnlineRequestById?.requesterName
: "-"}
</p>
</div>
</li>
<li>
<Typography variant="h6">Email</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.email
? state.onlineRequest?.getOnlineRequestById?.email
: "-"}
</p>
</div>
</li>
<li>
<Typography variant="h6">CC</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.cc
? state.onlineRequest?.getOnlineRequestById?.cc
?.split(",")
.map((item) => item + ", ")
: "-"}
</p>
</div>
</li>
<li>
<Typography variant="h6">City</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.cities
? state.onlineRequest?.getOnlineRequestById?.cities.name
: "-"}
</p>
</div>
</li>
<li>
<Typography variant="h6">Weight</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.weight
? state.onlineRequest?.getOnlineRequestById?.weight
: "-"}{" "}
Kg
</p>
</div>
</li>
<li>
<Typography variant="h6">Quantity</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.quantity
? state.onlineRequest?.getOnlineRequestById?.quantity
: "-"}{" "}
Qty
</p>
</div>
</li>
<li>
<Typography variant="h6">Pick up</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.pickUpLocation
? state.onlineRequest?.getOnlineRequestById?.pickUpLocation
: "-"}
</p>
</div>
</li>
<li>
<Typography variant="h6">Drop off</Typography>
<div className="value-block">
<p>
{state.onlineRequest?.getOnlineRequestById?.dropOffLocation
? state.onlineRequest?.getOnlineRequestById?.dropOffLocation
: "-"}
</p>
</div>
</li>
<li>
<Typography variant="h6">CTO</Typography>
<p>
{" "}
{state.onlineRequest?.getOnlineRequestById?.ctos
? state.onlineRequest?.getOnlineRequestById?.ctos?.name
: "-"}
</p>
</li>
</ul>
</div>
</div>
</div>
);
}
export default EditBlock;
|
<template >
<div class="card mt-3 text-center shadow">
<div class="card-header ">
<h2>{{ "Hi " + user.id + ", you are logged in as: " + user.userRole }}</h2>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6 my-2">
<div class="card shadow">
<div class="card-header">
Ticket Priority
</div>
<div class="card-body">
<Doughnut v-if="TicketPriorityData.loaded" :data="TicketPriorityData" :options="options" />
</div>
</div>
</div>
<div class=" my-2 col-md-6">
<div class="card shadow">
<div class="card-header">
Ticket Status
</div>
<div class="card-body">
<Doughnut v-if="TicketStatusData.loaded" :data="TicketStatusData" :options="options" />
</div>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="card shadow my-3">
<div class="card-body">
<div class="row">
<h2 class="col-auto ">Assign Tickets</h2>
</div>
<form id="search">
<div class="row">
<label class="col-md-2 col-form-label">Search: </label>
<div class="col-md-10">
<input class="form-control form-control-dark rounded-3 border-1 " v-model="searchQuery">
</div>
</div>
</form>
<table class="table align-items-center mb-0" v-if="filteredData.length">
<thead>
<tr>
<th @click="sortBy(gridColumns[0])" :class="{ 'text-secondary': sortKey !== gridColumns[0] }"
class="text-uppercase text-xxs font-weight-bolder">
{{ gridColumns[0] }} <span class="arrow"
:class="sortOrders[gridColumns[0]] > 0 ? 'asc' : 'dsc'"></span>
</th>
<th @click="sortBy(gridColumns[1])" :class="{ 'text-secondary': sortKey !== gridColumns[1] }"
class="text-center text-uppercase text-xxs font-weight-bolder">{{ gridColumns[1] }}
<span class="arrow" :class="sortOrders[gridColumns[1]] > 0 ? 'asc' : 'dsc'"></span>
</th>
<th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder ">Status</th>
<th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder ">pRIORITY</th>
<th class="text-secondary opacity-7"></th>
</tr>
</thead>
<tbody>
<tr v-for="entry in filteredData">
<td>
<div class="d-flex px-2 py-1">
<div class="d-flex flex-column justify-content-center">
<h6 class="mb-0 text-sm">{{ entry.name }}</h6>
</div>
</div>
</td>
<td class="align-middle text-center text-sm ">
<span class="text-secondary text-xs font-weight-bold">{{ entry.typ }}</span>
</td>
<td class="align-middle text-center text-sm">
<span class="text-secondary text-xs font-weight-bold">{{ entry.status }}</span>
</td>
<td class="align-middle text-center text-sm">
<span class="p-1 text-white bg-opacity-75 rounded-1"
:class="{ 'bg-success': entry.priority == 'LOW', 'bg-warning': entry.priority == 'MID', 'bg-danger': entry.priority == 'HIGH' }">
{{ entry.priority }}</span>
</td>
<td class="align-middle">
<router-link :to="{ path: '/ticket/' + entry.id }"
class="text-secondary font-weight-bold text-xs">Details</router-link>
</td>
</tr>
</tbody>
</table>
<p v-else class="mt-3">- No matches found.</p>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { computed, onMounted, ref, reactive } from 'vue';
import axios from "axios";
import { useStore } from 'vuex';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'
import { Doughnut } from 'vue-chartjs'
const options = {
responsive: true,
maintainAspectRatio: false
}
const TicketStatusData = reactive({
loaded: false,
labels: null,//['OPEN', 'ASSIGNED', 'MORE INFOS', 'CLOSED'],
datasets: [
{
backgroundColor: ['#41B883', '#00D8FF', '#DD1B16', '#E46651'],
data: null
}
]
});
const TicketPriorityData = reactive({
loaded: false,
labels: null,//['LOW', 'MID', 'HIGH', 'NONE'],
datasets: [
{
backgroundColor: ['#41B883', '#00D8FF', '#DD1B16', '#E46651'],
data: null
}
]
});
ChartJS.register(ArcElement, Tooltip, Legend)
const store = useStore();
let auth = computed(() => store.state.auth);
let user = computed(() => store.state.user);
let apiData = ref(null);
let apiTicketData = ref(null);
onMounted(async () => {
try {
const response = await axios.get("/appUsers/stats");
apiData = response.data;
TicketPriorityData.labels = Object.keys(apiData.totalTicktetsByPriority);
TicketPriorityData.datasets[0].data = Object.values(apiData.totalTicktetsByPriority);
//console.log ( Object.values(apiData.totalTicktetsByPriority ) );
TicketPriorityData.loaded = true;
TicketStatusData.labels = Object.keys(apiData.totalTicktetsByStatus);
TicketStatusData.datasets[0].data = Object.values(apiData.totalTicktetsByStatus);
//console.log ( Object.values(apiData.totalTicktetsByPriority ) );
TicketStatusData.loaded = true;
apiTicketData.value = await (await axios.get("/tickets/assignToMe")).data;
} catch (e) {
console.log(e);
}
});
const searchQuery = ref('')
const gridColumns = ['name', 'typ', 'status', 'priority']
const sortKey = ref('')
const sortOrders = ref(
gridColumns.reduce((o, key) => ((o[key] = 1), o), {})
)
const filteredData = computed(() => {
let data = apiTicketData.value ? apiTicketData.value : [];
if (searchQuery) {
let searchQuery1 = searchQuery.value.toLowerCase()
data = data.filter((row) => {
return Object.keys(row).some((key) => {
return String(row[key]).toLowerCase().indexOf(searchQuery1) > -1
})
})
}
const key = sortKey.value
// TODO implement sorting for pRIORITY LOW < MID
if (key) {
const order = sortOrders.value[key]
data = data.slice().sort((a, b) => {
a = a[key]
b = b[key]
return (a === b ? 0 : a > b ? 1 : -1) * order
})
}
//console.log(data)
return data
})
function sortBy(key) {
sortKey.value = key
sortOrders.value[key] *= -1
}
</script>
<style >
</style>
|
package com.leon.concurrencydemo.example.immutable;
import com.google.common.collect.Maps;
import com.leon.concurrencydemo.annotation.ThreadNotSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
@Slf4j
@ThreadNotSafe
public class ImmutableExample1 {
private final static Integer a = 1;
private final static String b = "2";
private final static Map<Integer, Integer> map = Maps.newHashMap();
static{
map.put(1, 2);
map.put(3, 4);
map.put(5, 6);
}
public static void main(String[] args) {
// a = 2;
// b = "3";
// finalไฟฎ้ฅฐ็ๅผ็จ็ฑปๅไธๅ
่ฎธๆๅๆฐ็ๅฏน่ฑก๏ผๆฌ่บซๅ
ๅฎนๅฏๅ็ๅๅ
// map = Maps.newHashMap();
log.info("{}", map.get(1));
map.put(1, 3);
log.info("{}", map.get(1));
}
private void finalParam(final int num) {
// ไผ ๅ
ฅ็ๅฎๅไธๅฏๅ
// num = 1;
}
}
|
import json
import urllib.request
def request(action, **params):
return { "action": action, "params": params, "version": 6 }
def invoke(action, **params):
requestJson = json.dumps(request(action, **params)).encode("utf-8")
response = json.load(urllib.request.urlopen(urllib.request.Request("http://127.0.0.1:8765", requestJson)))
if len(response) != 2:
raise Exception("The response has an unexpected number of fields.")
if "error" not in response:
raise Exception("The response is missing a required error field.")
if "result" not in response:
raise Exception("The response is missing a required result field.")
if response["error"] is not None:
raise Exception(response["error"])
return response["result"]
def tag_note(id, tags):
invoke("updateNote", note = {
"id": id,
"tags": tags
})
def find_unknown_kanjis(file_name):
unknown_kanjis = []
with open(file_name) as file:
kanji_grid = json.load(file)["units"]
for kanji in kanji_grid:
if kanji_grid[kanji][2] + kanji_grid[kanji][3] == 0:
unknown_kanjis.append(kanji)
return unknown_kanjis
def is_useless_word(word, unknown_kanjis):
for unknown_kanji in unknown_kanjis:
if unknown_kanji in word:
return False
return True
def main(deck_name, word_field, kanji_grid_path):
unknown_kanjis = find_unknown_kanjis(kanji_grid_path)
note_ids = invoke("findNotes", query = "deck:\"{}\" is:new".format(deck_name))
notes = invoke("notesInfo", notes = note_ids)
for i in range(0, len(notes)):
word = notes[i]["fields"][word_field]["value"]
if is_useless_word(word, unknown_kanjis):
tag_note(notes[i]["noteId"], ["useless"])
else:
tag_note(notes[i]["noteId"], ["useful"])
print("{}/{} - {}".format(i + 1, len(notes), word))
############################
######### Settings #########
############################
# The name of the deck to query.
deck_name = "ๆฅๆฌ่ช"
# The field that the word will be read from.
word_field = "Word"
# The file path of the exported kanji grid.
kanji_grid_path = "kanji_grid.json"
main(deck_name, word_field, kanji_grid_path)
|
function [wmap, wconv] = mri_field_map_reg_2d(yi, etime, varargin)
% function [wmap, wconv] = mri_field_map_reg_2d(yik, etime, varargin)
%
% MRI field map estimation using regularization and optimization transfer,
% based on a multiple image model:
% y_ik = mag_i * phase_ik * decay_ik + noise_ik
% phase_ik = exp(1i * wmap_i * (etime_k - etime_1))
% decay_ik = exp(-R2_i * (etime_k - etime_1))
% mag_i unknown magnitude map
% wmap_i unknown field map
% R2_i unknown relaxation map
% and etime_k are echo times (or relative echo times). Often etime(1)=0.
% Units of wmap will be reciprocal of units of etime_k vector.
% So if etime has units seconds, then wmap has units rad/sec.
%
% in
% yik [nx,ny,nsets] complex images at different echo times
% (these should be undistorted)
% etime [nsets] vector of echo times
%
% options
% l2b log_2(beta), regularization parameter
% order regularization order (default: 2)
% niter # of iterations
% fmax percent of median used in calculating scale factor
% thresh percent of median used in masking out for RMSerror
% winit [nx,ny] initial field map for iterating
% (default is to estimate from first two scans)
% mask [nx,ny] logical support mask (only estimate within this)
%
% out
% wmap [nx,ny] regularized estimate of field map
% wconv "" conventional estimate from first two scans
%
% The first data set (usually) has no phase offset (etime(1) = 0).
% The second data set (usually) tries to have no phase wrapping,
% i.e., etime(2)-etime(1) usually is small.
% The other (optional) datasets (usually) have phase wrapping, but higher SNR.
%
% Copyright 2007-12-15, Amanda Funai & Jeff Fessler, The University of Michigan
if nargin >= 1 && streq(yi, 'test')
wmap = mri_field_map_reg_2d_test(yi, varargin{:});
if ~nargout; clear wmap; end
return
end
if nargin < 2; help(mfilename); error(mfilename); end
% Specify defaults & check argument inputs
arg.l2b = -3;
arg.order = 2;
arg.niter = 40;
arg.niter_init = 10;
arg.fmax = .1;
arg.wthresh = .1;
arg.winit = [];
arg.mask = [];
arg = vararg_pair(arg, varargin);
[nx, ny, nsets] = size(yi);
if size(etime, 2) ~= nsets
fail 'etime vector must be length nsets';
end
if isempty(arg.mask)
arg.mask = true(nx, ny);
else
jf_equal(size(arg.mask), [nx ny]);
end
% scale data to make regularization effect invariant to scaling factors
[yi y2] = mri_field_map_reg_2d_scale(yi, etime, arg);
% Reshape y for use in SPS & in calculating cost
ycol = reshape(yi, nx * ny, nsets); ycol = ycol(arg.mask, :);
ycol2 = reshape(y2, nx * ny, 2); ycol2 = ycol2(arg.mask, :);
%% Iterative Estimation
Rq = Robject(arg.mask, 'type_denom', 'matlab', ...
'beta', 2^arg.l2b, 'order', arg.order); % quadratic regularization
% If needed, use regularized initialization from first two data sets
if isempty(arg.winit)
% start with conventional estimate
wconv = angle(y2(:, :, 2) .* conj(y2(:, :, 1))) / (etime(2) - etime(1));
arg.winit = unwrapping_sps_manysets(wconv(arg.mask), ycol2, ...
etime(1:2), Rq, arg.niter_init);
arg.winit = embed(arg.winit(:, end), arg.mask);
mag1 = abs(yi(:, :, 1));
good = mag1 > arg.wthresh * max(mag1(:));
arg.winit(~good) = mean(arg.winit(good));
end
% estimate field map from all scans using the given initialization
wmap = unwrapping_sps_manysets(arg.winit(arg.mask), ycol, etime, Rq, arg.niter);
wmap = embed(wmap(:, end), arg.mask);
%
% mri_field_map_reg_2d_scale()
%
function [yi y2] = mri_field_map_reg_2d_scale(yi, etime, arg)
[nx, ny, nsets] = size(yi);
y1 = yi(:, :, 1);
% Scale by median of first set of data to get rid of large mag_j effects
scalefactor = median(y1(y1(:) > arg.fmax * max(y1(:))));
yi = yi / scalefactor;
% Try to compensate for R2 effects on effective regularization.
% (This can be slightly different scaling for each pixel.)
% "approximate oracle scaling"
wjfactor = zeros(nx, ny);
wjfactor2 = zeros(nx, ny);
for j = 1:nsets
for k = 1:nsets
tmp = yi(:, :, j) .* yi(:, :, k) * (etime(k) - etime(j));
wjfactor = wjfactor + abs(tmp).^2;
if j <= 2 && k <= 2
wjfactor2 = wjfactor2 + abs(tmp).^2;
end
end
end
totalsum = sum(abs(yi).^2, 3) .* abs(yi(:, :, 1)).^2;
wjfactor = sqrt(wjfactor ./ totalsum);
totalsum2 = (abs(yi(:, :, 2)).^2 + abs(yi(:, :, 1)).^2) ./ (abs(yi(:, :, 1)).^2);
wjfactor2 = sqrt(wjfactor2 ./ totalsum2);
% Scale data by this factor
y2(:, :, 1) = yi(:, :, 1) ./ wjfactor2;
y2(:, :, 2) = yi(:, :, 2) ./ wjfactor2;
for j = 1:nsets
yi(:, :, j) = yi(:, :, j) ./ wjfactor;
end
%
% built-in test/example
%
function wmap = mri_field_map_reg_2d_test(type, varargin)
% first make multiple datasets based on etime and a given mag & field map.
printm 'simulate noisy data';
etime = [0 2 10] * 1e-3;
nsets = length(etime);
R2 = 20; % 1/sec decay
SNR = 20; % dB
dir = [path_find_dir('mri') '/phase-data/'];
wtrue = 2 * pi * fld_read([dir 'fieldmap128.fld']);
mag = fld_read([dir 'mag128.fld']);
[nx ny] = size(mag); % 128
im pl 2 3;
im(1, wtrue / (2 * pi), 'true field map', [-40, 128]); cbar('Hz');
im(4, mag, 'mag'); cbar;
image_power = 10 * log10(sum(sum(mag.^2)) / (nx * ny));
noise_power = image_power - SNR;
noise_std = sqrt(10^(noise_power / 10));
noise_std = noise_std / 2; % because complex
yik = zeros(nx, ny, nsets);
for kk = 1:nsets
yik(:, :, kk) = mag ...
.* exp(1i * wtrue * (etime(kk) - etime(1))) ...
.* exp(-R2 * (etime(kk) - etime(1)));
end
rng(0);
yik = yik + noise_std * (randn(size(yik)) + 1i * randn(size(yik)));
printm 'estimate field map';
[wmap wconv] = mri_field_map_reg_2d(yik, etime, 'l2b', -6, varargin{:});
mask = mag > 0.05 * max(mag(:));
im(2, wconv / (2 * pi), 'conventional field map', [-40, 128]); cbar('Hz');
error = (wconv - wmap) / (2 * pi);
im(5, error, 'error', [-25 25]); cbar('Hz');
xlabelf('RMS = %.1f Hz', sqrt(mean(error(mask).^2)));
im(3, wmap / (2 * pi), 'regularized field map', [-40, 128]); cbar('Hz');
error = (wtrue - wmap) / (2 * pi);
im(6, error, 'error', [-25 25]); cbar('Hz');
xlabelf('RMS = %.1f Hz', sqrt(mean(error(mask).^2)));
|
import React, {useState} from 'react'
import './MainPart.css'
import ChatBot from "/src/components/ChatBot/ChatBot"
import db from '../../../firebase'
import { collection, addDoc } from "firebase/firestore";
import {TbMessageChatbot} from 'react-icons/tb'
import Popup from '../../../components/popupchatbot/Popup';
const ChickenMainPart = () => {
const [imageUpload, setImageUpload] = useState(null)
const [form,setForm]=useState({
name:'',
prompt:'',
photo:'',
})
const [predictedDisease,setPredictedDisease]=useState("No Disease")
const [buttonPopup, setButtonPopup] = useState(false)
const view=()=>{
setButtonPopup(true);
}
console.log(imageUpload)
const handleUpload = (e) => {
const file=e.target.files[0]
setImageUpload(file);
if(file && file.type.substr(0,5)==='image'){
const reader=new FileReader()
reader.onloadend=()=>{
setForm({...form,photo:reader.result})
}
reader.readAsDataURL(file)
}
else{
alert('Please upload animage')
}
}
const handleChange=(e)=>{
setForm({...form,[e.target.name]:e.target.value})
}
//Most Important Function
const handlPrediction= async(e)=>{
e.preventDefault()
const data=await addDoc(collection(db, "chickendisease"), {
name:predictedDisease,
time: new Date().toLocaleString()
});
alert("Prediction added to database")
}
return (
<>
{/* <NavBar /> */}
<div className='main flex lg:flex-row flex-col justify-between mt-10 lg:mt-5'>
<div className="model flex flex-col justify-center items-center lg:w-[950px] lg:h-[600px] lg:border-solid border-[2px] lg:m-3 m-5 ">
<h1 className='lg:text-2xl text-1xl mb-10 font-bold'>Upload image to detect chicken disease</h1>
<form className='flex flex-col items-center justify center' onSubmit={handlPrediction}>
<div className='lg:text-xl text-1xl flex justify-center items-center md:w-[500px] md:h-[300px] border-solid border-2 rounded-[15px]'>
{form.photo ? <img src={form.photo} alt="uploaded" className=' w-[400px] h-[199px] md:w-[500px] md:h-[299px] border-2 lg:w-[500px] lg:h-[300px] border-solid border-4 rounded:-[5px] md:rounded-[15px]'/> : <h1 className=' font-bold'>No Image Uploaded</h1>}
</div>
<div className='flex'>
<label htmlFor="photo" className="cursor-pointer">
<div className='mt-3 text-white bg-[#6469ff] hover:text-[#6469ff] hover:bg-blue-200 font-medium rounded-md text-sm w-full sm:w-auto px-5 py-2.5 text-center'>Upload</div>
<input type="file" accept="image/*" capture='environment' name="photo" id="photo" className="sr-only" onChange={handleUpload} />
</label>
<button className='m-3 text-white bg-[#6469ff] hover:text-[#6469ff] hover:bg-blue-200 font-medium rounded-md text-sm w-full sm:w-auto px-5 py-2.5 text-center' type='submit'>Predict</button>
</div>
</form>
<h1 className='lg:text-2xl text-1xl font-bold m-5'>{predictedDisease}</h1>
</div>
<div className='hidden lg:block'>
<h1 className="font-bold flex justify-center lg:hidden">
HelperBot
</h1>
<ChatBot/>
</div>
{/* for mobile */}
<div className=' flex lg:hidden justify-end mr-10 text-2xl' >
<button onClick={view} className='flex'>
<TbMessageChatbot/> <h1 className='text-sm'>HelperBot</h1>
</button>
</div>
{/*Pop */}
<Popup trigger={buttonPopup} setTrigger={setButtonPopup} >
<div className="flex flex-col justify-center items-center lg:hidden">
<h1 className='text-xl font-bold text-gray-700 flex justify-center'>Helper Bot</h1>
<div className='w-[350px] h-[400px] flex justify-center items-center '>
<ChatBot/>
</div>
</div>
</Popup>
</div>
</>
)
}
export default ChickenMainPart
|
// clang-format: off
#include "drake/multibody/tree/multibody_tree-inl.h"
// clang-format: on
#include <gtest/gtest.h>
#include "drake/common/eigen_types.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/multibody/tree/rigid_body.h"
#include "drake/multibody/tree/rpy_floating_joint.h"
#include "drake/systems/framework/context.h"
namespace drake {
namespace multibody {
namespace {
const double kTolerance = 4 * std::numeric_limits<double>::epsilon();
using Eigen::Vector3d;
using math::RigidTransformd;
using math::RollPitchYawd;
using math::RotationMatrixd;
using systems::Context;
constexpr double kPositionLowerLimit = -1.0;
constexpr double kPositionUpperLimit = 1.5;
constexpr double kVelocityLowerLimit = -1.1;
constexpr double kVelocityUpperLimit = 1.6;
constexpr double kAccelerationLowerLimit = -1.2;
constexpr double kAccelerationUpperLimit = 1.7;
constexpr double kAngularDamping = 3;
constexpr double kTranslationalDamping = 4;
constexpr double kPositionNonZeroDefault =
(kPositionLowerLimit + kPositionUpperLimit) / 2;
class RpyFloatingJointTest : public ::testing::Test {
public:
// Creates a MultibodyTree model of a spherical pendulum.
void SetUp() override {
// Spatial inertia for adding bodies. The actual value is not important for
// these tests and therefore we do not initialize it.
const SpatialInertia<double> M_B; // Default construction is ok for this.
// Create an empty model.
auto model = std::make_unique<internal::MultibodyTree<double>>();
// Add some bodies so we can add joints between them:
body_ = &model->AddRigidBody("Body", M_B);
// Add a ball rpy joint between the world and body:
joint_ = &model->AddJoint<RpyFloatingJoint>(
"Joint", model->world_body(), std::nullopt, *body_, std::nullopt,
kAngularDamping, kTranslationalDamping);
mutable_joint_ = dynamic_cast<RpyFloatingJoint<double>*>(
&model->get_mutable_joint(joint_->index()));
DRAKE_DEMAND(mutable_joint_ != nullptr);
mutable_joint_->set_position_limits(
Vector6d::Constant(kPositionLowerLimit),
Vector6d::Constant(kPositionUpperLimit));
mutable_joint_->set_velocity_limits(
Vector6d::Constant(kVelocityLowerLimit),
Vector6d::Constant(kVelocityUpperLimit));
mutable_joint_->set_acceleration_limits(
Vector6d::Constant(kAccelerationLowerLimit),
Vector6d::Constant(kAccelerationUpperLimit));
// We are done adding modeling elements. Transfer tree to system and get
// a Context.
system_ = std::make_unique<internal::MultibodyTreeSystem<double>>(
std::move(model), true /* is_discrete */);
context_ = system_->CreateDefaultContext();
}
const internal::MultibodyTree<double>& tree() const {
return internal::GetInternalTree(*system_);
}
protected:
std::unique_ptr<internal::MultibodyTreeSystem<double>> system_;
std::unique_ptr<Context<double>> context_;
const RigidBody<double>* body_{nullptr};
const RpyFloatingJoint<double>* joint_{nullptr};
RpyFloatingJoint<double>* mutable_joint_{nullptr};
};
TEST_F(RpyFloatingJointTest, Type) {
const Joint<double>& base = *joint_;
EXPECT_EQ(base.type_name(), RpyFloatingJoint<double>::kTypeName);
}
// Verify the expected number of dofs.
TEST_F(RpyFloatingJointTest, NumDOFs) {
EXPECT_EQ(tree().num_positions(), 6);
EXPECT_EQ(tree().num_velocities(), 6);
EXPECT_EQ(joint_->num_positions(), 6);
EXPECT_EQ(joint_->num_velocities(), 6);
EXPECT_EQ(joint_->position_start(), 0);
EXPECT_EQ(joint_->velocity_start(), 0);
}
TEST_F(RpyFloatingJointTest, GetJointLimits) {
EXPECT_EQ(joint_->position_lower_limits().size(), 6);
EXPECT_EQ(joint_->position_upper_limits().size(), 6);
EXPECT_EQ(joint_->velocity_lower_limits().size(), 6);
EXPECT_EQ(joint_->velocity_upper_limits().size(), 6);
EXPECT_EQ(joint_->acceleration_lower_limits().size(), 6);
EXPECT_EQ(joint_->acceleration_upper_limits().size(), 6);
EXPECT_EQ(joint_->position_lower_limits(),
Vector6d::Constant(kPositionLowerLimit));
EXPECT_EQ(joint_->position_upper_limits(),
Vector6d::Constant(kPositionUpperLimit));
EXPECT_EQ(joint_->velocity_lower_limits(),
Vector6d::Constant(kVelocityLowerLimit));
EXPECT_EQ(joint_->velocity_upper_limits(),
Vector6d::Constant(kVelocityUpperLimit));
EXPECT_EQ(joint_->acceleration_lower_limits(),
Vector6d::Constant(kAccelerationLowerLimit));
EXPECT_EQ(joint_->acceleration_upper_limits(),
Vector6d::Constant(kAccelerationUpperLimit));
}
TEST_F(RpyFloatingJointTest, Damping) {
EXPECT_EQ(joint_->default_angular_damping(), kAngularDamping);
EXPECT_EQ(joint_->default_translational_damping(), kTranslationalDamping);
EXPECT_EQ(
joint_->default_damping_vector(),
(Vector6d() << kAngularDamping, kAngularDamping, kAngularDamping,
kTranslationalDamping, kTranslationalDamping, kTranslationalDamping)
.finished());
// Ensure the deprecated versions are correct until removal.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
EXPECT_EQ(joint_->angular_damping(), kAngularDamping);
EXPECT_EQ(joint_->translational_damping(), kTranslationalDamping);
EXPECT_EQ(
joint_->damping_vector(),
(Vector6d() << kAngularDamping, kAngularDamping, kAngularDamping,
kTranslationalDamping, kTranslationalDamping, kTranslationalDamping)
.finished());
#pragma GCC diagnostic pop
}
// Context-dependent value access.
TEST_F(RpyFloatingJointTest, ContextDependentAccess) {
const Vector3d angles_A(M_PI_2, 0., 1.);
const Vector3d angles_B(0.25, 0.5, M_PI_2);
const Vector3d translation(1., 2., 3.);
const Vector3d angular_velocity(0.5, 0.5, 0.5);
const Vector3d translational_velocity(0.1, 0.2, 0.3);
const RotationMatrixd rotation_matrix_A =
RotationMatrixd(RollPitchYawd(angles_A));
const RotationMatrixd rotation_matrix_B =
RotationMatrixd(RollPitchYawd(angles_B));
const RigidTransformd transform_A(rotation_matrix_A, translation);
// Pose access:
joint_->set_angles(context_.get(), angles_A);
EXPECT_EQ(joint_->get_angles(*context_), angles_A);
joint_->SetOrientation(context_.get(), rotation_matrix_B);
EXPECT_TRUE(
CompareMatrices(joint_->get_angles(*context_), angles_B, kTolerance));
joint_->set_translation(context_.get(), translation);
EXPECT_EQ(joint_->get_translation(*context_), translation);
joint_->set_angles(context_.get(), Vector3d::Zero()); // Zero out pose.
joint_->set_translation(context_.get(), Vector3d::Zero());
joint_->SetPose(context_.get(), transform_A);
// We expect a bit of roundoff error due to transforming between rpy
// and rotation matrix representations.
EXPECT_TRUE(
joint_->GetPose(*context_).IsNearlyEqualTo(transform_A, kTolerance));
// Angular velocity access:
joint_->set_angular_velocity(context_.get(), angular_velocity);
EXPECT_EQ(joint_->get_angular_velocity(*context_), angular_velocity);
joint_->set_translational_velocity(context_.get(), translational_velocity);
EXPECT_EQ(joint_->get_translational_velocity(*context_),
translational_velocity);
// Joint locking.
joint_->Lock(context_.get());
EXPECT_EQ(joint_->get_angular_velocity(*context_), Vector3d(0., 0., 0.));
EXPECT_EQ(joint_->get_translational_velocity(*context_), Vector3d::Zero());
// Damping.
const Vector6d damping =
(Vector6d() << kAngularDamping, kAngularDamping, kAngularDamping,
kTranslationalDamping, kTranslationalDamping, kTranslationalDamping)
.finished();
const Vector6d different_damping =
(Vector6d() << 2.3, 2.3, 2.3, 4.5, 4.5, 4.5).finished();
EXPECT_EQ(joint_->GetDampingVector(*context_), damping);
EXPECT_NO_THROW(joint_->SetDampingVector(context_.get(), different_damping));
EXPECT_EQ(joint_->GetDampingVector(*context_), different_damping);
// Expect to throw on invalid damping values.
EXPECT_THROW(joint_->SetDampingVector(context_.get(), Vector6d::Constant(-1)),
std::exception);
}
// Tests API to apply torques to joint.
TEST_F(RpyFloatingJointTest, AddInOneForce) {
const double some_value = M_PI_2;
MultibodyForces<double> forces(tree());
// Since adding forces to individual degrees of freedom of this joint is
// not supported, this method should throw.
EXPECT_THROW(joint_->AddInOneForce(*context_, 0, some_value, &forces),
std::exception);
}
// Tests API to add in damping forces.
TEST_F(RpyFloatingJointTest, AddInDampingForces) {
const Vector3d angular_velocity(0.1, 0.2, 0.3);
const Vector3d translational_veloctiy(0.4, 0.5, 0.6);
const double angular_damping = 3 * kAngularDamping;
const double translational_damping = 4 * kTranslationalDamping;
const Vector6d damping_forces_expected =
(Vector6d() << -angular_damping * angular_velocity,
-translational_damping * translational_veloctiy)
.finished();
joint_->set_angular_velocity(context_.get(), angular_velocity);
joint_->set_translational_velocity(context_.get(), translational_veloctiy);
joint_->SetDampingVector(context_.get(),
(Vector6d() << Vector3d::Constant(angular_damping),
Vector3d::Constant(translational_damping))
.finished());
MultibodyForces<double> forces(tree());
joint_->AddInDamping(*context_, &forces);
EXPECT_EQ(forces.generalized_forces(), damping_forces_expected);
}
TEST_F(RpyFloatingJointTest, Clone) {
auto model_clone = tree().CloneToScalar<AutoDiffXd>();
const auto& joint_clone = model_clone->get_variant(*joint_);
EXPECT_EQ(joint_clone.name(), joint_->name());
EXPECT_EQ(joint_clone.frame_on_parent().index(),
joint_->frame_on_parent().index());
EXPECT_EQ(joint_clone.frame_on_child().index(),
joint_->frame_on_child().index());
EXPECT_EQ(joint_clone.position_lower_limits(),
joint_->position_lower_limits());
EXPECT_EQ(joint_clone.position_upper_limits(),
joint_->position_upper_limits());
EXPECT_EQ(joint_clone.velocity_lower_limits(),
joint_->velocity_lower_limits());
EXPECT_EQ(joint_clone.velocity_upper_limits(),
joint_->velocity_upper_limits());
EXPECT_EQ(joint_clone.acceleration_lower_limits(),
joint_->acceleration_lower_limits());
EXPECT_EQ(joint_clone.acceleration_upper_limits(),
joint_->acceleration_upper_limits());
EXPECT_EQ(joint_clone.default_angular_damping(),
joint_->default_angular_damping());
EXPECT_EQ(joint_clone.default_translational_damping(),
joint_->default_translational_damping());
EXPECT_EQ(joint_clone.get_default_angles(), joint_->get_default_angles());
EXPECT_EQ(joint_clone.get_default_translation(),
joint_->get_default_translation());
}
TEST_F(RpyFloatingJointTest, SetVelocityAndAccelerationLimits) {
const double new_lower = -0.2;
const double new_upper = 0.2;
// Check for velocity limits.
mutable_joint_->set_velocity_limits(Vector6d::Constant(new_lower),
Vector6d::Constant(new_upper));
EXPECT_EQ(joint_->velocity_lower_limits(), Vector6d::Constant(new_lower));
EXPECT_EQ(joint_->velocity_upper_limits(), Vector6d::Constant(new_upper));
// Does not match num_velocities().
EXPECT_THROW(mutable_joint_->set_velocity_limits(VectorX<double>(6),
VectorX<double>()),
std::exception);
EXPECT_THROW(mutable_joint_->set_velocity_limits(VectorX<double>(),
VectorX<double>(6)),
std::exception);
// Lower limit is larger than upper limit.
EXPECT_THROW(mutable_joint_->set_velocity_limits(Vector6d::Constant(2),
Vector6d::Constant(0)),
std::exception);
// Check for acceleration limits.
mutable_joint_->set_acceleration_limits(Vector6d::Constant(new_lower),
Vector6d::Constant(new_upper));
EXPECT_EQ(joint_->acceleration_lower_limits(), Vector6d::Constant(new_lower));
EXPECT_EQ(joint_->acceleration_upper_limits(), Vector6d::Constant(new_upper));
// Does not match num_velocities().
EXPECT_THROW(mutable_joint_->set_acceleration_limits(VectorX<double>(6),
VectorX<double>()),
std::exception);
EXPECT_THROW(mutable_joint_->set_acceleration_limits(VectorX<double>(),
VectorX<double>(6)),
std::exception);
// Lower limit is larger than upper limit.
EXPECT_THROW(mutable_joint_->set_acceleration_limits(Vector6d::Constant(2),
Vector6d::Constant(0)),
std::exception);
}
TEST_F(RpyFloatingJointTest, CanRotateOrTranslate) {
EXPECT_TRUE(joint_->can_rotate());
EXPECT_TRUE(joint_->can_translate());
}
TEST_F(RpyFloatingJointTest, NameSuffix) {
EXPECT_EQ(joint_->position_suffix(0), "qx");
EXPECT_EQ(joint_->position_suffix(1), "qy");
EXPECT_EQ(joint_->position_suffix(2), "qz");
EXPECT_EQ(joint_->position_suffix(3), "x");
EXPECT_EQ(joint_->position_suffix(4), "y");
EXPECT_EQ(joint_->position_suffix(5), "z");
EXPECT_EQ(joint_->velocity_suffix(0), "wx");
EXPECT_EQ(joint_->velocity_suffix(1), "wy");
EXPECT_EQ(joint_->velocity_suffix(2), "wz");
EXPECT_EQ(joint_->velocity_suffix(3), "vx");
EXPECT_EQ(joint_->velocity_suffix(4), "vy");
EXPECT_EQ(joint_->velocity_suffix(5), "vz");
}
TEST_F(RpyFloatingJointTest, DefaultAnglesAndTranslation) {
const Vector3d lower_limit_angles = Vector3d::Constant(kPositionLowerLimit);
const Vector3d upper_limit_angles = Vector3d::Constant(kPositionUpperLimit);
const Vector3d default_angles = Vector3d::Zero();
const Vector3d new_default_angles =
Vector3d::Constant(kPositionNonZeroDefault);
const Vector3d out_of_bounds_low_angles =
lower_limit_angles - Vector3d::Constant(1);
const Vector3d out_of_bounds_high_angles =
upper_limit_angles + Vector3d::Constant(1);
// Constructor should set the default angle to Vector3d::Zero()
EXPECT_EQ(joint_->get_default_angles(), default_angles);
// Setting a new default angle should propagate so that `get_default_angle()`
// remains correct.
mutable_joint_->set_default_angles(new_default_angles);
EXPECT_EQ(joint_->get_default_angles(), new_default_angles);
// Setting the default angle out of the bounds of the position limits
// should NOT throw an exception
EXPECT_NO_THROW(mutable_joint_->set_default_angles(out_of_bounds_low_angles));
EXPECT_NO_THROW(
mutable_joint_->set_default_angles(out_of_bounds_high_angles));
EXPECT_EQ(joint_->get_default_translation(), Vector3d::Zero());
mutable_joint_->set_default_translation(Vector3d(1.0, 2.0, 3.0));
EXPECT_EQ(joint_->get_default_translation(), Vector3d(1.0, 2.0, 3.0));
EXPECT_TRUE(joint_->GetDefaultPose().IsNearlyEqualTo(
RigidTransformd(RollPitchYawd(joint_->get_default_angles()),
joint_->get_default_translation()),
kTolerance));
}
TEST_F(RpyFloatingJointTest, RandomState) {
RandomGenerator generator;
std::uniform_real_distribution<symbolic::Expression> uniform;
Eigen::Matrix<symbolic::Expression, 3, 1> zero_3(0.0, 0.0, 0.0);
// Default behavior is to set to zero.
tree().SetRandomState(*context_, &context_->get_mutable_state(), &generator);
EXPECT_TRUE(joint_->GetPose(*context_).IsExactlyIdentity());
// Set the angles & translation distribution to arbitrary values.
Eigen::Matrix<symbolic::Expression, 3, 1> angles_distribution;
Eigen::Matrix<symbolic::Expression, 3, 1> translation_distribution;
for (int i = 0; i < 3; i++) {
angles_distribution[i] = 0.0125 * (uniform(generator) + i + 1.0);
translation_distribution[i] = uniform(generator) + i + 1.0;
}
mutable_joint_->set_random_angles_distribution(angles_distribution);
mutable_joint_->set_random_translation_distribution(translation_distribution);
tree().SetRandomState(*context_, &context_->get_mutable_state(), &generator);
// We expect arbitrary non-zero values for the random state.
EXPECT_FALSE(joint_->GetPose(*context_).IsExactlyIdentity());
// Set position and quaternion distributions back to 0.
mutable_joint_->set_random_angles_distribution(zero_3);
mutable_joint_->set_random_translation_distribution(zero_3);
tree().SetRandomState(*context_, &context_->get_mutable_state(), &generator);
// We expect zero values for pose.
EXPECT_TRUE(joint_->GetPose(*context_).IsExactlyIdentity());
}
} // namespace
} // namespace multibody
} // namespace drake
|
<template>
<div class="section">
<div class="columns is-multiline">
<div class="column">
<p class="title">Compute Hash</p>
</div>
<div class="column is-narrow">
<button class="button is-light is-danger is-fullwidth" @click="reset">
Reset
</button>
</div>
</div>
<div class="box">
<label>
Enter your data
<textarea
v-model="input"
type="text"
class="textarea"
placeholder="Whatever data you want to hash"
></textarea>
</label>
</div>
<div class="box">
<div class="columns is-vcentered">
<div class="column"><p class="subtitle is-4">Hash</p></div>
<div class="column is-narrow">
<div class="select is-success is-fullwidth">
<select v-model="output_type">
<option value="hex">Hexadecimal</option>
<option value="bits">Bits</option>
</select>
</div>
</div>
<div class="column is-narrow">
<div class="select is-success is-fullwidth">
<select v-model="hash_function">
<option value="SHA256">SHA256</option>
<option value="SHA3">SHA3</option>
</select>
</div>
</div>
</div>
<code class="word-wrap">{{ hash }}</code>
<details class="content mt-4">
<summary style="cursor: pointer">Types of Hashes</summary>
<ul>
<li>
<b>SHA256</b> is a hash function from the SHA2 hash function family
with a 256 bit output length.
</li>
<li>
<b>SHA256</b> is one of the most popular hash functions, and is used
by Bitcoin. This will also be the hash function used for the Proof
of Work demo later on.
</li>
<li>
<b>SHA3</b> is a hash function from the SHA3 hash function family
with a 256 bit output length.
</li>
<li>
<b>SHA3</b> is supposed to be more secure than <b>SHA256</b>, and it
is used by the Ethereum blockchain.
</li>
</ul>
</details>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
// Utility function for converting a hexadecimal string to binary as string type.
const hex2bin = (data: string) =>
data
.split("")
.map((i) => parseInt(i, 16).toString(2).padStart(4, "0"))
.join("");
export default defineComponent({
name: "Hash",
data() {
return {
output_type: "hex",
hash_function: "SHA256",
input: "",
hash: "",
};
},
watch: {
// Watcher to call updateHash on input change
input() {
this.updateHash();
},
// Watcher to call updateHash on change of output type,
// as updateHash function sets the output
output_type() {
this.updateHash();
},
// Watcher to call updateHash on change of hash function
hash_function() {
this.updateHash();
},
},
// Run updateHash on created so to show the hash of the empty input
created() {
this.updateHash();
},
methods: {
/**
* Caller to await the results to get the hash function lazily
*/
async getHashFunction() {
// These es modules have a default export which is the hash function itself,
// so they are parsed out before returning to the caller.
switch (this.hash_function) {
case "SHA256":
return import("crypto-js/sha256").then(({ default: fn }) => fn);
case "SHA3":
return import("crypto-js/sha3").then(({ default: fn }) => fn);
default: {
const err = new Error("Invalid hash function selected!");
alert(err);
throw err;
}
}
},
async updateHash() {
// Lazily load the hash function
const fn = await this.getHashFunction();
// Output length config is required because the default length for the SHA3 function is 512bits
// So this is needed to set to use sha3-256, and the sha256 function will simply ignore this extra config object.
const hexString = fn(this.input, { outputLength: 256 }).toString();
this.hash = this.output_type === "hex" ? hexString : hex2bin(hexString);
},
reset() {
this.input = "";
},
},
});
</script>
|
import React, {useState} from 'react'
import Item from "../Item/Item";
import "./SimilarProduct.scss";
import ReactSimplyCarousel from 'react-simply-carousel';
import { SlArrowLeft, SlArrowRight } from "react-icons/sl";
const SimilarProduct = ({similarProducts}) => {
const [activeSlideIndex, setActiveSlideIndex] = useState(0);
const headingCategory = similarProducts[0].category;
return (
<div className='similar-products'>
<h3>Similar item related to {headingCategory}</h3>
<div className="similar-product-items">
<ReactSimplyCarousel
activeSlideIndex={activeSlideIndex}
onRequestChange={setActiveSlideIndex}
itemsToShow={1}
itemsToScroll={1}
forwardBtnProps={{
//here you can also pass className, or any other button element attributes
style: {
alignSelf: 'center',
border: 'none',
cursor: 'pointer',
fontSize: '20px',
width: 30,
},
children: <span>{<SlArrowRight />}</span>,
}}
backwardBtnProps={{
//here you can also pass className, or any other button element attributes
style: {
alignSelf: 'center',
border: 'none',
cursor: 'pointer',
fontSize: '20px',
width: 30,
},
children: <span>{<SlArrowLeft />}</span>,
}}
responsiveProps={[
{
itemsToShow: 4,
itemsToScroll: 2,
minWidth: 768,
},
]}
speed={400}
easing="linear">
{similarProducts.map((product) => (
<Item key={product.id} id={product.id} imgSrc={product.imgSrc} name={product.name} price={product.price} />
))}
</ReactSimplyCarousel>
</div>
</div>
)
}
export default SimilarProduct
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Webdevproof</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="index.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" type="text/css" href="./slick/slick.css" />
<link rel="stylesheet" type="text/css" href="./slick/slick-theme.css" />
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light ">
<div class="container-fluid">
<a class="navbar-brand" href="./index.html"> <img class="img-fluid" src="./img/Hijyen-Logo.png" > </a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse " id="navbarNavDropdown">
<ul class="navbar-nav mx-auto">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="hijyen-belgesi-page.html">Hijyen Belgesi</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="online-page.html">Online Baลvuru</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="sorular-page.html">Sฤฑkรงa Sorulan Sorular</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="sฤฑnavlar-page.html">Sฤฑnavlar</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="blog-page.html">Blog</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="iletiลim-page.html">Iletiลim</a>
</li>
<li class="nav-item">
<a style="color: rgb(20, 235, 250);" class="nav-link active btn--show-modal" href="">Giriล yap</a>
</li>
<li class="nav-item">
<a style="color: rgb(20, 235, 250);" class="nav-link active kayฤฑt--show-modal" href="">kayฤฑt Ol</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="modal-custom hidden">
<button class="btn--close-modal">×</button>
</h2>
<form class="modal__form">
<label style="color: white; font-weight: 400;">E-Posta</label>
<input type="email" />
<label style="color: white; font-weight: 400;">ลifre</label>
<input type="text" />
<button class="btn-modal">Giriล yap <i class="bi bi-arrow-bar-right"></i></button>
</form>
</div>
<div class="overlay hidden"></div>
<div class="modal--custom-kayฤฑt hidden">
<button class="btn--close-modal">×</button>
</h2>
<form class="modal__form">
<label style="color: white; font-weight: 400;">Ad Soyad</label>
<input type="text" />
<label style="color: white; font-weight: 400;">E-Posta</label>
<input type="email" />
<label style="color: white; font-weight: 400;">Telefon numarasฤฑ</label>
<input type="number" value="(5xx)-xxx-xx-xx" />
<label style="color: white; font-weight: 400;">ลifre</label>
<input type="text" />
<button class="btn-modal">Kayฤฑt ol <i class="bi bi-arrow-bar-right"></i></button>
</form>
</div>
<div class="overlay hidden"></div>
<div class="container-fluid" style="background-color:rgb(228, 240, 240); ">
<div class="row" style="text-align: center;">
<div class="col-md-4 offset-md-2" style="padding-top: 10vw; text-align: center;">
<h4 style="color:#002249; font-weight: 700;">Hijyen Akademisi gรผvencesiyle <br> hijyen sertifikanฤฑz elinizde</h4>
</div>
<div class="col-md-6">
<img style="width: 20rem; border-radius: 60px;" src="./img/hijyen-sert.jpg" alt="">
</div>
</div>
</div>
<div class="container section-belge">
<div style="text-align: center; padding-top: 50px;" class="row">
<h1>HฤฐJYEN BELGESฤฐ</h1>
<h5>hijyen belgesi hakkฤฑnda bilmeniz gerekenler</h5>
</div>
<div style="padding: 0 10vw;" class="row">
<h2 style="color: grey;">Hijyen belgesi nedir?</h2>
<p>Hijyen belgesi nedir, nereden alฤฑnฤฑr? Sorusu hala aktรผelliฤini koruyor. Bu yazฤฑmฤฑzda hijyen sertifikasฤฑ nedir, nereden alฤฑnฤฑr sorularฤฑnฤฑ cevaplayacaฤฤฑz. Hijyen belgesi, insanlarฤฑn saฤlฤฑฤฤฑna zarar verecek ortamlarda alฤฑnan tedbirleri uygulamalฤฑ olarak gรถsteren hijyen eฤitimi sonrasฤฑ verilen belgedir. Hijyen sertifikasฤฑ, ilgili bakanlฤฑk tarafฤฑndan yayฤฑnlanan hijyen eฤitimi yรถnetmeliฤine gรถre zorunludur.</p>
<p>Hijyen belgesi almak iรงin 0552 479 94 53 numaralฤฑ telefondan hemen bize ulaลarak gerekli bilgiyi alabilir ve hijyen sertifikasฤฑ sahibi olabilirsiniz. Hijyen eฤitimi yรถnetmeliฤi 2013 yฤฑlฤฑnda yรผrรผrlรผฤe girdi ve geรงen 5 yฤฑl iรงerisinde binlerce kiลi belgesini alarak รงalฤฑลanlarฤฑn daha saฤlฤฑklฤฑ ortamda iลlerini yapma imkanฤฑ tanฤฑdฤฑr. Hijyen belgesini almayฤฑ zorunlu kฤฑlan bu yรถnetmeliฤin amacฤฑ รถzellikle gฤฑda sektรถrรผnde รงalฤฑลan bireylerin hijyen konusunda bilinรงlenmesi ve iลรงilerin daha saฤlฤฑklฤฑ ortamda รงalฤฑลarak hastalฤฑklara yakalanmalarฤฑnฤฑn engellenmesidir. Hijyen sertifikasฤฑnฤฑn alฤฑnmasฤฑ zorunludur ve kurala uymayan kiลi ve iล yerlerine ceza kesilmesi esas gรถrรผlmรผลtรผr.</p>
<h2 style="color: grey;"> Hijyen Belgesi Hangi ฤฐลletmeler ฤฐรงin Zorunludur</h2>
<p>Her ลeyin baลฤฑ saฤlฤฑk, saฤlฤฑk olsun gibi sรถzleri gรผndelik hayatฤฑmฤฑzda o kadar รงok duyarฤฑz ki kendimiz de bir o kadar kullanฤฑrฤฑz. รรผnkรผ gerรงekten bu hayattaki belki de en รถnemli varlฤฑฤฤฑmฤฑzdฤฑr. ฤฐnsanlar genรงken varlฤฑk (mal-para) iรงin saฤlฤฑฤฤฑnฤฑ feda edercesine รงalฤฑลฤฑr, saฤlฤฑฤฤฑnฤฑ kaybedince ise tรผm varlฤฑฤฤฑnฤฑ harcamaktan รงekinmezmiล. Gerรงekten de bu denli รถnemli olan saฤlฤฑฤฤฑn ilk adฤฑmฤฑ ise hijyenden geรงiyor. Bu yรผzden hemen herkesin almasฤฑ gereken hijyen eฤitimleri, devlet tarafฤฑndan Hijyen Eฤitimi yรถnetmeliฤi ile de bazฤฑ iล kollarฤฑna zorunlu hale getirilmiลtir.</p>
<p>Bu yรถnetmelik gereฤi; <br>
Restoranlar, yemekhaneler gibi gฤฑda รผretimi yapฤฑlan yerler, otel, motel, pansiyonlar, gรผzellik merkezleri, dรถvme ve pirsing yapฤฑlan iลyerleri, kaplฤฑcalar, hamam iลletmesi yapฤฑlan yerler, masaj salonlarฤฑ, insani tรผketim amaรงlฤฑ sular รผreten iลyerleri ve komisyon tarafฤฑndan verilmesi uygun gรถrรผlen diฤer iล kollarฤฑ da bu eฤitimi aldฤฑrmakla yรผkรผmlรผdรผrler.</p>
<p>Eฤer iลveren kendisi de bu iล kollarฤฑnda bizzat รงalฤฑลฤฑyor ise kendisi de bu eฤitimi almak durumundadฤฑr. Bu eฤitimlerin alฤฑnmasฤฑndan iลveren bizzat sorumlu olup, hijyen eฤitimi sertifikasฤฑ bulunmayan personel รงalฤฑลtฤฑrmasฤฑ durumunda her bir personel iรงin ayrฤฑ ayrฤฑ 5 Temmuz 2013 tarihli Hijyen Eฤitimi Yรถnetmeliฤi ve 1593 Sayฤฑlฤฑ Umumi Hฤฑfzฤฑssฤฑhha Kanunun ilgili maddelerince bu eฤitimi aldฤฑrmayan ilgili iลyerlerine cezai iลlem uygulanmaktadฤฑr.</p>
<p>Bu yรถnetmeliฤin kapsadฤฑฤฤฑ iลyerlerinde Genel Mรผdรผrlรผk tarafฤฑndan verilen belgeye sahip olmayan kiลiler รงalฤฑลtฤฑrฤฑlamaz. Eฤitimler, Genel Mรผdรผrlรผฤe baฤlฤฑ รถฤretim kurumlarฤฑnca verilebilmektedir. Hijyen eฤitimleri yรถnetmelik gereฤi 8 saatten az olmamak รผzere komisyonca belirlenen eฤitim iรงeriklerine uygun olmak durumundadฤฑr. Sizler de bu konuda tรผm yeterliliฤini saฤlamฤฑล bulunan kurumumuzla iletiลime geรงebilirsiniz. ฤฐลyerinizin faaliyet konusu da gรถz รถnรผnde bulundurularak uygun eฤitim programlarฤฑ tarafฤฑmฤฑzca dรผzenlenecektir.</p>
<p>Katฤฑlฤฑmcฤฑlara รผniversite onaylฤฑ olarak ve e-devlet sistemi รผzerinden de gรถrรผntรผlenebilen katฤฑlฤฑm sertifikalarฤฑ dรผzenlenir ve bu belgeler kiลi hizmet verdiฤi mรผddetรงe geรงerlidir. Yani รงalฤฑลan 1 kez bu sertifikayฤฑ aldฤฑฤฤฑnda รงalฤฑลma hayatฤฑ boyunca geรงerliliฤini korur.</p>
<p>Unutmayalฤฑm ki saฤlฤฑk ve hijyen kendimiz, ailemiz, iลyerimiz ve toplumumuz iรงin elzemdir. Bilinรงli bireyler iรงin ve saฤlฤฑklฤฑ yarฤฑnlar iรงin uzman kadromuzla yanฤฑnฤฑzdayฤฑz.</p>
<h2 style="padding-top: 15px; color: grey;">Hijyen belgesi almasฤฑ zorunlu sektรถr ve kiลiler</h2>
<p>Hijyen belgesi sadece iลรงilere deฤil, iลyeri sahibi ve iลverenler iรงin de zorunludur. Belgeyi almasฤฑ gereken iลyerleri ลunlardฤฑr:</p>
<ul >
<li><i class="bi bi-arrow-right"></i> su รผretimi yapan yerler</li>
<li<i class="bi bi-arrow-right"></i> >Doฤal su ve mineral รผretimi yapan yerler</li>
<li><i class="bi bi-arrow-right"></i> Gฤฑda รผreten iลyerleri</li>
<li><i class="bi bi-arrow-right"></i> Perakende gฤฑda satฤฑลฤฑ yapan yerler</li>
<li><i class="bi bi-arrow-right"></i> Gฤฑda taลฤฑmacฤฑlฤฑฤฤฑ veya servisi yapan yerler</li>
<li><i class="bi bi-arrow-right"></i> Pansiyonlar</li>
<li><i class="bi bi-arrow-right"></i> Oteller</li>
<li><i class="bi bi-arrow-right"></i> Moteller</li>
<li><i class="bi bi-arrow-right"></i> Misafirhaneler</li>
<li><i class="bi bi-arrow-right"></i> Yurtlar</li>
<li><i class="bi bi-arrow-right"></i> รฤrenci Yurtlarฤฑ</li>
<li><i class="bi bi-arrow-right"></i> Konaklama yerleri</li>
<li><i class="bi bi-arrow-right"></i> Temizlik hizmetleri veren yerler</li>
<li><i class="bi bi-arrow-right"></i> ฤฐnsan teniyle direkt temasta bulunan hizmet veren kurumlar</li>
<li><i class="bi bi-arrow-right"></i> Kuafรถr</li>
<li><i class="bi bi-arrow-right"></i> Mutfaklar</li>
<li><i class="bi bi-arrow-right"></i> Berber</li>
<li><i class="bi bi-arrow-right"></i> Hamam</li>
<li<i class="bi bi-arrow-right"></i> >Havuz</li>
<li><i class="bi bi-arrow-right"></i> Sauna ve benzeri yerlerde รงalฤฑnanlar hijyen belgesi almak zorundadฤฑr.</li>
</ul>
<p>Hijyen.com.tr 'den alacaฤฤฑnฤฑz hijyen eฤitimini tek kiลiye veya toplu iลyerinin bรผtรผn รงalฤฑลanlarฤฑna aynฤฑ derste verilmektedir. Hijyen kursu minimum 8 saat olmalฤฑdฤฑr.</p>
<h3 style="color: grey;">Hijyen belgesi iรงin gerekli belgeler</h3>
<ul>
<li><i class="bi bi-arrow-right"></i> nรผfus cรผzdanฤฑ fotokopisi</li>
<li><i class="bi bi-arrow-right"></i> okuma yazma belgesi</li>
</ul>
<h3 style="color: grey;">Eฤitimin iรงeriฤi</h3>
<p>Hijyen belgesi eฤitiminde iลlenecek konular;</p>
<ul>
<li><i class="bi bi-arrow-right"></i> Hastalฤฑklar neden olan mikrop ve virรผslerin รถzellikleri</li>
<li><i class="bi bi-arrow-right"></i> Ne ลekilde bulaลtฤฑklarฤฑ</li>
<li><i class="bi bi-arrow-right"></i> Hastalฤฑklara yakalanma riskini azaltma รถnlemleri</li>
<li><i class="bi bi-arrow-right"></i> รalฤฑลanlara yรถnelik yasa</li>
<li><i class="bi bi-arrow-right"></i> Mikrop tanฤฑmฤฑ</li>
<li><i class="bi bi-arrow-right"></i> Mikrop รงeลitleri</li>
<li><i class="bi bi-arrow-right"></i> Mikroplarฤฑn bulaลma yollarฤฑ</li>
<li><i class="bi bi-arrow-right"></i> Hastalฤฑklarฤฑn Kaynaklarฤฑ</li>
<li><i class="bi bi-arrow-right"></i> Hastalฤฑklarฤฑn bulaลma yollarฤฑ</li>
<li<i class="bi bi-arrow-right"></i> >Enfeksiyon zinciri</li>
<li><i class="bi bi-arrow-right"></i> Sฤฑk gรถrรผlen hastalฤฑklar</li>
</ul>
<p>Hijyen belgesi eฤitimi, eฤitim iรงeriฤi ve fiyatlarฤฑ hakkฤฑnda รงekinmeden 0552 479 94 53 'dan bizi arayarak bilgi alabilirsiniz.
</p>
</div>
</div>
<div class="container-fluid section-iletiลim">
<div style="text-align: center;" class="row">
<div style="font-weight: 600; padding-top: 60px; font-size: 2.5rem; padding-bottom: 50px;" class="col-12">Biz sizi arayalฤฑm</div>
</div>
<div class="row pb-5">
<form>
Adฤฑnฤฑz,Soyadฤฑnฤฑz: <br>
<input style="width: 100%; border-style: hidden; border-radius: 10px;" type="text" id="name">
</form>
</div>
<div class="row pb-5">
<form>
Telefon numaranฤฑz: <br>
<input style="width: 100%; border-style: hidden; border-radius: 10px; color: grey;" type="number" maxlength="10" value="(5xx)-xxx-xx-xx">
</form>
</div>
<div class="row preference-section-button">
<button class="button-19" role="button">Gรถnder</button>
</div>
</div>
<footer>
<div class="container">
<div class="row" style="padding-top: 70px;">
<div class="col-md-4 ">
<img src="./img/Hijyen-Logo.png" class="footer-logo">
<br>
<div class="footer-text">HฤฐJYEN AKADEMฤฐ TARAFINDAN Profesyonel Ekibimizle , M.E.B ve รniversite onaylฤฑ tรผm kurum ve kuruluลlara danฤฑลmanlฤฑk vermekteyiz.
</div>
</div>
<div class="col-md-4 ">
<div class="footer-title"><b class="p-1"><i class="bi bi-align-start"></i>รalฤฑลma saatleri</b></div>
<div class="footer-connections">
<a class="footer-connections-item" href="#">pazartesi - Cuma: 7:00 - 17:00</a>
<a class="footer-connections-item" href="#">Cumartesi: 7:00 - 12:00</a>
</div>
</div>
<div class="col-md-4">
<div class="footer-text footer-title"><b class="p-1">E-BรLTEN</b></div>
<div class="footer-text">E-bรผltenimize kayฤฑt olarak etkinliklerimizden haberdar olabilirsiniz.</div>
<div class="input-group">
<input type="text" class="form-control form-value border-0" id="fldAboneOl">
<div class="input-group-btn">
<button type="button" style="margin-left:0; height:34px" class="btn btn-default w-100 h-100 border-0" onclick="AboneOl()">Abone Ol</button>
</div>
</div>
<div class="footer-text footer-title footer-social-title"><b class="p-1">SOSYAL MEDYA</b></div>
<div class="footer-text">Bizi sosyal medyadan takip edin.</div>
<div class="footer-social-icons">
<i class="bi footer-icon bi-facebook"></i>
<i class="bi footer-icon bi-instagram"></i>
</div>
</div>
</div>
</div>
</footer>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script>
const modal = document.querySelector('.modal-custom');
const overlay = document.querySelector('.overlay');
const btnCloseModal = document.querySelector('.btn--close-modal');
const btnsOpenModal = document.querySelectorAll('.btn--show-modal');
const openModal = function (e) {
e.preventDefault();
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
};
const closeModal = function () {
modal.classList.add('hidden');
overlay.classList.add('hidden');
};
btnsOpenModal.forEach(btn => btn.addEventListener('click', openModal));
btnCloseModal.addEventListener('click', closeModal);
overlay.addEventListener('click', closeModal);
</script>
<script>
const modal2 = document.querySelector('.modal--custom-kayฤฑt');
const overlay2 = document.querySelector('.overlay');
const btnCloseModal2 = document.querySelector('.btn--close-modal');
const btnsOpenModal2 = document.querySelectorAll('.kayฤฑt--show-modal');
const openModal2 = function (e) {
e.preventDefault();
modal2.classList.remove('hidden');
overlay2.classList.remove('hidden');
};
const closeModal2 = function () {
modal2.classList.add('hidden');
overlay2.classList.add('hidden');
};
btnsOpenModal2.forEach(btn => btn.addEventListener('click', openModal2));
btnCloseModal2.addEventListener('click', closeModal2);
overlay2.addEventListener('click', closeModal2);
</script>
</html>
|
import { Component, OnChanges, SimpleChanges, ElementRef, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { BaseDataUtils } from 'app/shared/base/base-data-utils.service';
import { AlertService } from 'app/core/util/alert.service';
import { EventManager } from 'app/core/util/event-manager.service';
import { IPersonalCustomer, PersonalCustomer } from './personal-customer.model';
import { PersonalCustomerService } from './personal-customer.service';
import { MessageService } from 'primeng/api';
import { AccountService } from 'app/core/auth/account.service';
import { CODE } from 'app/shared/constants/base.constants';
import { AbstractEntityBaseViewComponent } from 'app/shared/base/abstract-entity-view.component';
import { TranslateService } from '@ngx-translate/core';
import { IPartyType, PartyType } from 'app/entities/party-type/party-type.model';
import { PartyTypeService } from 'app/entities/party-type/party-type.service';
import { IPostalAddress, PostalAddress } from 'app/entities/postal-address/postal-address.model';
import { PostalAddressService } from 'app/entities/postal-address/postal-address.service';
import { IReligionType, ReligionType } from 'app/entities/religion-type/religion-type.model';
import { ReligionTypeService } from 'app/entities/religion-type/religion-type.service';
import { IWorkType, WorkType } from 'app/entities/work-type/work-type.model';
import { WorkTypeService } from 'app/entities/work-type/work-type.service';
import { IRoleCustomer, RoleCustomer } from 'app/entities/role-customer/role-customer.model';
import { RoleCustomerService } from 'app/entities/role-customer/role-customer.service';
type SelectableEntity = IPartyType | IPostalAddress | IReligionType | IWorkType | IRoleCustomer;
@Component({
selector: 'jhi-personal-customer-view',
templateUrl: './personal-customer-view.component.html',
})
export class PersonalCustomerViewComponent extends AbstractEntityBaseViewComponent<IPersonalCustomer> implements OnChanges {
@Input() id: string;
readonly CODE: typeof CODE = CODE;
partytypes: IPartyType[] = [];
postaladdresses: IPostalAddress[] = [];
religiontypes: IReligionType[] = [];
worktypes: IWorkType[] = [];
rolecustomers: IRoleCustomer[] = [];
partyTypeId: string;
postalAddressId: number;
religionTypeId: string;
workTypeId: string;
roleId: number;
constructor(
protected dataUtils: BaseDataUtils,
protected alertService: AlertService,
protected personalCustomerService: PersonalCustomerService,
protected partyTypeService: PartyTypeService,
protected postalAddressService: PostalAddressService,
protected religionTypeService: ReligionTypeService,
protected workTypeService: WorkTypeService,
protected roleCustomerService: RoleCustomerService,
protected elementRef: ElementRef,
protected activatedRoute: ActivatedRoute,
protected messageService: MessageService,
protected translateService: TranslateService,
protected eventManager: EventManager,
public account: AccountService
) {
super(personalCustomerService, messageService, elementRef, dataUtils, account, eventManager);
this.item = new PersonalCustomer();
}
ngOnChanges(changes: SimpleChanges) {
if (changes['id']) {
if (changes['id'].isFirstChange()) {
this.initialize();
}
if (this.id) {
this.item = new PersonalCustomer();
this.personalCustomerService.find(this.id).subscribe(result => {
this.item = result.body;
this.prepareView();
});
}
}
if (changes['item']) {
if (changes['item'].isFirstChange()) {
this.initialize();
}
if (this.item) {
this.prepareView();
}
}
if (changes['isSaving'] && this.item.id) {
if (this.isSaving) {
this.save();
}
}
}
initialize() {
this.partyTypeService.loadCacheAll().subscribe((res: IPartyType[]) => (this.partytypes = res || []));
this.postalAddressService.loadCacheAll().subscribe((res: IPostalAddress[]) => (this.postaladdresses = res || []));
this.religionTypeService.loadCacheAll().subscribe((res: IReligionType[]) => (this.religiontypes = res || []));
this.workTypeService.loadCacheAll().subscribe((res: IWorkType[]) => (this.worktypes = res || []));
this.roleCustomerService.loadCacheAll().subscribe((res: IRoleCustomer[]) => (this.rolecustomers = res || []));
}
prepareView() {}
get personalCustomer() {
return this.item;
}
set personalCustomer(personalCustomer: IPersonalCustomer) {
this.item = personalCustomer;
}
trackPartyTypeById(index: number, item: IPartyType) {
return item.id;
}
trackPostalAddressById(index: number, item: IPostalAddress) {
return item.id;
}
trackReligionTypeById(index: number, item: IReligionType) {
return item.id;
}
trackWorkTypeById(index: number, item: IWorkType) {
return item.id;
}
trackRoleCustomerById(index: number, item: IRoleCustomer) {
return item.id;
}
itemKey() {
return this.item.id;
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="demo">
<div v-for="(item,index) in list" :key='item.id'>
{{ item.id }} - {{ item.content }}
</div>
<hr>
<!-- ไธๅธธ่ง็จๆณ -->
<div v-for="(item, index) in userInfo" :key="index">
{{ index }} -- {{ item }}
</div>
<hr>
<div v-for="(item, index) in 7" :key="item">
{{ index }} -- {{ item }}
</div>
</div>
</div>
<script>
new Vue({
el:'#demo',
data: {
list:[
{
id:1,
content:'ๆจๅน'
},
{
id:2,
content:'ๅไบฆ่ฒ'
},
{
id:3,
content:'้ซๅๅ'
},
],
userInfo: {
username: '่ดพ็ฒ',
age: 18
}
}
})
</script>
</body>
</html>
|
import { useState } from 'react';
import { useForm } from '../hooks/useForm';
import { useRestaurants } from '../hooks/restaurants';
import styles from './RestaurantForm.css';
export default function RestaurantForm({
label = 'Edit Restaurant',
restaurant,
onSubmit,
onCopy
}) {
const { addNewRestaurant } = useRestaurants();
const { formState, handleFormChange, formError, setFormError } = useForm({
name: restaurant ? restaurant.name : '',
location: restaurant ? restaurant.location : '',
notes: restaurant ? restaurant.notes : '',
price: restaurant ? restaurant.price : '',
rating: restaurant ? restaurant.rating : '',
type: restaurant ? restaurant.type : '',
});
async function handleSubmit(event) {
event.preventDefault();
if (!formState.name) return setFormError('Name is required');
if (!formState.location) return setFormError('Location is required');
if (!formState.notes) return setFormError('Notes are required');
if (!formState.price) return setFormError('Price is required');
if (!formState.rating) return setFormError('Rating is required');
if (!formState.type) return setFormError('Type is required');
addNewRestaurant(formState);
}
async function handleUpdate(event) {
event.preventDefault();
if (!formState.name) return setFormError('Name is required');
if (!formState.location) return setFormError('Location is required');
if (!formState.notes) return setFormError('Notes are required');
if (!formState.price) return setFormError('Price is required');
if (!formState.rating) return setFormError('Rating is required');
if (!formState.type) return setFormError('Type is required');
onSubmit(formState);
}
async function handleCopy(event) {
event.preventDefault();
if (!formState.name) return setFormError('Name is required');
if (!formState.location) return setFormError('Location is required');
if (!formState.notes) return setFormError('Notes are required');
if (!formState.price) return setFormError('Price is required');
if (!formState.rating) return setFormError('Rating is required');
if (!formState.type) return setFormError('Type is required');
onCopy(formState);
}
return (
<section className={styles.section}>
<form className={styles.form} onSubmit={onSubmit ? handleUpdate : handleSubmit}>
<legend>{label}</legend>
<input
id="name"
name="name"
type="text"
placeholder="Name"
value={formState.name}
onChange={handleFormChange}
/>
<input
id="location"
name="location"
type="text"
placeholder="Location"
value={formState.location}
onChange={handleFormChange}
/>
<input
id="notes"
name="notes"
type="text"
placeholder="Notes"
value={formState.notes}
onChange={handleFormChange}
/>
<input
id="price"
name="price"
type="text"
placeholder="$$$$$"
value={formState.price}
onChange={handleFormChange}
/>
<input
id="rating"
name="rating"
type="number"
placeholder="Rating (out of 5)"
value={formState.rating}
onChange={handleFormChange}
/>
<input
id="type"
name="type"
type="text"
placeholder="Type"
value={formState.type}
onChange={handleFormChange}
/>
<button>Save</button>
</form>
</section>
);
}
|
'use strict'
/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
/** @type {import('@adonisjs/framework/src/Hash')} */
const Model = use('Model')
const Hash = use('Hash')
class User extends Model {
static boot () {
super.boot()
this.addHook('beforeSave', async (userInstance) => {
if (userInstance.dirty.password) {
userInstance.password = await Hash.make(userInstance.password)
}
})
}
/**
* @method tokens
*
* @return {Object}
*/
tokens () {
return this.hasMany('App/Models/Token')
}
client () {
return this.hasOne('App/Models/Client')
}
typeUser () {
return this.belongsTo('App/Models/TypeUser')
}
}
module.exports = User
|
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX LIB
#include "ob_lob_base.h"
#include "lib/utility/serialization.h"
namespace oceanbase {
namespace common {
int ObILobCursor::check_and_get(int64_t offset, int64_t len, const char *&ptr, int64_t &avail_len) const
{
INIT_SUCC(ret);
int64_t total_len = get_length();
if (offset >= total_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("offset overflow", K(ret), K(len), K(offset), K(total_len));
} else if ((avail_len = std::min(total_len - offset, len)) <= 0) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len is zero", K(ret), K(len), K(offset), K(total_len), K(avail_len));
} else if (OB_FAIL(get_ptr(offset, avail_len, ptr))) {
LOG_WARN("get_ptr fail", K(ret), K(avail_len), K(len), K(offset), K(total_len), KP(ptr));
} else if (OB_ISNULL(ptr)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("ptr is null", K(ret), K(avail_len), K(len), K(offset), K(total_len), KP(ptr));
}
return ret;
}
int ObILobCursor::read_bool(int64_t offset, bool *val) const
{
INIT_SUCC(ret);
static const int64_t max_bool_len = sizeof(bool);
int64_t avail_len = 0;
const char* ptr = nullptr;
if (OB_FAIL(check_and_get(offset, max_bool_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_bool_len), K(avail_len));
} else if (avail_len < max_bool_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len not enough", K(ret), K(avail_len), K(offset), K(max_bool_len));
} else {
*val = *reinterpret_cast<const bool*>(ptr);
}
return ret;
}
int ObILobCursor::read_i8(int64_t offset, int8_t *val) const
{
INIT_SUCC(ret);
static const int64_t max_i8_len = sizeof(int8_t);
int64_t avail_len = 0;
const char* ptr = nullptr;
if (OB_FAIL(check_and_get(offset, max_i8_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_i8_len), K(avail_len));
} else if (avail_len < max_i8_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len not enough", K(ret), K(avail_len), K(offset), K(max_i8_len));
} else {
*val = *reinterpret_cast<const int8_t*>(ptr);
}
return ret;
}
int ObILobCursor::read_i16(int64_t offset, int16_t *val) const
{
INIT_SUCC(ret);
static const int64_t max_i16_len = sizeof(int16_t);
int64_t avail_len = 0;
const char* ptr = nullptr;
if (OB_FAIL(check_and_get(offset, max_i16_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_i16_len), K(avail_len));
} else if (avail_len < max_i16_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len not enough", K(ret), K(avail_len), K(offset), K(max_i16_len));
} else {
*val = *reinterpret_cast<const int16_t*>(ptr);
}
return ret;
}
int ObILobCursor::read_i32(int64_t offset, int32_t *val) const
{
INIT_SUCC(ret);
static const int64_t max_i32_len = sizeof(int32_t);
int64_t avail_len = 0;
const char* ptr = nullptr;
if (OB_FAIL(check_and_get(offset, max_i32_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_i32_len), K(avail_len));
} else if (avail_len < max_i32_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len not enough", K(ret), K(avail_len), K(offset), K(max_i32_len));
} else {
*val = *reinterpret_cast<const int32_t*>(ptr);
}
return ret;
}
int ObILobCursor::read_i64(int64_t offset, int64_t *val) const
{
INIT_SUCC(ret);
static const int64_t max_i64_len = sizeof(int64_t);
int64_t avail_len = 0;
const char* ptr = nullptr;
if (OB_FAIL(check_and_get(offset, max_i64_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_i64_len), K(avail_len));
} else if (avail_len < max_i64_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len not enough", K(ret), K(avail_len), K(offset), K(max_i64_len));
} else {
*val = *reinterpret_cast<const int64_t*>(ptr);
}
return ret;
}
int ObILobCursor::read_float(int64_t offset, float *val) const
{
INIT_SUCC(ret);
static const int64_t max_float_len = sizeof(float);
int64_t avail_len = 0;
const char* ptr = nullptr;
if (OB_FAIL(check_and_get(offset, max_float_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_float_len), K(avail_len));
} else if (avail_len < max_float_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len not enough", K(ret), K(avail_len), K(offset), K(max_float_len));
} else {
*val = *reinterpret_cast<const float*>(ptr);
}
return ret;
}
int ObILobCursor::read_double(int64_t offset, double *val) const
{
INIT_SUCC(ret);
static const int64_t max_double_len = sizeof(double);
int64_t avail_len = 0;
const char* ptr = nullptr;
if (OB_FAIL(check_and_get(offset, max_double_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_double_len), K(avail_len));
} else if (avail_len < max_double_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len not enough", K(ret), K(avail_len), K(offset), K(max_double_len));
} else {
*val = *reinterpret_cast<const double*>(ptr);
}
return ret;
}
int ObILobCursor::decode_i16(int64_t &offset, int16_t *val) const
{
INIT_SUCC(ret);
static const int64_t max_i16_len = sizeof(int16_t);
int64_t avail_len = 0;
const char* ptr = nullptr;
int64_t pos = 0;
if (OB_FAIL(check_and_get(offset, max_i16_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_i16_len), K(avail_len));
} else if (OB_FAIL(serialization::decode_i16(ptr, avail_len, pos, val))) {
LOG_WARN("decode_i16 fail", K(ret), K(avail_len), K(max_i16_len), K(offset), K(pos), KP(ptr));
} else {
offset += pos;
}
return ret;
}
int ObILobCursor::decode_vi64(int64_t &offset, int64_t *val) const
{
INIT_SUCC(ret);
static const int64_t max_vi64_len = serialization::encoded_length_vi64(UINT64_MAX);
int64_t avail_len = 0;
const char* ptr = nullptr;
int64_t pos = 0;
if (OB_FAIL(check_and_get(offset, max_vi64_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_vi64_len), K(avail_len));
} else if (OB_FAIL(serialization::decode_vi64(ptr, avail_len, pos, val))) {
LOG_WARN("decode_i16 fail", K(ret), K(avail_len), K(max_vi64_len), K(offset), K(pos), KP(ptr));
} else {
offset += pos;
}
return ret;
}
int ObILobCursor::deserialize(int64_t &offset, number::ObNumber *number) const
{
INIT_SUCC(ret);
static const int64_t max_ob_number_len = sizeof(uint32_t) + sizeof(uint32_t) * number::ObNumber::MAX_CALC_LEN;
int64_t avail_len = 0;
const char* ptr = nullptr;
int64_t pos = 0;
if (OB_FAIL(check_and_get(offset, max_ob_number_len, ptr, avail_len))) {
LOG_WARN("check_and_get fail", K(ret), K(offset), K(max_ob_number_len), K(avail_len));
} else if (OB_FAIL(number->deserialize(ptr, avail_len, pos))) {
LOG_WARN("decode_i16 fail", K(ret), K(avail_len), K(max_ob_number_len), K(offset), K(pos), KP(ptr));
} else {
offset += pos;
}
return ret;
}
int ObILobCursor::get_for_write(int64_t offset, int64_t len, ObString &data)
{
INIT_SUCC(ret);
int64_t total_len = get_length();
int64_t avail_len = 0;
char* ptr = nullptr;
if (offset >= total_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("offset overflow", K(ret), K(len), K(offset), K(total_len));
} else if ((avail_len = std::min(total_len - offset, len)) < len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len is zero", K(ret), K(len), K(offset), K(total_len), K(avail_len));
} else if (OB_FAIL(get_ptr_for_write(offset, avail_len, ptr))) {
LOG_WARN("get ptr fail", K(ret), K(avail_len), K(len), K(offset), K(total_len), KP(ptr));
} else {
data.assign_ptr(ptr, avail_len);
}
return ret;
}
int ObILobCursor::write_i8(int64_t offset, int8_t val)
{
INIT_SUCC(ret);
static const int64_t max_i8_len = sizeof(int8_t);
int64_t total_len = get_length();
int64_t avail_len = 0;
char* ptr = nullptr;
if (offset >= total_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("offset overflow", K(ret), K(max_i8_len), K(offset), K(total_len));
} else if ((avail_len = std::min(total_len - offset, max_i8_len)) < max_i8_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len is not enough", K(ret), K(max_i8_len), K(offset), K(total_len), K(avail_len));
} else if (OB_FAIL(get_ptr_for_write(offset, avail_len, ptr))) {
LOG_WARN("ptr is null", K(ret), K(avail_len), K(max_i8_len), K(offset), K(total_len), KP(ptr));
} else {
int8_t *val_pos = reinterpret_cast<int8_t*>(ptr);
*val_pos = static_cast<int8_t>(val);
}
return ret;
}
int ObILobCursor::write_i16(int64_t offset, int16_t val)
{
INIT_SUCC(ret);
static const int64_t max_i16_len = sizeof(int16_t);
int64_t total_len = get_length();
int64_t avail_len = 0;
char* ptr = nullptr;
if (offset >= total_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("offset overflow", K(ret), K(max_i16_len), K(offset), K(total_len));
} else if ((avail_len = std::min(total_len - offset, max_i16_len)) < max_i16_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len is not enough", K(ret), K(max_i16_len), K(offset), K(total_len), K(avail_len));
} else if (OB_FAIL(get_ptr_for_write(offset, avail_len, ptr))) {
LOG_WARN("get ptr fail", K(ret), K(avail_len), K(max_i16_len), K(offset), K(total_len), KP(ptr));
} else {
int16_t *val_pos = reinterpret_cast<int16_t*>(ptr);
*val_pos = static_cast<int16_t>(val);
}
return ret;
}
int ObILobCursor::write_i32(int64_t offset, int32_t val)
{
INIT_SUCC(ret);
static const int64_t max_i32_len = sizeof(int32_t);
int64_t total_len = get_length();
int64_t avail_len = 0;
char* ptr = nullptr;
if (offset >= total_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("offset overflow", K(ret), K(max_i32_len), K(offset), K(total_len));
} else if ((avail_len = std::min(total_len - offset, max_i32_len)) < max_i32_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len is not enough", K(ret), K(max_i32_len), K(offset), K(total_len), K(avail_len));
} else if (OB_FAIL(get_ptr_for_write(offset, avail_len, ptr))) {
LOG_WARN("get ptr fail", K(ret), K(avail_len), K(max_i32_len), K(offset), K(total_len), KP(ptr));
} else {
int32_t *val_pos = reinterpret_cast<int32_t*>(ptr);
*val_pos = static_cast<int32_t>(val);
}
return ret;
}
int ObILobCursor::write_i64(int64_t offset, int64_t val)
{
INIT_SUCC(ret);
static const int64_t max_i64_len = sizeof(int64_t);
int64_t total_len = get_length();
int64_t avail_len = 0;
char* ptr = nullptr;
if (offset >= total_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("offset overflow", K(ret), K(max_i64_len), K(offset), K(total_len));
} else if ((avail_len = std::min(total_len - offset, max_i64_len)) < max_i64_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("avail_len is not enough", K(ret), K(max_i64_len), K(offset), K(total_len), K(avail_len));
} else if (OB_FAIL(get_ptr_for_write(offset, avail_len, ptr))) {
LOG_WARN("get ptr fail", K(ret), K(avail_len), K(max_i64_len), K(offset), K(total_len), KP(ptr));
} else {
int64_t *val_pos = reinterpret_cast<int64_t*>(ptr);
*val_pos = static_cast<int64_t>(val);
}
return ret;
}
int ObILobCursor::move_data(int64_t dst_offset, int64_t src_offset, int64_t move_len)
{
INIT_SUCC(ret);
int64_t total_len = get_length();
char* src_ptr = nullptr;
if (move_len == 0) { // skip
} else if (dst_offset >= total_len || src_offset >= total_len || dst_offset + move_len > total_len || src_offset + move_len > total_len) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("offset overflow", K(ret), K(dst_offset), K(src_offset), K(move_len), K(total_len));
} else if (OB_FAIL(get_ptr_for_write(src_offset, move_len, src_ptr))) {
LOG_WARN("get src ptr fail", K(ret), K(src_offset), K(move_len), K(total_len));
} else if (OB_FAIL(set(dst_offset, src_ptr, move_len, true))) {
LOG_WARN("set src_data fail", K(ret), K(dst_offset), K(src_offset), K(move_len), K(total_len), KP(src_ptr));
}
return ret;
}
int ObLobInRowUpdateCursor::init(const ObILobCursor *cursor)
{
INIT_SUCC(ret);
ObString data;
if (OB_ISNULL(cursor)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("cursor is null", K(ret));
} else if (OB_FAIL(cursor->get_data(data))) {
LOG_WARN("get_data fail", K(ret), KPC(cursor));
} else if (OB_FAIL(data_.append(data))) {
LOG_WARN("append fail", K(ret), KPC(cursor), K(data));
}
return ret;
}
int ObLobInRowUpdateCursor::set(int64_t offset, const char *buf, int64_t buf_len, bool use_memmove)
{
INIT_SUCC(ret);
int64_t append_len = offset + buf_len - data_.length();
if (OB_FAIL(data_.reserve(append_len))) {
LOG_WARN("reserve fail", K(ret), K(offset), K(buf_len), K(append_len), K(data_));
} else if (append_len > 0 && OB_FAIL(data_.set_length(data_.length() + append_len))) {
LOG_WARN("set_length fail", K(ret), K(offset), K(buf_len), K(append_len), K(data_));
} else {
if (use_memmove) {
MEMMOVE(data_.ptr() + offset, buf, buf_len);
} else {
MEMCPY(data_.ptr() + offset, buf, buf_len);
}
}
return ret;
}
} // common
} // oceanbase
|
import "../App.css";
import { Ref, forwardRef, useState } from "react";
import { MapLayerMouseEvent, MapRef, Map as MapWrapper, MarkerDragEvent } from "react-map-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import { IMarker, IViewState } from "../types";
import MapMarker from "./MapMarker";
const ACCESS_TOKEN = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;
interface Props {
markers: IMarker[] | undefined;
addMarker: (e: MapLayerMouseEvent) => void;
deleteMarker: (id: string, event: React.MouseEvent) => void;
onMarkerDragEnd: (e: MarkerDragEvent, questId: string) => void;
}
const Map = forwardRef(({ markers, addMarker, deleteMarker, onMarkerDragEnd }: Props, ref: Ref<MapRef>) => {
const [viewState, setViewState] = useState<Partial<IViewState>>({
longitude: 24.031111,
latitude: 49.842957,
zoom: 14,
});
return (
<div className="map">
<MapWrapper
ref={ref}
mapboxAccessToken={ACCESS_TOKEN}
{...viewState}
onMove={(evt) => setViewState(evt.viewState)}
style={{ width: "100%", height: "100%" }}
mapStyle="mapbox://styles/mapbox/streets-v9"
onClick={addMarker}
>
{markers?.map((marker) => (
<MapMarker key={marker.id} marker={marker} deleteMarker={deleteMarker} onMarkerDragEnd={onMarkerDragEnd} />
))}
</MapWrapper>
</div>
);
});
export default Map;
|
// Copyright (C) Ubiquitous AS. All rights reserved
// Licensed under the Apache License, Version 2.0.
using static Eventuous.CommandServiceDelegates;
namespace Eventuous;
public abstract partial class CommandService<TAggregate, TState, TId> {
/// <summary>
/// Register a handler for a command, which is expected to create a new aggregate instance.
/// </summary>
/// <param name="getId">A function to get the aggregate id from the command</param>
/// <param name="action">Action to be performed on the aggregate, given the aggregate instance and the command</param>
/// <param name="resolveStore">Resolve aggregate store from the command</param>
/// <typeparam name="TCommand">Command type</typeparam>
[Obsolete("Use On<TCommand>().InState(ExpectedState.New).GetId(...).Act(...).ResolveStore(...) instead")]
protected void OnNew<TCommand>(
GetIdFromCommand<TId, TCommand> getId,
ActOnAggregate<TAggregate, TCommand> action,
ResolveStore<TCommand>? resolveStore = null
) where TCommand : class
=> On<TCommand>().InState(ExpectedState.New).GetId(getId).Act(action).ResolveStore(resolveStore);
/// <summary>
/// Register a handler for a command, which is expected to use an existing aggregate instance.
/// </summary>
/// <param name="getId">A function to get the aggregate id from the command</param>
/// <param name="action">Action to be performed on the aggregate, given the aggregate instance and the command</param>
/// <param name="resolveStore">Resolve aggregate store from the command</param>
/// <typeparam name="TCommand">Command type</typeparam>
[Obsolete("Use On<TCommand>().InState(ExpectedState.Existing).GetId(...).Act(...).ResolveStore(...) instead")]
protected void OnExisting<TCommand>(
GetIdFromCommand<TId, TCommand> getId,
ActOnAggregate<TAggregate, TCommand> action,
ResolveStore<TCommand>? resolveStore = null
) where TCommand : class
=> On<TCommand>().InState(ExpectedState.Existing).GetId(getId).Act(action).ResolveStore(resolveStore);
/// <summary>
/// Register a handler for a command, which is expected to use an a new or an existing aggregate instance.
/// </summary>
/// <param name="getId">A function to get the aggregate id from the command</param>
/// <param name="action">Action to be performed on the aggregate, given the aggregate instance and the command</param>
/// <param name="resolveStore">Resolve aggregate store from the command</param>
/// <typeparam name="TCommand">Command type</typeparam>
[Obsolete("Use On<TCommand>().InState(ExpectedState.Any).GetId(...).Act(...).ResolveStore(...) instead")]
protected void OnAny<TCommand>(
GetIdFromCommand<TId, TCommand> getId,
ActOnAggregate<TAggregate, TCommand> action,
ResolveStore<TCommand>? resolveStore = null
) where TCommand : class
=> On<TCommand>().InState(ExpectedState.Any).GetId(getId).Act(action).ResolveStore(resolveStore);
}
|
import React from "react";
import ReactDOM from "react-dom/client";
//BrowserRouter need to wrap the whole App so that can use Routes and Route
import { BrowserRouter } from "react-router-dom";
import "./index.scss";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { UserProvider } from "./contexts/user.context";
import { CategoriesProvider } from "./contexts/categories.context";
import { CartProvider } from "./contexts/cart.context";
const root = ReactDOM.createRoot(document.getElementById("root"));
const basename = process.env.PUBLIC_URL;
//inside UserProvider can be access context
//ProductsProvider can reach up the UserProvider
root.render(
<React.StrictMode>
<BrowserRouter basename={basename}>
<UserProvider>
<CategoriesProvider>
<CartProvider>
<App />
</CartProvider>
</CategoriesProvider>
</UserProvider>
</BrowserRouter>
</React.StrictMode>
);
reportWebVitals();
|
package org.variantsync.diffdetective.mining.postprocessing;
import org.variantsync.diffdetective.metadata.ExplainedFilterSummary;
import org.variantsync.diffdetective.variation.Label;
import org.variantsync.diffdetective.variation.diff.VariationDiff;
import org.variantsync.diffdetective.variation.diff.filter.VariationDiffFilter;
import org.variantsync.diffdetective.variation.diff.filter.ExplainedFilter;
import org.variantsync.diffdetective.variation.diff.filter.TaggedPredicate;
import org.variantsync.diffdetective.variation.diff.transform.CutNonEditedSubtrees;
import org.variantsync.diffdetective.variation.diff.transform.VariationDiffTransformer;
import java.util.List;
import java.util.Map;
/**
* Generic Postprocessor for mined patterns.
* Patterns are represented as VariationDiffs and might be filtered or transformed.
*/
public class Postprocessor<L extends Label> {
private final List<VariationDiffTransformer<L>> transformers;
private final ExplainedFilter<VariationDiff<L>> filters;
/**
* Result type for prostprocessing.
* It contains the actual result, the list of processed trees, as well as metadata.
* The filterCounts document which filter caused how many variation diffs to be filtered out.
* Notice, that filters were ordered and when a filter was applied, subsequent filters were not tested.
* Thus, each filter operated on the unfiltered trees of the previous filter.
*/
public record Result<L extends Label>(List<VariationDiff<L>> processedTrees, Map<String, Integer> filterCounts) {}
private Postprocessor(
final List<VariationDiffTransformer<L>> transformers,
final List<TaggedPredicate<String, ? super VariationDiff<L>>> namedFilters) {
this.transformers = transformers;
this.filters = new ExplainedFilter<VariationDiff<L>>(namedFilters.stream());
}
/**
* Creates the default filter to distill semantic patterns from frequent subgraphs.
* This processor will
* - filter ill-formed trees
* - filter trees with less than two edit classes
* - filter duplicates w.r.t. isomorphism
* - {@link CutNonEditedSubtrees}
* @return the default postprocessor.
*/
public static <L extends Label> Postprocessor<L> Default() {
return new Postprocessor<>(
List.of(new CutNonEditedSubtrees<>()),
List.of(
// Filter ill-formed patterns
VariationDiffFilter.consistent(),
VariationDiffFilter.moreThanOneArtifactNode(),
VariationDiffFilter.hasAtLeastOneEditToVariability()
)
);
}
/**
* Performs the postprocessing described by this Postprocessor object on the list of subgraphs.
* To that end, all filters and transformers will be applied.
* @param frequentSubgraphs A list of subgraphs to which to apply the postprocessing.
* @return The processed variation diffs as well as some metadata.
*/
public Result<L> postprocess(final List<VariationDiff<L>> frequentSubgraphs) {
final List<VariationDiff<L>> processedTrees = frequentSubgraphs.stream()
.filter(filters)
.peek(tree -> VariationDiffTransformer.apply(transformers, tree))
.toList();
final Map<String, Integer> filterCounts = new ExplainedFilterSummary(filters).snapshot();
return new Result<>(processedTrees, filterCounts);
}
}
|
import { Transition } from '@headlessui/react';
import { Fragment, MutableRefObject, useRef } from 'react';
import { useOnClickOutside } from 'usehooks-ts';
interface ModalProps {
open: boolean;
title: string;
description: string;
btnCancel: {
name: string;
class: string;
onClick: () => void;
};
btnOK: {
name: string;
class: string;
onClick: () => void;
};
}
const Modal = ({ open, title, description, btnCancel, btnOK }: ModalProps) => {
const banModalRef = useRef(null);
useOnClickOutside(banModalRef, btnCancel.onClick);
return (
<div className={`modal ${open && 'modal-open'}`}>
<Transition
show={open}
enter="transition transform duration-300"
enterFrom="scale-0"
enterTo="scale-100"
leave="transition transform duration-300"
leaveFrom="scale-100"
leaveTo="scale-0"
>
<div
className="modal-box font-semibold text-center text-gray-500"
ref={banModalRef}
>
<p className="font-bold text-xl text-black mt-3 mb-1">{title}</p>
<p>{description}</p>
<p>Are you sure?</p>
<div className="modal-action mt-3">
<button className={btnCancel.class} onClick={btnCancel.onClick}>
{btnCancel.name}
</button>
<button onClick={btnOK.onClick} className={btnOK.class}>
{btnOK.name}
</button>
</div>
</div>
</Transition>
</div>
);
};
export default Modal;
|
import { shallowMount } from '@vue/test-utils';
import TermBox from '@/components/TermBox.vue';
import EditPen from '@/components/EditPen.vue';
import Fingerprint from '@/components/Fingerprint.vue';
import { createStore } from '@/store';
import {
NS_ENTITY,
NS_LINKS,
NS_USER,
} from '@/store/namespaces';
import { EDITABILITY_UPDATE } from '@/store/entity/mutationTypes';
import { EDIT_LINK_URL_UPDATE } from '@/store/links/mutationTypes';
import { LANGUAGE_INIT } from '@/store/user/mutationTypes';
import { mutation } from '@/store/util';
describe( 'TermBox.vue', () => {
it( 'contains a Fingerprint of the user\'s primary language', () => {
const store = createStore();
const userLanguage = 'en';
store.commit( mutation( NS_USER, LANGUAGE_INIT ), userLanguage );
const wrapper = shallowMount( TermBox, { store } );
expect( wrapper.find( Fingerprint ).props() )
.toHaveProperty( 'languageCode', userLanguage );
expect( wrapper.find( Fingerprint ).props() )
.toHaveProperty( 'isPrimary', true );
} );
describe( 'edit pen', () => {
it( 'is there given the entity is editable', () => {
const store = createStore();
const editLinkUrl = '/edit/Q42';
store.commit( mutation( NS_ENTITY, EDITABILITY_UPDATE ), true );
store.commit( mutation( NS_LINKS, EDIT_LINK_URL_UPDATE ), editLinkUrl );
const wrapper = shallowMount( TermBox, { store } );
expect( wrapper.find( EditPen ).props() )
.toHaveProperty( 'href', editLinkUrl );
} );
it( 'is not there given the entity is not editable', () => {
const store = createStore();
store.commit( mutation( NS_ENTITY, EDITABILITY_UPDATE ), false );
const wrapper = shallowMount( TermBox, { store } );
expect( wrapper.find( EditPen ).exists() ).toBeFalsy();
} );
} );
} );
|
package edu.hw4;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static edu.hw4.TasksFrom6To10.*;
import static org.assertj.core.api.Assertions.assertThat;
public class TasksFrom6To10Test {
List<Animal> animals = List.of(
new Animal("Whiskers", Animal.Type.CAT, Animal.Sex.M, 3, 30, 5, true),
new Animal("Buddy", Animal.Type.DOG, Animal.Sex.M, 4, 45, 20, true),
new Animal("Tweetie", Animal.Type.BIRD, Animal.Sex.F, 1, 10, 0, false),
new Animal("Goldie", Animal.Type.FISH, Animal.Sex.F, 2, 5, 0, false),
new Animal("Spinner", Animal.Type.SPIDER, Animal.Sex.M, 1, 2, 0, true),
new Animal("Fluffy", Animal.Type.CAT, Animal.Sex.F, 2, 25, 4, true),
new Animal("Rex", Animal.Type.DOG, Animal.Sex.M, 5, 50, 18, true),
new Animal("Sunny", Animal.Type.BIRD, Animal.Sex.F, 2, 15, 1, false),
new Animal("Nemo", Animal.Type.FISH, Animal.Sex.M, 1, 3, 0, false),
new Animal("Charlotte", Animal.Type.SPIDER, Animal.Sex.M, 1, 1, 0, true)
);
@Test
void task6Test() {
Map<Animal.Type, Animal> result = heaviestByType(animals);
assertThat(result.get(Animal.Type.CAT).name()).isEqualTo("Whiskers");
assertThat(result.get(Animal.Type.DOG).name()).isEqualTo("Buddy");
assertThat(result.get(Animal.Type.BIRD).name()).isEqualTo("Sunny");
assertThat(result.get(Animal.Type.FISH).name()).isEqualTo("Goldie");
assertThat(result.get(Animal.Type.SPIDER).name()).isEqualTo("Spinner");
}
@Test
void task7Test() {
Animal result = kthOldest(animals, 3);
assertThat(result.name()).isEqualTo("Whiskers");
}
@Test
void task8Test() {
Optional<Animal> result = heaviestBelowKHeight(animals, 40);
assertThat(result.get().name()).isEqualTo("Whiskers");
}
@Test
void task9Test() {
Integer result = totalPaws(animals);
assertThat(result).isEqualTo(36);
}
@Test
void task10Test() {
List<Animal> result = ageNotMatchingPaws(animals);
assertThat(result.size()).isEqualTo(8);
assertThat(result.get(0).name()).isEqualTo("Whiskers");
assertThat(result.get(1).name()).isEqualTo("Tweetie");
assertThat(result.get(2).name()).isEqualTo("Goldie");
assertThat(result.get(3).name()).isEqualTo("Spinner");
assertThat(result.get(4).name()).isEqualTo("Fluffy");
assertThat(result.get(5).name()).isEqualTo("Rex");
assertThat(result.get(6).name()).isEqualTo("Nemo");
assertThat(result.get(7).name()).isEqualTo("Charlotte");
}
}
|
/****************************************************************************
**
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Application Manager.
**
** $QT_BEGIN_LICENSE:LGPL-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company. For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
** SPDX-License-Identifier: LGPL-3.0
**
****************************************************************************/
#pragma once
#include <functional>
#include <QAbstractListModel>
#include <QtAppManCommon/global.h>
#if defined(AM_MULTI_PROCESS)
QT_FORWARD_DECLARE_CLASS(QWaylandSurface)
#endif
QT_FORWARD_DECLARE_CLASS(QQuickWindow)
QT_FORWARD_DECLARE_CLASS(QQuickItem)
QT_FORWARD_DECLARE_CLASS(QQmlEngine)
QT_FORWARD_DECLARE_CLASS(QJSEngine)
QT_FORWARD_DECLARE_CLASS(QWindow)
QT_FORWARD_DECLARE_CLASS(QQmlComponent)
QT_FORWARD_DECLARE_CLASS(QLocalServer)
QT_BEGIN_NAMESPACE_AM
class InProcessSurfaceItem;
class Window;
class WindowSurface;
class WindowManagerPrivate;
class Application;
class AbstractRuntime;
class WaylandCompositor;
class WindowManager : public QAbstractListModel
{
Q_OBJECT
Q_CLASSINFO("D-Bus Interface", "io.qt.WindowManager")
Q_CLASSINFO("AM-QmlType", "QtApplicationManager.SystemUI/WindowManager 2.0 SINGLETON")
Q_PROPERTY(int count READ count NOTIFY countChanged)
Q_PROPERTY(bool runningOnDesktop READ isRunningOnDesktop CONSTANT)
Q_PROPERTY(bool slowAnimations READ slowAnimations WRITE setSlowAnimations NOTIFY slowAnimationsChanged)
public:
~WindowManager() override;
static WindowManager *createInstance(QQmlEngine *qmlEngine, const QString &waylandSocketName = QString());
static WindowManager *instance();
static QObject *instanceForQml(QQmlEngine *qmlEngine, QJSEngine *);
void shutDown();
bool isRunningOnDesktop() const;
bool slowAnimations() const;
void setSlowAnimations(bool slowAnimations);
void enableWatchdog(bool enable);
bool addWaylandSocket(QLocalServer *waylandSocket);
// the item model part
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
QHash<int, QByteArray> roleNames() const override;
Q_INVOKABLE int count() const;
Q_INVOKABLE QVariantMap get(int index) const;
Q_INVOKABLE Window *window(int index) const;
Q_INVOKABLE QList<QObject *> windowsOfApplication(const QString &id) const;
Q_INVOKABLE int indexOfWindow(Window *window) const;
Q_INVOKABLE QObject *addExtension(QQmlComponent *component) const;
bool eventFilter(QObject *watched, QEvent *event) override;
signals:
void countChanged();
void raiseApplicationWindow(const QString &applicationId, const QString &applicationAliasId);
void windowAdded(Window *window);
void windowAboutToBeRemoved(Window *window);
void windowContentStateChanged(Window *window);
void windowPropertyChanged(Window *window, const QString &name, const QVariant &value);
void compositorViewRegistered(QQuickWindow *view);
void shutDownFinished();
void slowAnimationsChanged(bool);
void _inProcessSurfaceItemReleased(QSharedPointer<InProcessSurfaceItem>);
private slots:
void inProcessSurfaceItemCreated(QSharedPointer<InProcessSurfaceItem> surfaceItem);
void setupWindow(QT_PREPEND_NAMESPACE_AM(Window) *window);
public:
Q_SCRIPTABLE bool makeScreenshot(const QString &filename, const QString &selector);
QList<QQuickWindow *> compositorViews() const;
// evil hook to support in-process runtimes
void setupInProcessRuntime(QT_PREPEND_NAMESPACE_AM(AbstractRuntime) *runtime);
#if defined(AM_MULTI_PROCESS)
private slots:
void waylandSurfaceCreated(QWaylandSurface *surface);
void waylandSurfaceMapped(QT_PREPEND_NAMESPACE_AM(WindowSurface) *surface);
private:
void handleWaylandSurfaceDestroyedOrUnmapped(QWaylandSurface *surface);
#endif
private:
void registerCompositorView(QQuickWindow *view);
void addWindow(Window *window);
void removeWindow(Window *window);
void releaseWindow(Window *window);
void updateViewSlowMode(QQuickWindow *view);
WindowManager(QQmlEngine *qmlEngine, const QString &waylandSocketName);
WindowManager(const WindowManager &);
WindowManager &operator=(const WindowManager &);
static WindowManager *s_instance;
WindowManagerPrivate *d;
friend class WaylandCompositor;
};
QT_END_NAMESPACE_AM
|
import {Component, OnInit} from "@angular/core";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ToastrService} from "ngx-toastr";
import {AdminService} from "../service";
import {HttpParams} from "@angular/common/http";
import {Router} from "@angular/router";
@Component({
templateUrl: "./html/admin.login.page.html"
})
export class AdminLoginComp implements OnInit {
frmGroup!: FormGroup;
loading: boolean = false;
constructor(private _formBuilder: FormBuilder, private _toast: ToastrService,
private _adminService: AdminService, private _router: Router) {
}
ngOnInit(): void {
this.frmGroup = this._formBuilder.group({
username: ["", [Validators.required]],
password: ["", [Validators.required]]
});
}
loginEvent() {
this.loading = true;
const param = new HttpParams()
.append("username", `${this.frmGroup.controls["username"].value}`)
.append("password", `${this.frmGroup.controls["password"].value}`);
this._adminService.login(param).subscribe(res => {
this.loading = false;
this._toast.success(res.message, res.title);
sessionStorage.setItem("healthify.admin.userid", res.userid);
sessionStorage.setItem("healthify.admin.fullname", res.fullname);
sessionStorage.setItem("healthify.admin.emailaddress", res.emailaddress);
this._router.navigate(['/admin', 'panel', 'view-user']);
},
err => {
this.loading = false;
this._toast.error(err.error.message, err.error.title);
},
() => this.loading = false);
}
}
|
import { Request, Response, NextFunction } from 'express';
import statusCode from '../enum/httpStatus';
import questionSchema from '../validations/questionSchema';
import answerSchema from '../validations/answerSchema';
import QuestionError from '../errors/QuestionError';
import QuestionDTO from '../protocols/QuestionDTO';
import * as questionService from '../services/questionService';
import AnswerDTO from '../protocols/AnswerDTO';
export async function postQuestion(
req: Request,
res: Response,
next: NextFunction,
): Promise<Response> {
try {
const joiValidation = questionSchema.validate(req.body);
if (joiValidation.error) {
throw new QuestionError(joiValidation.error.message);
}
const newQuestion: QuestionDTO = req.body;
if (
!newQuestion.class.trim() ||
!newQuestion.question.trim() ||
!newQuestion.student.trim() ||
!newQuestion.tags.trim()
) {
throw new QuestionError('Please fill all the fields correctly.');
}
const createdQuestion = await questionService.createQuestion(newQuestion);
return res.send({ id: createdQuestion.id }).status(statusCode.CREATED);
} catch (err) {
if (err instanceof QuestionError) {
return res.status(err.statusCode).send(err.message);
}
next(err);
}
}
export async function postAnswer(
req: Request,
res: Response,
next: NextFunction,
): Promise<Response> {
try {
const joiValidation = answerSchema.validate(req.body);
if (joiValidation.error) {
throw new QuestionError(joiValidation.error.message);
}
const { id } = req.params;
const answer: AnswerDTO = {
questionId: Number(id),
answeredBy: req.body.userName,
answer: req.body.answer,
};
const answeredQuestion = await questionService.createAnswer(answer);
return res.status(statusCode.OK).send(answeredQuestion);
} catch (err) {
if (err instanceof QuestionError) {
return res.status(err.statusCode).send(err.message);
}
next(err);
}
}
export async function getQuestion(
req: Request,
res: Response,
next: NextFunction,
): Promise<Response> {
try {
const { id } = req.params;
const question = await questionService.getQuestion(Number(id));
delete question.id;
return res.status(statusCode.OK).send(question);
} catch (err) {
if (err instanceof QuestionError) {
return res.status(err.statusCode).send(err.message);
}
next(err);
}
}
export async function getUnansweredQuestions(
req: Request,
res: Response,
next: NextFunction,
): Promise<Response> {
try {
const questions = await questionService.getUnansweredQuestions();
return res.status(statusCode.OK).send(questions);
} catch (err) {
if (err instanceof QuestionError) {
return res.status(err.statusCode).send(err.message);
}
next(err);
}
}
|
// Simulate genetic inheritance of blood type
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Each person has two parents and two alleles
typedef struct person
{
struct person *parents[2];
char alleles[2];
char *mom;
char *dad;
}
person;
int GENERATIONS;
const int INDENT_LENGTH = 4;
person *create_family(int generations, char mom_alleles[2], char dad_alleles[2]);
void print_family(person *p, int generation);
void free_family(person *p);
char random_mom_alleles(char mom_alleles[2]);
char random_dad_alleles(char dad_alleles[2]);
char o_allele(char mom_alleles[2], char dad_alleles[2]);
void sort_alleles(char alleles[2]);
int main(void)
{
// Seed random number generator
srand(time(0));
char mom_alleles[2];
char dad_alleles[2];
// Cria um novo filho
person *child = malloc(sizeof(person));
// Hรก 6 pares de alelos, cada par com 2 alelos
char allele_pairs[6][2] =
{
{'A', 'A'},
{'A', 'B'},
{'A', 'O'},
{'B', 'B'},
{'B', 'O'},
{'O', 'O'}
};
//Verifica se os alelos sรฃo vรกlidos
bool valid_mom_alleles = false;
bool valid_dad_alleles = false;
while(!valid_mom_alleles || !valid_dad_alleles)
{
child->mom = malloc(256); // Alocar memรณria para o nome da mรฃe
printf("\nNome da mรฃe: ");
scanf(" %255s", child->mom);
printf("\nInsira os alelos da mรฃe: ");
scanf(" %c%c", &mom_alleles[0], &mom_alleles[1]);
for(int i = 0; i < 6; i++)
{
if ((mom_alleles[0] == allele_pairs[i][0] && mom_alleles[1] == allele_pairs[i][1]) ||
(mom_alleles[0] == allele_pairs[i][1] && mom_alleles[1] == allele_pairs[i][0]))
{
valid_mom_alleles = true;
printf("\nPar de alelos da mรฃe vรกlido.\n");
break;
}
}
if(!valid_mom_alleles)
{
printf("\nInsira um par de alelos da mรฃe que seja vรกlido. \n");
}
child->dad = malloc(256); // Alocar memรณria para o nome do pai
printf("\nNome do pai: ");
scanf(" %255s", child->dad);
printf("\nInsira os alelos do pai: ");
scanf(" %c%c", &dad_alleles[0], &dad_alleles[1]);
for(int i = 0; i < 6; i++)
{
if ((dad_alleles[0] == allele_pairs[i][0] && dad_alleles[1] == allele_pairs[i][1]) ||
(dad_alleles[0] == allele_pairs[i][1] && dad_alleles[1] == allele_pairs[i][0]))
{
valid_dad_alleles = true;
printf("\nPar de alelos do pai vรกlido.\n");
break;
}
}
if(!valid_dad_alleles)
{
printf("\nInsira um par de alelos do pai que seja vรกlido. \n");
}
}
printf("Quantidade de geraรงรตes a simular: ");
scanf(" %d", &GENERATIONS);
// Create a new family with three generations
person *p = create_family(GENERATIONS, mom_alleles, dad_alleles);
// Print family tree of blood types
print_family(p, 0);
// Free memory
free_family(p);
free(child);
}
// Create a new individual with `generations`
person *create_family(int generations, char mom_alleles[2], char dad_alleles[2])
{
// Allocate memory for new person
person *p = malloc(sizeof(person));
// Generation with parent data
if (generations > 1)
{
// Create blood type histories for parents
p->parents[0] = create_family(generations - 1, mom_alleles, dad_alleles);
p->parents[1] = create_family(generations - 1, mom_alleles, dad_alleles);
// Randomly assign child alleles based on parents
p->alleles[0] = random_mom_alleles(mom_alleles);
p->alleles[1] = random_dad_alleles(dad_alleles);
o_allele(mom_alleles, dad_alleles);
sort_alleles(mom_alleles);
sort_alleles(dad_alleles);
}
// Generation without parent data
else
{
// Set parent pointers to NULL
p->parents[0] = NULL;
p->parents[1] = NULL;
// Randomly assign child alleles based on parents
p->alleles[0] = random_mom_alleles(mom_alleles);
p->alleles[1] = random_dad_alleles(dad_alleles);
sort_alleles(mom_alleles);
sort_alleles(dad_alleles);
}
// Return newly created person
return p;
}
// Free `p` and all ancestors of `p`.
void free_family(person *p)
{
// TODO: Handle base case
if (p->parents[0] == NULL && p->parents[1] == NULL)
{
free(p); // Free the memory of the current person
return; // Return to the previous level of recursion
}
// TODO: Free parents
free_family(p->parents[0]);
free_family(p->parents[1]);
// TODO: Free child
free(p);
}
int LAST_GENERATION = -1;
// Print each family member and their alleles.
void print_family(person *p, int generation)
{
// Handle base case
if (p == NULL)
{
return;
}
// Print indentation
for (int i = 0; i < generation * INDENT_LENGTH; i++)
{
printf(" ");
}
// Print person
printf("Generation %i, blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
print_family(p->parents[0], generation + 1);
print_family(p->parents[1], generation + 1);
}
// Randomly chooses a blood type allele.
char random_mom_alleles(char mom_alleles[2])
{
int random_choice = rand() % 2;
if (random_choice == 0)
{
return mom_alleles[0];
}
else
{
return mom_alleles[1];
}
}
char random_dad_alleles(char dad_alleles[2])
{
int random_choice = rand() % 2;
if (random_choice == 0)
{
return dad_alleles[0];
}
else
{
return dad_alleles[1];
}
}
char o_allele(char mom_alleles[2], char dad_alleles[2])
{
if (mom_alleles[0] == dad_alleles[0] || mom_alleles[1] == dad_alleles[1] ||
mom_alleles[0] == dad_alleles[1] || mom_alleles[1] == dad_alleles[0])
{
int random_choice = rand() % 2;
if (random_choice == 0)
{
int chosen_mom_allele = rand() % 2;
if (chosen_mom_allele == 0)
{
mom_alleles[0] = 'O';
return mom_alleles[0];
}
else if (chosen_mom_allele == 1)
{
mom_alleles[1] = 'O';
return mom_alleles[1];
}
}
else if (random_choice == 1)
{
int chosen_dad_allele = rand() % 2;
if (chosen_dad_allele == 0)
{
dad_alleles[0] = 'O';
return dad_alleles[0];
}
else if (chosen_dad_allele == 1)
{
dad_alleles[1] = 'O';
return dad_alleles[1];
}
}
}
}
void sort_alleles(char alleles[2])
{
int i, j;
char temp;
for(i = 0; i < 1; i++)
{
for(j = 0; j < 1 - i; j++)
{
if(alleles[j] > alleles[j + 1])
{
temp = alleles[j];
alleles[j] = alleles[j + 1];
alleles[j + 1] = temp;
}
}
}
}
|
import Card from "@mui/material/Card";
import CardActions from "@mui/material/CardActions";
import CardContent from "@mui/material/CardContent";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
export default function Popularcard({ data }) {
const {
img,
name,
comprehensiveDescription,
date,
fees,
specializedServicesProvided,
division
} = data;
return (
<div>
<Card
sx={{
display: "flex",
boxShadow: "-2px -2px 8px",
flexDirection: "column",
justifyContent: "space-between",
height: {md:"450px"},
}}
>
<CardContent>
<img src={img} className="w-full h-52" alt="" />
<Typography gutterBottom variant="h5" component="div">
{name}
</Typography>
<Typography variant="body2" color="text.secondary">
{comprehensiveDescription}
</Typography>
<Typography
fontWeight={"700"}
sx={{ py: "10px" }}
variant="body2"
color="text.secondary"
>
{specializedServicesProvided}
</Typography>
<Typography
fontWeight={"700"}
sx={{ py: "10px" }}
variant="body3"
color="text.secondary"
>
{division}
</Typography>
</CardContent>
<CardActions>
<Button sx={{fontWeight:"700"}} color="error" size="small">
Date:{date}
</Button>
<Button sx={{fontWeight:"700"}} color="success" size="small">
fees:{fees}Tk
</Button>
<Button sx={{fontWeight:"700"}} size="small">Learn More</Button>
</CardActions>
</Card>
</div>
);
}
|
import 'package:equatable/equatable.dart';
import '../../utils/strings_manager.dart';
class ServerException extends Equatable implements Exception {
final String? msg;
const ServerException([this.msg]);
@override
List<Object?> get props => [msg];
@override
String toString() => "$msg";
}
class FetchDataException extends ServerException {
const FetchDataException([msg]) : super(ExceptionStrings.errDuringCommunication);
}
class BadRequestException extends ServerException {
const BadRequestException([msg]) : super(ExceptionStrings.badRequest);
}
class UnauthorizedException extends ServerException {
const UnauthorizedException([msg]) : super(ExceptionStrings.unauthorized);
}
class NotFoundException extends ServerException {
const NotFoundException([msg]) : super(ExceptionStrings.requestInfoNotFound);
}
class ConflictException extends ServerException {
const ConflictException([msg]) : super(ExceptionStrings.conflictOccurred);
}
class InternalServerErrorException extends ServerException {
const InternalServerErrorException([msg]) : super(ExceptionStrings.internalServerError);
}
class NoInternetConnectionException extends ServerException {
const NoInternetConnectionException([msg]) : super(ExceptionStrings.noInternetConnection);
}
class CacheException implements Exception {}
|
package com.example.bootcamp.ui.navigation
import android.view.View
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.navigation.NavController
import androidx.navigation.findNavController
import com.example.bootcamp.R
import com.example.bootcamp.base.MainActivity
import com.example.bootcamp.databinding.ActivityMainBinding
class TabManager(
private val mainActivity: MainActivity,
private val mainActivityBinding: ActivityMainBinding
) {
private val startDestinations = mapOf(
R.id.dashboardFragment to R.id.dashboardFragment,
R.id.historyFragment to R.id.historyFragment,
R.id.settingsFragment to R.id.settingsFragment,
R.id.calendarFragment to R.id.calendarFragment,
)
private var currentTabId: Int = R.id.dashboardFragment
var currentController: NavController? = null
var currentContainer: View? = null
private var tabHistory = TabHistory().apply { push(R.id.dashboardFragment) }
val navDashboardController: NavController by lazy {
mainActivity.findNavController(R.id.dashboardTab).apply {
graph = navInflater.inflate(R.navigation.nav_graph).apply {
setStartDestination(R.id.launchFragment)
}
}
}
private val navHistoryController: NavController by lazy {
mainActivity.findNavController(R.id.historyTab).apply {
graph = navInflater.inflate(R.navigation.nav_graph).apply {
setStartDestination(startDestinations.getValue(R.id.historyFragment))
}
}
}
private val navSettingsController: NavController by lazy {
mainActivity.findNavController(R.id.settingsTab).apply {
graph = navInflater.inflate(R.navigation.nav_graph).apply {
setStartDestination(startDestinations.getValue(R.id.settingsFragment))
}
}
}
private val navCalendarController: NavController by lazy {
mainActivity.findNavController(R.id.calendarTab).apply {
graph = navInflater.inflate(R.navigation.nav_graph).apply {
setStartDestination(startDestinations.getValue(R.id.calendarFragment))
}
}
}
private val dashboardsTabContainer: View by lazy { mainActivityBinding.dashboardContainer }
private val historyTabContainer: View by lazy { mainActivityBinding.historyContainer }
private val settingsTabContainer: View by lazy { mainActivityBinding.settingsContainer }
private val calendarTabContainer: View by lazy { mainActivityBinding.calendarContainer }
fun onBackPressed() {
currentController?.let {
if (it.currentDestination == null || it.currentDestination?.id == startDestinations.getValue(
currentTabId
)
) {
if (tabHistory.size > 1) {
val tabId = tabHistory.popPrevious()
switchTab(tabId, false)
mainActivityBinding.bottomBarView.menu.findItem(tabId).isChecked = true
} else {
mainActivity.finish()
}
}
it.popBackStack()
} ?: run {
mainActivity.finish()
}
}
fun switchTab(tabId: Int, addToHistory: Boolean = false) {
currentTabId = tabId
when (tabId) {
R.id.dashboardFragment -> {
currentController = navDashboardController
currentController?.navigate(R.id.dashboardFragment)
invisibleTabContainerExcept(dashboardsTabContainer)
}
R.id.calendarFragment -> {
currentController = navCalendarController
invisibleTabContainerExcept(calendarTabContainer)
}
R.id.historyFragment -> {
currentController = navHistoryController
invisibleTabContainerExcept(historyTabContainer)
}
R.id.settingsFragment -> {
currentController = navSettingsController
invisibleTabContainerExcept(settingsTabContainer)
}
}
if (addToHistory) {
tabHistory.push(tabId)
}
}
fun openSearchPageForAddBooking() {
currentController?.let {
// SearchFragment.navigate(it, SearchFragment.Companion.PageType.ADD_BOOKING)
}
}
private fun invisibleTabContainerExcept(container: View) {
dashboardsTabContainer.isInvisible = true
historyTabContainer.isInvisible = true
settingsTabContainer.isInvisible = true
calendarTabContainer.isInvisible = true
container.isVisible = true
currentContainer = container
}
}
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int getMoneySpent(int[] keyboards, int[] drives, int s){
int index_x, index_y, minDiff = s, diff = 0, price = 0, flag = 1, result = 0;
for(index_x = 0; index_x < keyboards.length; index_x++){
for(index_y = 0; index_y < drives.length; index_y++){
price = keyboards[index_x] + drives[index_y];
diff = s - price;
if(diff >= 0){
if(diff < minDiff){
minDiff = diff;
result = price;
flag = 0;
}
}
}
}
if(flag == 1){
return -1;
}else
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int n = in.nextInt();
int m = in.nextInt();
int[] keyboards = new int[n];
for(int keyboards_i=0; keyboards_i < n; keyboards_i++){
keyboards[keyboards_i] = in.nextInt();
}
int[] drives = new int[m];
for(int drives_i=0; drives_i < m; drives_i++){
drives[drives_i] = in.nextInt();
}
// The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
int moneySpent = getMoneySpent(keyboards, drives, s);
System.out.println(moneySpent);
}
}
|
Feature: Edit LTI Consumers
As user, I want to edit LTI consumers
Scenario: Loading edit LTI consumer page as admin
Given I'm a System Administrator
And I'm on 'manage lti' page
When I click the first consumer's Edit button
Then I should be on the 'edit lti consumer' page
Scenario: Editing a lti consumer as admin
Given I'm a System Administrator
And I'm on 'edit lti consumer' page for consumer with id '1abcABC123-abcABC123_Z'
When I fill form item 'consumer.oauth_consumer_key' in with 'new_consumer_key_1'
And I fill form item 'consumer.oauth_consumer_secret' in with 'new_consumer_secret_1'
And I fill form item 'consumer.global_unique_identifier_param' in with 'new_global_unique_identifier_param'
And I fill form item 'consumer.student_number_param' in with 'new_student_number_param'
And I fill form item 'consumer.custom_param_regex_sanitizer' in with 'new_custom_param_regex_sanitizer'
And I toggle the 'This consumer is actively being used' checkbox
And I submit form with the 'Save' button
Then I should be on the 'manage lti' page
And I should see '3' consumers listed
And I should see consumers with consumer keys:
| oauth_consumer_key |
| new_consumer_key_1 |
| consumer_key_2 |
| consumer_key_3 |
|
import axios from 'axios';
import React, { createContext, useEffect, useState } from 'react';
import toast from 'react-hot-toast';
export const studentContext = createContext({});
const Context = ({ children }) => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [address, setAddress] = useState('');
const [percentage, setPercentage] = useState('');
const [details, setDetails] = useState([]);
const [topClass, setTopClass] = useState(false);
const [studentNames, setStudentNames] = useState([]);
const [selectedStudent, setSelectedStudent] = useState('');
const [selectedStudentDetails, setSelectedStudentDetails] = useState(null);
const [isEditMode, setIsEditMode] = useState(false);
const [editedValues, setEditedValues] = useState({
email: '',
phone: '',
address: '',
percentage: '',
});
const handleSetTopClass = (value) => {
setTopClass(value);
};
const handleShowDetails = async () => {
try {
await axios
.get('https://elite-nwwo.onrender.com/api/studentDetail')
.then((res) => {
const serverDetails = res.data.data;
// Assuming the server response has an array of student details
const updatedDetails = serverDetails.map((student) => ({
...student,
topClass: student.percentage > 90,
}));
setDetails(updatedDetails);
toast.success('Welcome to Elite Tech Park Program', {
icon: 'โจ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
});
} catch (error) {
console.log(`Error: ${error}`);
toast.error('Something went Wrong!', {
icon: 'โ ๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
};
useEffect(() => {
handleShowDetails();
}, []);
const handleRegister = async () => {
try {
if (phone.length !== 10) {
toast('Please enter a valid 10-digit phone number', {
icon: '๐ฑ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
setPhone('');
return;
}
await axios
.post('https://elite-nwwo.onrender.com/api/studentRegister', {
name,
email,
phone,
address,
percentage,
topClass,
})
.then((res) => {
if (res.data.status === true) {
const isTopClass = percentage > 90;
handleSetTopClass(isTopClass);
setName('');
setAddress('');
setPercentage('');
setEmail('');
setPhone('');
setTopClass('');
toast.success(res.data.message, {
icon: '๐ฑ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
} else {
toast.error(res.data.message, {
icon: '๐ฑ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
});
} catch (error) {
console.log(`Error during registration:: ${error}`);
toast.error('Something went Wrong!', {
icon: 'โ ๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
};
const handleEdit = async (id, updatedDetails) => {
try {
const response = await axios.put(
`https://elite-nwwo.onrender.com/api/studentEdit/${id}`,
updatedDetails
);
if (response.data.status === true) {
const updatedStudent = response.data.updatedStudent;
setDetails((prevDetails) => {
return prevDetails.map((student) =>
student._id === updatedStudent._id ? updatedStudent : student
);
});
toast.success(response.data.message, {
icon: '๐ฑ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
window.location.reload();
} else {
toast.error(response.data.message, {
icon: '๐ฑ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
} catch (error) {
console.error(`Error during student update:${error}`);
toast.error('Error during student update:', {
icon: 'โ ๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
};
useEffect(() => {
const fetchStudentNames = async () => {
try {
const response = await axios.get(
'https://elite-nwwo.onrender.com/api/lookup'
);
console.log(response);
if (response.data.status) {
setStudentNames(response.data.data);
} else {
console.error(
`Error fetching student names: ${response.data.message}`
);
toast.error('Error fetching student names:', {
icon: 'โ ๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
} catch (error) {
console.error(`Error fetching student names: ${error}`);
toast.error('Error fetching student names:', {
icon: 'โ ๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
};
fetchStudentNames();
}, []);
const fetchStudentDetails = async (studentId) => {
try {
const response = await axios.get(
`https://elite-nwwo.onrender.com/api/student/${studentId}`
);
if (response.data.status) {
const { email, phone, address, percentage } = response.data.data;
setSelectedStudentDetails({ email, phone, address, percentage });
} else {
console.error(
`Error fetching student details: ${response.data.message}`
);
toast.error(`Error fetching student names:${response.data.message}`, {
icon: 'โ ๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
} catch (error) {
console.error(`Error fetching student details: ${error}`);
toast.error(`Error fetching student names`, {
icon: 'โ ๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
};
const handleStudentSelect = (studentId) => {
setSelectedStudent(studentId);
fetchStudentDetails(studentId);
setIsEditMode(false);
};
const handleSlectedEdit = (id) => {
if (selectedStudentDetails) {
setIsEditMode(true);
setEditedValues({
email: selectedStudentDetails.email,
phone: selectedStudentDetails.phone,
address: selectedStudentDetails.address,
percentage: selectedStudentDetails.percentage,
});
}
};
const handleSave = async (id) => {
try {
await axios.put(
`https://elite-nwwo.onrender.com/api/studentUpdate/${id}`,
editedValues
);
setIsEditMode(false);
toast.success('Record updated successfully!', {
icon: '๐',
style: {
borderRadius: '10px',
background: '#28a745',
color: '#fff',
},
});
} catch (error) {
console.error(`Error updating details: ${error}`);
toast.error('Error updating record', {
icon: 'โ ๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
};
const handleCancelEdit = () => {
setIsEditMode(false);
setEditedValues({
email: selectedStudentDetails.email,
phone: selectedStudentDetails.phone,
address: selectedStudentDetails.address,
percentage: selectedStudentDetails.percentage,
});
};
const handleDelete = async (id) => {
try {
await axios.delete(
`https://elite-nwwo.onrender.com/api/selectedStudentDelete/${id}`
);
toast.success('Student deleted successfully', {
icon: '๐๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
window.location.reload();
} catch (error) {
console.error(`Error during student delete: ${error}`);
toast.error('Error during student delete', {
icon: 'โ ๏ธ',
style: {
borderRadius: '10px',
background: '#333',
color: '#fff',
},
});
}
};
return (
<studentContext.Provider
value={{
handleSave,
handleCancelEdit,
handleDelete,
handleSlectedEdit,
handleStudentSelect,
fetchStudentDetails,
studentNames,
selectedStudent,
isEditMode,
editedValues,
setEditedValues,
handleRegister,
name,
email,
phone,
address,
percentage,
setName,
setAddress,
setPhone,
setPercentage,
setEmail,
handleShowDetails,
details,
topClass,
setTopClass,
handleEdit,
selectedStudentDetails,
setSelectedStudentDetails,
isEditMode,
setIsEditMode,
}}
>
{children}
</studentContext.Provider>
);
};
export default Context;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
crossorigin="anonymous">
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Bootstrap</a>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Git</a>
</li>
<li class="nav-item" >
<a class="nav-link disabled" href="#">Python</a> <!-- ๋์น ๋ถ๋ถ ์์์ด ์
์ ๋ถ๋ถ์ disabled๋ถ์ฌ์ผ ๋๋ ๊ฒ์ ๋์ณค์.-->
</li>
</ul>
</div>
</nav>
<!-- form -->
<div class="container">
<form class="mt-5"> <!-- ๋์น ๋ถ๋ถ ์ฌ๋ฐฑ์ ์ดํผ์ง ์์์.-->
<div class="form-group">
<label for="exampleInputEmail1">Email</label> <!-- ๋์น ๋ถ๋ถ ์ถ๋ ฅ ์ด๋ฆ์ ๊ผผ๊ผผํ๊ฒ ์ดํด๋ณด์ง ์์์.-->
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password Confirmation</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password Confirmation">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<!-- Card -->
<div class="container mt-5">
<div class="row">
<div class="card col-4">
<img src="../images/git.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Git</h5>
<p class="card-text">Git์ ๋ถ์ฐ๋ฒ์ ๊ด๋ฆฌ์์คํ
์ด๋ค.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
<div class="card col-4">
<img src="../images/git.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Git</h5>
<p class="card-text">Git์ ๋ถ์ฐ๋ฒ์ ๊ด๋ฆฌ์์คํ
์ด๋ค.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
<div class="card col-4">
<img src="../images/git.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Git</h5>
<p class="card-text">Git์ ๋ถ์ฐ๋ฒ์ ๊ด๋ฆฌ์์คํ
์ด๋ค.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
</div>
<!-- Homework Q.4 -->
<style>
div {
border: solid 1px black;
}
.row {
background-color: moccasin;
margin: 1px;
}
</style>
<div class="container">
<div class="row">
<div class="col-3">25%</div>
<div class="col-6">50%</div>
<div class="col-3">25%</div>
</div>
</div>
<!-- Bootstrap JS --> <!-- ๋์น ๋ถ๋ถ ๋ฃ์ด์ผ ๋ ์ค ๋ชฐ๋์.-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
crossorigin="anonymous"></script>
</body>
</html>
|
๏ปฟusing AutoMapper;
using BankApp.Data.DataModels;
using BankApp.Data.Interfaces;
using BankApp.Domain.Models.Dtos;
using BankApp.Domain.Models;
using Microsoft.EntityFrameworkCore;
namespace BankApp.Data.Repos
{
public class TransactionRepo : ITransactionRepo
{
private readonly BankAppDBContext _db;
private readonly IMapper _mapper;
public TransactionRepo(BankAppDBContext db, IMapper mapper)
{
_db = db;
_mapper = mapper;
}
public async Task<ServiceResponse<List<TransactionDto>>> GetTransactionsByCustomerId(int customerId)
{
var response = new ServiceResponse<List<TransactionDto>>();
var dbTransactions = await _db.Transactions
.Include(t => t.BankAccount)
.Where(t => t.BankAccount!.CustomerId == customerId).ToListAsync(); //only receive the Transactions that belong to the logged in Customerยดs Bank Accounts
response.Data = dbTransactions.Select(acc => _mapper.Map<TransactionDto>(acc)).ToList();
return response;
}
}
}
|
import { NextPage } from 'next'
import { IoHeart, IoHeartDislike } from 'react-icons/io5'
import { ref, remove, set } from '@firebase/database'
import { db } from '../../../firebase'
import { useAppSelector } from 'hooks/redux'
import { useState } from 'react'
import { message, Tooltip } from 'antd'
import styles from './styles.module.scss'
import { useAuth } from 'hooks/useAuth'
import { IMovieCard } from 'models/movie.interface'
import useTranslation from 'next-translate/useTranslation'
interface IProps {
movie: IMovieCard
}
const MovieFav: NextPage<IProps> = ({ movie }) => {
const { t: tGlobal } = useTranslation('global')
const { t: tFavorites } = useTranslation('favorites')
const [fav, setFav] = useState<IMovieCard>(movie)
const { isAuth } = useAuth()
const favorites = useAppSelector((state) => state.favorites.favorites)
const addToFav = async () => {
if (!isAuth) {
message.error(tFavorites('need-login'))
return
}
const reference = ref(db, 'favorites/' + `${localStorage.getItem('uid')!}/` + movie.id)
try {
await set(reference, { ...movie }).then(() => {
message.success(`${tGlobal('added')} ${movie.title ? tGlobal('movie') : tGlobal('tv')} ${movie.title}`)
})
} catch (e) {
console.log(e, 'addToFav DB')
}
}
const removeFromFav = async () => {
const reference = ref(db, 'favorites/' + `${localStorage.getItem('uid')!}/` + movie.id)
try {
await remove(reference).then(() => {
message.success(`${tGlobal('removed')} ${movie.title ? tGlobal('movie') : tGlobal('tv')} ${movie.title}`)
})
} catch (e) {
console.log(e, 'removeFromFav DB')
}
}
return (
<>
{favorites.some((item) => item.id === fav.id) ? (
<Tooltip title={tGlobal('remove-fav')}>
<div>
<IoHeartDislike onClick={removeFromFav} size='1.5rem' className={styles.icon} />
</div>
</Tooltip>
) : (
<Tooltip title={tGlobal('add-fav')}>
<div>
<IoHeart onClick={addToFav} size='1.5rem' className={styles.icon} />
</div>
</Tooltip>
)}
</>
)
}
export default MovieFav
|
class Node:
def __init__(self,left, right, father, data):
self.left = left
self.right = right
self.father = father
self.data = data
def getData(self):
return self.data
def setData(self, data):
self.data = data
def getLeft(self):
return self.left
def setLeft(self, node):
self.left = node
def getRight(self):
return self.right
def setRight(self, node):
self.right = node
def getFather(self):
return self.father
def setFather(self, node):
self.father = node
def isLeft(self):
father = self.getFather()
if father == None:
return False
if father.getLeft() == self:
return True
return False
def isRight(self):
father = self.getFather()
if father == None:
return False
if father.getRight() == self:
return True
return False
def isBrother(self):
father = self.getFather()
if father == None:
return False
if self.isLeft():
return father.getRight()
return father.getLeft()
class BinaryTree:
def __init__(self):
self.root = None
def getRoot(self):
return self.root
def setRoot(self, node):
self.root = node
def search(self, node, element):
if node == None or element == node.data:
return node
if element < node.data:
return self.search(node.getLeft(), element)
return self.search(node.getRight(), element)
def minimum(self, node):
while node.getLeft() is not None:
node = node.getLeft()
return node
def maximum(self, node):
while node.getRight() is not None:
node = node.getRight()
return node
def successor(self, element):
node = self.search(self.getRoot(), element)
if node == None:
return node
if node.getRight() is not None:
return self.minimum(node.getRight())
y = node.getFather()
while y is not None and node == y.getRight():
node = y
y = y.getFather()
return y
def InOrderTreeWalk(self,x):
if x is not None:
self.InOrderTreeWalk(x.getLeft())
print(x.getData())
self.InOrderTreeWalk(x.getRight())
def insert(self, node):
y = None
x = self.getRoot()
while x is not None:
y = x
if node.getData() < x.getData():
x = x.getLeft()
else:
x = x.getRight()
node.setFather(y)
if y == None:
self.setRoot(node)
elif node.getData() < y.getData():
y.setLeft(node)
else:
y.setRight(node)
def Transplant(self, u, v):
if u.getFather() is None:
self.setRoot(v)
elif u == u.getFather().getLeft():
u.getFather().setLeft(v)
else:
u.getFather().setRight(v)
if v is not None:
v.setFather(u.getFather())
def TreeDelete(self, z):
if z.getLeft() is None:
self.Transplant(z, z.getRight())
elif z.getRight() is None:
self.Transplant(z,z.getLeft())
else:
y = self.minimum(z.getRight())
if y.getFather() != z:
self.Transplant(y,y.getRight())
y.setRight(z.getRight())
y.getRight().setFather(y)
self.Transplant(z,y)
y.setLeft(z.getLeft())
y.getLeft().setFather(y)
|
import axios from "axios";
import { useState } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import { useAuth } from "../contextApi/store";
const REACT_APP_API = "http://localhost:5000";
const Login = () => {
const [loginData, setLoginData] = useState({
email: "",
password: "",
});
const navigateTo = useNavigate()
const location = useLocation()
const {auth,setAuth} = useAuth()
// console.log(auth)
const handleChange = (e) => {
const { name, value } = e.target;
setLoginData((prev) => ({ ...prev, [name]: value }));
};
const handleSubmit = async (e) => {
e.preventDefault();
// Add your Login logic here
console.log(loginData)
try {
const res = await axios.post(`${REACT_APP_API}/auth/login`, {
...loginData,
});
if (res.status) {
toast.success("Login Successful");
setAuth(prev=>({...prev,user:res.data.user}))
localStorage.setItem("activeUser",JSON.stringify(res.data.user))
navigateTo(location?.state || "/")
console.log(res.data.user)
} else toast.error("Invalid Credentials -- try");
} catch (e) {
toast.error("Invalid Credentials");
setLoginData((_) => {
return {
email: "",
password: "",
};
});
}
};
return (
<div className="text-indigo-800 bg-white h-[78.8vh] flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div>
<h2 className="mt-6 text-center text-3xl font-extrabold text-indigo-700">
Log in to your account
</h2>
</div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
<div className=" shadow-sm -space-y-px flex flex-col gap-4">
<div>
<label htmlFor="email-address" className="sr-only">
Email address
</label>
<input
id="email-address"
name="email"
type="email"
value={loginData.email}
autoComplete="email"
onChange={handleChange}
required
className="placeholder:text-indigo-700 appearance-none rounded-md relative block w-full px-3 py-2 border border-indigo-700 placeholder-gray-400 text-indigo-800 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
placeholder="Email address"
/>
</div>
<div>
<label htmlFor="password" className="sr-only">
Password
</label>
<input
id="password"
name="password"
value={loginData.password}
type="password"
autoComplete="current-password"
onChange={handleChange}
required
className="placeholder:text-indigo-700 appearance-none relative block w-full px-3 py-2 border border-indigo-700 placeholder-gray-400 text-indigo-800 rounded-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm"
placeholder="Password"
/>
</div>
</div>
<div>
<button
type="submit"
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
Login
</button>
<button className="my-2 group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
New User ?{" "}
<Link to="/register" className="underline ">
Register here
</Link>
</button>
<button className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
Forgot Password ?{" "}
<Link to="/forgotpassword" className="underline">
Click here๐
</Link>
</button>
</div>
</form>
</div>
</div>
);
};
export default Login;
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract BallotV4 {
struct Voter {
uint weight;
bool voted;
uint vote;
}
struct Proposal {
uint voteCount;
}
address chairperson;
mapping(address => Voter) voters;
Proposal[] proposals;
enum Phase { Init, Regs, Vote, Done }
Phase public state = Phase.Init;
modifier validPhase(Phase reqPhase) {
require(state == reqPhase);
_;
}
modifier onlyChair() {
require(msg.sender == chairperson);
_;
}
constructor (uint numProposals) {
chairperson = msg.sender;
voters[chairperson].weight = 2;
for (uint prop = 0; prop < numProposals; prop++) {
proposals.push(Proposal(0));
}
state = Phase.Regs;
}
function changeState(Phase x) public onlyChair {
if (x < state) revert();
state = x;
}
function register(address voter) public validPhase(Phase.Regs) onlyChair {
require(!voters[voter].voted)) revert();
voters[voter].weight = 1;
voters[voter].voted = false;
}
function vote(uint toProposal) public validPhase(Phase.Vote) {
Voter memory sender = voters[msg.sender];
require(!sender.voted);
require(toProposal < proposals.length);
sender.voted = true;
sender.vote = toProposal;
proposals[toProposal].voteCount += sender.weight;
}
function reqWinner() public validPhase(Phase.Done) view returns (uint winningProposal) {
uint winningVoteCount = 0;
for (uint prop = 0; prop < proposals.length; prop++) {
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
winningProposal = prop;
}
}
assert(winningVoteCount >= 3);
}
}
|
// Constructor.java
class Car {
private String maker;
private String color;
private String bodyType;
public Car() {
maker = "Porsche";
color = "Silver";
bodyType = "Coupe";
}
private String accelerate() {
String motion = "Accelerating -->";
return motion;
}
public void setCar(String brand, String paint, String style) {
maker = brand;
color = paint;
bodyType = style;
}
public void getCar() {
System.out.println(maker + " paint is " + color);
System.out.println(maker + " style is " + bodyType);
System.out.println(maker + " is " + accelerate() + "\n");
}
}
class Constructor {
public static void main (String[] args) {
Car Porsche = new Car();
Porsche.getCar();
Car Ferrari = new Car();
Ferrari.setCar("Ferrari", "Red", "Sport");
Ferrari.getCar();
}
}
|
/// <reference path="../../packages/com.adobe.indesign/references.d.ts"/>
declare namespace Adobe {
namespace Indesign {
class DisplaySetting extends Adobe.Csawlib.CSHostObject {
/**
* If true, uses anti-aliasing for text and bitmap images.
* @type {boolean}
*/
public antialiasing: boolean;
/**
* A collection of event listeners.
* @type {Adobe.Indesign.EventListeners}
* @readonly
*/
public readonly eventListeners: Adobe.Indesign.EventListeners;
/**
* A collection of events.
* @type {Adobe.Indesign.Events}
* @readonly
*/
public readonly events: Adobe.Indesign.Events;
/**
* The point size below which text is greeked.
* @type {number}
*/
public greekBelow: number;
/**
* The index of the DisplaySetting within its containing
* object.
* @type {number}
* @readonly
*/
public readonly index: number;
/**
* Returns true if the object specifier resolves to valid
* objects.
* @type {boolean}
* @readonly
*/
public readonly isValid: boolean;
/**
* The parent of the DisplaySetting (a Application).
* @type {Adobe.Indesign.Application}
* @readonly
*/
public readonly parent: Adobe.Indesign.Application;
/**
* A property that allows setting of several properties at the
* same time.
* @type {any}
*/
public properties: any;
/**
* The display method for raster images.
* @type {Adobe.Indesign.TagRaster}
*/
public raster: Adobe.Indesign.TagRaster;
/**
* The display setting for transparencies.
* @type {Adobe.Indesign.TagTransparency}
*/
public transparency: Adobe.Indesign.TagTransparency;
/**
* The display method for vector images.
* @type {Adobe.Indesign.TagVector}
*/
public vector: Adobe.Indesign.TagVector;
/**
* Adds an event listener.
* @param {string} eventTypeParam The event type.
* @param {any} handlerParam The event handler. Can accept:
* File or JavaScript Function.
* @param {boolean} capturesParam This parameter is obsolete.
* (Optional)
* @returns {Adobe.Indesign.EventListener}
*/
public addEventListenerDisplaySetting(eventTypeParam: string, handlerParam: any, capturesParam: boolean): Adobe.Indesign.EventListener;
/**
* Resolves the object specifier, creating an array of object
* references.
* @returns {any}
*/
public getElements(): any;
/**
* Removes the event listener.
* @param {string} eventTypeParam The registered event type.
* @param {any} handlerParam The registered event handler. Can
* accept: File or JavaScript Function.
* @param {boolean} capturesParam This parameter is obsolete.
* (Optional)
* @returns {boolean}
*/
public removeEventListenerDisplaySetting(eventTypeParam: string, handlerParam: any, capturesParam: boolean): boolean;
/**
* Retrieves the object specifier.
* @returns {string}
*/
public toSpecifier(): string;
}
}
}
|
// STYLESHEET
import "./App.css";
// FONTS
import "/assets/fonts/SherwoodRegular.ttf";
// COMPONENTS
import Content from "./components/UI/Content";
import Header from "./components/UI/Header";
// FUNCTIONS
import { useState, useEffect } from "react";
import { fetchEntry } from "./components/service/api/fetchEntry";
import { useLocalStorage } from "./components/useLocalStorage";
// round function that does the same as start game
function App() {
// LOCAL STORAGE
const { setData, getData } = useLocalStorage("value");
const [tiles, setTiles] = useState([]);
const [selection, setSelection] = useState([]);
const [points, setPoints] = useState(0);
const [best, setBest] = useState(getData());
const [isGameOver, setIsGameOver] = useState(false);
const [gameStart, setGameStart] = useState(false);
const [difficulty, setDifficulty] = useState(0);
// check clicks
useEffect(() => {
if (selection.length === 3 && difficulty === 1) {
checkPlay();
} else if (selection.length === 2 && difficulty == 2) {
checkPlay();
}
}, [selection, difficulty]);
// check round status
useEffect(() => {
if (difficulty === 1) {
if (points % 3 === 0) {
setHighScore();
startGame(1);
} else {
setHighScore();
}
} else if (difficulty === 2) {
if (points % 8 === 0) {
setHighScore();
startGame(2);
} else {
setHighScore();
}
}
}, [points]);
const checkPlay = () => {
if (difficulty === 1) {
const a = selection[0];
const b = selection[1];
const c = selection[2];
return (
a == b && b == c ? endGame("win") : endGame("lose"), setSelection([])
);
} else {
const a = selection[0];
const b = selection[1];
return a == b ? endGame("win") : endGame("lose"), setSelection([]);
}
};
const addPoint = () => {
return setPoints((points) => points + 1);
};
// flip play card
const handleFlip = (index) => {
let arr = [...tiles];
arr[index].flipped = true;
};
const setHighScore = () => {
return points > best ? setBest(points) : null, setData(best);
};
const endGame = (value) => {
if (value === "win") {
return addPoint(), setHighScore();
} else {
return setIsGameOver(!isGameOver), setHighScore();
}
};
const startGame = async (difficulty) => {
const arrPhase1 = await callAPI(difficulty);
const arrPhase2 = addUniqueID(arrPhase1);
const arrPhase3 = shuffle(arrPhase2);
setGameStart(true);
setDifficulty(difficulty);
setTiles(arrPhase3);
setTimeout(() => {
const phaseFinal = [...arrPhase3];
phaseFinal.map((obj) => {
return (obj.flipped = false);
});
setTiles(phaseFinal);
}, "3000");
};
return (
<>
<section className="app">
<Header />
<Content
points={points}
best={best}
setBest={setBest}
tiles={tiles}
setTiles={setTiles}
selection={selection}
setSelection={setSelection}
handleFlip={handleFlip}
gameStart={gameStart}
setGameStart={setGameStart}
isGameOver={isGameOver}
difficulty={difficulty}
setDifficulty={setDifficulty}
startGame={startGame}
/>
</section>
</>
);
}
const callAPI = async (difficulty) => {
let arr = [];
let num = Math.floor(Math.random() * 380);
if (difficulty === 1) {
for (let i = 0; i < 3; i++) {
const promise = await fetchEntry(num);
const res1 = { ...promise };
const res2 = { ...promise };
const res3 = { ...promise };
arr.push(res1, res2, res3);
}
return arr;
} else {
let num = Math.floor(Math.random() * 380);
for (let i = 0; i < 8; i++) {
const promise = await fetchEntry(num);
const res1 = { ...promise };
const res2 = { ...promise };
arr.push(res1, res2);
}
return arr;
}
};
const addUniqueID = (arr) => {
let newArr = arr;
newArr.map((value) => {
return (value.uniqueID = crypto.randomUUID());
});
return newArr;
};
// shuffle card order
const shuffle = (arr) => {
let newArr = arr
.map((value) => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value);
return newArr;
};
export default App;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- ็ถๆ้ฎ้ข ่ฏญไนๅhtml ๆ่ฝฝ็น wrapper-->
<div class="wrapper">
<!-- <button class="like-btn">
<span class="like-text">็น่ต</span>
</button> -->
</div>
<script>
// html str `` ๆทปๅ ๅฐ้กต้ข
// 2.่ฟ่ฆๅจไปไธ้ขๆทปๅ ไบไปถ?
const createDOMFromString = (domString)=>{
const oDiv = document.createElement('div'); // ๅๅปบไธไธชdom่็น
oDiv.innerHTML =domString; // ๆฝ่ฑก
return oDiv;
}
class LikeButton {
constructor() {
// isLiked ๅๆๅฑๆง
this.state = {
isLiked: false
}
}
render() {
console.log(this,'render');
// ไบไปถ็ๅฌ ???
// addEventListener ? dom node-type 1
// dom createElement appendChild
this.el = createDOMFromString(`
<button id = 'like-btn'>
<span class="like-text">็น่ต</span>
</button>
`)
// this
// this button ๅฏน่ฑก
// changeLikeText ๅฐๅค้ขๅๆฏไธ็งไผๅ ๆๅฉไบไปฃ็ ่่ดฃๅ็ฆป
// ไฝไธบไบไปถๅฝๆฐ, this ๆๅไบไปถๅ็็ๅ
็ด <div></div>
// .bind(this) ้ๆฐ็ปๅฎthisๅฐLikeButton็ฑป ้ๆฐๆๅๅฝๅๅฎไพ
// thisๅฐๆฐธไน
ๅฐ่ขซ็ปๅฎๅฐไบbind็็ฌฌไธไธชๅๆฐ๏ผๆ ่ฎบ่ฟไธชๅฝๆฐๆฏๅฆไฝ่ขซ่ฐ็จ็ใbind็ปๅฎ็ๅๆฐๅช็ๆไธๆฌกใ
this.el.addEventListener('click', this.changLikeText.bind(this), false);
return this.el;
}
// ไธไธชๆนๆณๅฐฑๅไธไธชไบๆ
changLikeText(){
// this.state.isLiked ๆนๅไธไธ
console.log(this); // this ่ขซๆนๅไบ
this.state.isLiked = ! this.state.isLiked;
// console.log(this.state.isLiked);
const likeText = this.el.querySelector('.like-text');
// ไธๅ
่ฟ็ฎ็ฌฆ
likeText.innerHTML = this.state.isLiked? 'ๅๆถ':'็น่ต';
}
}
const wrapper = document.querySelector('.wrapper');
const likeButton = new LikeButton(); //ๅฎไพๅ
// render ๅฝๆฐ ๆง่ก ่ฐ็จๆนๅผ ไฝไธบๅฏน่ฑก็ๆนๆณ
wrapper.appendChild(likeButton.render());
// ๅค็จ
const likeButton2 = new LikeButton();
wrapper.appendChild(likeButton2.render());
</script>
</body>
</html>
|
import transazione
import users
from colorama import Fore, Style
import datetime
import time
import sys
import pickle
def red(x): return f"{Fore.RED}{x}{Style.RESET_ALL}"
def green(x): return f"{Fore.GREEN}{x}{Style.RESET_ALL}"
def to_key(x): return x.strip().lower().replace(" ", "")
def string_to_data(string: str):
string = string.replace(" ", "")
componenti_data = string.split("/")
anno = int(componenti_data[0])
mese = int(componenti_data[1])
giorno = int(componenti_data[2])
data = datetime.date(anno, mese, giorno)
return data
# MENU
if __name__ == '__main__':
contenitore_utenti = {}
ceo = users.Utente('User 1', [], 5)
# Format Contenitore Utenti:
# USER_KEY(nospazi) : USER('nominativo', 'lista', 'saldo')
contenitore_utenti['user1'] = ceo
while True:
print(red("\nLista Utenti: "))
for pre_user in contenitore_utenti.values():
print(green(pre_user.nominativo))
print(green("\n\n\tMENU: "))
main_menu_choice = input(green('''
1. Creazione Nuovo Utente
2. Log In Utente
3. Effettuare BackUp o Ripristino
4. Esportare le transazioni in formato testuale
5. Uscire
'''))
if main_menu_choice == '1':
# Logica creazione nuovo utente:
nominativo = input("Inserisci nominativo: ")
user_key = to_key(nominativo)
if user_key in contenitore_utenti:
print(red("Utente giร registrato... Procedi con il Log In"))
continue
new_user = users.Utente(nominativo, [], 0)
contenitore_utenti[user_key] = new_user
elif main_menu_choice == '2':
user_key = to_key(input("Chiave o Nominativo User: "))
if user_key in contenitore_utenti:
nominativo = contenitore_utenti[user_key]
else:
print(red("\nUtente inesistenete..."))
continue
elif main_menu_choice == '3':
menu_ripristino = '''\n
1. Effettuare un BackUp degli utenti attuali
2. Ripristinare stato da un precedente backup
3. Tornare al menu principale\n
'''
print(green(menu_ripristino))
nome_file = 'backup.pkl'
backup_choice = input(": ")
if backup_choice == '1': # fare backup
users.crea_backup_utenti(nome_file, contenitore_utenti)
continue
elif backup_choice == '2': # ripristinare da backup
contenitore_utenti = users.load_backup_utenti(nome_file)
continue
elif backup_choice == '3':
continue
else:
print(red("\nInvalid choice, torno al menu principale"))
continue
elif main_menu_choice == '4':
nome_file_testuale = 'transazioni.txt'
# contiene
lista_transazioni_esportazione = []
for utente in contenitore_utenti.values():
for transazione_utente in utente.lista_transazioni:
lista_transazioni_esportazione.append(transazione_utente)
counter = 1
with open(nome_file_testuale, 'w') as f:
for tran in lista_transazioni_esportazione:
f.write(f"{counter}. {tran.print_transazione()}\n")
counter += 1
print(
green(f"Transazioni esportate con successo in {nome_file_testuale}"))
continue
elif main_menu_choice == '5':
print(red("\nTerminazione..."))
time.sleep(0.5)
sys.exit()
else:
print(red("Invalid choice...\n"))
continue
# Variabile per controllare il sottomenu: User choice
stay_on_second_menu = False
while not stay_on_second_menu and nominativo and user_key:
user = contenitore_utenti[user_key] # variable classe User
if user.saldo < 0:
print(
green(f"\n\nBentornato {user.nominativo}, Il tuo saldo attuale รจ: "), end='')
print(red(f"{user.saldo}โฌ "))
print(green("Cosa vuoi fare? \n\n"))
else:
print(
green(f"\n\nBentornato {user.nominativo}, Il tuo saldo attuale รจ: {user.saldo}โฌ \nCosa vuoi fare? \n\n"))
user_choice = input(green(
f"1. Nuovo Versamento\n2. Nuovo Prelievo\n3. Vedere lo storico delle operazioni\n4. Esportare storico delle operazioni\n5. Tornare al Menu Principale\n"))
# possibile scelte:
if user_choice == '1':
print(green(f"\n\t<< Nuovo Versamento: >>\n"))
versamento = int(
input(green("Quanto vuoi versare sul conto: ")))
if versamento <= 0:
print(red("Non puoi fare versamenti negativi..."))
continue
scelta_data = input(green(
f"Scegli la data della transazione [ YYYY/MM/DD ] o premi enter per selezionare la data odierna: \n"))
if scelta_data:
try:
scelta_data = scelta_data.replace(" ", "")
componenti_data = scelta_data.split("/")
anno = int(componenti_data[0])
mese = int(componenti_data[1])
giorno = int(componenti_data[2])
data_transazione = datetime.date(anno, mese, giorno)
except:
print(red("Formato della data errato! [ YYYY/MM/DD ]"))
continue
else:
data_transazione = datetime.date.today()
versamento_singolo = transazione.Transazione(
data_transazione, versamento, 'versamento')
user.lista_transazioni.append(versamento_singolo)
user.saldo += versamento
elif user_choice == '2':
print(green(f"\n\t<< Nuovo Prelievo: >>\n"))
prelievo = abs(
int(input(green("Quanto vuoi prelevare dal conto: "))))
data_prelievo = datetime.date.today()
prelievo_singolo = transazione.Transazione(
data_prelievo, prelievo, 'prelievo')
saldo_corrente = user.saldo - prelievo
if saldo_corrente <= 0:
print(
red(f"Attenzione il tuo saldo attuale risulta negativo: {saldo_corrente}โฌ"))
else:
print(green("Prelievo avvento con successo"))
user.lista_transazioni.append(prelievo_singolo)
user.saldo = saldo_corrente
# Vedere lo storico delle operazioni
elif user_choice == '3':
scelta_storico = input(
f"\n1. Vedere lo storico intero (comportamento default)\n2. Vedere lo storico filtrato per data\n")
if scelta_storico == '1' or not scelta_storico:
print("\n\nLista di tutte le transazioni registrate: ")
if user.lista_transazioni == []:
print(red("\nNon sono presenti transazioni a tuo nome! \n"))
continue
for tran in user.lista_transazioni:
print(green(f"{tran.print_transazione()}"), end='\n')
elif scelta_storico == '2':
try:
print(green("\nFormato data -> [ YYYY/MM/DD ]"))
stringa_data_inizio = input("Data Inizio: ")
stringa_data_fine = input("Data Fine: ")
data_inizio = string_to_data(stringa_data_inizio)
data_fine = string_to_data(stringa_data_fine)
lista_transazioni_filtrate = transazione.filtra_data(
user.lista_transazioni, data_inizio, data_fine)
print(
green(f"\n\nTransazioni registrate da {data_inizio} <-- a --> {data_fine}"))
for transazione_filtrata in lista_transazioni_filtrate:
print(
green(transazione_filtrata.print_transazione()), end='\n')
print("\n\n")
except:
print(
red("Formato data sbagliatoo! [ YYYY / MM / DD ]"))
continue
else:
print(red("\nScelta invalida...\n"))
continue
elif user_choice == '4':
try:
counter = 0
with open('transazioni_utente.txt', 'w') as file:
for transac in user.lista_transazioni:
file.write(
f"{counter}. {transac.print_transazione()}\n")
counter += 1
print("Esportazione riuscita in: transazioni_utente.txt !\n\n")
except:
print(red("Esportazione fallita... \nTermino Programma"))
time.sleep(1)
sys.exit()
elif user_choice == '5':
print(green("\nReturning to main menu: "))
stay_on_second_menu = True
else:
print(red("Scelta invalida "))
continue
|
defmodule BeaconWeb do
@moduledoc false
def controller do
quote do
use Phoenix.Controller,
namespace: BeaconWeb,
formats: [:html, :json],
layouts: [html: BeaconWeb.Layouts]
import Plug.Conn
import BeaconWeb.Gettext
end
end
def live_view do
quote do
use Phoenix.LiveView,
layout: {BeaconWeb.Layouts, :app}
unquote(html_helpers())
end
end
def live_component do
quote do
use Phoenix.LiveComponent
unquote(html_helpers())
end
end
def html do
quote do
use Phoenix.Component
# Import convenience functions from controllers
import Phoenix.Controller,
only: [get_csrf_token: 0, view_module: 1, view_template: 1]
# Include general helpers for rendering HTML
unquote(html_helpers())
end
end
defp html_helpers do
quote do
# HTML escaping functionality
import Phoenix.HTML
# Core UI components and translation
import BeaconWeb.CoreComponents
import BeaconWeb.Gettext
# Shortcut for generating JS commands
alias Phoenix.LiveView.JS
# Router helpers
alias BeaconWeb.Router.Helpers, as: Routes
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
|
export type Menu = {
id: number;
name: string;
time: string;
diet?: string[];
image: string;
};
export const menuData: Menu[] = [
{
id: 0,
name: "Butternut squash soup",
time: "30min",
diet: ["Vegetarian", "Gluten Free"],
image: "/images/butternut-squash-soup-600px.jpg",
},
{
id: 1,
name: "Carbonara pasta",
time: "30min",
diet: [],
image: "/images/carbonara-pasta-800px.jpg",
},
{
id: 2,
name: "Fried rice",
time: "30min",
diet: ["Vegetarian", "Gluten Free"],
image: "/images/fried-rice-800px.jpg",
},
{
id: 3,
name: "Spinach soup",
time: "30min",
diet: ["Vegan", "Gluten Free"],
image: "/images/vegan-soup-800px.jpg",
},
{
id: 4,
name: "Beef strew",
time: "30min",
diet: [],
image: "/images/beef-stew-800px.jpg",
},
{
id: 5,
name: "Chicken alfredo pasta",
time: "30min",
diet: [],
image: "/images/chicken-alfredo-pasta-900px.jpg",
},
{
id: 6,
name: "Chickpea tacos",
time: "30min",
diet: ["Vegan"],
image: "/images/chickpea-tacos-800px.jpg",
},
{
id: 7,
name: "Shrimp and rice",
time: "30min",
diet: [],
image: "/images/salmon-rice-800px.jpg",
},
{
id: 8,
name: "Ramen",
time: "30min",
diet: [],
image: "/images/ramen-800px.jpg",
},
{
id: 9,
name: "Sage lemon pasta",
time: "30min",
diet: ["Vegetarian"],
image: "/images/sage-lemon-pasta-800px.jpg",
},
{
id: 10,
name: "Shrimp pasta",
time: "30min",
diet: [],
image: "/images/shrimp-red-pasta-800px.jpg",
},
{
id: 11,
name: "Chicken katsu",
time: "30min",
diet: [],
image: "/images/katsu-800px.jpg",
},
{
id: 12,
name: "Nachos",
time: "30min",
diet: ["Gluten Free"],
image: "/images/nachos-800px.jpg",
},
{
id: 13,
name: "Lentil meatball soup",
time: "30min",
diet: ["Gluten Free"],
image: "/images/lentil-meatball-soup-800px.jpg",
},
{
id: 14,
name: "Veggie bowl",
time: "30min",
diet: ["Vegan", "Gluten Free"],
image: "/images/veggie-bowl-800px.jpg",
},
];
export type Filter = {
id: number;
name: string;
};
export const filterMenuData: Filter[] = [
{
id: 0,
name: "All",
},
{
id: 1,
name: "Vegetarian",
},
{
id: 2,
name: "Vegan",
},
{
id: 3,
name: "Gluten Free",
},
];
|
import { StyleSheet, Text, View,TouchableOpacity,Modal } from 'react-native'
import React, { useState } from 'react'
import { HStack, NativeBaseProvider } from 'native-base'
import { Avatar, Button, PaperProvider } from 'react-native-paper'
import { useNavigation } from '@react-navigation/native'
import axios from 'axios'
const ModalDelete = ({recipes_id}) => {
const navigation = useNavigation();
const [modalVisible, setModalVisible2] = useState(false);
const handleDelete = () => {
axios.delete(`https://mamarecipe-backend-mobile.vercel.app/recipes/${recipes_id}`)
.then(() => {
alert("delete success")
navigation.navigate("Home")
})
.catch((error) => console.log(error));
}
return (
<NativeBaseProvider>
<PaperProvider>
<View className="flex-1 flex-row items-center justify-end">
<TouchableOpacity onPress={() => setModalVisible2(!modalVisible)}>
<Avatar.Icon size={50} icon="delete-outline" color='red' backgroundColor="transparant" className="mr-[-10]" />
</TouchableOpacity>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible2(!modalVisible);
}}
>
<View style={styles.modalView}>
<Text marginLeft={'auto'} marginRight={'auto'} fontSize={20}>Apakah anda yakin ingin menghapus resep ini?</Text>
<HStack mt={5} style={{ marginLeft: 'auto', marginRight: 'auto' }}>
<Button
onPress={() => setModalVisible2(!modalVisible)}
mr={3}
>
Cancel
</Button>
<Button backgroundColor={'red.600'} w={20} onPress={handleDelete} >Hapus</Button>
</HStack>
</View>
</Modal>
</View>
</PaperProvider>
</NativeBaseProvider>
)
}
export default ModalDelete
const styles = StyleSheet.create({
modalView: {
marginTop: 100,
marginHorizontal: 10,
backgroundColor: "#EFEFEF",
borderRadius: 20,
padding: 35,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
},
})
|
import * as React from 'react'
import cn from 'classnames'
import useTranslation from 'next-translate/useTranslation'
import { useRouter } from 'next/router'
import { useTheme } from 'next-themes'
import Link from 'next/link'
import Image from 'next/image'
import useMobile from '@/hooks/useMobile'
import Dropdown, { Option } from '@/components/dropdown'
import { LANG } from '@/config/constants'
interface OptionProps {
option: Option
}
const SelectedLang: React.FC<OptionProps> = ({ option }) => {
return (
<div className="flex flex-row">
<span className="mr-2">{option.icon}</span>
</div>
)
}
const LangOption: React.FC<OptionProps> = ({ option }) => {
return (
<div className="text-lg flex flex-row">
<span>{option.icon}</span>
<span className="ml-2">{option.label}</span>
</div>
)
}
interface MenuItemProps {
menu: string
}
const MenuItem: React.FC<MenuItemProps> = ({ menu }) => {
const { t } = useTranslation('header')
return (
<Link href={`#${menu}`} passHref>
<span className="text-lg cursor-pointer hover:text-orange-300">
{t(menu)}
</span>
</Link>
)
}
const enum Theme {
LIGHT = 'light',
DARK = 'dark',
SYSTEM = 'system',
}
const THEME = [Theme.LIGHT, Theme.DARK, Theme.SYSTEM]
const Header: React.FC = () => {
const { push } = useRouter()
const { isMobile } = useMobile()
const { theme, setTheme } = useTheme()
const { lang } = useTranslation()
const themeIcon = React.useMemo(() => {
if (theme === Theme.SYSTEM) return 'settings_suggest'
if (theme === Theme.DARK) return 'dark_mode'
return 'light_mode'
}, [theme])
const onThemeToggle = React.useCallback(() => {
const nextThemeIndex = THEME.findIndex(_theme => _theme === theme) + 1
setTheme(THEME[nextThemeIndex % THEME.length])
}, [setTheme, theme])
const onTranslate = React.useCallback(
selectedLang => push('/', '', { locale: selectedLang }),
[push]
)
return (
<div className="w-full sticky top-0 flex flex-row justify-between px-8 py-6 bg-slate-100 dark:bg-slate-800 dark:text-white z-10 shadow-sm">
<div className="basis-1/3">
<Link href="/">
<>
{isMobile ? (
<Image src="/logo.svg" width="45" height="45" alt="logo" />
) : (
<Image
src="/logo.svg"
className="hover:transition-transform hover:rotate-[360deg] cursor-pointer"
width="55"
height="55"
alt="logo"
/>
)}
</>
</Link>
</div>
<div className="flex-row items-center basis-1/3 justify-between hidden lg:flex">
<MenuItem menu="experiences" />
<MenuItem menu="skills" />
<MenuItem menu="projects" />
<MenuItem menu="contact" />
</div>
<div className="flex flex-row items-center space-x-10 basis-1/3 justify-end">
<div
role="button"
tabIndex={0}
className="flex cursor-pointer shadow-neumorphism-slate-100-xs dark:shadow-neumorphism-slate-800-xs hover:shadow-none dark:hover:shadow-none rounded-full p-2 w-10 h-10"
onClick={onThemeToggle}
onKeyDown={onThemeToggle}
>
<span
className={cn('material-icons text-md', {
'text-gray-100': theme === Theme.DARK,
'text-yellow-500': theme === Theme.LIGHT,
'text-gray-500': theme === Theme.SYSTEM,
})}
>
{themeIcon}
</span>
</div>
<Dropdown
className="w-[82px] shadow-neumorphism-slate-100-xs dark:shadow-neumorphism-slate-800-xs hover:shadow-none dark:hover:shadow-none"
options={LANG}
onSelect={onTranslate}
renderSelected={option => <SelectedLang option={option} />}
renderOption={option => <LangOption option={option} />}
defaultValue={lang}
/>
</div>
</div>
)
}
export default Header
|
import pandas as pd
from ortools.linear_solver import pywraplp
import os
os.chdir("C:\\Users\\GabyL\\analisisOpti")
# Cargar datos
demanda = pd.read_csv("demanda.csv")
capacidad = pd.read_csv("capacidad.csv")
# Crear el modelo
solver = pywraplp.Solver.CreateSolver('SCIP')
# Crear variables
num_empleados = 8
num_franjas = len(demanda)
trabaja = {}
pausa_activa = {}
almuerza = {}
nada = {}
for i in range(num_empleados):
for j in range(num_franjas):
trabaja[i, j] = solver.IntVar(0, 1, f'Trabaja_{i}_{j}')
pausa_activa[i, j] = solver.IntVar(0, 1, f'PausaActiva_{i}_{j}')
almuerza[i, j] = solver.IntVar(0, 1, f'Almuerza_{i}_{j}')
nada[i, j] = solver.IntVar(0, 1, f'Nada_{i}_{j}')
# Restricciones
for i in range(num_empleados):
# Restricciรณn de mรญnimo 1 hora de trabajo continuo
for j in range(num_franjas - 3):
solver.Add(trabaja[i, j] + trabaja[i, j + 1] + trabaja[i, j + 2] + trabaja[i, j + 3] >= 1)
# Restricciรณn de mรกximo 2 horas de trabajo continuo
for j in range(num_franjas - 8):
solver.Add(trabaja[i, j] + trabaja[i, j + 1] + trabaja[i, j + 2] + trabaja[i, j + 3] +
trabaja[i, j + 4] + trabaja[i, j + 5] + trabaja[i, j + 6] + trabaja[i, j + 7] <= 2)
# Restricciรณn de almuerzo de 1 hora y media
for j in range(num_franjas - 4):
solver.Add(almuerza[i, j] + almuerza[i, j + 1] + almuerza[i, j + 2] + almuerza[i, j + 3] +
almuerza[i, j + 4] == 1)
# Restricciรณn de hora mรญnima y mรกxima para almuerzo
solver.Add(almuerza[i, 6] + almuerza[i, 7] + almuerza[i, 8] == 1)
solver.Add(almuerza[i, 11] + almuerza[i, 12] + almuerza[i, 13] == 1)
solver.Add(almuerza[i, 14] + almuerza[i, 15] + almuerza[i, 16] == 1)
# Jornada laboral de 8 horas
solver.Add(sum(trabaja[i, j] for j in range(num_franjas)) == 8)
# Estado Nada al inicio y final del dรญa
solver.Add(nada[i, 0] == 1)
solver.Add(nada[i, num_franjas - 1] == 1)
# รltimo estado debe ser Trabaja
solver.Add(trabaja[i, num_franjas - 1] == 1)
# Debe haber al menos 1 empleado trabajando en cada franja horaria
solver.Add(sum(trabaja[i, j] for i in range(num_empleados)) >= 1)
# Cualquier franja de trabajo debe durar entre 1 y 2 horas
for j in range(num_franjas - 1):
solver.Add(trabaja[i, j] + trabaja[i, j + 1] <= 1)
# Funciรณn objetivo
solver.Minimize(solver.Sum(demanda.iloc[j]["Clientes"] - sum(trabaja[i, j] for i in range(num_empleados))
for j in range(num_franjas)))
# Resolver el modelo
solver.Solve()
# Obtener resultados
horario_optimo = pd.DataFrame(columns=["Empleado", "Franja", "Estado"])
for i in range(num_empleados):
for j in range(num_franjas):
if trabaja[i, j].solution_value() == 1:
estado = "Trabaja"
elif pausa_activa[i, j].solution_value() == 1:
estado = "Pausa Activa"
elif almuerza[i, j].solution_value() == 1:
estado = "Almuerza"
else:
estado = "Nada"
horario_optimo = horario_optimo.append({"Empleado": f"E{i+1}", "Franja": j, "Estado": estado}, ignore_index=True)
# Guardar resultados en un archivo CSV
horario_optimo.to_csv("horario_optimo_parte1.csv", index=False)
|
package homework;
import homework.homework12.PasswordValidator;
import homework.homework12.WrongLoginException;
import homework.homework12.WrongPasswordException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class HomeworkTwelve {
public static void main(String[] args) {
/*
ะะฐะดะฐัะฐ 1:
ะกะพะทะดะฐัั ะบะปะฐัั, ะฒ ะบะพัะพัะพะผ ะฑัะดะตั ััะฐัะธัะตัะบะธะน ะผะตัะพะด. ะญัะพั ะผะตัะพะด ะฟัะธะฝะธะผะฐะตั ะฝะฐ ะฒั
ะพะด ััะธ
ะฟะฐัะฐะผะตััะฐ: login, password, confirmPassword. ะัะต ะฟะพะปั ะธะผะตัั ัะธะฟ ะดะฐะฝะฝัั
String. ะะปะธะฝะฐ
login ะดะพะปะถะฝะฐ ะฑััั ะผะตะฝััะต 20 ัะธะผะฒะพะปะพะฒ ะธ ะฝะต ะดะพะปะถะตะฝ ัะพะดะตัะถะฐัั ะฟัะพะฑะตะปั. ะัะปะธ login ะฝะต
ัะพะพัะฒะตัััะฒัะตั ััะธะผ ััะตะฑะพะฒะฐะฝะธัะผ, ะฝะตะพะฑั
ะพะดะธะผะพ ะฒัะฑัะพัะธัั WrongLoginException. ะะปะธะฝะฐ
password ะดะพะปะถะฝะฐ ะฑััั ะผะตะฝััะต 20 ัะธะผะฒะพะปะพะฒ, ะฝะต ะดะพะปะถะตะฝ ัะพะดะตัะถะฐัั ะฟัะพะฑะตะปะพะผ ะธ ะดะพะปะถะตะฝ
ัะพะดะตัะถะฐัั ั
ะพัั ะฑั ะพะดะฝั ัะธััั. ะขะฐะบะถะต password ะธ confirmPassword ะดะพะปะถะฝั ะฑััั ัะฐะฒะฝั.
ะัะปะธ password ะฝะต ัะพะพัะฒะตัััะฒัะตั ััะธะผ ััะตะฑะพะฒะฐะฝะธัะผ, ะฝะตะพะฑั
ะพะดะธะผะพ ะฒัะฑัะพัะธัั
WrongPasswordException. WrongPasswordException ะธ WrongLoginException -
ะฟะพะปัะทะพะฒะฐัะตะปััะบะธะต ะบะปะฐััั ะธัะบะปััะตะฝะธั ั ะดะฒัะผั ะบะพะฝััััะบัะพัะฐะผะธ โ ะพะดะธะฝ ะฟะพ ัะผะพะปัะฐะฝะธั,
ะฒัะพัะพะน ะฟัะธะฝะธะผะฐะตั ัะพะพะฑัะตะฝะธะต ะธัะบะปััะตะฝะธั ะธ ะฟะตัะตะดะฐะตั ะตะณะพ ะฒ ะบะพะฝััััะบัะพั ะบะปะฐััะฐ Exception.
ะะตัะพะด ะฒะพะทะฒัะฐัะฐะตั true, ะตัะปะธ ะทะฝะฐัะตะฝะธั ะฒะตัะฝั, false ะฒ ะฟัะพัะธะฒะฝะพะผ ัะปััะฐะต.
*/
System.out.println(PasswordValidator.isValid("lo gin", "password2", "password2"));
System.out.println(PasswordValidator.isValid("login", "password2", "word"));
System.out.println(PasswordValidator.isValid("login", "password6", "password6"));
/*
ะะฐะดะฐัะฐ *:
ะะฐะฟะธัะฐัั try/catch/finally, ะฒ ะบะพัะพัะพะผ finally ะฒัะทะฒะฐะฝ ะฝะต ะฑัะดะตั.
*/
//1-ัะน ัะฟะพัะพะฑ - ะทะฐะฒะตััะธัั ัะฐะฑะพัั JVM
try {
System.exit(1);
} finally {
System.out.println("FINALLY");
}
//2-ะพะน ัะฟะพัะพะฑ - ะฟัะธะฒะตััะธ ะฟัะธะปะพะถะตะฝะธะต ะบ ะพัะธะฑะบะต, ะฝะฐะฟัะธะผะตั, OutOfMemory.
List<Long> longList = new ArrayList<>();
Random random = new Random();
try {
while(true){
longList.add(random.nextLong());
}
}finally {
System.out.println("FINALLY");
}
}
}
|
# 2022.11.14 ๆ่ฝฌ๏ผUI็ณป็ป็ๅธๅฑๅImageๆงไปถ
## ๅๅ
ๆฐ่กจ็คบไปไน
ๅๅ
ๆฐๆฏไธ็งๆ่ฝฌ็่กจ็คบๆนๆณ
## ๅฆไฝๆฒฟไธ็ๅๆ ่ฝดๆ่ฝฌ
```
// ๅฐๆจชๅ่พๅ
ฅ่ฝฌๅไธบๅทฆๅณๆ่ฝฌ๏ผๅฐ็บตๅ่พๅ
ฅ่ฝฌๅไธบไฟฏไปฐๆ่ฝฌ๏ผๅพๅฐไธไธชๅพๅฐ็ๆ่ฝฌๅๅ
ๆฐ
Quaternion smallRotate = Quaternion.Euler(v, h, 0);
transform.rotation = smallRotate * transform.rotation;
```
## ๅฆไฝๆฒฟๅฑ้จๅๆ ่ฝดๆ่ฝฌ
```
transform.rotation = transform.rotation * smallRotate;
```
## UI็ณป็ปๆฏไปไน
UI็ณป็ปๆฏๅบ็จไธ็จๆทไบคไบ็็ชๅฃ,็ฑCanvasไปฅๅๅ็งUI็ปไปถ็ปๆ
## ่ฐไธไธไฝ ๅฏนUI็ณป็ปๅธๅฑ็็่งฃ
### Pivotๆฏไปไน
Pivotๆฏ็ฉไฝ็ไธญๅฟ็น๏ผๅฝ็ฉไฝๆ่ฝฌๆถไผๅด็ป็ไธญๅฟ็นๆ่ฝฌ
### Anchor Presets่กจ็คบไปไน
Anchor Presetsๆฏไธไธชๅฏ่ช่ก่ฎพ็ฝฎ็ๅบๅฎ็น๏ผไฝ็จๆฏๅฝ็ถ็ฉไฝๆๅจ๏ผๅๆขๆถ๏ผ่ฏฅ็ฉไฝไผ็ธๅฏนไบ้็นๅ็ธๅบ็่ฟๅจ๏ผๅฏไปฅ่ฟ่กๆงๅถ็ผฉๆพๅUI็ๅฏน้ฝๆนๅผ
## Image็ๅกซๅ
ๅจ็ปๅฆไฝๅฎ็ฐ
```
void Start(){
// ๅฐๅพ็็ฑปๅๆนไธบFilled๏ผ360ๅบฆๅกซๅ
๏ผๆนไพฟๅถไฝๆ่ฝฌๅจ็ป
image.type = Image.Type.Filled;
image.fillMethod = Image.FillMethod.Radial360;
}
void Update(){
// ๅถไฝไธไธชๆ่ฝฌๆพ็คบ็ๅจ็ปๆๆ๏ผ็ด็บฟๆๆไนๆฏ็ฑปไผผ็
// ๅๅผๅจ0~1ไน้ด
image.fillAmount = fillAmount;
fillAmount += 0.02f;
if (fillAmount > 1){
fillAmount = 0;
}
}
```
# ่ฏพๅ ็ปไน
## ๆฒฟไธ็ๅๆ ่ฝดๆ่ฝฌ
```
// ๅฐๆจชๅ่พๅ
ฅ่ฝฌๅไธบๅทฆๅณๆ่ฝฌ๏ผๅฐ็บตๅ่พๅ
ฅ่ฝฌๅไธบไฟฏไปฐๆ่ฝฌ๏ผๅพๅฐไธไธชๅพๅฐ็ๆ่ฝฌๅๅ
ๆฐ
transform.rotation = smallRotate * transform.rotation;
```
## ๆฒฟๅฑ้จๅๆ ่ฝดๆ่ฝฌ
```
transform.rotation = transform.rotation * smallRotate;
```
## ๅฉ็จๆๅผๅฎ็ฐๆ่ฝฌๅจๆๅฉ็จๆๅผๅฎ็ฐๆ่ฝฌๅจๆ
```
rotationObj.transform.rotation = Quaternion.Slerp(rotationObj.transform.rotation, Quaternion.LookRotation(d - s), Time.deltaTime * 0.2f);
```
## ๆไฝImage็ปไปถๅฎ็ฐๅจ็ปๅกซๅ
ๆๆๆไฝImage็ปไปถๅฎ็ฐๅจ็ปๅกซๅ
ๆๆ
```
void Start(){
// ๅฐๅพ็็ฑปๅๆนไธบFilled๏ผ360ๅบฆๅกซๅ
๏ผๆนไพฟๅถไฝๆ่ฝฌๅจ็ป
image.type = Image.Type.Filled;
image.fillMethod = Image.FillMethod.Radial360;
}
void Update(){
// ๅถไฝไธไธชๆ่ฝฌๆพ็คบ็ๅจ็ปๆๆ๏ผ็ด็บฟๆๆไนๆฏ็ฑปไผผ็
// ๅๅผๅจ0~1ไน้ด
image.fillAmount = fillAmount;
fillAmount += 0.02f;
if (fillAmount > 1){
fillAmount = 0;
}
}
```
|
import { useContext, useState, useEffect } from "react";
import { SocketContext } from "../utils/contexts/SocketContext";
import { UserContext } from "../utils/contexts/UserContext";
import { Box, Typography, LinearProgress, useMediaQuery, Theme } from "@mui/material";
import { calculateLevel } from "../utils/helpers";
import { th } from "date-fns/locale";
export const XPDisplay = () => {
const { loading, loadedSiteVer, setLoadedSiteVer, counter, setCounter } = useContext(UserContext);
const socket = useContext(SocketContext);
const [xp, setXP] = useState<any>(0);
useEffect(() => {
socket.on(`xp`, function(data) {
if(counter) {setXP(prevXP => {return parseInt(prevXP) + parseInt(data)})}
});
return (() => {
socket.off('xp');
});
}, [loading])
useEffect(() => {
if(counter) {setXP(counter.xp)}
}, [loading])
const isDesktop = useMediaQuery((theme: Theme) => theme.breakpoints.up('lg'))
return (
isDesktop ?
<Box style={{ marginLeft: '8px', width: '100px' }}>
<Typography variant="body1">LVL {calculateLevel(xp).level}</Typography>
<LinearProgress variant="determinate" color='secondary' title={`${xp.toString()} / ${calculateLevel(xp).xpRequired}`} value={((xp - calculateLevel(xp).minXP) / (calculateLevel(xp).xpRequired - calculateLevel(xp).minXP)) * 100} sx={{borderRadius: '10px'}} />
<Typography sx={{fontSize: '9px', mt: 0.5}}>{`${parseInt(xp).toLocaleString()} / ${calculateLevel(xp).xpRequired.toLocaleString()}`}</Typography>
</Box>
:
<Box style={{ marginLeft: '3px' }}>
<Typography variant="body1">LVL {calculateLevel(xp).level}</Typography>
<LinearProgress variant="determinate" color='secondary' title={`${xp.toString()} / ${calculateLevel(xp).xpRequired}`} value={((xp - calculateLevel(xp).minXP) / (calculateLevel(xp).xpRequired - calculateLevel(xp).minXP)) * 100} sx={{borderRadius: '10px'}} />
<Typography sx={{fontSize: '9px', mt: 0.5}}>{`${parseInt(xp).toLocaleString()} / ${calculateLevel(xp).xpRequired.toLocaleString()}`}</Typography>
</Box>
)
}
|
package com.example.banks;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.*;
@Entity
@Table(name = "compte")
public class Compte {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String iban;
@Column(name = "decouverautorise")
private boolean decouverteAutorise;
private Double montantdecouvert;
private double solde;
@ManyToOne
@JoinColumn(name = "client_id")
private Client client;
public Compte() {
}
public Compte(String iban, boolean decouverteAutorise, double solde, Client client) {
this.iban = iban;
this.decouverteAutorise = decouverteAutorise;
this.solde = solde;
this.client = client;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIban() {
return iban;
}
public double getMontantdecouvert() {
return montantdecouvert;
}
public void setMontantdecouvert(Double montantdecouvert) {
this.montantdecouvert = montantdecouvert;
}
public void setIban(String iban) {
this.iban = iban;
}
public boolean isDecouverteAutorise() {
return decouverteAutorise;
}
public void setDecouverteAutorise(boolean decouverteAutorise) {
this.decouverteAutorise = decouverteAutorise;
}
public double getSolde() {
return solde;
}
public void setSolde(double solde) {
this.solde = solde;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
}
|
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group([
'prefix' => 'v1'
], function(){
Route::resource(
'convenios',
'ConveniosController',
[
'only' => ['index'],
]
);
Route::resource(
'instituicoes',
'InstituicoesController',
[
'only' => ['index'],
]
);
Route::resource(
'simulacoes',
'SimulacoesController',
[
'only' => ['store'],
]
);
});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
|
<mat-card>
<mat-card-header>
<mat-card-title>ะกัะฐะฒะฝะธ ััััะพะนััะฒะฐ</mat-card-title>
<button mat-stroked-button (click)="clearDevices()" [disabled]="!(firstDevice && secondDevice)">ะะทัะธััะธ</button>
</mat-card-header>
<mat-card-content>
<div class="grid-container" *ngIf="!showDifferences">
<div class="grid-col padding-right">
<app-select-device [device]="firstDevice!"
[devices]="devicesToChoose"
(deviceSelect)="onSelectDevice($event, 1)"></app-select-device>
</div>
<div class="grid-col padding-left">
<app-select-device [device]="secondDevice!"
[devices]="devicesToChoose"
(deviceSelect)="onSelectDevice($event, 2)"></app-select-device>
</div>
</div>
<table mat-table [dataSource]="dataSource" *ngIf="showDifferences && firstDevice && secondDevice">
<ng-container matColumnDef="criteria">
<th mat-header-cell *matHeaderCellDef> ะัะธัะตัะธะธ </th>
<td mat-cell *matCellDef="let element" [matTooltip]="element.tip"> {{element.criteria}} </td>
</ng-container>
<ng-container [matColumnDef]="firstDevice.name">
<th mat-header-cell *matHeaderCellDef [class]="firstDeviceHighlight!.length > secondDeviceHighlight!.length ? 'highlight': ''"> {{firstDevice.name}} </th>
<td mat-cell *matCellDef="let element" [class]="firstDeviceHighlight?.includes(element.objectKey) ? 'highlight' : ''">
<app-energy-class-color *ngIf="element.objectKey === 'energyEfficiency'" [energyClass]="element.firstDeviceValue" [showLabel]="true"></app-energy-class-color>
<span *ngIf="element.objectKey !== 'energyEfficiency'">{{element.firstDeviceValue}}</span>
</td>
</ng-container>
<ng-container [matColumnDef]="secondDevice.name">
<th mat-header-cell *matHeaderCellDef [class]="secondDeviceHighlight!.length > firstDeviceHighlight!.length ? 'highlight': ''"> {{secondDevice.name}} </th>
<td mat-cell *matCellDef="let element" [class]="secondDeviceHighlight?.includes(element.objectKey) ? 'highlight' : ''">
<app-energy-class-color *ngIf="element.objectKey === 'energyEfficiency'" [energyClass]="element.secondDeviceValue" [showLabel]="true"></app-energy-class-color>
<span *ngIf="element.objectKey !== 'energyEfficiency'">{{element.secondDeviceValue}}</span>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</mat-card-content>
</mat-card>
|
import './App.css';
import Navbar from './components/Navbar'
import Home from './components/Home'
import About from './components/About'
import Services from './components/Services'
import Contact from './components/Contact'
import Footer from './components/Footer'
import { Route, Routes } from 'react-router-dom';
import Login from './components/Login';
import Register from './components/Register';
import Dashboard from './components/Dashboard';
function App() {
return (
<div className="App">
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/services" element={<Services />} />
<Route path="/contact" element={<Contact />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
<Footer />
</div>
);
}
export default App;
|
package entity
import (
"os"
"github.com/forest33/tapir/pkg/structs"
)
// UI response statuses
const (
debugEnv = "TAPIR_DEBUG"
)
// GUIResponseStatus response status
type GUIResponseStatus string
// GUIRequest UI request
type GUIRequest struct {
Cmd GUICommand `json:"name"`
Payload interface{} `json:"payload"`
Error error `json:"error,omitempty"`
}
// GUIResponse UI response
type GUIResponse struct {
Payload interface{} `json:"payload,omitempty"`
Error string `json:"error,omitempty"`
}
// IsDebug returns true if application runs on debug mode
func IsDebug() bool {
return os.Getenv(debugEnv) != ""
}
type ConnectRequest struct {
ConnID int32 `json:"id"`
IsConnect bool `json:"connect"`
}
func (r *ConnectRequest) Model(payload map[string]interface{}) error {
if payload == nil {
return nil
}
if v, ok := payload["id"]; ok && v != nil {
r.ConnID = int32(v.(float64))
}
if v, ok := payload["connect"]; ok && v != nil {
r.IsConnect = v.(bool)
}
return nil
}
type UpdateConnectionRequest struct {
ConnID int32 `json:"id"`
Name string `json:"name"`
ServerHost string `json:"serverHost"`
PortMin uint16 `json:"portMin"`
PortMax uint16 `json:"portMax"`
UseTCP *bool `json:"useTCP"`
UseUDP *bool `json:"useUDP"`
Username string `json:"username"`
Password string `json:"password"`
}
func (r *UpdateConnectionRequest) Model(payload map[string]interface{}) error {
if payload == nil {
return nil
}
if v, ok := payload["id"]; ok && v != nil {
r.ConnID = int32(v.(float64))
}
if v, ok := payload["name"]; ok && v != nil {
r.Name = v.(string)
}
if v, ok := payload["serverHost"]; ok && v != nil {
r.ServerHost = v.(string)
}
if v, ok := payload["portMin"]; ok && v != nil {
r.PortMin = uint16(v.(float64))
}
if v, ok := payload["portMax"]; ok && v != nil {
r.PortMax = uint16(v.(float64))
}
if v, ok := payload["useTCP"]; ok && v != nil {
r.UseTCP = structs.Ref(v.(bool))
}
if v, ok := payload["useUDP"]; ok && v != nil {
r.UseUDP = structs.Ref(v.(bool))
}
if v, ok := payload["username"]; ok && v != nil {
r.Username = v.(string)
}
if v, ok := payload["password"]; ok && v != nil {
r.Password = v.(string)
}
return nil
}
type DeleteConnectionRequest struct {
ConnID int32 `json:"id"`
}
func (r *DeleteConnectionRequest) Model(payload map[string]interface{}) error {
if payload == nil {
return nil
}
if v, ok := payload["id"]; ok && v != nil {
r.ConnID = int32(v.(float64))
}
return nil
}
type ImportConnectionRequest struct {
File string `json:"file"`
}
func (r *ImportConnectionRequest) Model(payload map[string]interface{}) error {
if payload == nil {
return nil
}
if v, ok := payload["file"]; ok && v != nil {
r.File = v.(string)
}
return nil
}
|
import { Box, Divider, Select, Text } from "@chakra-ui/react";
import { Controller, useFormContext } from "react-hook-form";
import { IntentionForms } from "@/app/(wrapped)/intentions/saisie/intentionForm/defaultFormValues";
import { AutreMotifRefusField } from "./AutreMotifRefusField";
import { MotifRefusBlock } from "./MotifRefusBlock";
export const StatusBlock = ({ disabled }: { disabled: boolean }) => {
const { control } = useFormContext<IntentionForms>();
return (
<Box bg="white" p="6" mt="6" borderRadius={6}>
<Text fontSize={20} mb={4} fontWeight={700}>
Statut de la demande
</Text>
<Divider mb={4} />
<Controller
name="status"
control={control}
rules={{ required: "Le type de demande est obligatoire." }}
render={({ field: { onChange, name, value } }) => (
<Select w="xs" onChange={onChange} name={name} value={value}>
<option value="draft">Projet de demande</option>
<option value="submitted">Validรฉe</option>
<option value="refused">Refusรฉe</option>
</Select>
)}
/>
<MotifRefusBlock disabled={disabled} mb="6" mt={6} />
<AutreMotifRefusField disabled={disabled} mb="6" maxW="752px" />
</Box>
);
};
|
/* Universal Selector */
* {
font-family: Verdana, Geneva, Tahoma, sans-serif;
/* color:chocolate */
}
span {
background-color: aquamarine;
}
li {
background-color: red;
}
.listClass {
background-color: orange;
}
#listId {
background-color: yellow;
}
li[value="list"] {
background-color: green;
}
.listClass1, .listClass2 {
background-color: skyblue;
}
ul .listClass3 {
background-color: indigo;
color: white;
}
/* Pseudo-Classes */
.hoverBtn:hover {
background-color: black;
color: white;
cursor: pointer;
}
.activeBtn:active {
background-color: gray;
color: black;
}
.focusInput:focus {
background-color: skyblue;
border-width: 5px;
}
.visitedLink:visited {
color: red;
}
/* Pseudo Element */
.firstLetter::first-letter {
font-size: 2em;
}
.firstLine::first-line {
color: blue;
}
.beforeAndAfter::before {
/* can see it but can't selected; There are also some scenarios that you might want to protect the contents of your website and don't want them to copy and paste your content. Let's say sensitive data like recipe or personal details. Their purpose is for viewing only. */
content: "before $";
color: red;
}
.beforeAndAfter::after {
content: "after";
color: blue;
}
.selectParts::selection {
background-color: crimson;
}
/* Earlier Rule */
.cascade {
color: red !important;
}
/* Later Rule */
.cascade {
color: blue;
}
/* Box Model */
.boxModel {
background-color: white;
/* border-color: black;
border-width: 5px;
border-style: dashed; */
border: orchid 5px solid;
border-radius: 50px 5px;
border-style: solid dotted;
/* margin: 10px;
margin-bottom: 30px;
padding: 10px;
padding-left: 30px; */
/* 1 value = all sides
2 values = top & bottom, right & left
3 values = top, right & left , bottom
4 values = top, right, bottom, left*/
margin: 10px 20px 30px 40px;
padding: 20px 100px 10px;
}
|
import * as React from 'react';
import { useTheme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableFooter from '@mui/material/TableFooter';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import IconButton from '@mui/material/IconButton';
import FirstPageIcon from '@mui/icons-material/FirstPage';
import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight';
import LastPageIcon from '@mui/icons-material/LastPage';
import TableHead from '@mui/material/TableHead';
import { styled } from '@mui/material/styles';
import { useAppSelector, useAppDispatch } from "store/hooks";
import { createdReport } from "store/modules/report/selectors";
import { BsFillTrashFill, BsPencilFill } from "react-icons/bs";
import { deleteReportAPI } from 'hooks/reports';
import { getreporting } from "store/modules/report";
import AsyncLocalStorage from "@createnextapp/async-local-storage";
import { updatedReportAPI } from 'hooks/reports'
import {useFormik} from "formik";
import {UpdatedReport} from "../../store/modules/report/types";
import { Modal, Form, Container, Button} from 'react-bootstrap';
const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: theme.palette.common.white,
color: "#934036",
border: "1px solid #ab9c5b"
},
[`&.${tableCellClasses.body}`]: {
fontSize: 14,
border: "1px solid #ab9c5b"
},
}));
interface TablePaginationActionsProps {
count: number;
page: number;
rowsPerPage: number;
onPageChange: (
event: React.MouseEvent<HTMLButtonElement>,
newPage: number,
) => void;
}
function TablePaginationActions(props: TablePaginationActionsProps) {
const theme = useTheme();
const { count, page, rowsPerPage, onPageChange } = props;
const handleFirstPageButtonClick = (
event: React.MouseEvent<HTMLButtonElement>,
) => {
onPageChange(event, 0);
};
const handleBackButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onPageChange(event, page - 1);
};
const handleNextButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onPageChange(event, page + 1);
};
const handleLastPageButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
};
return (
<Box sx={{ flexShrink: 0, ml: 2.5 }}>
<IconButton
onClick={handleFirstPageButtonClick}
disabled={page === 0}
aria-label="first page"
>
{theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
</IconButton>
<IconButton
onClick={handleBackButtonClick}
disabled={page === 0}
aria-label="previous page"
>
{theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
</IconButton>
<IconButton
onClick={handleNextButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="next page"
>
{theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
</IconButton>
<IconButton
onClick={handleLastPageButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="last page"
>
{theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
</IconButton>
</Box>
);
}
function CustomPaginationActionsTable() {
const addedReport = useAppSelector(createdReport);
const dispatch = useAppDispatch();
const [page, setPage] = React.useState(0);
const [rowsPerPage, setRowsPerPage] = React.useState(5);
const [reportName, setReportName] = React.useState("");
const [show, setShow] = React.useState(false);
const [dataid, setDataid] = React.useState("");
const [datacontent, setDatacontent] = React.useState("");
// Avoid a layout jump when reaching the last page with empty rows.
const emptyRows =
page > 0 ? Math.max(0, (1 + page) * rowsPerPage - addedReport?.length) : 0;
const handleChangePage = (
event: React.MouseEvent<HTMLButtonElement> | null,
newPage: number,
) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (
event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const init = async () => {
const user = await AsyncLocalStorage.getItem("username");
setReportName(user);
return user
}
const handleDelete = async (_id: string) => {
await deleteReportAPI(_id).then((res:any) => {
init().then((username: string) =>
dispatch(getreporting(username))
);
})
};
const handleClose = () => setShow(false);
const handleShow = (data: any) => {setShow(true); setDataid(data._id); setDatacontent(data.content);}
console.log(datacontent)
const initialValues = {
_id: "",
content: "",
updatedAt: ""
}
console.log("newPoint")
const formik = useFormik({
initialValues,
onSubmit: (values, actions) => {
const d = new Date().toLocaleDateString();
values.updatedAt = d;
values._id = dataid;
updatedReportAPI(values).then((res:any) => {
init().then((username: string) =>
dispatch(getreporting(username))
);
});
actions.resetForm({ values: initialValues });
},
});
return (
<TableContainer component={Paper}>
<Table className='borderTable' sx={{ Width: 500 }} aria-label="custom pagination table" >
<TableHead>
<TableRow>
<StyledTableCell>Name</StyledTableCell>
<StyledTableCell align="center">Content</StyledTableCell>
<StyledTableCell align="center">Date</StyledTableCell>
<StyledTableCell align="center">Action</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{(rowsPerPage > 0
? addedReport.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
: addedReport
).map((row:any, key: any) => (
<TableRow key={key} style={{border: "1px solid #ab9c5b"}}>
<StyledTableCell component="th" scope="row">
{row?.name}
</StyledTableCell>
<StyledTableCell style={{ maxWidth: 120,whiteSpace: "nowrap",textOverflow: "ellipsis",overflow: "hidden" }} align="left">
{row?.content}
</StyledTableCell>
<StyledTableCell style={{ width: 160 }} align="left">
{row?.createdAt}
</StyledTableCell>
< StyledTableCell style={{ textAlign:"center"}}>
<BsFillTrashFill onClick={() => handleDelete(row?._id)} style={{color:"red"}}/>
<BsPencilFill onClick={() => handleShow(row)} style={{color:"blue"}}/>
</StyledTableCell>
</TableRow>
))}
{emptyRows > 0 && (
<TableRow style={{ height: 53 * emptyRows,border: "1px solid #ab9c5b" }}>
<StyledTableCell colSpan={6} />
</TableRow>
)}
</TableBody>
<TableFooter>
<TableRow style={{border: "1px solid #ab9c5b"}}>
<TablePagination
rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]}
colSpan={4}
count={addedReport?.length}
rowsPerPage={rowsPerPage}
page={page}
SelectProps={{
inputProps: {
'aria-label': 'rows per page',
},
native: true,
}}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
ActionsComponent={TablePaginationActions}
style={{border: "1px solid #ab9c5b"}}
/>
</TableRow>
</TableFooter>
<Modal show={show} onHide={handleClose}>
<Form onSubmit={formik.handleSubmit}>
<Modal.Header closeButton>
<Modal.Title>Overwrite</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form.Group
className="mb-3"
>
<Form.Label>Quickly!</Form.Label>
<Form.Control
as="textarea"
rows={3}
type="text"
name="content"
id="content"
defaultValue={datacontent}
onChange={formik.handleChange}
/>
</Form.Group>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button type="submit" variant="secondary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Form>
</Modal>
</Table>
</TableContainer>
);
}
export default CustomPaginationActionsTable;
|
import React, { useEffect, useState } from 'react'
import { NavLink, Link } from 'react-router-dom'
import { useAuth } from '../../context/auth'
import SearchInput from './SearchInput';
import axios from 'axios';
const Header = () => {
const [auth, setAuth] = useAuth();
const [categories, setCategories] = useState([])
const getAllCategories = async () => {
try {
const { data } = await axios.get('http://localhost:8080/api/v1/category/category');
console.log(data?.categories)
if (data?.categories) setCategories(data?.categories);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
getAllCategories();
console.log('helloww')
console.log(categories);
}, [])
// console.log(auth.user?.role);
const whichDashboard = (auth.user?.role) ? "/admin/dashboard" : "/dashboard"
const handleLogout = (e) => {
localStorage.clear();
setAuth({
user: null,
token: ""
})
}
return (
<>
<nav className="navbar navbar-expand-lg bg-body-tertiary">
<div className="container-fluid">
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon" />
</button>
<div className="collapse navbar-collapse" id="navbarTogglerDemo01">
<Link to="/" className="navbar-brand">
๐ Ecommerce App
</Link>
<ul className="navbar-nav ms-auto mb-2 mb-lg-0">
<li className="nav-item">
<SearchInput />
</li>
<li className="nav-item">
<NavLink to="/" className="nav-link ">
Home
</NavLink>
</li>
<li className="nav-item">
<li className="nav-item dropdown">
<NavLink
className="nav-link dropdown-toggle"
href="#"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Category
</NavLink>
<ul className="dropdown-menu">
<li>
<NavLink
onClick={handleLogout}
to="/category"
className="dropdown-item"
>
All Categories
</NavLink>
</li>
{
categories.map(c => {
const whereTo = `/category/${c.slug}`
return (
<li>
<NavLink to={whereTo} className="dropdown-item">
{c.slug}
</NavLink>
</li>
)
})
}
</ul>
</li>
</li>
{
(auth.user) ? (
<>
<li className="nav-item dropdown">
<NavLink
className="nav-link dropdown-toggle"
href="#"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
{auth?.user?.name}
</NavLink>
<ul className="dropdown-menu">
<li>
<NavLink to={whichDashboard} className="dropdown-item">
Dashboard
</NavLink>
</li>
<li>
<NavLink
onClick={handleLogout}
to="/login"
className="dropdown-item"
>
Logout
</NavLink>
</li>
</ul>
</li>
</>
)
: (
<>
<li className="nav-item">
<NavLink to="/register" className="nav-link">
Register
</NavLink>
</li>
<li className="nav-item">
<NavLink to="/login" className="nav-link">
Login
</NavLink>
</li>
</>
)
}
<li className="nav-item">
<NavLink to="/cart" className="nav-link">
Cart (0)
</NavLink>
</li>
</ul>
</div>
</div>
</nav>
</>
)
}
export default Header
|
import Router from 'next/router';
import { useEffect, useState } from 'react';
import StripeCheckout from 'react-stripe-checkout';
import useRequest from '../../hooks/use-request';
const OrderShow = ({ currentUser, order }) => {
const [timeLeft, setTimeLeft] = useState(0);
const { doRequest, errors } = useRequest({
url: '/api/payments',
method: 'post',
body: {
orderId: order.id
},
onSuccess: () => Router.push('/orders')
});
useEffect(() => {
const findTimeLeft = () => {
const msLeft = new Date(order.expiresAt) - new Date();
setTimeLeft(Math.round(msLeft / 1000));
};
findTimeLeft();
// reference to findTimeLeft instead of invoking it
const timerId = setInterval(findTimeLeft, 1000);
return () => {
clearInterval(timerId);
};
}, [])
if (timeLeft < 0) {
return <div>Order Expired</div>;
}
return (
<div>
Time left to pay: {timeLeft} seconds
<StripeCheckout
token={({ id }) => doRequest({ token: id })}
stripeKey="pk_test_51H3SXVFw1u5mmp7z93W8l003XQVtTJF2yWzEPzgsPda0D87RXLQAZgxeDeXsItPBWz4TXkkYvz0s9mYwxJ8HgNK800kW6YDVuY"
amount={order.ticket.price * 100}
email={currentUser.email}
/>
{errors}
</div>
);
};
OrderShow.getInitialProps = async (context, client) => {
const { orderId } = context.query;
const { data } = await client.get(`/api/orders/${orderId}`);
return { order: data };
};
export default OrderShow;
|
# Docker ้ๅไธ่ฝฝๅจ
[English](README.md) | ็ฎไฝไธญๆ
ไธไธช็จไบ็ผๅญ Docker ้ๅๆไปถ็ GitHub Actionใ
## ไฝฟ็จ
fork ๅนถ clone ๆฌไปๅบ๏ผๅนถๆ นๆฎ้่ฆไธ่ฝฝ็้ๅๅ็งฐๅๅปบ git tag๏ผGitHub Action ๅฐไผๆ้ๅๆไปถ `image.tar` ๅญๅจๅจ Artifacts ไธญใ
ๆณจๆ๏ผ
- ๅ ไธบ git tag ไธญไธ่ฝๆ `:`๏ผๅ ๆญคไฝ ้่ฆไฝฟ็จ `--` ๆฅไปฃๆฟ้ๅๅ็งฐไธญ็ `:`ใ
- ๅทฅไฝๆต้ป่ฎคไฝฟ็จ `linux/amd64` ๅนณๅฐ๏ผๅฆๆไฝ ๆณ่ฆ `linux/arm64` ็้ๅ๏ผๅฏไปฅๅจๆ ็ญพๅไธญๆทปๅ ๅ็ผ `-arm64`ใ
- ้ป่ฎคๆ
ๅตไธ๏ผGitHub Action ๅจ fork ไปๅบ้ๆฏๆชๅฏ็จ็๏ผๅ ๆญคไฝ ๅฏ่ฝ้่ฆๆๅจๅฏ็จๅฎใ่ฏทๅ้
[ๆๆกฃ](https://docs.github.com/en/actions/using-workflows/disabling-and-enabling-a-workflow?tool=webui#enabling-a-workflow)ใ
็ฐๅจๅ่ฎพไฝ ่ฆไธ่ฝฝ Docker ้ๅ `testcontainers/ryuk:0.5.1`๏ผ้ฃไนไฝ ๅบ่ฏฅๅจ้กน็ฎ็ฎๅฝๆง่กไปฅไธๅฝไปค๏ผ
```shell
# 'testcontainers/ryuk--0.5.1' ไปฃ่กจ้ๅ 'testcontainers/ryuk:0.5.1'
git tag testcontainers/ryuk--0.5.1
git push origin --tags
```
tag ๆจ้ๅๅฐ่ชๅจ่งฆๅ GitHub Action๏ผไฝ ๅฏไปฅ่ฟๅ
ฅไฝ ็ fork ไปๅบ็ [actions](https://github.com/whhe/docker-images-downloader/actions) ้กต้ข๏ผๅจๆๆฐ็ workflow ้กต้ขๆฅ็ๆง่ก่ฏฆๆ
ใ
GitHub Action ็ workflow ๅฎๆๅ๏ผๆจๅฏไปฅไป Artifacts ้จๅไธ่ฝฝ้ๅๆไปถ๏ผ็ถๅ้่ฟไปฅไธๅฝไปคๅ ่ฝฝ Docker ้ๅ๏ผ
```shell
unzip image.zip
docker load -i image.tar
```
## ่ฎธๅฏ่ฏ
่ฏทๅ้
[LICENSE](LICENSE)ใ
|
import { OnInit } from '@angular/core';
import { Component, Input } from '@angular/core';
import { Post } from '../post.model';
import { PostService } from '../post.service';
import { Subscription } from 'rxjs';
import { OnDestroy } from '@angular/core';
import { PageEvent } from '@angular/material/paginator';
import { Authservice } from 'src/app/auth/auth.service';
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css']
})
export class PostListComponent implements OnInit, OnDestroy {
// posts = [
// {title : 'First Post' , content : 'First post Content'},
// {title : 'Second Post' , content : 'Second post Content'},
// {title : 'Third Post' , content : 'Third post Content'}
// ]
private subscription : Subscription;
isLoading = false;
posts: Post[] = [];
totalPost = 0;
postPerPage = 2;
currentPage = 1;
pageSizeOptions = [1,2,5,10];
private authSub : Subscription;
userIsAuthenticated = false;
userId : string;
constructor(public postService: PostService , private authService : Authservice) {}
ngOnInit() {
this.isLoading = true;
this.postService.getPost(this.postPerPage,this.currentPage);
this.userId = this.authService.getUserId();
this.subscription = this.postService.getPostUpdated().subscribe(( postData: {posts:Post[],postCount : number}) => {
this.isLoading = false;
this.totalPost = postData.postCount;
this.posts = postData.posts;
});
this.userIsAuthenticated = this.authService.getIsAuth();
this.authSub = this.authService.getAuthStatusListener().subscribe(isAuthenticated => {
this.userIsAuthenticated = isAuthenticated;
this.userId = this.authService.getUserId();
});
}
onChangedPage(pageData : PageEvent){
this.isLoading = true;
this.currentPage = pageData.pageIndex + 1;
this.postPerPage = pageData.pageSize;
this.postService.getPost(this.postPerPage,this.currentPage);
}
onDelete(postId : string){
this.postService.onDeletePost(postId).subscribe(()=>{
this.postService.getPost(this.postPerPage,this.currentPage);
},() => {
this.isLoading = false;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
this.authSub.unsubscribe();
}
}
|
from enum import Enum
from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
class Item(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
# fastapi dev tutorial.py
# Path Parametersยถ
#@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id": item_id}
# Path parameters with typesยถ
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
# Order matters
@app.get("/users/me")
async def read_user_me():
return {"user_id": "the current user"}
@app.get("/users/{user_id}")
async def read_user(user_id: str):
return {"user_id": user_id}
@app.get("/users")
async def read_users():
return ["Rick", "Morty"]
@app.get("/users")
async def read_users2():
return ["Bean", "Elfo"]
"""
Order matters for route `/users`
The first one will always be used since the path matches first.
"""
# Predefined values
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
# Compare enumeration membersยถ
if model_name is ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
# Get the enumeration value
if model_name.value == "lenet":
return {"model_name": model_name, "message": "LeCNN all the images"}
# Return enumeration members
return {"model_name": model_name, "message": "Have some residuals"}
# Query Parameters
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]
"""
http://127.0.0.1:8000/items/?skip=0&limit=10
"""
# Optional parameters
#@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
"http://127.0.0.1:8000/items/foo?q=1"
# Query parameter type conversion
#@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = None, short: bool = False):
item = {"item_id": item_id}
if q:
item.update({"q": q})
if not short:
item.update(
{"description": "This is an amazing item that has a long description"}
)
return item
"""
http://127.0.0.1:8000/items/foo?short=1
http://127.0.0.1:8000/items/foo?short=True
http://127.0.0.1:8000/items/foo?short=true
"""
# Request Body
#@app.post("/items/")
async def create_item(item: Item):
return item
# Use the model
"""
Inside of the function, you can access all the attributes of the model object directly:
"""
@app.post("/items/")
async def create_item(item: Item):
item_dict = item.dict()
if item.tax:
price_with_tax = item.price + item.tax
item_dict.update({"price_with_tax": price_with_tax})
return item_dict
# Request body + path parameters
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}
|
from __future__ import absolute_import
import pytest
from mock import patch, MagicMock
import os
from scanomatic.server.analysis_effector import AnalysisEffector
from scanomatic.models.factories.rpc_job_factory import RPC_Job_Model_Factory
from scanomatic.models.rpc_job_models import JOB_TYPE, JOB_STATUS
from scanomatic.models.factories.analysis_factories import AnalysisModelFactory
from scanomatic.models.analysis_model import DEFAULT_PINNING_FORMAT
from tests.factories import make_calibration
@pytest.fixture
def calibrationstore():
return MagicMock()
@pytest.fixture(autouse=True)
def store_from_env(calibrationstore):
calibrationstore.get_all_calibrations.return_value = [
make_calibration(identifier='default', active=True),
]
calibrationstore.get_calibration_by_id.return_value = (
make_calibration(active=True)
)
with patch(
'scanomatic.models.factories.analysis_factories.store_from_env',
) as store_from_env:
store_from_env.return_value.__enter__.return_value = calibrationstore
yield
@pytest.fixture
def analysis_job():
content_model = AnalysisModelFactory.create(
compilation='fake.project.instructions',
)
return RPC_Job_Model_Factory.create(
id='test',
type=JOB_TYPE.Analysis,
status=JOB_STATUS.Running,
content_model=content_model
)
@pytest.fixture
def analysis_effector(analysis_job):
return AnalysisEffector(analysis_job)
@patch.object(AnalysisModelFactory, 'validate', return_value=True)
def test_setup_can_execute(mock, analysis_effector):
analysis_effector.setup(analysis_effector._job)
assert analysis_effector._allow_start is True
@patch(
"scanomatic.io.first_pass_results.CompilationResults",
return_value=MagicMock(plates=[1, 2, 3]),
)
@patch(
"scanomatic.image_analysis.analysis_image.ProjectImage",
return_value=MagicMock(set_grid=lambda: True),
)
@patch.object(AnalysisModelFactory.serializer, "dump")
@patch.object(os, "makedirs")
def test_first_iteration_sets_pinning_formats(
compilation_results_mock,
project_image_mock, serializer_dump,
mkdirs_mock, analysis_effector,
):
analysis_effector.setup(analysis_effector._job, save_log=False)
with patch.object(
analysis_effector, "_remove_files_from_previous_analysis"
) as remove_files_mock:
analysis_effector._setup_first_iteration()
serializer_dump.assert_called()
mkdirs_mock.assert_called()
remove_files_mock.assert_called()
compilation_results_mock.assert_called()
project_image_mock.assert_called()
pinnings = analysis_effector._analysis_job.pinning_matrices
assert pinnings == [DEFAULT_PINNING_FORMAT] * 3
def test_set_default_pinning_formats(analysis_effector):
analysis_effector.setup_pinning(13)
pinnings = analysis_effector._analysis_job.pinning_matrices
assert pinnings == [DEFAULT_PINNING_FORMAT] * 13
|
import styles from "./burger-ingredient.module.css";
import { useEffect } from 'react';
import { useDispatch, useSelector } from "react-redux";
import PropTypes from "prop-types";
import Tabs from './tabs';
import Article from "./article";
import ItemList from "./item-list";
import { SET_CURRENT_TAB_ONE, SET_CURRENT_TAB_TWO, SET_CURRENT_TAB_THREE } from '../../services/actions/tab';
import { SET_CLOSE } from '../../services/actions/modal';
import { DELETE_INGREDIENT_DETAILS } from '../../services/actions/ingredient-details';
import Modal from "./modal";
import { IngredientDetails } from "./ingridient-details";
export default function BurgerIngredients() {
const currentIngredient = useSelector(
(store) => store.setIngredientDetailsReducer.ingredient
);
const dispatch = useDispatch();
const closeModal = () => {
dispatch({type: DELETE_INGREDIENT_DETAILS})
dispatch({type: SET_CLOSE})
}
useEffect(()=> {
const container = document.querySelector('.custom-scroll');
container.addEventListener('scroll', ()=>{
if(container.scrollTop <= 300) {
dispatch({type: SET_CURRENT_TAB_ONE})
} else if(container.scrollTop > 300 && container.scrollTop <= 800) {
dispatch({type: SET_CURRENT_TAB_TWO})
} else if(container.scrollTop > 800) {
dispatch({type: SET_CURRENT_TAB_THREE})
}
})
},[])
return (
<section className={styles.sectionBurgerIngredients}>
<h1 className="text text_type_main-large">ะกะพะฑะตัะธัะต ะฑััะณะตั </h1>
<Tabs />
<div className={`${styles.ingredientsWrapper} custom-scroll`}>
<Article text={"ะัะปะบะธ"}>
<ItemList type="bun" />
</Article>
<Article text={"ะกะพััั"}>
<ItemList type="sauce" />
</Article>
<Article text={"ะะฐัะธะฝะบะธ"}>
<ItemList type="main" />
</Article>
<>
{currentIngredient && (
<Modal onClose = {closeModal}>
<IngredientDetails />
</Modal>
)}
</>
</div>
</section>
);
}
BurgerIngredients.propTypes = {
children: PropTypes.any
};
|
import React from "react";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import createSagaMiddleware from "redux-saga";
import AppWithNavigationState, { middleware } from "./src/containers/AppNavigator";
import rootReducer from "./src/reducers/index";
import {productWatchers} from "./src/sagas/product";
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
rootReducer,
{
productState: {
products: [],
product: {},
isLoading: false,
isRefreshing: false,
filteredAllProducts: [],
page: 1,
limit:40
},
storeState: { stores: [], isLoading: false }
},
applyMiddleware(middleware, sagaMiddleware)
);
sagaMiddleware.run(productWatchers);
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<AppWithNavigationState />
</Provider>
);
}
}
|
"""MNIST-INRs model."""
import torch
from torch import nn
from models import base_model
class CrossEntropyLoss(nn.Module):
def __init__(self, config):
super().__init__()
self._ce_loss = torch.nn.CrossEntropyLoss()
def forward(self, target, prediction):
loss = self._ce_loss(prediction, target)
return loss.mean()
class MnistInrClassificationModel(base_model.BaseModel):
"""MNIST model class."""
def __init__(self, config, network, init_step, device):
super().__init__(config, network, init_step, device)
# Losses.
loss_config = self._config['loss_functions']
if loss_config['loss_name'] == 'cross_entropy':
self._loss_fn = CrossEntropyLoss(loss_config)
else:
raise ValueError('Only cross_entropy is supported.')
self._network_name = config['network']['network_name']
self._device = device
def model_outputs(self, inputs):
outputs = self._network(inputs)
return outputs
def compute_loss(self, inputs, outputs):
"""Calculate losses."""
loss = self._loss_fn(inputs.label, outputs)
return loss
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.