text stringlengths 184 4.48M |
|---|
#pragma once
#include "define.h"
#include <stdlib.h>
#include <atomic>
#include <cstdio>
#include <new>
#ifdef TASK_COROUTINE_DEBUG
#include <thread>
#endif
#include "task_context.h"
namespace task_coroutine {
#ifdef TASK_COROUTINE_DEBUG
extern std::atomic<size_t> g_task_meta_created_count;
extern std::atomic<size_t> g_task_meta_destroy_count;
#endif
// 关键问题
// 1. 哪些地方会使task_meta运行时的task_group发生变化?
// task_meta运行时被换出,重新被调度到的时候,第一次运行时的task_group和第二次的task_group可能不同
// 如果task_meta的栈上保存了tls_task_group变量,则需要刷新一下
//
// 2. task_meta的回收点?
// (1)运行task结束
// (2)从换出点切回
// (3)reschedule进入到run_main_task
// TODO:
// 1. 优化栈分配,懒加载
// TaskMeta
// 生命周期由与其关联的coroutine和将其执行完成的task_group共同管理,原因:
// 1. coroutine join时需要task_meta存在,在coroutine未析构时,task_meta不能析构
// 2. coroutine析构时,task_meta未必执行,需要task_group来析构
// 析构时机:
// 1. task_meta析构必须是已经完成并且task_group切换到其他task_meta时
// 2. 关联的coroutine已经析构,则task_group执行下一个task_meta时执行析构
// 3. task_group执行完该task_meta,开始执行下一个task_meta后,关联的coroutine析构/join时将其析构
struct TaskMeta {
void* (*fn)(void*);
void* arg;
void* stack;
void* memory;
std::atomic<size_t> state;
// state 3位bit表示
// 100 完成fn(arg)
// 010 所属Coroutine调用析构
// 001 完成该task_meta的task_group调度下一个task
// 所属Coroutine join的条件为 state & 0x04
// 销毁的条件为所属Coroutine析构 && 运行其的task_group调度下一个task,即 state
// & 0x03 == 0x03
#ifdef TASK_COROUTINE_DEBUG
size_t id;
static constexpr size_t state_had_destory = 1 << 4;
static constexpr size_t state_start_run = 1 << 3;
#endif
static constexpr size_t state_fn_done = 1 << 2;
static constexpr size_t state_coroutine_destructor = 1 << 1;
static constexpr size_t state_task_group_sched_next_one = 1;
TaskMeta(void* (*fn_)(void*), void* arg_, void* stack_, void* memory_)
: fn(fn_), arg(arg_), stack(stack_), memory(memory_), state(0) {}
TaskMeta(const TaskMeta&) = delete;
TaskMeta& operator=(const TaskMeta&) = delete;
~TaskMeta() { free(memory); }
// run 运行函数
void run() {
fn(arg);
// TODO: 添加memory_order
state.fetch_or(state_fn_done);
}
// main_task 创建主函数的task
static TaskMeta* main_task() {
return new (std::nothrow) TaskMeta{nullptr, nullptr, nullptr, nullptr};
}
// new_task 创建任务
// 参数:fn是运行函数,arg是函数参数,jump_fn是jump_fcontext时跳转的函数
// 返回值:使用null方法判空
static TaskMeta* new_task(void* (*fn)(void*), void* arg, void (*jump_fn)()) {
constexpr size_t stacksize = 1024 * 8;
void* m = malloc(stacksize);
if (m == nullptr) {
return nullptr;
}
TaskMeta* task_meta = new (std::nothrow) TaskMeta{
fn, arg, task_coroutine_make_fcontext((char*)m + stacksize, jump_fn),
m}; // 注意stack的bottom在memory +
// stacksize,因为栈增长的方向是地址下降
if (task_meta == nullptr) {
free(m);
return nullptr;
}
#ifdef TASK_COROUTINE_DEBUG
// 初始化task_meta的id
task_meta->id = g_task_meta_created_count.fetch_add(1, std::memory_order_relaxed) + 1;
#endif
return task_meta;
}
// destory 删除任务
static void destory(TaskMeta* task_meta) {
#ifdef TASK_COROUTINE_DEBUG
// 标记已经删除
if (task_meta->state.fetch_or(TaskMeta::state_had_destory) &
TaskMeta::state_had_destory) {
printf("%s:%d thread_id = %lu, re destory {id = %lu}\n", __FILE__,
__LINE__, std::hash<std::thread::id>()(std::this_thread::get_id()),
task_meta->id);
abort();
}
g_task_meta_destroy_count.fetch_add(1, std::memory_order_relaxed);
#endif
delete task_meta;
}
};
} // namespace task_coroutine |
import {
createContext,
useContext,
useEffect,
useState
} from "react"
import { defaultUser } from '@/model/eUser';
import eProduct, { defaultProduct } from '@/model/eProduct';
import { defaultCart } from '@/model/eCart';
import eCate from '@/model/eCate';
import menuContext from '@/model/menuContext';
import { useRouter } from "next/router";
const GlobalCtx = createContext<menuContext>({
user: defaultUser,
setUser: () => { },
allProducts: [defaultProduct],
setAllProducts: () => { },
cart: defaultCart,
setCart: () => { },
addItemToCart: (product: eProduct) => { },
categories: [],
setCategories: () => { },
kw: '',
setKw: () => { },
productFilter: Function
});
const useGContext = () => useContext(GlobalCtx);
const useDirect = () => {
const { user } = useGContext();
const { push } = useRouter();
useEffect(() => {
user.isAdmin === '0' && push('/');
}, []);
}
const GlobalContext = ({ children }: { children: JSX.Element }) => {
const [user, setUser] = useState(defaultUser);
const [allProducts, setAllProducts] = useState<Array<eProduct>>([]);
const [cart, setCart] = useState(defaultCart);
const [kw, setKw] = useState("");
const [categories, setCategories] = useState<eCate[]>([]);
const addItemToCart = (product: eProduct) => {
const newCart = { ...cart };
console.group('Begin: ');
// console.log(cart);
if (newCart.detail.length === 0) {
newCart.detail.push({
quantity: 1,
product: product,
isSelected: false
});
}
else {
const match = newCart.detail.find(_ => _.product.id === product.id);
if (match) {
match.quantity += 1;
} else {
newCart.detail.push({
quantity: 1,
product: product,
isSelected: false
});
}
newCart.quantity = newCart.detail.reduce((total, _) => total + _.quantity, 0)
}
setCart(newCart)
// console.log(cart);
console.groupEnd()
}
const productFilter = (k: string) => {
let arr = allProducts;
return arr.filter(p => p.name.toUpperCase().includes(k.toUpperCase())) ||
arr.filter(p => p.name.toLowerCase().includes(k.toLowerCase())) ||
arr.filter(p => p.manufacturer.toLowerCase().includes(k.toLowerCase())) ||
arr.filter(p => p.manufacturer.toUpperCase().includes(k.toUpperCase())) ||
arr.filter(p => p.id.toLowerCase().includes(k.toLowerCase())) ||
arr.filter(p => p.id.toUpperCase().includes(k.toUpperCase()))
}
const val = {
user,
setUser,
allProducts,
setAllProducts,
cart,
setCart,
addItemToCart,
categories,
setCategories,
kw,
setKw,
productFilter
}
return (
<GlobalCtx.Provider value={val}>
{children}
</GlobalCtx.Provider>
)
}
export default GlobalContext;
export { useGContext, useDirect }; |
package com.nullnumber1.lab1.service;
import com.nullnumber1.lab1.model.Payment;
import com.nullnumber1.lab1.model.User;
import com.nullnumber1.lab1.repository.UserRepository;
import com.nullnumber1.lab1.service.kafka.ProducerService;
import com.nullnumber1.lab1.util.enums.RoleEnum;
import lombok.AllArgsConstructor;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@AllArgsConstructor
public class ReviewScheduler {
private final PaymentService paymentService;
private final MessageService messageService;
private final UserRepository userRepository;
private final ProducerService producerService;
@Scheduled(fixedDelay = 50000)
@SchedulerLock(name = "info_to_admin_lock", lockAtLeastFor = "50s", lockAtMostFor = "55s")
public void scheduleReview() {
List<Payment> payments = paymentService.getPayments();
if (payments.isEmpty()) return;
List<User> admins = userRepository.getUsersByRolesContaining(RoleEnum.ADMIN);
if (admins.isEmpty()) return;
String message = messageService.getNeedReviewBody(payments);
admins.forEach(admin -> producerService.send("mail-topic", admin.getEmail(), message));
}
} |
# Solana Data Program V0
Solana Data Program is a program that allows users to initialize a _data account_, read and modify its data, and optionally finalize it.
## ✨ Key Features
- Allows System owned accounts to create (if not done already) and initialize a _data account_ and _metadata account_ that is linked to the `authority` (but owned by the Data Program) to store data of any format (JSON, IMG, HTML, Custom, etc.)
- Allows the `authority` of the _data account_ to modify the `data_type` and/or `data`
- Optionally allows _data account_ to be dynamic i.e., [`realloc`](https://docs.rs/solana-sdk/latest/solana_sdk/account_info/struct.AccountInfo.html#method.realloc)'s the _data account_ on every update instruction to ensure no additional storage is wasted
- Allows the `authority` to update the data starting at a particular offset
- Allows the `authority` to verify that the `data` is of the same data type as expected by the `data_type` field by passing in a `verify_flag: bool`
- Allows the `authority` to update the `authority` field but requires the new authority to also be a signer so that there is no accidental authority transfer
- Allows the `authority` to finalize the data in the _data account_ - finalized data can no longer be updated
- Allows the `authority` to close both the _data account_ and _metadata account_ to reclaim SOL
## Account Overview
### 📄 Metadata PDA Account
The Metadata PDA Account stores information about the `data account`. It is created and initialized by `InitializeDataAccount` and is updated by all other instructions.
| Field | Offset | Size | Description |
| ---------------------- | ------ | ---- | --------------------------------------------------------------------------------------------------------------------------- |
| `data_status` | 0 | 1 | Status of the data. Initially set to `INITIALIZED`. `FinalizeDataAccount` sets this to `FINALIZED`. |
| `serialization_status` | 1 | 1 | Status of the data serialization. Initially set to `UNVERIFIED`. `UpdateDataAccount` with a set `verify_flag` updates this. |
| `authority` | 2 | 32 | `PubKey` of the authority of the data account. |
| `is_dynamic` | 34 | 1 | `bool` to determine if the data account is dynamic (can realloc) or static. Set initially via `InitializeDataAccount`. |
| `data_version` | 35 | 1 | `u8` to keep track of the version of the Data Program used. |
| `data_type` | 36 | 1 | `u8` to store the Data Type of the data. |
| `bump_seed` | 37 | 1 | `u8` to store the bump seed. |
### 📄 Data Account
The Data Account stores the data as a raw data byte array.
| Field | Offset | Size | Description |
| ------ | ------ | ---- | ------------------------------------- |
| `data` | 0 | ~ | The data to be stored in the account. |
## Instruction Overview
### 📄 `InitializeDataAccount`
This instruction creates and initializes the Metadata PDA Account and optionally creates a Data Account.
<details>
<summary>Accounts</summary>
| Name | Writable | Signer | Description |
| ---------------- | :------: | :----: | ---------------------------------------------------------------------------------------------- |
| `feepayer` | ✅ | ✅ | Payer of the transaction. |
| `data` | ✅ | ✅ | The account that will contain the data. Can be created prior to this instruction. |
| `pda` | ✅ | | The PDA account that will be created and initialized by this instruction to hold the metadata. |
| `system_program` | | | The Solana System Program ID. |
</details>
<details>
<summary>Arguments</summary>
| Argument | Offset | Size | Description |
| ------------ | ------ | ---- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `authority` | 0 | 32 | The `PubKey` of the data account authority. |
| `space` | 32 | 64 | The initial space taken by the data account. If the data account is created prior to this instruction, this value will be ignored. |
| `is_dynamic` | 96 | 1 | The flag that sets the data account to be dynamic or static. A dynamic data account can realloc up or down. |
| `is_created` | 97 | 1 | The flag that determines whether the data account would need to be created in this instruction. |
| `debug` | 98 | 1 | The flag that determines whether the instruction should output debug logs. |
</details>
### 📄 `UpdateDataAccount`
This instruction updates the `data_type` field in the Metadata PDA Account and the data in the Data Account.
<details>
<summary>Accounts</summary>
| Name | Writable | Signer | Description |
| ---------------- | :------: | :----: | ------------------------------------------- |
| `authority` | ✅ | ✅ | The Authority of the Data Account. |
| `data` | ✅ | | The account that contains the data. |
| `pda` | ✅ | | The PDA account that contains the metadata. |
| `system_program` | | | The Solana System Program ID. |
</details>
<details>
<summary>Arguments</summary>
| Argument | Offset | Size | Description |
| -------------- | ------ | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data_type` | 0 | 1 | The data type of the `data`. |
| `data` | 1 | ~ | The new data (stored as `Vec<u8>`) to be written. **Note:** since the `data` field is an array of variable length, the byte position of any field that follows cannot be guaranteed. |
| `offset` | ~ | 64 | The offset from where to start writing the new data. |
| `realloc_down` | ~ | 1 | The flag that determines whether the data account should realloc down if the writing of the new data leads to unused space. This value is ignored if the data account is static. |
| `verify_flag` | ~ | 1 | The flag that determines whether the data should be verified that it conforms to its `data_type`. If the data type can be verified, the `serialization_status` will be set to `VERIFIED` or `FAILED` depending on the verification result. Otherwise it is set to `UNVERIFIED`. |
| `debug` | ~ | 1 | The flag that determines whether the instruction should output debug logs. |
</details>
### 📄 `UpdateDataAccountAuthority`
This instruction updates the `authority` of the Data Account by updating the value in the Metadata PDA Account. It requires both the old and new authority to be signers to prevent accidental transfers
<details>
<summary>Accounts</summary>
| Name | Writable | Signer | Description |
| --------------- | :------: | :----: | ------------------------------------------- |
| `old_authority` | | ✅ | The old Authority of the Data Account. |
| `data` | | | The account that contains the data. |
| `pda` | ✅ | | The PDA account that contains the metadata. |
| `new_authority` | | ✅ | The new Authority of the Data Account. |
</details>
<details>
<summary>Arguments</summary>
| Argument | Offset | Size | Description |
| -------- | ------ | ---- | -------------------------------------------------------------------------- |
| `debug` | 0 | 1 | The flag that determines whether the instruction should output debug logs. |
</details>
### 📄 `FinalizeDataAccount`
This instruction finalizes the data in the Data Account by setting the `data_status` in the Metadata PDA Account to be `FINALIZED`. Finalized data can no longer be updated.
<details>
<summary>Accounts</summary>
| Name | Writable | Signer | Description |
| ----------- | :------: | :----: | ------------------------------------------- |
| `authority` | | ✅ | The Authority of the Data Account. |
| `data` | | | The account that contains the data. |
| `pda` | ✅ | | The PDA account that contains the metadata. |
</details>
<details>
<summary>Arguments</summary>
| Argument | Offset | Size | Description |
| -------- | ------ | ---- | -------------------------------------------------------------------------- |
| `debug` | 0 | 1 | The flag that determines whether the instruction should output debug logs. |
</details>
### 📄 `CloseDataAccount`
This instruction closes the Data Account and the Metadata PDA Account and transfers the lamports to the `authority`.
<details>
<summary>Accounts</summary>
| Name | Writable | Signer | Description |
| ----------- | :------: | :----: | ------------------------------------------- |
| `authority` | ✅ | ✅ | The Authority of the Data Account. |
| `data` | ✅ | | The account that contains the data. |
| `pda` | ✅ | | The PDA account that contains the metadata. |
</details>
<details>
<summary>Arguments</summary>
| Argument | Offset | Size | Description |
| -------- | ------ | ---- | -------------------------------------------------------------------------- |
| `debug` | 0 | 1 | The flag that determines whether the instruction should output debug logs. |
</details>
## 🧑💻 Getting Started
### Typescript SDK
- Follow the instructions in the `package` directory on how to install and use the [`solana-data-program`](https://www.npmjs.com/package/solana-data-program) SDK
- tl;dr:
- **Installation**:
```shell
npm i solana-data-program
```
- **Usage**:
```javascript
import { DataProgram } from "solana-data-program";
```
### CLI
1. Navigate to the `js` directory and install all dependencies using `npm install`
2. Create a `.env` file and add the following to it:
```
CONNECTION_URL=https://api.devnet.solana.com # if deployed on devnet
AUTHORITY_PRIVATE=<REPLACE WITH PRIVATE KEY OF AUTHORITY WALLET>
```
3. To view details about a Data Account, run:
```
npx ts-node src/index.ts --view --account <REPLACE WITH DATA ACCOUNT PUBKEY>
```
- This displays the parsed metadata and data
- If you want to view the raw metadata and data, include the `--debug` flag
4. To upload a file from your file system, run:
```
npx ts-node src/index.ts --upload <REPLACE WITH FILEPATH>
```
- This creates a new static Data Account, initializes it and uploads the file to the Data Account in chunks
- If you already have an existing Data Account, you can upload to it by including the `--account <REPLACE WITH DATA ACCOUNT PUBKEY>` flag
- If you want the Data Account to be dynamic, include the `--dynamic` flag
## 📈 Flow Diagram

## 🚀 Examples
- The `examples` directory contains example projects that build on top of the Data Program to showcase stuff that can be built using it
- Follow in the instructions in the `examples` README to try them out for yourself! ;) |
5 Day Challenge [ REACT JS ]
Today Learning ( 18-09-2022 )
//! UseRef Hook
import React,{useEffect , useRef} from 'react';
function FocusInput() {
const userRef = useRef(null)
useEffect(()=>{
// ? Focus Input
userRef.current.focus()
}, [])
return (
<div>
<input ref={userRef} type='text' ></input>
</div>
);
}
export default FocusInput;
---------------------------------------------------------------------------------------------------
App.js
import './App.css';
import FocusInput from './components/FocusInput';
function App() {
return (
<div className="App">
<FocusInput />
</div>
);
}
export default App; |
import React, { Component } from "react";
/**
* State: là trạng thái của một component
* Khi mà chúng ta tương tác trên giao diện mà có sự thay đổi.
* state: là thuộc tính kế thừa từ lớp Component
*/
export default class State extends Component {
// 1. Cách khai báo state: isLogin
// Chú ý: Khai báo tất cả state ở trong thuộc tính state.
state = {
isLogin: false,
todos: [],
value: "",
};
handleLogin = () => {
// error
// this.state.isLogin=true;
// this.render();
const newState = {
isLogin: true,
};
// 2. Cách set lại state.
// mỗi lần chúng ta set lại state thì react nó tự động render lại UI (re-render).
// setState: là method kế thừa từ lớp Component
// sẽ tự động merge những state cũ và mới lại với nhau.
this.setState(newState);
// this.render(); không cần gọi lại method này.
};
handleLogout = () => {
this.setState({
isLogin: false,
//? sử dụng state nào thì nên khai báo rõ ở trên thuộc tính state
// isCompelte: true, // nó sẽ thêm vào state cho chúng ta nếu như chưa có. //! TRÁNH DÙNG.
})
};
renderContent = () => {
if (this.state.isLogin) {
return <p>Cyber Soft</p>;
}
return (
<button
onClick={this.handleLogin}
className="btn btn-outline-success mx-2"
type="submit"
>
Login
</button>
);
};
render() {
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container-fluid">
<a className="navbar-brand" href="#">
Navbar
</a>
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon" />
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<a className="nav-link active" aria-current="page" href="#">
Home
</a>
</li>
<li className="nav-item">
<a className="nav-link" href="#">
Link
</a>
</li>
<li className="nav-item dropdown">
<a
className="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Dropdown
</a>
<ul className="dropdown-menu" aria-labelledby="navbarDropdown">
<li>
<a className="dropdown-item" href="#">
Action
</a>
</li>
<li>
<a className="dropdown-item" href="#">
Another action
</a>
</li>
<li>
<hr className="dropdown-divider" />
</li>
<li>
<a className="dropdown-item" href="#">
Something else here
</a>
</li>
</ul>
</li>
<li className="nav-item">
<a
className="nav-link disabled"
href="#"
tabIndex={-1}
aria-disabled="true"
>
Disabled
</a>
</li>
</ul>
<div className="d-flex">
{/* 1. xử lý trực tiếp tại đây: toán tử 3 ngôi */}
{/* Chú ý: không sử dụng được if else */}
{/* {this.state.isLogin ? (
<p>Cyber Soft</p>
) : (
<button
onClick={this.handleLogin}
className="btn btn-outline-success mx-2"
type="submit"
>
Login
</button>
)} */}
{/* 2. Xử dùng hàm */}
{this.renderContent()}
<button
onClick={this.handleLogout}
className="btn btn-outline-success"
type="submit"
>
Log Out
</button>
</div>
</div>
</div>
</nav>
);
}
} |
package common
import (
"cmp"
"github.com/go-gl/mathgl/mgl32"
"math"
)
type IT interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
// / Returns the square of the value.
// / @param[in] a The value.
// / @return The square of the value.
func Sqr[T IT](a T) T {
return a * a
}
func Sqrt(x float64) float64 {
return math.Sqrt(x)
}
// / Returns the absolute value.
// / @param[in] a The value.
// / @return The absolute value of the specified value.
func Abs[T IT](a T) T {
if a < 0 {
return -a
}
return a
}
// / Performs a vector addition. (@p v1 + @p v2)
// / @param[out] dest The result vector. [(x, y, z)]
// / @param[in] v1 The base vector. [(x, y, z)]
// / @param[in] v2 The vector to add to @p v1. [(x, y, z)]
func Vadd(res []float64, v1, v2 []float64) {
res[0] = v1[0] + v2[0]
res[1] = v1[1] + v2[1]
res[2] = v1[2] + v2[2]
}
// / Performs a vector subtraction. (@p v1 - @p v2)
// / @param[out] dest The result vector. [(x, y, z)]
// / @param[in] v1 The base vector. [(x, y, z)]
// / @param[in] v2 The vector to subtract from @p v1. [(x, y, z)]
func Vsub(res, v1, v2 []float64) {
res[0] = v1[0] - v2[0]
res[1] = v1[1] - v2[1]
res[2] = v1[2] - v2[2]
}
// / Selects the minimum value of each element from the specified vectors.
// / @param[in,out] mn A vector. (Will be updated with the result.) [(x, y, z)]
// / @param[in] v A vector. [(x, y, z)]
func Vmin(mn, v []float64) {
mn[0] = Min(mn[0], v[0])
mn[1] = Min(mn[1], v[1])
mn[2] = Min(mn[2], v[2])
}
// / Selects the maximum value of each element from the specified vectors.
// / @param[in,out] mx A vector. (Will be updated with the result.) [(x, y, z)]
// / @param[in] v A vector. [(x, y, z)]
func Vmax(mx, v []float64) {
mx[0] = Max(mx[0], v[0])
mx[1] = Max(mx[1], v[1])
mx[2] = Max(mx[2], v[2])
}
// / Returns the distance between two points.
// / @param[in] v1 A point. [(x, y, z)]
// / @param[in] v2 A point. [(x, y, z)]
// / @return The distance between the two points.
func Vdist(v1, v2 []float64) float64 {
dx := v2[0] - v1[0]
dy := v2[1] - v1[1]
dz := v2[2] - v1[2]
return Sqrt(dx*dx + dy*dy + dz*dz)
}
// / Returns the square of the distance between two points.
// / @param[in] v1 A point. [(x, y, z)]
// / @param[in] v2 A point. [(x, y, z)]
// / @return The square of the distance between the two points.
func VdistSqr(v1, v2 []float64) float64 {
dx := v2[0] - v1[0]
dy := v2[1] - v1[1]
dz := v2[2] - v1[2]
return dx*dx + dy*dy + dz*dz
}
// / Normalizes the vector.
// / @param[in,out] v The vector to normalize. [(x, y, z)]
func Vnormalize(v []float64) { //向量的单位化
d := 1.0 / Sqrt(Sqr(v[0])+Sqr(v[1])+Sqr(v[2]))
v[0] *= d
v[1] *= d
v[2] *= d
}
// / Returns the minimum of two values.
// / @param[in] a Value A
// / @param[in] b Value B
// / @return The minimum of the two values.
func Min[T IT](a, b T) T {
if a < b {
return a
}
return b
}
// / Returns the maximum of two values.
// / @param[in] a Value A
// / @param[in] b Value B
// / @return The maximum of the two values.
func Max[T IT](a, b T) T {
if a > b {
return a
}
return b
}
// / Performs a 'sloppy' colocation check of the specified points.
// / @param[in] p0 A point. [(x, y, z)]
// / @param[in] p1 A point. [(x, y, z)]
// / @return True if the points are considered to be at the same location.
// /
// / Basically, this function will return true if the specified points are
// / close enough to eachother to be considered colocated.
func Vequal(p0 []float64, p1 []float64) bool {
thr := Sqr(1.0 / 16384.0)
d := VdistSqr(p0, p1)
return d < thr
}
// / Scales the vector by the specified value. (@p v * @p t)
// / @param[out] dest The result vector. [(x, y, z)]
// / @param[in] v The vector to scale. [(x, y, z)]
// / @param[in] t The scaling factor.
func Vscale(res []float64, v []float64, t float64) {
res[0] = v[0] * t
res[1] = v[1] * t
res[2] = v[2] * t
}
/// @}
/// @name Vector helper functions.
/// @{
// / Derives the cross product of two vectors. (@p v1 x @p v2)
// / @param[out] dest The cross product. [(x, y, z)]
// / @param[in] v1 A Vector [(x, y, z)]
// / @param[in] v2 A vector [(x, y, z)]
func Vcross(res []float64, v1, v2 []float64) { //求向量的叉集
res[0] = v1[1]*v2[2] - v1[2]*v2[1]
res[1] = v1[2]*v2[0] - v1[0]*v2[2]
res[2] = v1[0]*v2[1] - v1[1]*v2[0]
}
// / Derives the dot product of two vectors. (@p v1 . @p v2)
// / @param[in] v1 A Vector [(x, y, z)]
// / @param[in] v2 A vector [(x, y, z)]
// / @return The dot product.
func Vdot(v1, v2 []float64) float64 { //求向量的点积
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
}
// / Performs a scaled vector addition. (@p v1 + (@p v2 * @p s))
// / @param[out] dest The result vector. [(x, y, z)]
// / @param[in] v1 The base vector. [(x, y, z)]
// / @param[in] v2 The vector to scale and add to @p v1. [(x, y, z)]
// / @param[in] s The amount to scale @p v2 by before adding to @p v1.
func Vmad(res []float64, v1, v2 []float64, s float64) {
res[0] = v1[0] + v2[0]*s
res[1] = v1[1] + v2[1]*s
res[2] = v1[2] + v2[2]*s
}
// / Clamps the value to the specified range.
// / @param[in] value The value to clamp.
// / @param[in] minInclusive The minimum permitted return value.
// / @param[in] maxInclusive The maximum permitted return value.
// / @return The value, clamped to the specified range.
func Clamp[T cmp.Ordered](value, minInclusive, maxInclusive T) T {
if value < minInclusive {
return minInclusive
}
if value > maxInclusive {
return maxInclusive
}
return value
}
// / Sets the vector elements to the specified values.
// / @param[out] dest The result vector. [(x, y, z)]
// / @param[in] x The x-value of the vector.
// / @param[in] y The y-value of the vector.
// / @param[in] z The z-value of the vector.
func Vset(dest []float64, x, y, z float64) {
dest[0] = x
dest[1] = y
dest[2] = z
}
// / Checks that the specified vector's 2D components are finite.
// / @param[in] v A point. [(x, y, z)]
func Visfinite2D(v []float64) bool {
return IsFinite(v[0]) && IsFinite(v[2])
}
// / Derives the xz-plane 2D perp product of the two vectors. (uz*vx - ux*vz)
// / @param[in] u The LHV vector [(x, y, z)]
// / @param[in] v The RHV vector [(x, y, z)]
// / @return The perp dot product on the xz-plane.
// /
// / The vectors are projected onto the xz-plane, so the y-values are ignored.
func Vperp2D(u, v []float64) float64 {
return u[2]*v[0] - u[0]*v[2]
}
// / Derives the dot product of two vectors on the xz-plane. (@p u . @p v)
// / @param[in] u A vector [(x, y, z)]
// / @param[in] v A vector [(x, y, z)]
// / @return The dot product on the xz-plane.
// /
// / The vectors are projected onto the xz-plane, so the y-values are ignored.
func Vdot2D(u, v []float64) float64 {
return u[0]*v[0] + u[2]*v[2]
}
// / Derives the square of the distance between the specified points on the xz-plane.
// / @param[in] v1 A point. [(x, y, z)]
// / @param[in] v2 A point. [(x, y, z)]
// / @return The square of the distance between the point on the xz-plane.
func Vdist2DSqr(v1, v2 []float64) float64 {
dx := v2[0] - v1[0]
dz := v2[2] - v1[2]
return dx*dx + dz*dz
}
// / Derives the distance between the specified points on the xz-plane.
// / @param[in] v1 A point. [(x, y, z)]
// / @param[in] v2 A point. [(x, y, z)]
// / @return The distance between the point on the xz-plane.
// /
// / The vectors are projected onto the xz-plane, so the y-values are ignored.
func Vdist2D(v1, v2 []float64) float64 {
dx := v2[0] - v1[0]
dz := v2[2] - v1[2]
return math.Sqrt(dx*dx + dz*dz)
}
// / Derives the scalar length of the vector.
// / @param[in] v The vector. [(x, y, z)]
// / @return The scalar length of the vector.
func Vlen(v []float64) float64 {
return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
}
// / Performs a linear interpolation between two vectors. (@p v1 toward @p v2)
// / @param[out] dest The result vector. [(x, y, x)]
// / @param[in] v1 The starting vector.
// / @param[in] v2 The destination vector.
// / @param[in] t The interpolation factor. [Limits: 0 <= value <= 1.0]
func Vlerp(dest []float64, v1, v2 []float64, t float64) []float64 {
dest[0] = v1[0] + (v2[0]-v1[0])*t
dest[1] = v1[1] + (v2[1]-v1[1])*t
dest[2] = v1[2] + (v2[2]-v1[2])*t
return dest
}
// / Derives the square of the scalar length of the vector. (len * len)
// / @param[in] v The vector. [(x, y, z)]
// / @return The square of the scalar length of the vector.
func VlenSqr(v []float64) float64 {
return v[0]*v[0] + v[1]*v[1] + v[2]*v[2]
}
/// @}
/// @name Computational geometry helper functions.
/// @{
// / Derives the signed xz-plane area of the triangle ABC, or the relationship of line AB to point C.
// / @param[in] a Vertex A. [(x, y, z)]
// / @param[in] b Vertex B. [(x, y, z)]
// / @param[in] c Vertex C. [(x, y, z)]
// / @return The signed xz-plane area of the triangle.
func TriArea2D(a, b, c []float64) float64 {
abx := b[0] - a[0]
abz := b[2] - a[2]
acx := c[0] - a[0]
acz := c[2] - a[2]
return acx*abz - abx*acz
}
// / Checks that the specified vector's components are all finite.
// / @param[in] v A point. [(x, y, z)]
// / @return True if all of the point's components are finite, i.e. not NaN
// / or any of the infinities.
func Visfinite(v []float64) bool {
return !(IsFinite(v[0]) && IsFinite(v[1]) && IsFinite(v[2]))
}
func IsFinite(v float64) bool {
return math.IsInf(v, -1) || math.IsInf(v, 1) || math.IsNaN(v)
}
// / Gets the direction for the specified offset. One of x and y should be 0.
// / @param[in] offsetX The x offset. [Limits: -1 <= value <= 1]
// / @param[in] offsetZ The z offset. [Limits: -1 <= value <= 1]
// / @return The direction that represents the offset.
func GetDirForOffset(offsetX, offsetZ int) int {
dirs := []int{3, 0, -1, 2, 1}
return dirs[((offsetZ+1)<<1)+offsetX]
}
// / Gets the standard width (x-axis) offset for the specified direction.
// / @param[in] direction The direction. [Limits: 0 <= value < 4]
// / @return The width offset to apply to the current cell position to move in the direction.
func GetDirOffsetX(direction int) int {
offset := [4]int{-1, 0, 1, 0}
return offset[direction&0x03]
}
// TODO (graham): Rename this to rcGetDirOffsetZ
// / Gets the standard height (z-axis) offset for the specified direction.
// / @param[in] direction The direction. [Limits: 0 <= value < 4]
// / @return The height offset to apply to the current cell position to move in the direction.
func GetDirOffsetY(direction int) int {
offset := [4]int{0, 1, 0, -1}
return offset[direction&0x03]
}
func NextPow2(v int) int {
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
return v
}
func Ilog2(v int) int {
getBool := func(b bool) int {
if b {
return 1
}
return 0
}
var r int
var shift int
r = getBool((v > 0xffff)) << 4
v >>= r
shift = getBool((v > 0xff)) << 3
v >>= shift
r |= shift
shift = getBool((v > 0xf)) << 2
v >>= shift
r |= shift
shift = getBool((v > 0x3)) << 1
v >>= shift
r |= shift
r |= (v >> 1)
return r
}
func GetVs3[T IT](verts []T, index int) []T {
return verts[index*3 : index*3+3]
}
func GluProject[T1 int32 | int](obj []float64, projection, modelview []float64, view []T1) []float64 {
o := mgl32.Vec3{}
for i := range obj {
o[i] = float32(obj[i])
}
p := mgl32.Mat4{}
for i := range projection {
p[i] = float32(projection[i])
}
v := mgl32.Mat4{}
for i := range modelview {
v[i] = float32(modelview[i])
}
res := mgl32.Project(o, v, p, int(view[0]), int(view[1]), int(view[2]), int(view[3]))
return []float64{float64(res[0]), float64(res[1]), float64(res[2])} //TODO
}
func UnGluProject[T1 int32 | int](obj []float64, projection, modelview []float64, view []T1) ([]float64, error) {
o := mgl32.Vec3{}
for i := range obj {
o[i] = float32(obj[i])
}
p := mgl32.Mat4{}
for i := range projection {
p[i] = float32(projection[i])
}
v := mgl32.Mat4{}
for i := range modelview {
v[i] = float32(modelview[i])
}
res, err := mgl32.UnProject(o, v, p, int(view[0]), int(view[1]), int(view[2]), int(view[3]))
if err != nil {
return []float64{}, err
}
return []float64{float64(res[0]), float64(res[1]), float64(res[2])}, err
} |
<template>
<Welcome intro="Update Project" signature="" />
<form
enctype="application/x-www-form-urlencoded"
action="http://localhost:3000/update/project"
method="post"
>
<div class="flex flex-row h-14 my-3 border-b border-purple-200">
<label for="oldtitle">Project:</label>
<select id="oldtitle" name="oldtitle" @change="updateFiller">
<option :value="fillerValue">~~ Select An Option ~~</option>
<option
v-for="project in projects"
:key="project.id"
:value="project.title"
>
{{ project.title }}
</option>
</select>
</div>
<div class="flex flex-row h-14 my-3 border-b border-purple-200">
<label for="title">New Title:</label>
<input
id="title"
v-model="title"
class="w-56 overflow-x-auto"
type="text"
name="title"
/>
</div>
<div class="flex flex-row h-14 my-3 border-b border-purple-200">
<label for="category">New Category:</label>
<input
id="category"
v-model="category"
class="w-36 overflow-x-auto"
type="text"
name="category"
/>
</div>
<div class="flex flex-row my-3 border-b border-purple-200">
<label for="description">New Description:</label>
<textarea
id="description"
v-model="input"
placeholder="## Enter description here..."
name="description"
></textarea>
<div
class="prose prose-sm md:prose lg:prose-lg xl:prose-xl 2xl:prose-2xl prose-purple w-2/5 h-96 mb-4 p-6 overflow-y-auto rounded-r-lg border-2 border-l-0 border-purple-400 font-montserrat"
>
{{ compiledMarkdown }}
</div>
</div>
<input type="submit" value="Update!" />
</form>
</template>
<script>
import Welcome from "@/components/Welcome.vue";
import { marked } from "marked";
import DOMPurify from "dompurify";
import axios from "axios";
export default {
name: "UpdateProject",
components: {
Welcome,
},
data() {
return {
projects: [],
title: "",
category: "",
input: "",
};
},
computed: {
compiledMarkdown() {
return DOMPurify.sanitize(marked(this.input));
},
fillerValue() {
return (
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15)
);
},
},
async created() {
try {
const res = await axios.get(
`http://localhost:3000/project/user/${this.$store.state.auth.user.id}`
);
this.projects = res.data;
} catch (e) {
console.error(e);
}
},
methods: {
updateFiller() {
const selected = document.getElementById("oldtitle").value;
axios
.get(`http://localhost:3000/project/${encodeURIComponent(selected)}`)
.then((res) => {
this.title = res.data[0].title;
this.category = res.data[0].category;
this.input = res.data[0].description;
});
},
},
};
</script>
<style lang="postcss" scoped>
form {
@apply text-left py-2;
}
label,
.fake-label,
input {
@apply text-left text-lg font-montserrat font-semibold;
}
label,
.fake-label {
@apply w-48 p-2 mb-4;
}
.fake-label {
@apply align-middle;
}
input[type="text"] {
@apply p-2 mb-4 rounded-md ring-2 ring-black focus:ring-purple-400;
}
input,
textarea {
@apply focus:outline-none;
}
textarea[name="description"] {
@apply w-2/5 h-96 resize-none text-base font-montserrat mb-4 p-6 rounded-l-lg border-2 border-black focus:border-gray-500;
}
input[type="submit"] {
@apply px-6 py-2 m-2 rounded-2xl text-white font-quicksand bg-purple-400 hover:bg-purple-600 duration-300;
}
</style> |
// ** React Imports
import { useState } from 'react'
// ** MUI Imports
import Drawer from '@mui/material/Drawer'
import Select from '@mui/material/Select'
import Button from '@mui/material/Button'
import MenuItem from '@mui/material/MenuItem'
import { styled } from '@mui/material/styles'
import TextField from '@mui/material/TextField'
import IconButton from '@mui/material/IconButton'
import InputLabel from '@mui/material/InputLabel'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import FormControl from '@mui/material/FormControl'
import FormHelperText from '@mui/material/FormHelperText'
import Grid from '@mui/material/Grid'
import FormControlLabel from '@mui/material/FormControlLabel'
import Switch from '@mui/material/Switch'
import toast from 'react-hot-toast'
// ** Third Party Imports
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import { useForm, Controller } from 'react-hook-form'
// ** Icon Imports
import Icon from 'src/@core/components/icon'
// ** Store Imports
import { useDispatch } from 'react-redux'
// ** Actions Imports
import { addUser } from 'src/store/apps/user'
import axios from 'axios'
import Global from 'src/pages/acl/Global'
const showErrors = (field, valueLen, min) => {
if (valueLen === 0) {
return `${field} field is required`
} else if (valueLen > 0 && valueLen < min) {
return `${field} must be at least ${min} characters`
} else {
return ''
}
}
const Header = styled(Box)(({ theme }) => ({
display: 'flex',
alignItems: 'center',
padding: theme.spacing(6),
justifyContent: 'space-between'
}))
const schema = yup.object().shape({
proveedorNombre: yup.string().required(),
proveedorApellido: yup.string().required(),
proveedorTelefono: yup.string().required(),
proveedorServicio: yup.string().required()
})
const defaultValues = {
proveedorNombre: '',
proveedorApellido: '',
proveedorTelefono: '',
proveedorServicio: ''
}
const SidebarAddUser = props => {
// ** Props
const { open, toggle } = props
// ** State
const [precio, setPrecio] = useState(0)
const [NuevoPrecio, setNuevoPrecio] = useState(0)
const [validationErrors, setvalidationErrors] = useState({})
const [showError, setshowError] = useState(false)
const [nombre, setnombre] = useState('')
const [Apellido, setApellido] = useState('')
const [Telefono, setTelefono] = useState('')
const [Servicio, setServicio] = useState('')
// ** Hooks
const dispatch = useDispatch()
const {
reset,
control,
handleSubmit,
formState: { errors }
} = useForm({
defaultValues
})
const onSubmit = data => {
console.log(data)
setnombre(data.proveedorNombre)
setApellido(data.proveedorApellido)
setTelefono(data.proveedorTelefono)
setServicio(data.proveedorServicio)
CreateAction(data)
}
const handleClose = () => {
setPrecio(0)
setNuevoPrecio(0)
setshowError(false)
toggle()
reset()
}
const CreateAction = e => {
if (!precio) {
setvalidationErrors({ UserName: 'Debe ingresar una nombre de usuario' })
setshowError(true)
} else {
let prov = {
prov_Id: 0,
prov_Nombre: nombre,
prov_Apellido: Apellido,
prov_Telefono: Telefono,
prov_Servicio: Servicio,
prov_Precio: precio,
serv_Precio_Nuevo: NuevoPrecio.toString()
}
console.log(prov)
axios
.post(Global.url + '/api/Proveedores/InsertProveedores', prov)
.then(r => {
console.log(r.data)
if (r.data.messageStatus === 'Este Proveedor ya existe') {
toast.error(r.data.messageStatus, {
duration: 4000
})
} else if (r.data.messageStatus === 'Registro Agregado Exitosamente') {
handleClose()
setPrecio(0)
setNuevoPrecio(0)
} else {
console.log('Cago')
toast.error(r.data.messageStatus, {
duration: 4000,
position: 'top-mid'
})
}
})
.catch(e => console.error(e))
}
}
return (
<Drawer
open={open}
anchor='right'
variant='temporary'
onClose={handleClose}
ModalProps={{ keepMounted: true }}
sx={{ '& .MuiDrawer-paper': { width: { xs: 300, sm: 400 } } }}
>
<Header>
<Typography variant='h6'>Nuevo Servicio</Typography>
<IconButton
size='small'
onClick={handleClose}
sx={{ borderRadius: 1, color: 'text.primary', backgroundColor: 'action.selected' }}
>
<Icon icon='tabler:x' fontSize='1.125rem' />
</IconButton>
</Header>
<Box sx={{ p: theme => theme.spacing(0, 6, 6) }}>
<form onSubmit={handleSubmit(onSubmit)}>
<FormControl fullWidth sx={{ mb: 4 }}>
<Controller
name='proveedorNombre'
control={control}
rules={{ required: true }}
render={({ field: { value, onChange } }) => (
<TextField
value={value}
autoFocus
fullWidth
type='text'
onChange={onChange}
error={Boolean(errors.proveedorNombre)}
label='Nombre del Proveedor'
/>
)}
/>
{errors.proveedorNombre && (
<FormHelperText sx={{ color: 'error.main' }} id='validation-basic-first-name'>
This field is required
</FormHelperText>
)}
</FormControl>
<FormControl fullWidth sx={{ mb: 4 }}>
<Controller
name='proveedorApellido'
control={control}
rules={{ required: true }}
render={({ field: { value, onChange } }) => (
<TextField
value={value}
autoFocus
fullWidth
type='text'
onChange={onChange}
error={Boolean(errors.proveedorApellido)}
label='Apellido del proveedor'
/>
)}
/>
{errors.proveedorApellido && (
<FormHelperText sx={{ color: 'error.main' }} id='validation-basic-first-name'>
This field is required
</FormHelperText>
)}
</FormControl>
<FormControl fullWidth sx={{ mb: 4 }}>
<Controller
name='proveedorTelefono'
control={control}
rules={{ required: true }}
render={({ field: { value, onChange } }) => (
<TextField
value={value}
autoFocus
fullWidth
type='text'
onChange={onChange}
error={Boolean(errors.proveedorTelefono)}
label='Telefono del Proveedor'
/>
)}
/>
{errors.proveedorTelefono && (
<FormHelperText sx={{ color: 'error.main' }} id='validation-basic-first-name'>
This field is required
</FormHelperText>
)}
</FormControl>
<FormControl fullWidth sx={{ mb: 4 }}>
<Controller
name='proveedorServicio'
control={control}
rules={{ required: true }}
render={({ field: { value, onChange } }) => (
<TextField
value={value}
autoFocus
fullWidth
type='text'
onChange={onChange}
error={Boolean(errors.proveedorServicio)}
label='Servicio del Proveedor'
/>
)}
/>
{errors.proveedorServicio && (
<FormHelperText sx={{ color: 'error.main' }} id='validation-basic-first-name'>
This field is required
</FormHelperText>
)}
</FormControl>
<FormControl fullWidth sx={{ mb: 4 }}>
<Grid item xs={12}>
<Grid container spacing={6}>
<Grid item xs={12} sm={6}>
<TextField
id='provPrecio'
name='provPrecio'
value={precio}
autoFocus
fullWidth
type='text'
onChange={e => {
setPrecio(e.target.value)
setNuevoPrecio(parseInt(e.target.value) * 0.1 + parseInt(e.target.value))
setshowError(false)
}}
error={showError}
helperText={showError && validationErrors.precio}
label='Precio del Servicio'
/>
</Grid>
<Grid item xs={12} sm={3}>
<TextField
id='provPrecio'
name='provPrecio'
value={NuevoPrecio}
autoFocus
fullWidth
type='text'
onChange={e => {
setNuevoPrecio(e.target.value)
setshowError(false)
}}
error={showError}
disabled
helperText={showError && validationErrors.precio}
label='Precio del Servicio'
/>
</Grid>
</Grid>
</Grid>
</FormControl>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<Button type='submit' variant='contained' sx={{ mr: 3 }}>
Submit
</Button>
<Button variant='outlined' color='secondary' onClick={handleClose}>
Cancel
</Button>
</Box>
</form>
</Box>
</Drawer>
)
}
export default SidebarAddUser |
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Header } from "../../../../components/Header";
import { TextsNavigation } from "../../../../components/TextsNavigation";
import { MdWest } from "react-icons/md";
import styles from "../../textos.module.scss";
import { useTitle } from "../../../../hooks/useTitle";
export function RuidoEstrutura() {
const [transition, setTransition] = useState(false);
const navigation = useNavigate();
useTitle("Ruído, estrutura");
function handleRedirect(path) {
setTransition(true)
setTimeout(() => navigation(path), 1000)
}
useEffect(() => {
window.scrollTo({
top: 0,
behavior: "smooth"
})
}, [])
return (
<div className={`${styles.container} ${transition ? styles.transition : ''}`}>
<Header handleRedirect={handleRedirect} />
<section className={styles.wrapper}>
<div className={styles.backLink} onClick={() => handleRedirect('/um-som-estrangeiro')}>
<MdWest size="3rem" />
</div>
<h2>Ruído, estrutura</h2>
<hr />
<p>
Há alguns anos, em um trabalho de faculdade sobre
<a href="https://www.youtube.com/watch?v=AO8Af1lYbps" target="_blank" rel="noreferrer">Iracema, uma Transa Amazônica </a>,
filme de Jorge Bodansky, recebi uma devolutiva da professora - acompanhada de uma medíocre e emburrada nota 7 - que nunca me
escapou da cabeça. A breve nota dizia, sem rodeios, algo como <em>a articulação de ideias é boa </em>- sempre é por aí que se
começa - <em>no entanto você deveria saber que as discussões sobre o horizonte de nação já estão obsoletas há pelo menos 20 anos</em>.
Difícil de se esquecer, de fato.
</p>
<p>Mas este texto não quer falar sobre propriamente de nação.</p>
<p>
Parto deste ponto apenas porque, como pesadamente sabemos, João Gilberto se foi. Com ele, se foi também uma das partes
mais importantes deste debate sobre o que somos ou poderíamos ter sido como país: aquilo que ali vivia como promessa, como
alegria melancólica, como distensão sem hiato. Não vou adentrar esta vereda, é claro. Lorenzo Mammi, Nuno Ramos, Walter
Garcia já o fizeram com muito maior propriedade. O quero pegar deste debate é apenas um único ponto (e dele partir para o
disparate): a beleza absoluta de se conceber, pelo encantamento do som e por uma forma particular de lidar com o tempo –
com a forma –, um alcance e uma potência particulares em um projeto artístico: como se pode, a partir de (meras?) canções,
pensar o destino conjunto de toda uma gente e investi-lo uma vez mais, de sentido: como é possível um ponto de partida tão
simples em um debate tão amplo quanto este. Lidar com a forma pode ser, assim, lidar com um ponto privilegiado para se observar
de que maneira tem se construído <em>o normal</em>, em suas consequências indisfarçáveis.
</p>
<p>
A proposta aqui, então, é buscar uma simetria inóspita entre duas canções: a primeira
é <a href="https://www.youtube.com/watch?v=v_4e8Tq-CKQ" target="_blank" rel="noreferrer">The Diamond Sea</a>, do
Sonic Youth. A segunda é <a href="https://www.youtube.com/watch?v=vk4NL1vpAiE" target="_blank" rel="noreferrer">Undiú</a>, de João Gilberto.
</p>
<p className={styles.center}><strong>*</strong></p>
<p>
O ruído é uma questão tão ou mais urgente quanto a música. Ele é, na verdade, simultâneo e, em muitos aspectos, indissociável
a qualquer história da música que se faça com alguma responsabilidade. Os trítonos, a síncope, o ruído são uma contra-história
da música: a história de uma gestão política do sentido, do aceitável, do audível, do pensável. Não houve poder hegemônico que
tenha se constituído sem praticar o esforço de gerir os limites entre som e sentido, ruído e música, natureza e cultura. Nestas
beiras vive até hoje o impossível esforço de se domesticar as fronteiras do viável, de evitar o excesso e o gozo descontrolado.
O ruído margeia - e dá sentido, pelo negativo - a tudo isso que se constituiu como cultura hegemônica, como música limpa,
erudita e educada.
</p>
<p>
Em um movimento historicista, podemos observar, contudo, que somente se constituíram como vanguarda da música popular ocidental
no século XX países que se abriram - com muita dor e violência - ao ruído. Falo, em particular, de Brasil, Estados Unidos e Cuba.
A música destes países se proliferou e diversificou a partir da invasão da síncope, da quebra de tempos estáveis, da sobreposição
de elementos, da melodização em primeiro plano: da admissão do equívoco como elemento constitutivo da linguagem, como seu ponto de
partida e ética. Esta que talvez tenha sido a herança mais duradoura e profícua que a África tenha dado ao resto do mundo.
</p>
<p>
Por isso, e apressando muito o passo, chego então ao Sonic Youth como fruto temporão desta árvore. O fascínio que a música
destes estadunidenses promove se deve, muito em particular, pelo tratamento ético que se dá aí ao ruído. Isto porque, dentro
do que se chamou de <em>rock</em>, isto é, de um gênero musical em que barulho, altura e performance
constituem <a href="https://docplayer.com.br/22912842-Prolegomenos-a-uma-estetica-do-rock.html" target="_blank" rel="noreferrer">o parâmetro daquilo que é bom</a>,
e, mais do que isso, de um lugar em que o timbre - ou seja, algo que foge da harmonia, da partitura, da possibilidade de escrita do som -
cria uma experiência diferencial, constituir-se como uma banda que se baseia, essencialmente, em formas de distorção é algo que sugere
enormes dificuldades de proposição de um projeto particular.
</p>
<p>
E no entanto é este projeto que presenciamos. Creio que o diferencial do SY se observa sobretudo em contato com outras
experiências em que ruído, barulho e distorção assumem o primeiro plano: por exemplo, o que se faz no shoegaze ou
no <a href="https://www.youtube.com/watch?v=G5RzpPrOd-4&ab_channel=4AD" target="_blank" rel="noreferrer">dream-pop</a>.
Nestes dois gêneros, o que se tem é o turvamento das bordas entre os instrumentos e suas as linhas melódicas, a ponto de
se surgir uma ambientação totalmente pautada em uma espécie de neblina sonora em que não se consegue distinguir as unidades
mínimas: a música cria subterfúgios para si, a performance tende a grau zero (ou à totalização, a depender do ponto de vista),
o espaço está assegurado em sua própria pressuposição de instabilidade. Em gêneros como o metal, por outro lado, é a altura
que consegue guiar a construção da canção como um ato orgânico e disperso no tempo, e o ouvinte tende então a ser levado a
zonas cômodas e confortáveis, previstas e previsíveis - mesmo que altas e ruidosas para o padrão da música comercial: a música
torna-se a garantia de si mesma, naquilo que justamente há de interesse comercial em se traçar <em>gêneros</em> na arte.
</p>
<p>
Ouvindo SY, vive-se uma experiência qualitativamente distinta. O que temos em geral é a construção de um rock prototípico
e, concorrentemente a ele, a sua iminente destruição dentro da canção. Cada música do SY são duas,
portanto: <a href="https://www.youtube.com/watch?v=3-jp4hk7VIU">a canção e a contracanção</a>.Creio que a melhor forma
de se ouvir a essa discografia é, portanto, observando aquilo que está no segundo plano, como uma espécie de resto da melodia
central: ali, abaixo, cruzando de lado - a - lado, está o ruído, como uma pulsão de morte, borrando a facilidade do que
poderia ser um grande e canônico rock.O SY, como o Miguel Gomes de <em> Mil e uma Noites</em> ou o Cabral
de <em> Educação pela Pedra</em>, escolhe não viver da própria estrutura que ergue para si dentro das canções:
a dissolve, a complica, a questiona.Proposição e reproposição.
</p>
<p>
A maior radicalização deste procedimento está em <strong>Diamond Sea</strong>, do disco <em>Washing Machine</em>, de
1995. A monstruosa canção de quase 20 minutos que encerra o álbum é como uma epopeia, uma metáfora do que seria este mar
que lhe dá título. Não à toa, a letra evoca uma imagem do tempo em seu primeiro verso - a distensão temporal é a grande
matéria desta canção -, e a partir dele cria um retrato da divisibilidade do indivíduo, da quebra da imagem de si mesmo
diante do espelho. Nada no SY é autocoincidente.
</p>
<p>
A música se inicia, pois, com uma linha melódica baseada numa distorção raríssima, que facilmente se poderia dizer das
melhores da história do gênero: um achado de pesquisa, que poderia pautar toda a canção. E não pauta. Tão logo entra a
voz sobre bateria e baixo, e sucedem-se quatro codas distintas, o mar passa a guiar. É nítido, portanto, que a estrutura
da canção é irrastreável. De uma linha melódica simples a música vai aos poucos dissolvendo-se em dezenas de variações de
si mesma, vão emergindo gradativamente sons de camadas subterrâneas até que, enfim, eles ocupam o primeiro plano da música
e mimetizam o mar sinestésico - azul mas pontiagudo, belo mas duro - de onde se parte. Sucedem-se mais de 10 minutos de pura
distorção, puro ruído (será ainda ruído o que ocupa o primeiro plano?) em mar agitado até que, enfim, retorna o sossego da
praia aliviada da melodia final.
</p>
<p>
A experiência de <strong>Diamond Sea</strong> é a experiência de uma organicidade das fronteiras entre som e sentido, entre
música e não-música: é, acima de tudo, a possibilidade de vislumbrar uma gestão desta fronteira que não seja um tipo de
despotismo, mas uma construção de um espaço heterogêneo em que se produza significado a partir da diferença. Não é necessário
erguer um muro definitivo na fronteira: o muro é uma escolha ética, como é o limite: é tudo puramente contextual.
</p>
<p className={styles.center}><strong>*</strong></p>
<p>
O disco branco de João Gilberto é, para muitos, a maior obra da história da música brasileira. Para alguns isso pode
soar forçoso diante da magnitude de outras experiências que temos por aqui, mas acredito de fato que ali haja uma relação
poucas vezes encontrada entre abstração e síncope, delícia e simplicidade, grandiosidade e minimalismo. O disco branco
parece ser o momento em que o juazeirense chegou mais próximo de assumir um projeto total de sua música. Os arranjos são
claros. A capa é simples. As letras são reduzidas ou mesmo subtraídas. O repertório é absolutamente irrastreável.
</p>
<p>
<strong>Undiú</strong> me parece, enfim, o exemplo máximo disso. A composição enigmática traz em si o arranjo enxuto
característico de João Gilberto dando suporte a sua voz em absoluto transe a repetir esta palavra que não nos leva a
sentido algum, mas que nem por isso deixa de ser uma palavra
– <a href="https://www.youtube.com/watch?v=ypPlQA8XTuk" target="_blank" rel="noreferrer">Levaguiã Terê, de Vítor Araújo</a>,
compreendeu isso.Ela distende - se no tempo como som puro, e pensamos estar ouvindo apenas uma linha melódica; no entanto,
em seguida, nos recordamos do título da canção e novamente estamos entregues à busca tão natural pelo sentido daquilo que é
pronunciado.Hesitação.Undiú <em> é e não é</em> uma palavra: é som e é sentido, girando incessantemente nesta voz que ativa
a todo momento este campo de indefinições.
</p>
<p>
Para além dos momentos de <em>undiú</em>, temos também as transições em que João canta melodias feias de maneira bela
(ou o inverso), como a integrar a embocadura de um cantador sertanejo - em sua lógica exterior à Canção - em um arranjo
jazzista, cosmopolita: e novamente giramos juntos com esta voz que aciona dois campos distintos da experiência, tanto
musical quanto social. Há aí, no encantamento da melodia e da entonação, a presença sutil do ruído, que se insinua mesmo
na capa deste disco, no nome quebrado de João Gilberto disposto pelas linhas, na foto que <em>parece</em> ter sido tirada
sem que ele próprio percebesse. A relação, contudo, entre o sertanejo e jazzista não é, em Undiú, a de síntese simples,
muito menos a de emulação - como ocorre na versão de Caetano Veloso para Asa Branca, por exemplo: há aí uma espécie de
acionamento de uma consciência de que estamos lidando com as mesmas questões, com a própria possibilidade de se fazer
sentido diante do mundo e diante das coisas. Questão que a palavra (palavra?) undiú não deixa de ecoar.
</p>
<p>
A apuração e a abstração das canções de João Gilberto nos fazem sempre esquecer de um dado importante: estamos ali
no mundo da síncope, diante do enigma que pode significar algo
como <a href="https://youtu.be/yBm6S9JZK3Q?t=360" target="_blank" rel="noreferrer">os instantes finais de todas as canções de Amoroso</a>,
em que um dos instrumentos parece roubar a cena e quebrar a orquestração; ou como a percussão da versão
de <a href="https://www.youtube.com/watch?v=RatV3LsQzPw" target="_blank" rel="noreferrer"><em>Na Baixa do Sapateiro</em>, do mesmo álbum branco</a>:
sublime e composta na tampa de uma lixeira. Estamos ali na quebra em que se encontram duas tradições do ruído, dois
instantes de genealogia: o jazz e o samba depõem sobre a ética. O jogo da abstração e do encantamento de João é também
um jogo de gestão do ruído em que se constituem espaços em que a quebra torna-se constitutiva, e o equívoco consegue
passar para o lado da estrutura que soa como pura. A pureza do que é impuro, a impureza do que é
puro, <em>as impurezas do branco</em>. Há aí um imenso testemunho sobre como dizemos o mundo.
</p>
<p className={styles.center}><strong>*</strong></p>
<p>
A distância de Sonic Youth a João Gilberto me parece, então, a distância entre dois pontos simétrica e impensavelmente dispostos
ao redor de um centro estável, que poderíamos chamar de ética. Se em Sonic Youth o ruído impede a estabilização, leva sempre a
regiões imprevistas e subterrâneas, em João Gilberto a abstração internaliza o ruído como condição de existência, como aspecto
construtivo do encantamento – no sentido forte do termo. O que temos de ambos os lados é uma gestão do heterogêneo que foge
tanto da síntese fria como da exclusão despótica: estamos lidando com topologias em que campos de relação são criados como
novas formas de dizibilidade. E isso me parece muita coisa sobre o que somos ou poderíamos propor como experiência social.
</p>
<p>
Por isso volto à questão inicial, pensando em que termos a música conseguiria oferecer um escopo para discussões sobre
o indivíduo e suas relações sociais. Creio que o que está em jogo aqui é justamente o que se pode dizer, de que maneira
se pode dizer, e em quais circunstâncias. A música parece, enfim, oferecer um espaço privilegiado para pensar maneiras
de se lidar com essas demandas políticas: e basta pensar, por exemplo, como do encontro de João Gilberto com Sonic Youth
podemos chegar a algo como o Metá Metá, rock cantado sobre ijexá e samba, em brasileiro ou iorùbá.
</p>
<p>
Neste sentido, ouso duvidar rancorosamente de minha professora, e lhe pergunto de volta: como abdicar da tentativa
de ampliar algum tipo de vida sensível para o campo da experiência coletiva, seja ela posta sob o nome de nação ou
outro qualquer? O que está em jogo é o fim de qualquer perspectiva de se falar sobre o outro a partir da sobreposição
das vozes num possível <em>nós</em>? Ou estamos abdicando de algo como a nação em troca de meras experiências individuais
somadas em que cada um assuma seu lugar próprio de enunciação? Tudo isso apenas sugiro. Que restem aqui ao menos as
canções, ressoando na cama de seus erros, e já estou/estamos vingado/s.
</p>
</section >
<TextsNavigation currentCiclo="umSomEstrangeiro" handleRedirect={handleRedirect} />
</div >
);
} |
import { Db } from 'mongodb'
import { createMachine, createActor } from 'xstate'
const resourceMachine = createMachine({
id: 'Resource',
initial: 'undefined',
states: {
undefined: { on: {
Creating: { target: 'Created', guard: 'Cancelled' },
} },
Created: { on: {
Updating: { target: 'Updated', guard: 'Cancelled' },
Deleting: { target: 'Deleting', guard: 'Cancelled' },
} },
Updated: { on: {
Updating: { target: 'Updated', guard: 'Cancelled' },
Deleting: { target: 'Deleting', guard: 'Cancelled' },
} },
Cancelled: { on: { Toggle: 'inactive' } },
Deleted: { type: 'final' },
},
})
// Machine instance with internal state
const streamingService = (db: Db) => {
const documentService = createActor(resourceMachine).start()
documentService.subscribe((state) => console.log(state.value))
documentService.send({ type: 'Toggle' })
documentService.send({ type: 'Toggle' })
}
// Stateless machine definition
// machine.transition(...) is a pure function used by the interpreter.
const toggleMachine = createMachine({
id: 'Switch',
initial: 'inactive',
states: {
inactive: { on: { Toggle: 'active' } },
active: { on: { Toggle: 'inactive' } },
},
})
// Machine instance with internal state
const toggleService = createActor(toggleMachine).start()
toggleService.subscribe((state) => console.log(state.value))
// => 'inactive'
toggleService.send({ type: 'Toggle' })
// => 'active'
toggleService.send({ type: 'Toggle' })
// => 'inactive' |
<?php
/**
* This is the model class for table "{{tribe_migration}}".
*
* The followings are the available columns in table '{{tribe_migration}}':
* @property string $id
* @property string $entity_id
* @property string $to_id
* @property string $added
* @property string $executed_at
*
* The followings are the available model relations:
* @property Entity $entity
* @property Tribe $to
*/
class TribeMigration extends TribeMigrationBase
{
const STATUS_PENDING = 'pending';
const STATUS_CONFIRMED = 'confirmed';
const STATUS_REJECTED = 'rejected';
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return TribeMigrationBase the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{tribe_migration}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('entity_id, to_id', 'required'),
array('entity_id, to_id', 'length', 'max'=>11),
array('added, executed_at', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, entity_id, to_id, added, executed_at', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'entity' => array(self::BELONGS_TO, 'Entity', 'entity_id'),
'tribe' => array(self::BELONGS_TO, 'Tribe', 'to_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'entity_id' => 'Entity',
'to_id' => 'To',
'added' => 'Added',
'executed_at' => 'Executed At',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id,true);
$criteria->compare('entity_id',$this->entity_id,true);
$criteria->compare('to_id',$this->to_id,true);
$criteria->compare('added',$this->added,true);
$criteria->compare('executed_at',$this->executed_at,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
} |
import Head from "next/head";
import {useAppSelector} from "store";
import Navbar1 from "components/navbar-1";
import LeftSidebar1 from "components/left-sidebar-1";
import RightSidebar1 from "components/right-sidebar-1";
export type Layout1Props = {
children: React.ReactNode;
};
const Layout1: React.FC<Layout1Props> = ({children}) => {
const config = useAppSelector((state) => state.config);
const {background, layout, collapsed} = config;
return (
<>
<Head>
<title>D-board</title>
</Head>
<div
data-layout={layout}
data-collapsed={collapsed}
data-background={background}
className={`font-sans antialiased text-sm disable-scrollbars ${
background === "dark" ? "dark" : ""
}`}>
<RightSidebar1 />
<div className="wrapper">
<LeftSidebar1 />
<div className="main w-full bg-gray-50 text-gray-900 dark:bg-gray-900 dark:text-white">
<Navbar1 />
<div className="w-full min-h-screen p-4">{children}</div>
</div>
</div>
</div>
</>
);
};
export default Layout1; |
<?php
namespace App\Exceptions;
use App\Traits\ApiResponseTrait; //引用特徵
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response; //引用網址不允許此動詞
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; //引用網址輸入錯誤
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
class GlobalExceptionHandler extends ExceptionHandler
{
use ApiResponseTrait; //使用特徵,類似將Trait撰寫的方法貼到這個類別中
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
public function render($request, Throwable $exception)
{
//TODO: 這邊以後可以規劃拆分response code(模組 code + 定義 ErrorCode), statusCode (ex: 400、500...)
# Model 找不到資料
if ($exception instanceof ModelNotFoundException) {
return $this->errorResponse(
'找不到指定資料',
Response::HTTP_NOT_FOUND
);
}
# 網址輸入錯誤
if ($exception instanceof NotFoundHttpException) {
return $this->errorResponse(
'無法找到此網址',
Response::HTTP_NOT_FOUND
);
}
# 網址不允許該請求的動作
if ($exception instanceof MethodNotAllowedHttpException) {
return $this->errorResponse(
$exception->getMessage(), //回傳例外內的訊息
Response::HTTP_NOT_FOUND
);
}
# Request Validation Error
if ($exception instanceof ValidationException) {
return $this->errorResponse(
$exception->getMessage(), //回傳例外內的訊息
Response::HTTP_BAD_REQUEST
);
}
# 自定義 exception
if ($exception instanceof ApiException) {
return $this->errorResponse(
$exception->getMessage(), //回傳例外內的訊息
$exception->getCode() //自定義statusCode
);
}
//TODO: 先自定義 500 statusCode
# DB Sql Exception
if ($exception instanceof QueryException) {
return $this->errorResponse(
$exception->getMessage(), //回傳 DB 拋出的 error message
500,
);
}
return parent::render($request, $exception);
}
protected function unauthenticated($request, AuthenticationException $exception)
{
# 客戶端請求JSON格式
if ($request->expectsJson()) {
return $this->errorResponse(
$exception->getMessage(),
Response::HTTP_UNAUTHORIZED
);
} else {
# 客戶端非請求JSON格式轉回登入畫面
redirect()->guest($exception->redirectTo() ?? route('login'));
}
}
} |
export default class mainScene extends Phaser.Scene {
constructor() {
super("mainScene");
this.grond;
this.platforms;
this.player;
this.cursor;
}
preload() {
this.load.image("sky", "../assets/sky.png");
this.load.image("ground", "../assets/ground.png");
this.load.image("platform", "../assets/platform.png");
this.load.spritesheet("player", "../assets/player/player.png", {
frameWidth: 32,
frameHeight: 32,
});
}
create() {
this.add.image(400, 300, "sky");
this.grond = this.physics.add.staticGroup();
this.grond.create(400, 600, "ground");
this.platforms = this.physics.add.staticGroup();
this.platforms.create(200, 350, "platform");
this.platforms.create(50, 500, "platform");
this.platforms.create(550, 350, "platform");
this.platforms.create(600, 500, "platform");
this.player = this.physics.add.sprite(100, 100, "player");
this.player.setCollideWorldBounds(true);
this.player.setBounce(0.2);
this.cursor = this.input.keyboard.createCursorKeys();
this.physics.add.collider(this.player, this.platforms);
this.physics.add.collider(this.player, this.grond);
}
update() {
if (this.cursor.left.isDown) {
this.player.setVelocityX(-160);
this.player.anims.play("left", true);
} else if (this.cursor.right.isDown) {
this.player.setVelocityX(160);
this.player.anims.play("right", true);
} else {
this.player.setVelocityX(0);
this.player.anims.play("turn");
}
if (this.cursor.up.isDown && this.player.body.touching.down) {
this.player.setVelocityY(-330);
}
}
} |
import java.awt.*;
/**
* The Bishop class represents a chess bishop piece with a specified color and name.
*/
public class Bishop extends ChessPiece {
/**
* Creates a new Bishop instance with the given color and name.
*
* @param color The color of the bishop.
*/
public Bishop(Color color) {
super(color);
this.name = "Bishop";
}
/**
* Checks if a move from one chess square to another is a valid move for a bishop.
*
* @param board The chessboard represented as an array of chess squares.
* @param fromRow The row of the source square.
* @param fromCol The column of the source square.
* @param toRow The row of the target square.
* @param toCol The column of the target square.
* @return true if the move is a valid diagonal move for a bishop, false otherwise.
*/
@Override
public boolean isValidMove(ChessSquare[][] board, int fromRow, int fromCol, int toRow, int toCol) {
// Check for diagonal movement
if (Math.abs(toRow - fromRow) == Math.abs(toCol - fromCol)) {
return isWayClear(board, fromRow, fromCol, toRow, toCol);
}
// Invalid move for a Bishop: not diagonal
return false;
}
} |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
"""
import logging
import os
import powerflex_write as pfw
import serial.tools.list_ports
import subprocess
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk
class Window(tk.Frame):
def __init__(self, main=None):
tk.Frame.__init__(self, main)
self.main = main
self.l5x_file = tk.StringVar()
self.l5x_file.set("")
self.port_val = tk.StringVar()
self.port_val.set("")
self.output_val = tk.StringVar()
self.output_val.set("output/")
self.files = tk.StringVar()
self.file_name = self.l5x_file.get()
# make the output directory to put generated files
if not os.path.exists("output"):
os.mkdir("output")
self.files = self.get_vfd_files()
self.log_file = "{}logjammin.log".format(self.output_val.get())
logging.basicConfig(filename=self.log_file, filemode="w", format='%(asctime)s - %(message)s')
self.log = logging.getLogger()
self.log.setLevel(logging.DEBUG)
self.frame1 = tk.LabelFrame(self.main, text="Choose L5X")
self.l5x_entry = tk.Entry(self.frame1, textvariable=self.l5x_file)
self.open = tk.Button(self.frame1, text="...", command=self.file_open)
self.start_vfd = tk.Button(self.frame1, text="Generate VFD Files", command=self.generate_vfd)
self.frame3 = tk.LabelFrame(self.main, text="Write VFD")
self.com_lbl = tk.Label(self.frame3, text="COM Port:")
self.com_port = ttk.Combobox(self.frame3, textvariable=self.port_val)
self.out_lbl = tk.Label(self.frame3, text="Output Dir:")
self.output_dir = tk.Entry(self.frame3, textvariable=self.output_val)
self.write_parm = tk.Button(self.frame3, text="Write All Parameter Files", command=self.write_vfd)
self.frame4 = tk.LabelFrame(self.main, text="Files")
self.files_list = pfw.enhanced_listbox.EnhancedListbox(self, self.frame4, selectmode="multiple")
self.parser = pfw.parser.Parse(self)
self.writer = pfw.vfd.Writer(self)
self.init_window()
def init_window(self):
self.log.info("GUI - Initializing UI")
# update title
self.main.title("Write Power-flex Parameters - {}".format(pfw.__version__))
# create a menu
menu = tk.Menu(self.main)
self.main.config(menu=menu)
# Add file dropdown with exit
file = tk.Menu(menu)
file.add_command(label="Open L5X", command=self.file_open)
file.add_command(label="Open Log", command=self.open_log)
file.add_command(label="Refresh Com", command=self.refresh_com)
file.add_command(label="Exit", command=self.close)
menu.add_cascade(label="File", menu=file)
# frame for file/open
self.frame1.pack(fill=tk.BOTH, padx=5, pady=5)
self.l5x_entry.pack(side=tk.LEFT, expand=True, fill=tk.X, padx=5)
self.open.pack(side=tk.LEFT, expand=tk.NO, padx=5, pady=5)
self.start_vfd.pack(side=tk.BOTTOM, padx=5, pady=5)
self.start_vfd['state'] = 'disabled'
# frame for writing VFD parameters
self.frame3.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.com_lbl.grid(row=0, column=0, pady=2, sticky="e")
self.com_port.grid(row=0, column=1, pady=2, sticky="w")
self.out_lbl.grid(row=1, column=0, pady=2, stick="e")
self.output_dir.grid(row=1, column=1, pady=2, sticky="w")
self.write_parm.grid(row=2, column=0, padx=5, pady=5)
self.frame4.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.files_list.pack(fill=tk.BOTH, padx=5, pady=5)
self.refresh_file_list()
self.log.info("GUI - UI Loaded v{}".format(pfw.__version__))
def file_open(self):
"""
Handle opening a L5X file
"""
filetypes = [('L5X files', '*.L5X')]
self.log.info("GUI - Opening file")
self.file_name = filedialog.askopenfilename(filetypes=filetypes)
self.log.info("GUI - File {} opened".format(self.file_name))
if self.file_name:
self.log.info("GUI - Parsing file {}".format(self.file_name))
self.l5x_file.set(self.file_name)
self.log.info("GUI - File {} parsed".format(self.file_name))
self.start_vfd['state'] = 'normal'
def generate_vfd(self):
"""
Generate files for writing IP address to VFDs
"""
self.log.info("GUI - Generate VFD files requested")
self.parser.generate_vfd_files(self.file_name)
messagebox.showinfo("Information", "VFD files generated")
self.refresh_file_list()
def refresh_file_list(self):
"""
Clear out our file list, then refresh it
"""
self.files_list.delete(0, tk.END)
self.files = self.get_vfd_files()
for f in self.files:
self.files_list.insert(tk.END, f)
def write_vfd(self):
"""
Write VFD parameters from generated files
"""
self.log.info("GUI - Write VFD parameters requested")
self.writer.write(self.write_callback)
def write_callback(self, name):
"""
Called each time a drive is successfully written to.
Delete the name from the list
"""
idx = self.files_list.get(0, tk.END).index(name)
self.files_list.delete(idx)
def refresh_com(self):
"""
update our com port combo box with available
ports
"""
self.log.info("GUI - Refreshing com ports")
ports = serial.tools.list_ports.comports()
stuff = []
for port, desc, hwid in sorted(ports):
self.log.info("GUI - Found COM port: {}".format(port))
stuff.append(port)
self.com_port["values"] = stuff
try:
self.com_port.current(len(ports)-1)
except (Exception, ):
self.log.info("GUI - Failed to refresh com ports")
def get_vfd_files(self):
"""
Find all text files in the current directory
and return them as a list
"""
drive_files = []
for text_file in os.listdir(self.output_val.get()):
if text_file.endswith('.vfd'):
drive_files.append(text_file)
drive_files.sort()
return drive_files
def open_log(self):
"""
Open log file from menu
"""
self.log.info("GUI - Opening log file with notepad")
subprocess.call(["notepad.exe", self.log_file])
def close(self):
"""
Exit app
"""
self.log.info("GUI - User exit requested")
exit()
root = tk.Tk()
root.geometry("460x360")
root.resizable(False, False)
app = Window(root)
root.mainloop() |
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy } from 'passport-facebook';
import { IEnvironment } from '@noinghe/shared/utils/lib/interfaces';
import { IOauthUser } from '@noinghe/api/core/lib/request';
@Injectable()
export class FacebookStrategy extends PassportStrategy(Strategy, 'facebook') {
constructor(private readonly configService: ConfigService) {
super(config(configService));
}
async validate(
accessToken: string,
refreshToken: string,
profile: Profile,
done: (err: any, user: any, info?: any) => void,
): Promise<any> {
try {
const { emails } = profile;
const id = profile.id;
const fullname = profile.displayName;
const avatar = (profile.photos || []).find((photo) => photo.value)?.value || '';
const email = (profile.emails || []).find((email) => email.value)?.value || '';
const user: IOauthUser = {
emails,
accessToken,
verified: true,
avatar,
email,
fullname,
id,
social: 'facebook',
};
done(null, user);
} catch (err) {
done(err, false);
}
}
}
export const config = (configService: ConfigService) => {
const FACEBOOK_CONFIG = configService.get('facebookConfig') as IEnvironment['facebookConfig'];
const { baseUrl } = configService.get('apiConfigOptions') as IEnvironment['apiConfigOptions'];
return {
clientID: FACEBOOK_CONFIG.clientId || 'disabled',
clientSecret: FACEBOOK_CONFIG.clientSecret || 'disabled',
callbackURL: FACEBOOK_CONFIG.oauthRedirectUri || `${baseUrl}/api/auth/facebook/callback`,
scope: 'email',
profileFields: ['emails', 'displayName', 'picture', 'id'],
};
}; |
@extends('layouts.app')
@section('content')
<div class="col-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">User Info</th>
<th scope="col">Category Count</th>
<th>Article Count</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
<tbody>
@forelse ($users as $key => $user)
<tr>
<th scope="row">{{ $key + 1 }}</th>
<td>
{{ $user->name }}
<p class="text-black-50">
{{ $user->email }}
</p>
</td>
{{-- <td> {{$user->categories->pluck('title')}} </td> --}}
<td class="text-center"> {{ $user->categories->count() }}</td>
<td class="text-center"> {{ $user->articles->count() }} </td>
<td>
{{-- >diffforhumans() //15mins ago 3hrs ago --}}
<p class="mb-0 small"> <i class="bi bi-clock-history"></i>
{{ $user->created_at->format('H:i a') }} </p>
<p class="mb-0 small"> <i class="bi bi-calendar-check"></i>
{{ $user->created_at->format('d m Y') }} </p>
</td>
<td>
<p class="small mb-0"> <i class="bi bi-clock-history"> </i>
{{ $user->updated_at->format('H:i a') }} </p>
<p class="small mb-0"> <i class="bi bi-calendar-check"></i>
{{ $user->updated_at->format('d m Y') }} </p>
</td>
</tr>
@empty
<tr>
<td colspan="5" class="text-center">
<p class="text-secondary">
There's no article.
</p>
<a href="{{ route('articles.create') }}"
class="btn btn-outline-primary inline-block mb-2">Create an article</a>
</td>
</tr>
@endforelse
</tbody>
</table>
<div class="float-end">
{{ $users->onEachSide(2)->links() }}
</div>
</div>
@endsection |
/*!
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project.
*/
import { useMemo } from 'react'
import { useCausalFactors } from '../../state/causalFactors.js'
import { useDefinitions } from '../../state/definitions.js'
import { useSubjectIdentifier } from '../../state/subjectIdentifier.js'
import { isFullDatasetPopulation } from '../../utils/definition.js'
import { useAllVariables } from '../useAllVariables.js'
import { useOutputTable } from '../useOutputTable.js'
import { useIsDataTypeValid } from '../validateColumnDataTypes.js'
import { useIsMicrodata } from './useIsMicrodata.js'
export function useDataErrors(): {
isMicrodata: boolean
isMissingVariable: boolean
isMissingIdentifier: boolean
isNotInOutputTable: boolean
isValidDataType: boolean
hasAnyError: boolean
} {
const outputTable = useOutputTable()
const subjectIdentifier = useSubjectIdentifier()
const definitions = useDefinitions()
const causalFactors = useCausalFactors()
const allVariables = useAllVariables(causalFactors, definitions)
const isMicrodata = useIsMicrodata(outputTable, subjectIdentifier)
const [isValidDataType = true] = useIsDataTypeValid() || []
const variablesColumns = useMemo(
() => [subjectIdentifier, ...allVariables.map(v => v.column)],
[subjectIdentifier, allVariables],
)
const outputTableColumns = useMemo(
() => outputTable?.columnNames() || [],
[outputTable],
)
const isMissingVariable = useMemo(
() => allVariables.some(i => !i.column),
[allVariables],
)
const isNotInOutputTable = useMemo(
() =>
variablesColumns
.filter(v => !!v)
.some(i => {
const missing = !outputTableColumns.includes(i || '')
if (
missing &&
!!definitions.find(
x => x.column === i && isFullDatasetPopulation(x),
)
) {
return false
}
return missing
}),
[variablesColumns, outputTableColumns, definitions],
)
const isMissingIdentifier = !subjectIdentifier && !!outputTable
const hasAnyError = useMemo((): boolean => {
return (
!isMicrodata ||
isMissingVariable ||
isMissingIdentifier ||
isNotInOutputTable ||
!isValidDataType
)
}, [
isMicrodata,
isMissingVariable,
isMissingIdentifier,
isNotInOutputTable,
isValidDataType,
])
return {
isMicrodata,
isMissingVariable,
isMissingIdentifier,
isNotInOutputTable,
isValidDataType,
hasAnyError,
}
} |
package com.ifeanyi.read.core.services
import android.content.Context
import com.ifeanyi.read.core.enums.AppTheme
import com.ifeanyi.read.core.enums.DisplayStyle
import com.ifeanyi.read.core.util.Constants
import android.speech.tts.Voice
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.util.Locale
class PreferenceService(private val context: Context) {
companion object {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "store")
}
fun getString(key: String): Flow<String?> {
return context.dataStore.data.map { pref ->
pref[stringPreferencesKey(key)]
}
}
suspend fun saveString(key: String, value: String) {
context.dataStore.edit { preferences ->
preferences[stringPreferencesKey(key)] = value
}
}
fun getVoice(): Flow<Voice> {
return context.dataStore.data.map { pref ->
val items = pref[stringPreferencesKey(Constants.voice)]?.split("/") ?: listOf("en-us-x-tpf-local", "en", "US")
Voice(items[0], Locale(items[1], items[2]), 400, 200, false, emptySet())
}
}
fun getTheme(): Flow<AppTheme> {
return context.dataStore.data.map { pref ->
AppTheme.valueOf(pref[stringPreferencesKey(Constants.theme)] ?: "System")
}
}
fun getDisplayStyle(): Flow<DisplayStyle> {
return context.dataStore.data.map { pref ->
DisplayStyle.valueOf(pref[stringPreferencesKey(Constants.displayStyle)] ?: "Grid")
}
}
} |
package exer;
/**
* 一道面试题 考察的是String的不可变性。 局部变量指向了一个新串的位置,原来的位置的东西没变。
* @author shkstart
* @create 2019 上午 11:32
*/
public class StringTest {
String str = new String("good");
char[] ch = { 't', 'e', 's', 't' };
public void change(String str, char ch[]) {
str = "test ok";
ch[0] = 'b';
}
public static void main(String[] args) {
StringTest ex = new StringTest();
ex.change(ex.str, ex.ch);
System.out.println(ex.str);//good
System.out.println(ex.ch);//best
}
} |
//
// File.swift
//
//
// Created by Dan Tran on 20/12/2023.
//
import ComposableArchitecture
import SwiftUI
import Common
@Reducer
public struct CartListDomain {
public init() {}
public struct State: Equatable {
public var carts: IdentifiedArrayOf<CartDomain.State> = []
public var totalPrice: Double = 0
public init(carts: IdentifiedArrayOf<CartDomain.State> = []) {
self.carts = carts
}
}
public enum Action: Equatable {
case cart(id: String, action: CartDomain.Action)
case getTotalPrice
}
public var body: some Reducer<State, Action> {
Reduce { state, action in
switch action {
case .cart(let id, let action):
switch action {
case .delete:
state.carts.removeAll(where: { $0.id == id })
return .send(.getTotalPrice)
}
case .getTotalPrice:
state.totalPrice = state.carts.reduce(0.0, {
$0 + ($1.cart.product.price * Double($1.cart.quantity))
})
return .none
}
}
.forEach(\.carts, action: /Action.cart(id:action:)) {
CartDomain()
}
}
}
public struct CartListView: View {
let store: StoreOf<CartListDomain>
public init(store: StoreOf<CartListDomain>) {
self.store = store
}
public var body: some View {
WithViewStore(self.store, observe: { $0 }) { viewStore in
NavigationView {
List {
ForEachStore(
self.store.scope(
state: \.carts,
action: CartListDomain.Action.cart(id:action:)
),
content: CartView.init(store:)
)
}
.safeAreaInset(edge: .bottom) {
Text("Total price: \(viewStore.totalPrice.description)")
}
.onAppear {
viewStore.send(.getTotalPrice)
}
.navigationTitle("Cart")
}
}
}
}
#Preview {
CartListView(
store: Store(
initialState: CartListDomain.State(
carts: IdentifiedArrayOf(
uniqueElements: Cart.sample.map {
CartDomain.State(cart: $0)
}
)
), reducer: {
CartListDomain()
}
)
)
} |
import BaseController from "./BaseController";
import formatter from "../model/formatter";
import { IRolesOutRoot } from "common";
import Event from "sap/ui/base/Event";
import Input from "sap/m/Input";
import MessageBox from "sap/m/MessageBox";
import { ModelNames } from "../model/models";
import JSONModel from "sap/ui/model/json/JSONModel";
import Message from "sap/ui/core/Message";
/**
* @namespace com.gavdilabs.ui5template.controller
*/
export default class Main extends BaseController {
private formatter = formatter;
public async onSearchUser(event: Event): Promise<void> {
//Gotta love TS & SAPUI5 - we need to cast to allow getSource
const userId = (event.getSource() as Input).getValue();
//Same username? => return
if (
this.getModel(ModelNames.USER_DETAILS) &&
userId ===
(this.getModel(ModelNames.USER_DETAILS) as JSONModel).getProperty(
"/userId"
)
) {
return;
}
//Set busy state
this.getOwnerComponent().setIsBusy(true);
//First user details then fill the roles
this.fillUserDetails(userId)
.then(() => {
this.fillUserRoles(userId);
//Set busy state
this.getOwnerComponent().setIsBusy(false);
})
.catch((errMessage: string) => {
MessageBox.error(errMessage);
//Set busy state
this.getOwnerComponent().setIsBusy(false);
});
}
} |
import { PHONE_NUMBER_REGEX } from "@/constants"
import * as yup from "yup"
export const emailSchema = yup.object().shape({
email: yup.string().email("Email không hợp lệ!").required("Không được bỏ trống"),
})
export const phoneNumberSchema = yup.object().shape({
phone: yup
.string()
.matches(PHONE_NUMBER_REGEX, "Số điện thoại không hợp lệ")
.required("Không được để trống"),
})
export const requiredSchema = (name: string) => {
const requiredSchema = yup.object().shape({
[name]: yup.string().required("Không được bỏ trống"),
})
return requiredSchema
}
export const getSchema = (name: string) => {
switch (name) {
case "email":
return emailSchema
case "phone":
return phoneNumberSchema
default:
break
}
} |
var currentModule = "";
var currentQuestionIndex = 0;
var currentQuestionIndexList = [];
var currentQuestion = [];
var moduleQuestions = [];
var questions = [];
function loadQuestions(module) {
currentModule = module;
if(currentModule == 'all'){
moduleQuestions = questions;
}else{
moduleQuestions = questions.filter(question => question.module === module);
}
var randomQuestionNumber = Math.floor(Math.random() * moduleQuestions.length);
if(currentQuestionIndexList.includes(randomQuestionNumber)){
return loadQuestions(module);
}
currentQuestionIndexList.push(randomQuestionNumber);
currentQuestionIndex = randomQuestionNumber;
displayQuestion(moduleQuestions[currentQuestionIndex]);
}
function displayQuestion(question) {
if(question.question == undefined){
return loadHomeScreen();
}
var questionDiv = document.getElementById('question');
var answersDiv = document.getElementById('answers');
questionDiv.textContent = question.question;
answersDiv.innerHTML = "";
var options = [];
for (var key in question) {
if (key.startsWith('answer')) {
options.push({ originalValue: options.length, shuffledValue: question[key] });
}
}
// Shuffle the array using the Fisher-Yates algorithm
for (var i = options.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
// Swap elements
[options[i], options[j]] = [options[j], options[i]];
}
var answersDiv = document.getElementById('answers');
options.forEach((option, index) => {
var optionButton = document.createElement('button');
optionButton.textContent = option.shuffledValue;
optionButton.classList.add('optionsBtn');
optionButton.setAttribute('data-v', index + option.originalValue);
optionButton.addEventListener('click', function() {
if (document.getElementsByClassName('selected')[0]) {
document.getElementsByClassName('selected')[0].classList.remove('selected');
}
if (document.getElementsByClassName('correct')[0]) {
document.getElementsByClassName('correct')[0].classList.remove('correct');
}
if (document.getElementsByClassName('wrong')[0]) {
document.getElementsByClassName('wrong')[0].classList.remove('wrong');
}
this.classList.add('selected');
// Add logic to check if the selected option is correct or wrong
// You can compare this.textContent with the correct answer, for example
});
answersDiv.appendChild(optionButton);
});
currentQuestion = question;
document.getElementById('homeScreen').style.display = 'none';
document.getElementById('flashcard').style.display = 'block';
}
function checkAnswer() {
var answerButtons = document.getElementById('answers');
var answerButtonsSelected = document.getElementsByClassName('selected')[0];
var index = Array.prototype.indexOf.call(answerButtons.children, answerButtonsSelected);
if(document.getElementsByClassName('selected')[0]){
document.getElementsByClassName('selected')[0].classList.remove('selected');
}
if(document.getElementsByClassName('correct')[0]){
document.getElementsByClassName('correct')[0].classList.remove('correct');
}
if(document.getElementsByClassName('wrong')[0]){
document.getElementsByClassName('wrong')[0].classList.remove('wrong');
}
if(index !== -1){
var og = answerButtonsSelected.getAttribute('data-v') - index;
if(currentQuestion.correctAnswer == (og + 1)){
answerButtonsSelected.classList.add('correct');
}else{
answerButtonsSelected.classList.add('wrong');
}
}
}
function nextQuestion() {
if (currentQuestionIndexList.length < moduleQuestions.length) {
var randomQuestionNumber = Math.floor(Math.random() * moduleQuestions.length);
if(currentQuestionIndexList.includes(randomQuestionNumber)){
return nextQuestion();
}
currentQuestionIndexList.push(randomQuestionNumber);
currentQuestionIndex = randomQuestionNumber;
displayQuestion(moduleQuestions[currentQuestionIndex]);
} else {
loadHomeScreen();
}
}
function loadHomeScreen() {
currentQuestionIndexList = [];
currentModule = "";
currentQuestionIndex = 0;
document.getElementById('homeScreen').style.display = 'block';
document.getElementById('flashcard').style.display = 'none';
}
async function initialize() {
var csvRows = await loadQuestionsFromCSV();
var headers = csvRows[0].split(',');
for (var i = 1; i < csvRows.length; i++) {
var values = csvRows[i].split(',');
var questionObject = {};
for (var j = 0; j < headers.length; j++) {
questionObject[headers[j]] = values[j];
}
questions.push(questionObject);
}
}
async function loadQuestionsFromCSV() {
const response = await fetch('questions.csv');
const csvText = await response.text();
var csvRows = csvText.split('\r\n');
var modules = [...new Set(csvRows.slice(1).map(row => row.split(',')[0]))];
var moduleButtonsDiv = document.getElementById('moduleButtons');
modules.forEach(module => {
if (module.trim() === '') return;
var button = document.createElement('button');
button.textContent = module.trim();
button.classList.add('button');
button.addEventListener('click', function() {
loadQuestions(module);
});
moduleButtonsDiv.appendChild(button);
});
return csvRows;
}
initialize(); |
package utils
import org.apache.commons.math3.analysis.UnivariateFunction
import org.apache.commons.math3.analysis.integration.TrapezoidIntegrator
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.math.*
fun cot(x: Double): Double {
return 1.0 / tan(x)
}
fun coth(x: Double): Double {
return 1.0 / tanh(x)
}
fun sec(x: Double): Double {
return 1.0 / cos(x)
}
fun csc(x: Double): Double {
return 1.0 / sin(x)
}
fun sech(x: Double): Double {
return 1.0 / cosh(x)
}
fun csch(x: Double): Double {
return 1.0 / sinh(x)
}
fun multifactorial(number: Double, factorial: Double = 1.0, i: Int = 0): Double {
if (number < 0) return Double.NaN
if (factorial == 1.0) return number.gammaFactorial()
if (number <= factorial) return number
return number * multifactorial(number - factorial, factorial, i + 1)
}
fun Double.gammaFactorial(): Double {
return gamma(this + 1)
}
fun gammaLanczos(x: Double): Double {
var xx = x
val p = doubleArrayOf(
0.99999999999980993,
676.5203681218851,
-1259.1392167224028,
771.32342877765313,
-176.61502916214059,
12.507343278686905,
-0.13857109526572012,
9.9843695780195716e-6,
1.5056327351493116e-7
)
val g = 7
if (xx < 0.5) return Math.PI / (Math.sin(Math.PI * xx) * gammaLanczos(1.0 - xx))
xx--
var a = p[0]
val t = xx + g + 0.5
for (i in 1 until p.size) a += p[i] / (xx + i)
return Math.sqrt(2.0 * Math.PI) * Math.pow(t, xx + 0.5) * Math.exp(-t) * a
}
fun gamma(x: Double): Double {
val bigDecimal = BigDecimal(gammaLanczos(x)).setScale(8, RoundingMode.HALF_UP)
return bigDecimal.toDouble()
}
fun integrate(a: Double, b: Double, f: (Double)->Double): Double {
val value = integral(
a,
b,
10000,
::simpson,
f
)
val bigDecimal = BigDecimal(value).setScale(2, RoundingMode.HALF_UP)
return bigDecimal.toDouble()
} |
import React, { ReactNode, useCallback, useState } from "react"
import { fetchNui } from "../utils/fetchNui"
export type ContextType = {
templates: DocumentTemplate[] | null
templatesLoading: boolean
setTemplatesLoading: (isLoading: boolean) => void
handleGetTemplates: () => void
documents: K5Document[] | null
documentsLoading: boolean
setDocumentsLoading: (isLoading: boolean) => void
handleGetDocuments: () => void
viewDocument: K5Document | undefined
setViewDocument: (doc: K5Document | undefined) => void
isViewDocOpen: boolean
setViewDocOpen: (open: boolean) => void
documentCopies: K5Document[] | null
documentCopiesLoading: boolean
setDocumentCopiesLoading: (isLoading: boolean) => void
handleGetDocumentCopies: () => void
}
export const Context = React.createContext<ContextType>({} as ContextType)
export const ContextProvider = (props: {children: ReactNode}) => {
const [templates, setTemplates] = useState<DocumentTemplate[] | null>(null)
const [templatesLoading, setTemplatesLoading] = useState(false)
const [documents, setDocuments] = useState<K5Document[] | null>(null)
const [documentsLoading, setDocumentsLoading] = useState(false)
const [documentCopies, setDocumentCopies] = useState<K5Document[] | null>(null)
const [documentCopiesLoading, setDocumentCopiesLoading] = useState(false)
const [viewDocument, setViewDocument] = useState<K5Document | undefined>()
const [isViewDocOpen, setViewDocOpen] = useState(false)
const handleGetTemplates = useCallback(() => {
fetchNui('getMyTemplates').then(retData => {
setTemplatesLoading(false)
setTemplates(retData)
}).catch(_e => {
console.error('An error has occured')
})
}, [])
const handleGetDocuments = useCallback(() => {
fetchNui('getIssuedDocuments').then(retData => {
setDocumentsLoading(false)
setDocuments(retData)
}).catch(_e => {
console.error('An error has occured')
})
}, [])
const handleGetDocumentCopies = useCallback(() => {
fetchNui('getPlayerCopies').then(retData => {
setDocumentCopiesLoading(false)
setDocumentCopies(retData)
}).catch(_e => {
console.error('An error has occured')
})
}, [])
return (
<Context.Provider value={{
templates,
templatesLoading,
setTemplatesLoading,
handleGetTemplates,
documents,
documentsLoading,
setDocumentsLoading,
handleGetDocuments,
viewDocument,
setViewDocument,
isViewDocOpen,
setViewDocOpen,
documentCopies,
documentCopiesLoading,
setDocumentCopiesLoading,
handleGetDocumentCopies
}}>
{props.children}
</Context.Provider>
)
} |
import Select from "react-select";
import { useNavigate, useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import axios from "axios";
import { constants } from "../constant";
import FeatureCard from "../components/FeatureCard";
export const SearchPage = () => {
const navigateTo = useNavigate();
const { searchUrl } = useParams();
const [users, setUsers] = useState([]);
const CONSTANTS = constants();
const options = [
{
value: 1973,
label: "1973",
},
{
value: 1974,
label: "1974",
},
{
value: 1975,
label: "1975",
},
{
value: 1976,
label: "1976",
},
];
useEffect(() => {
axios
.get(`${CONSTANTS.API_BASE_URL}verified-users`)
.then((res) => {
const filteredUsers = res.data.filter((user) => {
const regex = new RegExp(searchUrl, "i"); // 'i' flag for case-insensitive search
return regex.test(user.firstName) || regex.test(user.lastName);
});
console.log(filteredUsers);
setUsers(filteredUsers);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<div className="batches ">
<h1 className="sm:text-3xl text-lg font-semibold text-center text-gray-900 mt-4">
Search Results
</h1>
<div className="grid mt-12 grid-cols-1 md:grid-cols-4 gap-6">
{users.length === 0 && (
<p className="text-center text-3xl">No results found</p>
)}
{users.map((user) => {
return (
<div className="h-[25rem]">
<FeatureCard
key={user._id}
id={user._id}
avatar={user?.photos.length > 0 && user?.photos[0]}
name={user.firstName + user?.lastName}
branch={`${user?.branch} ${user?.graduationYear}`}
description={user?.about}
/>
</div>
);
})}
</div>
</div>
);
}; |
package org.anoitos.parser.statement.statements
import org.anoitos.lexer.token.Token
import org.anoitos.lexer.token.TokenType
import org.anoitos.parser.extensions.search
import org.anoitos.parser.statement.Statement
import org.anoitos.parser.statement.StatementParser
data class FunStatement(
val name: Token,
val parameters: List<String>,
val body: BlockStatement
) : Statement {
companion object : StatementParser<FunStatement> {
override fun parse(input: List<Token>): Pair<Int, FunStatement>? {
val (size, _, name, _, parameters, _, _, body, _) = input.search(
TokenType.FUN,
TokenType.ID,
TokenType.LPAREN,
TokenType.SEARCH_GROUP,
TokenType.RPAREN,
TokenType.LBRACE,
TokenType.SEARCH_GROUP,
TokenType.RBRACE
) ?: return null
val parameterNames = mutableListOf<String>()
for (index in 0..parameters.lastIndex step 2) {
parameterNames.add(parameters[index].value)
}
return size to FunStatement(
name[0],
parameterNames,
BlockStatement.parse(body).second
)
}
}
} |
import Head from "next/head";
import { useAuth } from "@/contexts/auth";
import useResource from "@/hooks/useResource";
export default function Home() {
// const user = null; // this will be authentication code
// const user = { username: 'somebody' }; // this will be authentication code
const { user, login, logout } = useAuth(); // user variable and login() function come from the useAuth hook
return (
<div>
<Head>
<title>Cookie Stand Admin</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="p-4 space-y-8 text-center">
<h1 className="text-4xl">
Fetching Data from Authenticated API
</h1>
{user ? (
<>
<h2>Welcome username: {user.username}</h2>
<h2>Whose email is {user.email}</h2>
<button
onClick={logout}
className="p-2 text-white bg-gray-500 rounded"
>
Logout
</button>
{/* <StandList stands={resources} loading={loading} /> */}
<CookieStandAdmin />
</>
) : (
<>
{/* <h2>Need to log in</h2>
<button
onClick={() => login("admin", "1234")}
className="p-2 text-white bg-gray-500 rounded"
>
Login
</button> */}
<LoginForm onLogin={login} />
</>
)}
</main>
</div>
);
}
function LoginForm({ onLogin }) {
async function handleSubmit(event) {
event.preventDefault();
onLogin(event.target.username.value, event.target.password.value);
}
return (
<form onSubmit={handleSubmit}>
<fieldset autoComplete="off">
<legend>Log In</legend>
<label htmlFor="username">Username</label>
<input name="username" />
<label htmlFor="password">Password</label>
<input type="password" name="password" />
<button>Log In</button>
</fieldset>
</form>
);
}
// Don't need a <li> we need a table!
// function StandList({ stands, loading }) {
// if (loading) {
// return <p>Loading...</p>;
// }
// return (
// <ul>
// {stands.map((stand) => (
// <li key={stand.id}>{stand.location}</li>
// ))}
// </ul>
// );
// }
function CookieStandAdmin() {
const { resources, deleteResource } = useResource();
return (
<>
<CookieStandForm />
<CookieStandTable
stands={resources || []}
deleteStand={deleteResource}
/>
</>
);
}
function CookieStandForm() {
const { user } = useAuth();
const { createResource } = useResource();
function handleSubmit(event) {
event.preventDefault();
const info = {
location: event.target.location.value,
minimum_customers_per_hour: parseInt(event.target.minimum.value),
maximum_customers_per_hour: parseInt(event.target.maximum.value),
average_cookies_per_sale: parseFloat(event.target.average.value),
owner: user.id,
};
createResource(info);
}
return (
<form onSubmit={handleSubmit}>
<fieldset>
<legend>Create Cookie Stand</legend>
<input placeholder="location" name="location" />
<input placeholder="minimum" name="minimum" />
<input placeholder="maximum" name="maximum" />
<input placeholder="average" name="average" />
<button>create</button>
</fieldset>
</form>
);
}
function CookieStandTable({ stands, deleteStand }) {
return (
<table className="my-8">
<thead>
<tr>
<th>Location</th>
<th>6 am</th>
<th>7 am</th>
<th>8 am</th>
<th>9 am</th>
<th>10 am</th>
<th>11 am</th>
<th>12 pm</th>
<th>1 pm</th>
<th>2 pm</th>
<th>3 pm</th>
<th>4 pm</th>
<th>5 pm</th>
<th>6 pm</th>
<th>7 pm</th>
<th>totals</th>
</tr>
</thead>
<tbody>
{stands.map((stand) => (
<CookieStandRow
key={stand.id}
info={stand}
deleteStand={deleteStand}
/>
))}
</tbody>
</table>
);
}
function CookieStandRow({ info, deleteStand }) {
function clickHandler() {
deleteStand(info.id);
}
if (info.hourly_sales.length == 0) {
// bunk data
info.hourly_sales = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
}
return (
<tr>
<td>
{info.location} <button onClick={clickHandler}>[x]</button>
</td>
{info.hourly_sales.map((slot, index) => (
<td key={index}>{slot}</td>
))}
<td>{info.hourly_sales.reduce((num, sum) => num + sum, 0)}</td>
</tr>
);
} |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Form.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mgiovana <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/20 15:23:42 by mgiovana #+# #+# */
/* Updated: 2024/05/20 15:23:44 by mgiovana ### ########.fr */
/* */
/* ************************************************************************** */
#include "Form.hpp"
Form::Form(const std::string& setName, const int setSing, const int setExe) :
name(setName), sign_Grade(setSing), exe_Grade(setExe)
{
std::cout << "Form base constructor called." << std::endl;
if (sign_Grade < 1 || exe_Grade < 1)
throw Form::GradeTooHighException();
else if (sign_Grade > 150 || exe_Grade > 150)
throw Form::GradeTooLowException();
}
Form::Form(): name(""), sign(false), sign_Grade(0), exe_Grade(0)
{
std::cout << "Form default constructor called." << std::endl;
}
Form::~Form()
{
std::cout << "Form destructor called." << std::endl;
}
Form::Form(const Form& src) : name(src.name), sign(src.sign), sign_Grade(src.sign_Grade), exe_Grade(src.exe_Grade)
{
std::cout << "Form copy constructor called." << std::endl;
*this = src;
}
std::string Form::getName() const
{
return this->name;
}
int Form::getSignedGrade() const
{
return this->sign_Grade;
}
int Form::getExeGrade() const
{
return this->exe_Grade;
}
bool Form::isSign() const
{
return this->sign;
}
Form& Form::operator=(const Form& src){
if (this != &src)
this->sign = src.sign;
return *this;
}
const char* Form::GradeTooHighException::what() const throw()
{
return "Grade too high";
}
const char* Form::GradeTooLowException::what() const throw()
{
return "Grade too low";
}
void Form::beSigned(Bureaucrat const &b){
if (b.getGrade() > this->sign_Grade)
throw Form::GradeTooLowException();
this->sign = true;
}
std::ostream& operator<<(std::ostream& os, const Form& f)
{
os << "Form name : " <<f.getName() << std::endl;
os << "Signed : ";
if (f.isSign())
os << "True" << std::endl;
else
os << "False" << std::endl;
os << "Form need Grade " << f.getSignedGrade() << "to sign, and Grade " << f.getExeGrade() << " to execute";
return os;
} |
/* Copyright (c) 2014, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include "async_bio.h"
#include <errno.h>
#include <string.h>
#include <openssl/mem.h>
namespace {
extern const BIO_METHOD g_async_bio_method;
struct AsyncBio {
bool datagram;
bool enforce_write_quota;
size_t read_quota;
size_t write_quota;
};
AsyncBio *GetData(BIO *bio) {
if (bio->method != &g_async_bio_method) {
return NULL;
}
return (AsyncBio *)bio->ptr;
}
static int AsyncWrite(BIO *bio, const char *in, int inl) {
AsyncBio *a = GetData(bio);
if (a == NULL || bio->next_bio == NULL) {
return 0;
}
if (!a->enforce_write_quota) {
return BIO_write(bio->next_bio, in, inl);
}
BIO_clear_retry_flags(bio);
if (a->write_quota == 0) {
BIO_set_retry_write(bio);
errno = EAGAIN;
return -1;
}
if (!a->datagram && (size_t)inl > a->write_quota) {
inl = a->write_quota;
}
int ret = BIO_write(bio->next_bio, in, inl);
if (ret <= 0) {
BIO_copy_next_retry(bio);
} else {
a->write_quota -= (a->datagram ? 1 : ret);
}
return ret;
}
static int AsyncRead(BIO *bio, char *out, int outl) {
AsyncBio *a = GetData(bio);
if (a == NULL || bio->next_bio == NULL) {
return 0;
}
BIO_clear_retry_flags(bio);
if (a->read_quota == 0) {
BIO_set_retry_read(bio);
errno = EAGAIN;
return -1;
}
if (!a->datagram && (size_t)outl > a->read_quota) {
outl = a->read_quota;
}
int ret = BIO_read(bio->next_bio, out, outl);
if (ret <= 0) {
BIO_copy_next_retry(bio);
} else {
a->read_quota -= (a->datagram ? 1 : ret);
}
return ret;
}
static long AsyncCtrl(BIO *bio, int cmd, long num, void *ptr) {
if (bio->next_bio == NULL) {
return 0;
}
BIO_clear_retry_flags(bio);
int ret = BIO_ctrl(bio->next_bio, cmd, num, ptr);
BIO_copy_next_retry(bio);
return ret;
}
static int AsyncNew(BIO *bio) {
AsyncBio *a = (AsyncBio *)OPENSSL_malloc(sizeof(*a));
if (a == NULL) {
return 0;
}
memset(a, 0, sizeof(*a));
a->enforce_write_quota = true;
bio->init = 1;
bio->ptr = (char *)a;
return 1;
}
static int AsyncFree(BIO *bio) {
if (bio == NULL) {
return 0;
}
OPENSSL_free(bio->ptr);
bio->ptr = NULL;
bio->init = 0;
bio->flags = 0;
return 1;
}
static long AsyncCallbackCtrl(BIO *bio, int cmd, bio_info_cb fp) {
if (bio->next_bio == NULL) {
return 0;
}
return BIO_callback_ctrl(bio->next_bio, cmd, fp);
}
const BIO_METHOD g_async_bio_method = {
BIO_TYPE_FILTER,
"async bio",
AsyncWrite,
AsyncRead,
NULL /* puts */,
NULL /* gets */,
AsyncCtrl,
AsyncNew,
AsyncFree,
AsyncCallbackCtrl,
};
} // namespace
ScopedBIO AsyncBioCreate() {
return ScopedBIO(BIO_new(&g_async_bio_method));
}
ScopedBIO AsyncBioCreateDatagram() {
ScopedBIO ret(BIO_new(&g_async_bio_method));
if (!ret) {
return nullptr;
}
GetData(ret.get())->datagram = true;
return ret;
}
void AsyncBioAllowRead(BIO *bio, size_t count) {
AsyncBio *a = GetData(bio);
if (a == NULL) {
return;
}
a->read_quota += count;
}
void AsyncBioAllowWrite(BIO *bio, size_t count) {
AsyncBio *a = GetData(bio);
if (a == NULL) {
return;
}
a->write_quota += count;
}
void AsyncBioEnforceWriteQuota(BIO *bio, bool enforce) {
AsyncBio *a = GetData(bio);
if (a == NULL) {
return;
}
a->enforce_write_quota = enforce;
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using Oracle.ManagedDataAccess.Client;
namespace EclipseLibrary.Oracle.Helpers
{
/// <summary>
/// Provides a way to convert results returned by a query into strongly typed objects
/// </summary>
/// <typeparam name="T"></typeparam>
/// <remarks>
/// </remarks>
public class SqlBinder<T> : SqlBinderBase
{
#region Constructors
internal SqlBinder(string actionName)
: base(actionName)
{
}
#endregion
#region Parameter chaining
public SqlBinder<T> Parameter(string field, string value)
{
base.InParameterString(field, value);
return this;
}
public SqlBinder<T> Parameter(string field, int? value)
{
base.InParameterInt(field, value);
return this;
}
public SqlBinder<T> Parameter(string field, int value)
{
base.InParameterInt(field, value);
return this;
}
public SqlBinder<T> Parameter(string field, DateTime? value)
{
base.InParameterDateTime(field, value);
return this;
}
public SqlBinder<T> Parameter(string field, DateTime value)
{
base.InParameterDateTime(field, value);
return this;
}
public SqlBinder<T> Parameter(string field, DateTimeOffset? value)
{
base.InParameterTimeStampTZ(field, value);
return this;
}
public SqlBinder<T> Parameter(string field, decimal? value)
{
base.InParameterDecimal(field, value);
return this;
}
public SqlBinder<T> Parameter(string field, decimal value)
{
base.InParameterDecimal(field, value);
return this;
}
public SqlBinder<T> OutRefCursorParameter(string parameterName)
{
var param = GetBindParameter(parameterName, ParameterDirection.Output);
param.OracleDbType = OracleDbType.RefCursor;
return this;
}
#endregion
#region Factory
private Func<OracleDataRow2, T> _factory;
/// <summary>
/// The factory can be set once via one of the <see cref="SqlBinder.Create"/> overloads.
/// </summary>
public Func<OracleDataRow2, T> Factory
{
get
{
return _factory;
}
internal set
{
_factory = value;
}
}
/// <summary>
/// After the reader is executed, this function is responsible for caling the factory for each row retrieved
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
/// <remarks>
/// Only in DEBUG mode, it ensures that all columns retrieved by the query have been accessed.
/// The finally block ensures that an exception has not been thrown and then proceeds to call <see cref="OracleDataRow2.DebugCheck"/>.
/// http://stackoverflow.com/questions/2788793/how-to-get-the-current-exception-without-having-passing-the-variable
/// </remarks>
internal IEnumerable<T> MapRows(OracleDataReader reader)
{
Debug.Assert(_factory != null);
return DoMapRows(reader, _factory);
// // Compatibility code
// var list = new List<T>();
// while (reader.Read())
// {
//#pragma warning disable 612
// // Backward compatibility code. Obsolete warning disabled
// var dict = new OracleDataRow(_mapper, reader);
// list.Add(_mapper.Engine.Map<IOracleDataRow, T>(dict));
//#pragma warning restore 612
// }
// return list;
}
/// <summary>
/// After the reader is executed, this function is responsible for caling the factory for each row retrieved
/// </summary>
/// <param name="reader"></param>
/// <param name="factory"></param>
/// <returns></returns>
/// <remarks>
/// Only in DEBUG mode, it ensures that all columns retrieved by the query have been accessed.
/// The finally block ensures that an exception has not been thrown and then proceeds to call <see cref="OracleDataRow2.DebugCheck"/>.
/// http://stackoverflow.com/questions/2788793/how-to-get-the-current-exception-without-having-passing-the-variable
/// </remarks>
protected IEnumerable<T> DoMapRows(OracleDataReader reader, Func<OracleDataRow2, T> factory)
{
#if DEBUG
var inException = false;
EventHandler<FirstChanceExceptionEventArgs> x = (object s, FirstChanceExceptionEventArgs e) => inException = true;
#endif
var row = new OracleDataRow2(reader.GetSchemaTable());
try
{
#if DEBUG
AppDomain.CurrentDomain.FirstChanceException += x;
#endif
while (reader.Read())
{
row.SetValues(reader);
yield return factory(row);
}
}
finally
{
#if DEBUG
if (!inException)
{
row.DebugCheck();
}
AppDomain.CurrentDomain.FirstChanceException -= x;
#endif
}
}
#endregion
}
} |
<template>
<div class="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div class="max-w-md w-full space-y-8">
<div>
<h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">
Sign in to your account
</h2>
</div>
<form class="mt-8 space-y-6" @submit.prevent="submitForm">
<input type="hidden" name="remember" value="true">
<div class="rounded-md shadow-sm -space-y-px">
<div>
<label for="email-address" class="sr-only">Email address</label>
<input id="email-address" name="email" type="email" v-model="form.email" autocomplete="email" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Email address">
</div>
<div>
<label for="password" class="sr-only">Password</label>
<input id="password" name="password" type="password" v-model="form.password" autocomplete="current-password" required class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Password">
</div>
</div>
<div>
<div class="text-sm">
<a href="#" class="font-medium text-indigo-600 hover:text-indigo-500">
Zapomniałeś hasła?
</a>
</div>
</div>
<div>
<button :disabled="form.processing" type="submit" class="disabled:bg-gray-500 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">
Panel
</button>
</div>
<div class="text-red-500">
{{ form.error }}
</div>
</form>
</div>
</div>
</template>
<script setup lang="ts">
import LoginParams from "~/types/Auth/login";
import axios from 'axios';
import guest from "~/middleware/guest";
definePageMeta({
middleware: [ guest ],
});
const form = reactive<LoginParams>({
email: '',
password: '',
error: '',
processing: false,
});
const submitForm = async (): Promise<void> => {
try {
form.processing = true;
const { data } = await axios.post(`${useRuntimeConfig().public.API_URL}require-token`, form);
const token = useCookie('token');
token.value = data.token;
navigateTo('/dashboard');
} catch (error: any) {
form.error = error.response.data.error;
} finally {
form.processing = false;
}
};
</script>
` |
// Created by a-bphillips, 2021
// Copyright Bungie, Inc.
import BlockPlusButton from "@Areas/Seasons/ProductPages/Season14/Components/BlockPlusButton";
import { SectionHeader } from "@Areas/Seasons/ProductPages/Season14/Components/SectionHeader";
import { Responsive } from "@Boot/Responsive";
import { useDataStore } from "@bungie/datastore/DataStoreHooks";
import { Localizer } from "@bungie/localization";
import classNames from "classnames";
import React, {
LegacyRef,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import styles from "./Activities14.module.scss";
interface IParallaxElementData {
anchorRef: React.MutableRefObject<HTMLDivElement>;
scrollRate: number;
nameInState: string;
maxTranslate?: number;
}
interface IParallaxStateProps {
[key: string]: number;
}
interface Season14ActivitiesProps {
inputRef: LegacyRef<HTMLDivElement>;
toggleOverrideModal: () => void;
toggleExpungeModal: () => void;
}
const Activities14: React.FC<Season14ActivitiesProps> = (props) => {
const responsive = useDataStore(Responsive);
const s14 = Localizer.Season14;
// refs of wrapping anchors for each parallax element
const block1Ref = useRef<HTMLDivElement | null>(null);
const block2Ref = useRef<HTMLDivElement | null>(null);
const block3Ref = useRef<HTMLDivElement | null>(null);
const bgBlockRef = useRef<HTMLDivElement | null>(null);
// translation amounts for parallax elements
const [translations, setTranslations] = useState<IParallaxStateProps>({
background: 0,
block1: 0,
block2: 0,
block3: 0,
});
useEffect(() => {
window.addEventListener("scroll", throttle(handleScroll, 17));
return () =>
window.removeEventListener("scroll", throttle(handleScroll, 17));
}, []);
// handle image parallax effects on scroll
const handleScroll = () => {
// array with data for parallaxing elements
const parallaxBlocks = [
{ anchorRef: bgBlockRef, scrollRate: 1.1, nameInState: "background" },
{ anchorRef: block1Ref, scrollRate: 1.3, nameInState: "block1" },
{ anchorRef: block2Ref, scrollRate: 1.2, nameInState: "block2" },
{ anchorRef: block3Ref, scrollRate: 1.2, nameInState: "block3" },
];
parallax(parallaxBlocks);
};
/**
* parallax - updates parallax state
* *
* @param parallaxElements - array of objects with data on how to parallax an element
*/
const parallax = (parallaxElements: IParallaxElementData[]) => {
// new translations to update state with
const newTranslations: { [key: string]: number } = {};
for (const eleObj of parallaxElements) {
const { scrollRate, anchorRef, nameInState, maxTranslate } = eleObj;
// element wrapping parallaxing element, used to calculate parallax amount
const anchor = anchorRef.current;
let translateAmount: number;
if (!anchor) {
// don't translate if no anchor found
translateAmount = 0;
} else {
const anchorTop = anchor.getBoundingClientRect().top;
const modifiedRate = scrollRate - 1;
translateAmount = anchorTop * modifiedRate;
// compare new translate to max if given
if (maxTranslate) {
translateAmount = Math.max(translateAmount, maxTranslate);
}
}
newTranslations[nameInState] = translateAmount;
}
// update state with new translations
setTranslations({ ...translations, ...newTranslations });
};
/**
* throttle - throttle for scroll event listeners
* @param fn - callback function
* @param wait - ms to wait between callback function calls
*/
const throttle = useCallback((fn: () => void, wait: number) => {
let time = Date.now();
return () => {
if (time + wait - Date.now() < 0) {
fn();
time = Date.now();
}
};
}, []);
return (
<div className={styles.activities}>
<div
className={styles.sectionIdAnchor}
id={"activities"}
ref={props.inputRef}
/>
<div className={styles.sectionBg} />
<div
className={classNames(
styles.parallaxBlockWrapper,
styles.bgParallaxWrapper
)}
ref={bgBlockRef}
>
<img
className={classNames(styles.parallaxBlock, styles.bgParallaxBlock)}
src={"/7/ca/destiny/bgs/season14/s14_activities_parallax_mid.png"}
style={{ transform: `translateY(${translations.background}px)` }}
/>
</div>
<div className={styles.contentWrapperNormal}>
<SectionHeader
title={s14.ActivitiesHeading}
seasonText={s14.SectionHeaderSeasonText}
sectionName={s14.ActivitiesSectionName}
/>
<div className={styles.btnFlexWrapper}>
<BlockPlusButton
title={s14.OverrideBtnHeading}
smallTitle={s14.OverrideBtnSmallHeading}
toggleModalFunc={props.toggleOverrideModal}
className={styles.blockBtn}
isHalfWidth={!responsive.mobile}
hasRightMargin={!responsive.mobile}
hasBottomMargin={responsive.mobile}
backgroundImage={
"/7/ca/destiny/bgs/season14/s14_activities_modal_button_1.jpg"
}
/>
<BlockPlusButton
title={s14.ExpungeBtnHeading}
smallTitle={s14.ExpungeBtnSmallHeading}
toggleModalFunc={props.toggleExpungeModal}
className={styles.blockBtn}
isHalfWidth={!responsive.mobile}
backgroundImage={
"/7/ca/destiny/bgs/season14/s14_activities_modal_button_2.jpg"
}
/>
</div>
<div
className={classNames(styles.parallaxBlockWrapper, styles.block1)}
ref={block1Ref}
>
<img
className={classNames(styles.parallaxBlock)}
src={
"/7/ca/destiny/bgs/season14/s14_activities_parallax_block_2.png"
}
style={{ transform: `translateY(${translations.block1}px)` }}
/>
</div>
<div
className={classNames(styles.parallaxBlockWrapper, styles.block2)}
ref={block2Ref}
>
<img
className={classNames(styles.parallaxBlock)}
src={
"/7/ca/destiny/bgs/season14/s14_activities_parallax_block_3.png"
}
style={{ transform: `translateY(${translations.block2}px)` }}
/>
</div>
<div
className={classNames(styles.parallaxBlockWrapper, styles.block3)}
ref={block3Ref}
>
<img
className={classNames(styles.parallaxBlock)}
src={
"/7/ca/destiny/bgs/season14/s14_activities_parallax_block_1.png"
}
style={{ transform: `translateY(${translations.block3}px)` }}
/>
</div>
</div>
</div>
);
};
export default Activities14; |
/* eslint-disable react-native/no-inline-styles */
import {Dimensions, Image, View} from 'react-native';
import React from 'react';
import CustomText from '../../components/CustomText';
import {paletteColor} from '../../themes/Utility';
import RowJustifyContent from '../../components/RowJustifyContent';
import CustomCircle from '../../components/CustomCircle';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
const Carte8 = ({data}: any) => {
return (
<View
style={{
flexDirection: 'column',
height: 200,
justifyContent: 'space-between',
}}>
{/* Logo */}
<View
style={{
justifyContent: 'center',
alignItems: 'center',
height: 100,
marginTop: 10,
}}>
{data.img.length > 0 && (
<Image
source={{
uri: data.img,
}}
style={{width: 50, height: 50}}
/>
)}
{data.nomEntreprise.length > 0 && (
<CustomText
marginTop={10}
textAlign="center"
color="#C89E61"
fontWeight="bold"
textTransform="capitalize"
fontSize={12}>
{data.nomEntreprise}
</CustomText>
)}
</View>
{/* Info user */}
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: '12%',
height: 100,
}}>
{/* nom user */}
<View style={{width: '50%', alignItems: 'center'}}>
<View>
{(data.nom.length > 0 || data.prenom.length > 0) && (
<CustomText
fontWeight="900"
fontSize={14}
textAlign="center"
numberOfLines={1}>
{data.nom} {data.prenom}
</CustomText>
)}
{data.titrePro.length > 0 && (
<CustomText fontSize={8} fontWeight="bold" numberOfLines={1}>
{data.titrePro}
</CustomText>
)}
</View>
</View>
{/* contact user */}
<View
style={{
width: Dimensions.get('screen').width / 2.7,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
top: -30,
}}>
<View>
{data.contact.length > 0 && (
<RowJustifyContent
top={-15}
alignItems="center"
justifyContent="flex-start">
<CustomCircle
borderRadius={0}
size={15}
backgroundColor={paletteColor.BLACK}>
<MaterialCommunityIcons
name="phone"
size={8}
color={paletteColor.WHITE}
/>
</CustomCircle>
<CustomText marginLeft={5} fontWeight="700" fontSize={8}>
{data.contact.join('\n')}
</CustomText>
</RowJustifyContent>
)}
{data.web.length > 0 && (
<RowJustifyContent
marginTop={5}
top={-15}
alignItems="center"
justifyContent="flex-start">
<CustomCircle
borderRadius={0}
size={15}
backgroundColor={paletteColor.BLACK}>
<MaterialCommunityIcons
name="web"
size={8}
color={paletteColor.WHITE}
/>
</CustomCircle>
<CustomText
marginLeft={5}
fontWeight="700"
fontSize={8}
numberOfLines={1}>
{data.web}
</CustomText>
</RowJustifyContent>
)}
{data.email.length > 0 && (
<RowJustifyContent
marginTop={5}
top={-15}
alignItems="center"
justifyContent="flex-start">
<CustomCircle
borderRadius={0}
size={15}
backgroundColor={paletteColor.BLACK}>
<MaterialCommunityIcons
name="email"
size={8}
color={paletteColor.WHITE}
/>
</CustomCircle>
<CustomText
marginLeft={5}
fontWeight="700"
fontSize={8}
numberOfLines={1}>
{data.email}
</CustomText>
</RowJustifyContent>
)}
{data.adresse.length > 0 && (
<RowJustifyContent
marginTop={5}
top={-15}
alignItems="center"
justifyContent="flex-start">
<CustomCircle
borderRadius={0}
size={15}
backgroundColor={paletteColor.BLACK}>
<MaterialCommunityIcons
name="map-marker"
size={8}
color={paletteColor.WHITE}
/>
</CustomCircle>
<CustomText
marginLeft={5}
fontWeight="700"
fontSize={8}
numberOfLines={1}>
{data.adresse}
</CustomText>
</RowJustifyContent>
)}
</View>
</View>
</View>
</View>
);
};
export default Carte8; |
import 'package:equatable/equatable.dart';
class TestLeaderboardModel extends Equatable {
final String userId;
final int listeningScore;
final int readingScore;
final int structureScore;
final int totalScore;
final String name;
final DateTime date;
const TestLeaderboardModel({
required this.userId,
required this.listeningScore,
required this.readingScore,
required this.structureScore,
required this.totalScore,
required this.name,
required this.date,
});
factory TestLeaderboardModel.fromJson(Map<String, dynamic> json) {
return TestLeaderboardModel(
userId: json['user_id'] as String,
listeningScore: json['listening_score'] as int,
readingScore: json['reading_score'] as int,
structureScore: json['structure_score'] as int,
totalScore: json['total_score'] as int,
name: json['users']['name'] as String,
date: DateTime.parse(json['created_at'] as String),
);
}
@override
List<Object> get props => [
userId,
readingScore,
listeningScore,
structureScore,
totalScore,
name,
date,
];
} |
import { useState } from "react";
import { createDjService } from "../../services/djs.services";
import { uploadImageService } from "../../services/upload.services";
import { useNavigate } from "react-router-dom";
import Form from "react-bootstrap/Form";
import ScaleLoader from "react-spinners/ScaleLoader";
function AddDjForm(props) {
// Destructurar props
const { getData, toggleForm } = props;
const navigate = useNavigate();
// Estados para registrar los cambios
const [name, setName] = useState("");
const [image, setImage] = useState("");
const handleNameChange = (e) => setName(e.target.value);
const handleImageChange = (e) => setImage(e.target.value);
const [imageUrl, setImageUrl] = useState(null);
const [isUploading, setIsUploading] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setIsLoading(true);
try {
const newDj = {
name,
image: imageUrl,
};
await createDjService(newDj);
getData();
toggleForm();
} catch (error) {
if (error.response.status === 400) {
setErrorMessage(error.response.data.message);
setIsLoading(false);
}
}
};
const handleFileUpload = async (event) => {
if (!event.target.files[0]) {
return;
}
setIsUploading(true);
const uploadData = new FormData();
uploadData.append("image", event.target.files[0]);
try {
const response = await uploadImageService(uploadData);
setImageUrl(response.data.imageUrl);
setIsUploading(false);
} catch (error) {
console.log(error.response);
if (error.response.status === 400) {
setErrorMessage("Archivo demasiado grande ( 10485760 bytes max )");
setIsLoading(false);
setIsUploading(false);
}
}
};
return (
<div className="myDjFormContainer">
<h3>Añadir Dj</h3>
<Form onSubmit={handleSubmit} className="myDjForm">
<Form.Group className="mb-3" id="formBasicTitle">
<Form.Label htmlFor="title">Name</Form.Label>
<Form.Control
type="text"
name="name"
onChange={handleNameChange}
value={name}
/>
</Form.Group>
<br />
<div>
<Form.Group className="mb-3" id="formBasicDate">
<Form.Label>Imagen</Form.Label>
<Form.Control
type="file"
name="image"
onChange={handleFileUpload}
disabled={isUploading}
/>
{isUploading ? (
<ScaleLoader color={"#471971"} loading={true} />
) : null}
{imageUrl ? (
<div className="preview">
<img src={imageUrl} alt="img" width={200} />
</div>
) : null}
</Form.Group>
</div>
<br />
<button className="myButtons" type="submit" disabled={isLoading}>
Agregar
</button>
{errorMessage && <p style={{ color: "red" }}>{errorMessage}</p>}
</Form>
</div>
);
}
export default AddDjForm; |
using System.Net;
using AutoMapper;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Moq;
using NUnit.Framework;
using WeatherApi.BusinessLogic.Abstraction.Models;
using WeatherApi.BusinessLogic.Clients.WeatherApi;
using WeatherApi.BusinessLogic.Mappings;
using WeatherApi.BusinessLogic.Services;
using WeatherApi.Data;
using WeatherApi.Data.Entities;
using WeatherApi.Tests;
[TestFixture]
public class WeatherServiceTests
{
private WeatherContext _weatherContext;
private IMapper _mapper;
private WeatherService _weatherService;
private Mock<IWeatherApiClient> _weatherApiClientMock;
[SetUp]
public void Setup()
{
var options = new DbContextOptionsBuilder<WeatherContext>()
.UseInMemoryDatabase(databaseName: "WeatherTestDb" + Guid.NewGuid())
.Options;
_weatherContext = new WeatherContext(options);
_weatherApiClientMock = new Mock<IWeatherApiClient>();
var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new WeatherForecastProfile()); });
_mapper = mappingConfig.CreateMapper();
_weatherService = new WeatherService(_weatherApiClientMock.Object, _weatherContext, _mapper);
}
[TearDown]
public void Teardown()
{
_weatherContext.Database.EnsureDeleted(); // This deletes the in-memory database
_weatherContext.Dispose(); // Dispose the context to free up resources
}
[Test]
public async Task GetForecastAsync_LocationExists_ReturnsLocationDto()
{
// Arrange
_weatherContext.Locations.AddRange(
new Location { Latitude = 30.0, Longitude = 50.0 }
);
_weatherContext.SaveChanges();
var locationId = _weatherContext.Locations.Select(x => x.Id).First();
_weatherApiClientMock.Setup(x => x.FetchWeatherAsync(It.IsAny<double>(), It.IsAny<double>())).ReturnsAsync(WeatherClientHelper.GetSampleData());
// Act
var result = await _weatherService.GetForecastAsync(locationId);
// Assert
result.Should().NotBeNull();
result.Should().BeOfType<LocationDto>();
}
[Test]
public async Task AddLocation_NewLocation_AddsLocation()
{
// Arrange
var newLocationDto = new LocationDto { Latitude = 25.0, Longitude = 45.0 };
// Act
await _weatherService.AddLocation(newLocationDto);
var location = await _weatherContext.Locations.FirstOrDefaultAsync(l => l.Latitude == 25.0 && l.Longitude == 45.0);
// Assert
location.Should().NotBeNull();
location.Latitude.Should().Be(25.0);
location.Longitude.Should().Be(45.0);
}
[Test]
public void AddLocation_DuplicateLocation_ThrowsArgumentException()
{
// Arrange
var duplicateLocationDto = new LocationDto { Latitude = 20.0, Longitude = 40.0 }; // Coordinates already exist in the database
// Act
Func<Task> act = async () => await _weatherService.AddLocation(duplicateLocationDto);
// Assert
act.Should().ThrowAsync<ArgumentException>().WithMessage("Location already exists");
}
[Test]
public async Task DeleteLocation_ExistingLocation_DeletesLocation()
{
// Arrange
var locationId = 1; // Assuming a location with ID 1 exists from setup
// Act
await _weatherService.DeleteLocation(locationId);
var location = await _weatherContext.Locations.FindAsync(locationId);
// Assert
location.Should().BeNull();
}
[Test]
public async Task GetAllLocations_WhenCalled_ReturnsPagedLocations()
{
// Arrange
// Add more sample data if needed
_weatherContext.Locations.AddRange(
new Location { Latitude = 30.0, Longitude = 50.0 },
new Location { Latitude = 35.0, Longitude = 55.0 }
);
_weatherContext.SaveChanges();
// Act
var result = await _weatherService.GetAllLocations(1, 2);
// Assert
result.Should().NotBeNull();
result.Data.Should().HaveCount(2);
result.Pagination.TotalPages.Should().Be(1);
result.Pagination.PageSize.Should().Be(2);
result.Pagination.TotalItems.Should().Be(2);
}
} |
import {
Route,
RouteComponentProps,
Switch,
useHistory,
useLocation,
useRouteMatch,
} from "react-router-dom";
import * as React from "react";
import { ToastContainer } from "react-toastify";
import AppHooks from "../coreUI/contexts/AppHooks";
import PopUps from "../coreUI/contexts/Modals";
import { Box } from "@mui/system";
import UIComponents from "../views/UiComponents";
import Routes from "./Routes";
import "react-toastify/dist/ReactToastify.css";
import "./App.css";
import "swiper/css/navigation";
import "swiper/css";
import { useDispatch } from "react-redux";
import { selectAppLoading, setAppLoading } from "src/models/Ui";
import { useAppSelector } from "src/models/hooks";
import {
setProjectsStatistics,
setStatisticsFilterDefaults,
} from "src/models/Statistics";
import {
AuthActions,
getUserInfo,
logout,
selectUserState,
} from "src/models/Auth";
import { getUserTokenInfo, isAuthedUser } from "src/services/api";
import {
getAllDepartments,
selectAllDepartments,
} from "src/models/Departments";
import { getAllCategories } from "src/models/Categories";
import { getAllClients } from "src/models/Clients";
import { getManagers } from "src/models/Managers";
import {
ProjectsActions,
getAllProjects,
getAllTasks,
} from "src/models/Projects";
import { getNotifications, getUnNotified } from "src/models/Notifications";
const App: React.FC = (props) => {
const location = useLocation<any>();
const history = useHistory<any>();
const match = useRouteMatch<any>();
const departments = useAppSelector(selectAllDepartments);
const dispatch = useDispatch();
React.useEffect(() => {
dispatch(setAppLoading(true));
return () => {
dispatch(setAppLoading(false));
};
}, []);
const [mounted, setMounted] = React.useState(false);
const [filtermounted, setFilterMounted] = React.useState(false);
const userState = useAppSelector(selectUserState);
const [tokenInfo, setTokenInfo] = React.useState(getUserTokenInfo());
React.useEffect(() => {
if (isAuthedUser()) {
setTokenInfo(getUserTokenInfo());
if (tokenInfo?.id)
dispatch(
getUserInfo({
id: tokenInfo?.id,
})
);
dispatch(AuthActions.changeAuth(true));
} else setTokenInfo(null);
return () => {
if (isAuthedUser()) {
dispatch(getAllDepartments(null));
dispatch(getAllCategories(null));
dispatch(getAllClients(null));
dispatch(getManagers(null));
dispatch(getAllProjects(null));
dispatch(getAllTasks(null));
dispatch(getUnNotified(null));
dispatch(getNotifications(`/${0}/${10}`));
setMounted(true);
}
};
}, [userState.authed, dispatch]);
React.useEffect(() => {
if (mounted === true && filtermounted === false && departments.length > 0) {
dispatch(ProjectsActions.fireSetStatisticsHook(null));
dispatch(
setStatisticsFilterDefaults({
boards: departments
.filter((i) => i.priority === 1)
.map((i) => i.boardId),
})
);
setFilterMounted(true);
}
}, [departments]);
return (
<Box height={"100%"} bgcolor="#FAFAFB !important">
<AppHooks>
<ToastContainer
data-test-id="toastMessage"
position="top-right"
autoClose={5000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
limit={1}
draggable
/>
{isAuthedUser() && (
<PopUps history={history} match={match} location={location} />
)}
<Switch>
{process.env.NODE_ENV === "development" && (
<Route key="/DevComponents" path="/Dev" component={UIComponents} />
)}
<Routes />
</Switch>
</AppHooks>
</Box>
);
};
export default App; |
import css from './Form.module.css';
import { nanoid } from 'nanoid';
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
number: Yup.number().required('Phone is required'),
});
export default function FormBook({ onSubmitButton }) {
const handleSubmit = (values, actions) => {
const id = nanoid();
onSubmitButton({ ...values, id });
actions.resetForm();
};
const inputNameId = nanoid();
const inputTelId = nanoid();
return (
<>
<Formik
initialValues={{ name: '', number: '' }}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
<Form className={css.phoneBook}>
<label htmlFor={inputNameId} className={css.lbl}>
Name
</label>
<Field id={inputNameId} type="text" name="name" />
<ErrorMessage name="name" />
<label htmlFor={inputTelId} className={css.lbl}>
Phone number
</label>
<Field type="tel" id={inputTelId} name="number" />
<ErrorMessage name="number" />
<button type="submit" className={css.btn}>
Add contact
</button>
</Form>
</Formik>
</>
);
}
// Варіант без Formik (використання state)
// import css from './Form.module.css';
// import { nanoid } from 'nanoid';
// import React from 'react';
// export default class Form extends React.Component {
// state = {
// name: '',
// id: '',
// number: '',
// };
// handleInputChange = event => {
// const { name, value, id } = event.currentTarget;
// this.setState({
// [name]: value,
// id,
// });
// };
// handleSubmit = event => {
// event.preventDefault();
// this.props.onSubmitButton(this.state);
// this.reset();
// };
// reset = () => {
// this.setState({ name: '', number: '' });
// };
// render() {
// const inputNameId = nanoid();
// const inputTelId = nanoid();
// return (
// <>
// <form className={css.phoneBook} onSubmit={this.handleSubmit}>
// <label htmlFor={inputNameId} className={css.lbl}>
// Name
// </label>
// <input
// id={inputNameId}
// type="text"
// name="name"
// pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$"
// title="Name may contain only letters, apostrophe, dash and spaces. For example Adrian, Jacob Mercer, Charles de Batz de Castelmore d'Artagnan"
// required
// value={this.state.name}
// onChange={this.handleInputChange}
// />
// <label htmlFor={inputTelId} className={css.lbl}>
// Phone number
// </label>
// <input
// type="tel"
// id={inputTelId}
// name="number"
// // pattern="\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}"
// // title="Phone number must be digits and can contain spaces, dashes, parentheses and can start with +"
// required
// value={this.state.number}
// onChange={this.handleInputChange}
// />
// <button type="submit" className={css.btn}>
// Add contact
// </button>
// </form>{' '}
// </>
// );
// }
// } |
// * NOTE: We have created a custom render to render the component with the OrderDetailsProvider wrapper
// @see https://testing-library.com/docs/react-testing-library/setup
// The only change we did here is that instead of importing from @testing-library/react we are importing from our @/test-utils.tsx file
import { render, screen, waitFor } from '@/test-utils'
import OrderEntry from './OrderEntry'
import { rest } from 'msw'
import { server } from '@/mocks/server'
import { apiURL } from '@/config'
import { useRouter } from 'next/router'
// mock useRouter - jest.fn() returns a mock function (it doesn't do anything, but it is useful to avoid errors)
jest.mock('next/router', () => ({
useRouter: jest.fn(),
}))
describe('OrderEntry', () => {
test('handles error for scoops and toppings routes', async () => {
// TIP: We are using the server.resetHandlers() method here to set up a new behavior for these routes. In this case we want to return a 500 error for both routes. This is a good way to test error handling in your app.
server.resetHandlers(
rest.get(`${apiURL}/scoops`, (req, res, ctx) => {
return res(ctx.status(500))
}),
rest.get(`${apiURL}/toppings`, (req, res, ctx) => {
return res(ctx.status(500))
})
)
render(<OrderEntry />)
// TIP: waitFor() allows us to wait for something to happen before continuing with the test. In this case we are waiting for both the alerts to show up
await waitFor(async () => {
const alerts = await screen.findAllByRole('alert')
expect(alerts).toHaveLength(2)
})
})
})
// TIP: use test.only() to run only one test
// TIP: use test.skip() to skip a test |
import { Textarea, Toast } from "@skbkontur/react-ui";
import Head from "next/head";
import { useEffect, useRef, useState } from "react";
import useSpreadsheetData from "../../hooks/useSpreadsheetData";
import Container from "../Container";
import Layer from "../Layer";
import Map, { MapRef } from "../Map";
import Marker from "../Marker";
const HomeContent: React.FC = () => {
const mapRef = useRef<MapRef>(null);
const [initialCenter] = useState(new window.google.maps.LatLng(55, 37))
const [{ isLoading, places }, setSpreadsheetData] = useSpreadsheetData(
() => {
Toast.push("Location data is loaded, sheet url is saved in your browser");
},
() => {
Toast.push("Loading data using sheet url saved in your browser");
},
(message: string) => {
Toast.push(`Can't fetch location data${message}`);
}
);
const markers: Array<React.ReactElement<google.maps.MarkerOptions>> =
places
?.map((place) => (
<Marker
key={place.placeId}
position={place.location}
label={place.names.length.toString(10)}
/>
))
.flat() ?? [];
const textAreaPlaceholder = isLoading
? "Loading..."
: "Share the sheet to anyone and paste the link here";
useEffect(() => {
const bounds = new google.maps.LatLngBounds();
places?.forEach((place) => bounds.extend(place.location));
mapRef.current?.fitBounds(bounds);
}, [places]);
return (
<Container>
<Head>
<title>Map</title>
<meta name="description" content="A map to display coworkers" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Layer>
<Map ref={mapRef} streetViewControl={false} mapTypeControl={false} center={initialCenter} zoom={3}>
{markers}
</Map>
</Layer>
<Layer padding direction="column">
<Textarea
width={360}
disabled={isLoading}
onValueChange={(value) => setSpreadsheetData(value)}
rows={1}
resize="none"
placeholder={textAreaPlaceholder}
value=""
/>
</Layer>
</Container>
);
};
export default HomeContent; |
require("dotenv").config(); // ALLOWS ENVIRONMENT VARIABLES TO BE SET ON PROCESS.ENV SHOULD BE AT TOP
const express = require("express");
const app = express();
// Middleware
app.use(express.json({limit: '50mb'})); // parse json bodies in the request object
// Redirect requests to endpoint starting with /posts to postRoutes.js
app.use("/login", require("./routes/loginRoutes"));
app.use("/genre", require("./routes/genreRoutes"));
app.use("/book", require("./routes/bookRoutes"));
app.use("/search", require("./routes/searchRoutes"));
app.use("/detail", require("./routes/detailRoutes"));
app.use("/propose", require("./routes/proposeRoutes"));
app.use("/user", require("./routes/userRoutes"));
app.use("/nxb", require("./routes/NXBRoutes"));
app.use("/feedback", require("./routes/feedbackRoutes"));
// Global Error Handler. IMPORTANT function params MUST start with err
app.use((err, req, res, next) => {
console.log(err.stack);
console.log(err.name);
console.log(err.code);
res.status(500).json({
message: "Something went rely wrong",
});
});
// Listen on pc port
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on PORT ${PORT}`)); |
package com.example.notesprojectapp.viewmodel
import android.app.DownloadManager.Query
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.domain.model.HomeNotesModel
import com.example.domain.model.TemplateNotesModel
import com.example.domain.usecase.NotesUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class NotesViewModel @Inject constructor(private val useCase: NotesUseCase):ViewModel() {
private val _notesHome = MutableStateFlow(NotesState())
val notesHome: StateFlow<NotesState> = _notesHome
private val _pinnedNotes = MutableStateFlow<List<HomeNotesModel>>(emptyList())
val pinnedNotes: StateFlow<List<HomeNotesModel>> = _pinnedNotes
fun searchHome(query: String) {
viewModelScope.launch {
try {
val searchHomeResult = useCase.searchHomeNotes(query)
_notesHome.value = NotesState(homeNotes = searchHomeResult)
} catch (e:Exception){
}
}
}
fun searchTemp(query: String){
viewModelScope.launch {
try {
val searchTemp = useCase.searchTemplateNotes(query)
_notesHome.value = NotesState(templateNotes = searchTemp)
} catch (e:Exception){
}
}
}
fun delete(id:String) {
viewModelScope.launch {
try {
useCase.delete(id)
val deleteUpdate = useCase.repository.getHomeNotes(id)
_notesHome.value = NotesState(homeNotes = deleteUpdate)
} catch (e:Exception){
}
}
}
fun update(id: String, updatedHomeNotesModel: HomeNotesModel) {
viewModelScope.launch {
try {
// Вызовите метод для обновления данных в репозитории
useCase.repository.updateHomeNote (id, updatedHomeNotesModel)
// Получите обновленный список заметок после сохранения
val updatedNotes = useCase.repository.getHomeNotes(id)
// Обновите состояние _notesHome внутри ViewModel
_notesHome.value = NotesState(homeNotes = updatedNotes)
} catch (e: Exception) {
// Обработка ошибок
}
}
}
fun addTemplateNotes(id:String, templateNotesModel: TemplateNotesModel){
viewModelScope.launch {
try {
val updatesTemplateNotes = useCase(id, templateNotesModel)
_notesHome.value = NotesState(templateNotes = updatesTemplateNotes)
} catch (e:Exception){
// Обработка ошибок
}
}
}
fun refreshTemplatesNotes(id: String) {
viewModelScope.launch {
try {
val updatedTemplatesNotes = useCase.repository.getTemplateNotes(id) // Получите список заметок из репозитория для указанного id
_notesHome.value = NotesState(templateNotes = updatedTemplatesNotes)
} catch (e: Exception) {
// Обработка ошибок
}
}
}
fun addNotes(id: String, homeNotesModel: HomeNotesModel) {
viewModelScope.launch {
try {
val updatedNotes = useCase(id, homeNotesModel)
_notesHome.value = NotesState(homeNotes = updatedNotes)
Log.d("NotesViewModel", "Добавление заметки в NotesViewModel: $homeNotesModel")
} catch (e: Exception) {
Log.e("NotesViewModel", "Ошибка при добавлении заметки в NotesViewModel", e)
}
}
}
fun refreshNotes(id: String) {
viewModelScope.launch {
try {
val updatedNotes = useCase.repository.getHomeNotes(id) // Получите список заметок из репозитория для указанного id
_notesHome.value = NotesState(homeNotes = updatedNotes)
} catch (e: Exception) {
// Обработка ошибок
}
}
}
fun addPinnedNote(note: HomeNotesModel) {
val currentList = _pinnedNotes.value.toMutableList()
currentList.add(note)
_pinnedNotes.value = currentList
}
} |
# Index of contents
1. [Code deployment instructions for web application](#code-deployment-for-web-application)
2. [Instruction to use web application](#instruction-to-use-web-application)
3. [File structure explanation for web application](#file-structure-for-web-application)
4. [Code deployment instructions for desktop application](#code-deployment-for-desktop-application)
5. [ML-model explanation](#code-explantion-for-ml-model)
6. [ML-model limitations](#limitations-of-ml-model)
# Specifications for code deployment
1. Node.js version >= 16.3.2
2. Terminal -> Git bash
3. Code editor -> VS code
4. Python version >= 3.9.10
# Code Deployment for web application
1. Check version of Node.
```
node -v
```
2. If Node is not available download it for here https://nodejs.org/en/download/ for linux.
3. In the terminal clone the project.
```
git clone https://github.com/Submission-interiit/MP_ISRO_T16
```
4. Navigate to client folder.
```
cd web_application/inter_iit/client
```
5. Install node modules in the client.
```
npm install
```
6. Start local development server
```
npm start
```
7. New tab in browser will open.
8. In another terminal navigate to web_application -> server
```
cd web_application/server
```
9. Create a virtual environment for flask server.
```
python -m venv .venv
```
10. Select python interpreter path (In vscode press ctrl + shift + p) and select interpreter by going to .venv/Scripts/python.exe
11. Activate .venv/Scripts/activate.bat for cmd and .venv/Scripts/activate.ps1 for ps1
```
.venv/Scripts/activate.ps1
```
12. Install the required python packages.
```
pip install -r requirements.txt
```
13. To run the server. Navigate to server.
```
python -m flask run
```
# Instruction to use web application
1. On the home page click Input data button to open sidebar.

2. In the Upload file section and upload a file in .lc format. Ensure that lc file has two columns labelled TIME and RATE.

3. Click on the submit button to get results.
4. Loading of chart usually takes 30 seconds.
5. Results appear as below.

6. Click on the top arrow to enlarge the chart.
7. Chart has two options raw and convolved. Buttons are disabled in raw option.
8. Chart can be zoomed in, zoomed out and reset with button on the below-right.

9. In convolved section click on the toggle peak curve button to show peaks. Click on the toggle peak button again to remove peaks.

10. Click on the toggle fit curve buttons to show fit curve. To remove fit curve click the button again.

11. On the right, click on the arrow to show table.

12. Table is visible which shows category of solar bursts, decay time, rise time, peak flux, peak time, start time, end time. Table could be scrolled horizontally to see other parameters.

# File structure for web application

1. src folder all the source code.
2. api folder contains backend api.
3. assets folder contains static images.
4. components folder all react components.
# Code Deployment for desktop application
1. Navigate to standalone_application
```
cd standalone_application
```
2. Install node modules.
```
npm install
npm run watch
```
3. In another terminal
```
npm start
```
4. The desktop app will start.
# Code explantion for ml-model
1. The lc file is read using astropy table which is then converted to pandas dataframe
2. The dataframe is then convolved using gaussian kernal with width size 60
3. The scipy find_peaks() function is then called to get the index of the peaks in a light curve
4. The peak width function is then called to get a portion of the curve around the peak required to fit the curve
5. The background flux is then calculated by calling bgdata() function which returns two output
i) Returns the light curve after removing the peak width
ii) Returns the median calculated on light curve after removing the median
6. The standard deviation is then calculated for rates after removing peak width from the light curve
7. User defined peak fitter function is called
i) We scale the rate using mix max scaler which is required for better fit
ii) We fit the portion around the peak to our light curve function and get the parameters of the function
iii) Using the parameters we got we extend the function to both side of the peakwidth
iv) we reverse scale rate to original value using rev_scaler()
v) The time and rate for the extended curve corresponding to each peak is stored in newcurve
vi) Scaled curve contains the fitted rate for peak width
8. Startidx() function is then called to get start and end index corresponding to start and end time of a burst
i) The start and end time are calculated as the point where the background flux+standard deviation meet the newcurve (i.e.Extended fitted curve)
ii) Unfit peaks are also eliminated in this function where the peak flux is lower than background flux +(115% of standard deviation) and the extended fitted curve cuts the background+standard deviation just once
9. Params function is called which then converts all the obtained information for all the peaks in a curve in a dataframe and classifies the peak on the basis of flux
10. Stitcher function is then called which stiches the scaled curve(i.E. Fitted curve for peak width) for multiple peaks and background data.
# Limitations of ml-model
1. In order to display the fitted curve over the convolved data without discontinuities we have implemented a stitch function, this function uses the median in place of the unavailable fit for portion between 2 peaks and because of that in certain parts the gradient of the fitted curve appears to large and distorts the fitted curve.
2. Incase of a very large rise or decay time where the start and end time extend beyond the duration of measurement, the curve is not able to fit optimally due to lack of information. |
//
// CameraModel.swift
// fruitDetector
//
// Created by Luca Lacerda on 22/02/24.
//
import SwiftUI
import AVFoundation
import CoreImage
import CoreML
import Foundation
class CameraModel:NSObject, ObservableObject {
@Published var frama:UIImage?
private var lastFrames:[UIImage] = []
private var captureSession:AVCaptureSession = AVCaptureSession()
private var videoOutput:AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()
private var context = CIContext()
private var backCamera:AVCaptureDevice?
private var backInput:AVCaptureDeviceInput?
private var imageClassifier: HomeObjects?
override init() {
super.init()
checkPermission()
setupCaptureSession()
}
func checkPermission() {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
return
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { (autorized) in
if !autorized{
fatalError()
}
}
default:
fatalError()
}
}
func setupCaptureSession() {
DispatchQueue.global(qos: .userInitiated).async {
self.captureSession.beginConfiguration()
if self.captureSession.canSetSessionPreset(.photo) {
self.captureSession.sessionPreset = .photo
}
self.captureSession.automaticallyConfiguresCaptureDeviceForWideColor = true
self.setupInputs()
self.setupOutputs()
self.captureSession.commitConfiguration()
self.captureSession.startRunning()
}
}
func setupOutputs() {
let videoQueue = DispatchQueue(label: "videoQueue", qos: .userInitiated)
videoOutput.setSampleBufferDelegate(self, queue: videoQueue)
if captureSession.canAddOutput(videoOutput) {
captureSession.addOutput(videoOutput)
} else {
fatalError()
}
videoOutput.connections.first?.videoRotationAngle = 90
}
func setupInputs() {
if let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back){
self.backCamera = device
} else {
fatalError()
}
guard let bInput = try? AVCaptureDeviceInput(device: self.backCamera!) else {fatalError()}
backInput = bInput
if !captureSession.canAddInput(backInput!) {
fatalError()
}
captureSession.addInput(backInput!)
}
func classifyImage()-> String {
do {
let model = try HomeObjects(configuration: MLModelConfiguration())
guard let pixelBuffer = frama?.toCVPixelBuffer() else { return "" }
let prediction = try model.prediction(image: pixelBuffer)
if verifyTarget(target: prediction.target){
return prediction.target
} else {
return ""
}
} catch {
// Lide com o erro aqui, por exemplo, imprimindo a mensagem de erro
print("Erro ao classificar a imagem: \(error)")
}
return ""
}
func verifyTarget(target:String)-> Bool {
var targetCount = 0
let framesToAnalyze = self.lastFrames
do{
for frame in framesToAnalyze{
let model = try HomeObjects(configuration: MLModelConfiguration())
guard let pixelBuffer = frame.toCVPixelBuffer() else { return false }
let prediction = try model.prediction(image: pixelBuffer)
if prediction.target == target {
targetCount += 1
}
}
if targetCount == 8 {
return true
} else {
return false
}
}catch {
print("erro ao classificar imagem")
}
return false
}
func lastFramesControl(uiImage:UIImage) {
if lastFrames.count < 8 {
lastFrames.append(uiImage)
} else if lastFrames.count == 8 {
lastFrames.removeFirst()
lastFrames.append(uiImage)
}
}
}
extension CameraModel: AVCaptureVideoDataOutputSampleBufferDelegate{
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let uiImage = imageFromSampleBuffer(sampleBuffer: sampleBuffer) else {return}
lastFramesControl(uiImage: uiImage)
DispatchQueue.main.async { [unowned self] in
self.frama = uiImage
}
}
private func imageFromSampleBuffer(sampleBuffer: CMSampleBuffer) -> UIImage? {
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {return nil}
let ciImage = CIImage(cvPixelBuffer: imageBuffer)
guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else {return nil}
let uiImage = UIImage(cgImage: cgImage)
return uiImage
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
namespace AttributeStudy
{
public partial class Form1 : Form
{
private List<Type> heroTypes = new List<Type>();
private object selectedHero;
public Form1()
{
InitializeComponent();
//通过反射属性加载所有英雄
/*
* Assembly 程序集
* GetExecutingAssembly() ,执行当前代码的程序集
* GetTypes() ,所有的类型
* Where 扩展方法结合Lamdba表达式进行筛选
*/
heroTypes = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.GetCustomAttributes(typeof(AttributeClass.HeroAttribute), false).Any()).ToList();
//初始化英雄列表
heroListBox.Items.AddRange(heroTypes.Select(t => t.Name).ToArray());
}
private void heroListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (heroListBox.SelectedIndex == -1) return; //如果未选定则跳出
//获取当前旋转的英雄
var selectedHeroType = heroTypes[heroListBox.SelectedIndex];
selectedHero = Activator.CreateInstance(selectedHeroType);
//获取改英雄类型的所有技能方法
var skillMethods = selectedHeroType.GetMethods()
.Where(m => m.GetCustomAttributes(typeof(AttributeClass.SkillAttribute), false).Any()).ToList();
//初始划技能方法
skillListBox.Items.Clear();
skillListBox.Items.AddRange(skillMethods.Select(m => m.Name).ToArray());
}
private void skillListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(skillListBox.SelectedIndex == -1) return;
//获取当前点击的技能
var selectedSikllMethod = selectedHero.GetType().GetMethod(skillListBox.SelectedItem.ToString());
//调用该技能方法
selectedSikllMethod?.Invoke(selectedHero,null);
}
}
/*
* 特性,为程序元素额外添加声明信息的一种方式,类似生活中的标签。
* 反射,是一种能力,运行时获取程序集中的元信息。
* 程序运行时会产生一个应用程序域,里面有程序集Assembly,反射能读取程序集当中的元信息,特性也属于元信息。
*/
} |
import { Flex, Icon } from '@chakra-ui/react';
import Link from 'next/link';
import type { ReactNode, VFC } from 'react';
import { memo } from 'react';
import type { IconType } from 'react-icons';
type Props = {
href: string;
icon: IconType;
children: ReactNode;
};
export const NavItem: VFC<Props> = memo((props) => {
const { href, icon, children } = props;
return (
<Link href={href} passHref>
<Flex
align="center"
fontSize="sm"
p="4"
mx="4"
borderRadius="lg"
role="group"
cursor="pointer"
_hover={{
bg: 'cyan.400',
color: 'white',
}}>
{icon && (
<Icon
mr="4"
fontSize="16"
_groupHover={{
color: 'white',
}}
as={icon}
/>
)}
{children}
</Flex>
</Link>
);
}); |
<!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" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf"
crossorigin="anonymous"
/>
<link
href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;700&display=swap"
rel="stylesheet"
/>
<!-- Added new relative path to reflect changes to the file architecture-->
<link rel="stylesheet" href="./assets/css/style.css" />
<title>Work Day Scheduler</title>
</head>
<body>
<header class="p-5 mb-4">
<h1 class="display-3">Work Day Scheduler</h1>
<p class="lead">A simple calendar app for scheduling your work day</p>
<p id="currentDay" class="lead"></p>
</header>
<div class="container-fluid px-5">
<!-- Use class for "past", "present", and "future" to apply styles to the
time-block divs accordingly. The javascript will need to do this by
adding/removing these classes on each div by comparing the hour in the
id to the current hour.
The html provided below is meant to be an example
demonstrating how the css provided can be leveraged to create the
desired layout and colors. The html below should be removed or updated
in the finished product. Remember to delete this comment once the
code is implemented.
-->
<!-- The following section of code is utilized for all one-hour time slots, spanning across the standard
business hours from 9:00AM to 5:00PM. Each block will have its own save button and will have a modifiable
text area for the user to enter different events. The save button allows each event for each time block to be
saved to localStorage. Each time block will be able to be color-coded based on whether that time slot is in the
past, present, or future. -->
<!-- Example of a past time block. The "past" class adds a gray background color. -->
<div class="time-block-container row time-block" id="hour-9">
<div class="col-2 col-md-1 hour text-center py-3">9AM</div>
<textarea class="col-8 col-md-10 description" rows="3"> </textarea>
<button class="btn saveBtn col-2 col-md-1" aria-label="save">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
</div>
<!-- Example of a present time block. The "present" class adds a red background color. -->
<div class="time-block-container row time-block" id="hour-10">
<div class="col-2 col-md-1 hour text-center py-3">10AM</div>
<textarea class="col-8 col-md-10 description" rows="3"> </textarea>
<button class="btn saveBtn col-2 col-md-1" aria-label="save">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
</div>
<!-- Example of a future time block. The "future" class adds a green background color. -->
<div class="time-block-container row time-block" id="hour-11">
<div class="col-2 col-md-1 hour text-center py-3">11AM</div>
<textarea class="col-8 col-md-10 description" rows="3"> </textarea>
<button class="btn saveBtn col-2 col-md-1" aria-label="save">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
</div>
<!-- Time block for 12PM-->
<div class="time-block-container row time-block" id="hour-12">
<div class="col-2 col-md-1 hour text-center py-3">12PM</div>
<textarea class="col-8 col-md-10 description" rows="3"> </textarea>
<button class="btn saveBtn col-2 col-md-1" aria-label="save">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
</div>
<!-- Time block for 1PM-->
<div class="time-block-container row time-block" id="hour-13">
<div class="col-2 col-md-1 hour text-center py-3">1PM</div>
<textarea class="col-8 col-md-10 description" rows="3"> </textarea>
<button class="btn saveBtn col-2 col-md-1" aria-label="save">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
</div>
<!-- Time block for 2PM-->
<div class="time-block-container row time-block" id="hour-14">
<div class="col-2 col-md-1 hour text-center py-3">2PM</div>
<textarea class="col-8 col-md-10 description" rows="3"> </textarea>
<button class="btn saveBtn col-2 col-md-1" aria-label="save">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
</div>
<!-- Time block for 3PM-->
<div class="time-block-container row time-block" id="hour-15">
<div class="col-2 col-md-1 hour text-center py-3">3PM</div>
<textarea class="col-8 col-md-10 description" rows="3"> </textarea>
<button class="btn saveBtn col-2 col-md-1" aria-label="save">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
</div>
<!-- Time block for 4PM-->
<div class="time-block-container row time-block" id="hour-16">
<div class="col-2 col-md-1 hour text-center py-3">4PM</div>
<textarea class="col-8 col-md-10 description" rows="3"> </textarea>
<button class="btn saveBtn col-2 col-md-1" aria-label="save">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
</div>
<!-- Time block for 5PM-->
<div class="time-block-container row time-block" id="hour-17">
<div class="col-2 col-md-1 hour text-center py-3">5PM</div>
<textarea class="col-8 col-md-10 description" rows="3"> </textarea>
<button class="btn saveBtn col-2 col-md-1" aria-label="save">
<i class="fas fa-save" aria-hidden="true"></i>
</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"
integrity="sha256-iu/zLUB+QgISXBLCW/mcDi/rnf4m4uEDO0wauy76x7U="
crossorigin="anonymous"></script>
<!-- New relative path added to reflect new file architecture-->
<script src="./assets/js/script.js"></script>
</body>
</html> |
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreProductRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'image' => ['nullable','image','mimes:jpeg,png,jpg,gif|max:2048'],
'category_id' => ['required', 'exists:categories,id'],
'supplier_id' => ['required', 'exists:suppliers,id'],
];
}
public function attributes()
{
return [
'name' => 'product name',
'image' => 'product image',
'category_id' => 'category',
'supplier_id' => 'supplier',
];
}
} |
<?php
/**
* Class to work with user capability
*
* @package User-Role-Editor
* @subpackage Admin
* @author Vladimir Garagulya <support@role-editor.com>
* @copyright Copyright (c) 2010 - 2016, Vladimir Garagulya
**/
class URE_Capability {
const SPACE_REPLACER = '_URE-SR_';
const SLASH_REPLACER = '_URE-SLR_';
const VERT_LINE_REPLACER = '_URE-VLR_';
public static function escape($cap_id) {
$search = array(' ', '/', '|');
$replace = array(self::SPACE_REPLACER, self::SLASH_REPLACER, self::VERT_LINE_REPLACER);
$cap_id_esc = str_replace($search, $replace, $cap_id);
return $cap_id_esc;
}
// end escape()
// sanitize user input for security
// do not allow to use internally used capabilities
public static function validate($cap_id_raw) {
$match = array();
$found = preg_match('/[A-Za-z0-9_\-]*/', $cap_id_raw, $match);
if (!$found || ($found && ($match[0]!=$cap_id_raw))) { // some non-alphanumeric charactes found!
$data = array(
'result'=>false,
'message'=>esc_html__('Error: Capability name must contain latin characters and digits only!', 'user-role-editor'),
'cap_id'=>'');
return $data;
}
$cap_id = strtolower($match[0]);
if ($cap_id=='do_not_allow') {
$data = array(
'result'=>false,
'message'=>esc_html__('Error: this capability is used internally by WordPress', 'user-role-editor'),
'cap_id'=>'do_not_allow');
return $data;
}
if ($cap_id=='administrator') {
$data = array(
'result'=>false,
'message'=>esc_html__('Error: this word is used by WordPress as a role ID', 'user-role-editor'),
'cap_id'=>'administrator');
return $data;
}
$data = array(
'result'=>true,
'message'=>'Success',
'cap_id'=>$cap_id);
return $data;
}
// end of validate()
/**
* Add new user capability
*
* @global WP_Roles $wp_roles
* @return string
*/
public static function add( $ure_object ) {
global $wp_roles;
if ( !current_user_can( 'ure_create_capabilities' ) ) {
return esc_html__( 'Insufficient permissions to work with User Role Editor', 'user-role-editor' );
}
$mess = '';
if (!isset($_POST['capability_id']) || empty($_POST['capability_id'])) {
return esc_html__( 'Wrong Request', 'user-role-editor' );
}
$data = self::validate( $_POST['capability_id'] );
if ( !$data['result'] ) {
return $data['message'];
}
$cap_id = $data['cap_id'];
$lib = URE_Lib::get_instance();
$full_capabilities = $lib->init_full_capabilities( $ure_object );
if ( !isset( $full_capabilities[$cap_id] ) ) {
$admin_role = $lib->get_admin_role();
$wp_roles->use_db = true;
$wp_roles->add_cap( $admin_role, $cap_id );
$mess = sprintf( esc_html__( 'Capability %s was added successfully', 'user-role-editor' ), $cap_id );
} else {
$mess = sprintf( esc_html__( 'Capability %s exists already', 'user-role-editor' ), $cap_id );
}
return $mess;
}
// end of add()
/**
* Extract capabilities selected from deletion from the $_POST global
*
* @return array
*/
private static function get_caps_for_deletion_from_post( $caps_allowed_to_remove ) {
if ( isset( $_POST['values'] ) ) {
$input_buff = $_POST['values'];
} else {
$input_buff = $_POST;
}
$caps = array();
foreach( $input_buff as $key=>$value ) {
if ( substr( $key, 0, 3 )!=='rm_' ) {
continue;
}
if ( !isset( $caps_allowed_to_remove[$value]) ) {
continue;
}
$caps[] = $value;
}
return $caps;
}
// end of get_caps_for_deletion_from_post()
private static function revoke_caps_from_user($user_id, $caps) {
$user = get_user_to_edit($user_id);
foreach($caps as $cap_id) {
if (!isset($user->caps[$cap_id])) {
continue;
}
// Prevent sudden revoke role 'administrator' from a user during 'administrator' capability deletion.
if ($cap_id=='administrator') {
continue;
}
$user->remove_cap($cap_id);
}
}
// end of revoke_caps_from_user()
private static function revoke_caps_from_role($wp_role, $caps) {
foreach($caps as $cap_id) {
if ($wp_role->has_cap($cap_id)) {
$wp_role->remove_cap($cap_id);
}
}
}
// end of revoke_caps_from_role()
private static function revoke_caps($caps) {
global $wpdb, $wp_roles;
// remove caps from users
$users_ids = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
foreach ($users_ids as $user_id) {
self::revoke_caps_from_user($user_id, $caps);
}
// remove caps from roles
foreach ($wp_roles->role_objects as $wp_role) {
self::revoke_caps_from_role($wp_role, $caps);
}
}
// end of revoke_caps()
/**
* Delete capability
*
* @global WP_Roles $wp_roles
* @return string - information message
*/
public static function delete() {
if ( !current_user_can( 'ure_delete_capabilities' ) ) {
return esc_html__( 'Insufficient permissions to work with User Role Editor','user-role-editor' );
}
$capabilities = URE_Capabilities::get_instance();
$mess = '';
$caps_allowed_to_remove = $capabilities->get_caps_to_remove();
if ( !is_array( $caps_allowed_to_remove ) || count( $caps_allowed_to_remove )==0 ) {
return esc_html__( 'There are no capabilities available for deletion!', 'user-role-editor' );
}
$caps = self::get_caps_for_deletion_from_post( $caps_allowed_to_remove );
if ( empty($caps) ) {
return esc_html__( 'There are no capabilities available for deletion!', 'user-role-editor' );
}
self::revoke_caps( $caps );
if ( count($caps)==1 ) {
$mess = sprintf( esc_html__( 'Capability %s was removed successfully', 'user-role-editor' ), $caps[0] );
} else {
$lib = URE_Lib::get_instance();
$short_list_str = $lib->get_short_list_str( $caps );
$mess = count( $caps ) .' '. esc_html__( 'capabilities were removed successfully', 'user-role-editor' ) .': '.
$short_list_str;
}
return array('message'=>$mess, 'deleted_caps'=>$caps);
}
// end of delete()
}
// end of class URE_Capability |
import com.pluralsight.application.BlackJackConsole;
import com.pluralsight.application.UnoConsole;
import com.pluralsight.models.cards.Card;
import com.pluralsight.models.cards.Deck;
import com.pluralsight.models.cards.facecards.FaceCard;
import com.pluralsight.models.cards.facecards.FaceCardDeck;
import com.pluralsight.models.games.CardGame;
import com.pluralsight.ui.UserInput;
import com.pluralsight.ui.UserOutput;
import com.pluralsight.ui.enumerations.GameOptions;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CardGamesApplication
{
public static void main(String[] args)
{
CardGame game;
Deck deck;
GameOptions option = UserInput.gameToPlay();
while(option != GameOptions.Quit)
{
if (option == GameOptions.BlackJack)
{
deck = loadFaceCardDeck("face.txt");
game = new BlackJackConsole((FaceCardDeck) deck);
game.play();
}
else if (option == GameOptions.Uno)
{
deck = loadDeck("uno.txt");
game = new UnoConsole(deck);
game.play();
}
option = UserInput.gameToPlay();
}
UserOutput.thankYou();
}
// these 2 methods could be implemented better through inheritance, but I didn't have time
private static Deck loadDeck(String filePath)
{
List<Card> cards = new ArrayList<>();
Deck deck = new Deck(cards);
File file = new File(filePath);
// open the file
try (Scanner fileReader = new Scanner(file.getAbsoluteFile()))
{
fileReader.nextLine(); // skip the first line
while(fileReader.hasNextLine())
{
String line = fileReader.nextLine();
String[] columns = line.split("\\|");
// create variables from the split
String name = columns[0].trim();
String face = columns[1].trim();
int value = Integer.parseInt(columns[2].trim());
String color = columns[3].trim();
// create card from input
Card card = new Card(value, color, face);
cards.add(card);
}
}
catch(FileNotFoundException e)
{
System.out.println("There was an error loading the file.");
}
return deck;
}
// these 2 methods could be implemented better through inheritance, but I didn't have time
private static FaceCardDeck loadFaceCardDeck(String filePath)
{
List<FaceCard> cards = new ArrayList<>();
FaceCardDeck deck = new FaceCardDeck(cards);
File file = new File(filePath);
// open the file
try (Scanner fileReader = new Scanner(file.getAbsoluteFile()))
{
fileReader.nextLine(); // skip the first line
while(fileReader.hasNextLine())
{
String line = fileReader.nextLine();
String[] columns = line.split("\\|");
// create variables from the split
String name = columns[0].trim();
String face = columns[1].trim();
int value = Integer.parseInt(columns[2].trim());
String suit = columns[3].trim();
// create card from input
FaceCard card = new FaceCard(suit, value, face);
cards.add(card);
}
deck = new FaceCardDeck(cards);
}
catch(FileNotFoundException e)
{
System.out.println("There was an error loading the file.");
}
return deck;
}
} |
package com.raf.si.patientservice.mapper;
import com.raf.si.patientservice.dto.request.CreateAppointmentRequest;
import com.raf.si.patientservice.dto.response.AppointmentListResponse;
import com.raf.si.patientservice.dto.response.AppointmentResponse;
import com.raf.si.patientservice.dto.response.http.DepartmentResponse;
import com.raf.si.patientservice.dto.response.http.UserResponse;
import com.raf.si.patientservice.exception.NotFoundException;
import com.raf.si.patientservice.model.Appointment;
import com.raf.si.patientservice.model.Patient;
import com.raf.si.patientservice.utils.TokenPayload;
import com.raf.si.patientservice.utils.TokenPayloadUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.annotations.NotFound;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
@Slf4j
@Component
public class AppointmentMapper {
private final PatientMapper patientMapper;
public AppointmentMapper(PatientMapper patientMapper) {
this.patientMapper = patientMapper;
}
public Appointment createAppointmentRequestToAppointment(CreateAppointmentRequest request,
Patient patient) {
Appointment appointment = new Appointment();
appointment.setPatient(patient);
appointment.setNote(request.getNote());
appointment.setReceiptDate(request.getReceiptDate());
TokenPayload token = TokenPayloadUtil.getTokenPayload();
appointment.setPbo(token.getPbo());
appointment.setEmployeeLBZ(token.getLbz());
return appointment;
}
public AppointmentResponse appointmentToAppointmentResponse(Appointment appointment,
DepartmentResponse departmentResponse,
UserResponse employeeResponse) {
AppointmentResponse response = new AppointmentResponse();
response.setPatient(patientMapper.patientToPatientResponse(appointment.getPatient()));
response.setDepartment(departmentResponse);
response.setEmployee(employeeResponse);
response.setId(appointment.getId());
response.setStatus(appointment.getStatus());
response.setNote(appointment.getNote());
response.setReceiptDate(appointment.getReceiptDate());
return response;
}
public AppointmentListResponse appointmentsToAppointmentListResponse(List<Appointment> appointments,
Long count,
DepartmentResponse departmentResponse,
Map<UUID, UserResponse> lbzToUserResponse) {
List<AppointmentResponse> responses = new ArrayList<>();
for (Appointment appointment : appointments) {
UserResponse userResponse = lbzToUserResponse.get(appointment.getEmployeeLBZ());
checkUser(userResponse, appointment.getEmployeeLBZ());
AppointmentResponse response = appointmentToAppointmentResponse(
appointment,
departmentResponse,
userResponse
);
responses.add(response);
}
return new AppointmentListResponse(responses, count);
}
private void checkUser(UserResponse userResponse, UUID lbz) {
if (userResponse == null) {
String errMessage = String.format("Korisnik sa lbz-om %s ne postoji", lbz);
log.error(errMessage);
throw new NotFoundException(errMessage);
}
}
} |
import numpy as np
import pandas as pd
class BirthDeath:
def __init__(self, b: float, d: float, N0: int, mu: float = None) -> None:
"""
initialize the population
:param b: float, birth rate per individual
:param d: float, death rate per individual
:param mu: float, mutation rate per individual
:param N0: int, initial population size
"""
self.b = b
self.d = d
self.mu = mu
self.N = N0 # current population size / number of individuals / number of cells
self.t = 0. # time since beginning of simulation
self.N_history = [N0] # list to record history of number of individuals
self.t_history = [0.] # list to record time of all events
self.c = [] # list to record cells where the event occurs
self.events = []
self.t_events = []
self.is_extinct = self.extinct()
def analytic(self, dt: np.ndarray):
return self.N * np.exp((self.b - self.d) * dt)
def next_event(self):
"""
generate the expected waiting time and identity of the next event
:param:
T: float, simulation time horizon
:return:
t: float, waiting time before next event (birth or death)
event: int, 0 means birth and 1 means death
"""
"""
Method 1. to determine next event type
# scale param: is an inverse of rate (odwrotność współczynnika)
t_b = np.random.exponential(
scale=1 / b_rate) # draw a random number from exponential dist as expected birth time
t_d = np.random.exponential(
scale=1 / d_rate) # draw a random number from exponential dist as expected death time
if t_b < t_d: # birth happens first
event = 0 # 0 to label birth
return t_b, event
event = 1 # death happens first, 1 to label death
return t_d, event
"""
# """
# Method 2. to determine next event type
b_rate = self.N * self.b # total birth rate
d_rate = self.N * self.d # total death rate
if self.mu:
mu_rate = self.N * self.mu # total mutation rate
rate = b_rate + d_rate + mu_rate # parameter N(b + d + mu)
else:
rate = b_rate + d_rate
t = np.random.exponential(scale=1 / rate) # t ~ exp(N(b + d + mu)) lub t ~ exp(N(b + d))
u = np.random.default_rng().uniform(0, 1) # random number from uniform dist
c_i = int(np.ceil(self.N * u)) # cell where the event occures
if self.mu:
event = 2 if u * rate <= mu_rate else 0 if u * rate <= (b_rate + mu_rate) else 1
else:
event = 0 if u * rate <= b_rate else 1
return t, event, c_i
# """
def count_N_in_timestep(self, df: pd.DataFrame, k_i: int, m_dt: np.ndarray) -> pd.DataFrame:
"""
:param k_i: int, number of simulations
:param df: DataFrame
:param m_dt: array of times; time sampling from 0 to T with step 0.05
:return: df
"""
for m in m_dt:
for index, t_i in enumerate(self.t_history):
if index < len(self.t_history) - 1:
if t_i <= m < self.t_history[index + 1]:
df.at[k_i, m] = self.N_history[index]
continue
if m > self.t_history[-1]:
df.at[k_i, m] = self.N
return df
def extinct(self):
return True if self.N == 0 else False |
🔙 [Back to Main](README.md)
### What is an `API`?
----
- `APIs` are mechanisms that enable two software components to communicate with each other using a set of definitions and protocols. For example, the weather bureau’s software system contains daily weather data. The weather app on your phone “talks” to this system via APIs and shows you daily weather updates on your phone. </br>
### What does `API` stand for?
----
- `API` stands for `Application Programming Interface`. In the context of `APIs`, the word Application refers to any software with a distinct function. Interface can be thought of as a contract of service between two applications. This contract defines how the two communicate with each other using requests and responses. Their `API` documentation contains information on how developers are to structure those requests and responses. </br>
### How do APIs work?
----
- `API` architecture is usually explained in terms of client and server. The application sending the request is called the client, and the application sending the response is called the server. So in the weather example, the bureau’s weather database is the server, and the mobile app is the client. </br>
- There are four different ways that `APIs` can work depending on when and why they were created. </br>
#### `SOAP APIs`
- These `APIs` use Simple Object Access Protocol. Client and server exchange messages using XML. </br>
- This is a less flexible `API` that was more popular in the past. </br>
#### `RPC APIs`
- These `APIs` are called Remote Procedure Calls. The client completes a function (or procedure) on the server, and the server sends the output back to the client. </br>
#### `Websocket APIs`
- `Websocket API` is another modern `web API` development that uses JSON objects to pass data. </br>
- A WebSocket API supports two-way communication between client apps and the server. The server can send callback messages to connected clients, making it more efficient than `REST API`.
#### `REST APIs`
- These are the most popular and flexible APIs found on the web today. </br>
- The client sends requests to the server as data. </br>
- The server uses this client input to start internal functions and returns output data back to the client. Let’s look at REST APIs in more detail below. </br>
### What are `REST APIs`?
----
- REST stands for `Representational State Transfer`. </br>
- REST defines a set of functions like GET, PUT, DELETE, etc. that clients can use to access server data. Clients and servers exchange data using HTTP </br>
- The main feature of `REST API` is statelessness. Statelessness means that servers do not save client data between requests. Client requests to the server are similar to URLs you type in your browser to visit a website. The response from the server is plain data, without the typical graphical rendering of a web page. </br>
### What is `web API`?
----
- A `Web API` or `Web Service API` is an application processing interface between a web server and web browser. All web services are APIs but not all APIs are web services. REST API is a special type of Web API that uses the standard architectural style explained above. </br>
- The different terms around `APIs`, like Java API or service APIs, exist because historically, `APIs` were created before the world wide web. Modern web APIs are REST APIs and the terms can be used interchangeably. </br>
### What are `API` integrations?
----
- `API integrations` are software components that automatically update data between clients and servers. Some examples of API integrations are when automatic data sync to the cloud from your phone image gallery, or the time and date automatically sync on your laptop when you travel to another time zone. Enterprises can also use them to efficiently automate many system functions.
### What are the benefits of REST APIs?
----
REST APIs offer four main benefits:
1. Integration </br>
- APIs are used to integrate new applications with existing software systems. </br>
- This increases development speed because each functionality doesn’t have to be written from scratch. You can use APIs to leverage existing code. </br>
2. Innovation </br>
- Entire industries can change with the arrival of a new app. </br>
- Businesses need to respond quickly and support the rapid deployment of innovative services. </br>
- They can do this by making changes at the API level without having to re-write the whole code. </br>
3. Expansion </br>
- APIs present a unique opportunity for businesses to meet their clients’ needs across different platforms. </br>
- For example, maps API allows map information integration via websites, Android,iOS, etc. Any business can give similar access to their internal databases by using free or paid `APIs`. </br>
4. Ease of maintenance </br>
- The API acts as a gateway between two systems. </br>
- Each system is obliged to make internal changes so that the `API` is not impacted. This way, any future code changes by one party do not impact the other party.
### What are the different types of APIs?
----
`APIs` are classified both according to their architecture and scope of use. We have already explored the main types of API architectures so let’s take a look at the scope of use.
#### `Private APIs`
- These are internal to an enterprise and only used for connecting systems and data within the business.
#### `Public APIs`
- These are open to the public and may be used by anyone. There may or not be some authorization and cost associated with these types of `APIs`.
#### `Partner APIs`
- These are only accessible by authorized external developers to aid business-to-business partnerships.
#### `Composite APIs`
- These combine two or more different APIs to address complex system requirements or behaviors.
### What is an API endpoint and why is it important?
----
- API endpoints are the final touchpoints in the API communication system. These include server URLs, services, and other specific digital locations from where information is sent and received between systems. API endpoints are critical to enterprises for two main reasons:
1. `Security`
- `API` endpoints make the system vulnerable to attack. API monitoring is crucial for preventing misuse.
2. `Performance`
- `API` endpoints, especially high traffic ones, can cause bottlenecks and affect system performance.
### How to secure a REST API?
----
All APIs must be secured through proper authentication and monitoring. The two main ways to secure REST APIs include: </br>
1. `Authentication tokens` </br>
- These are used to authorize users to make the API call. Authentication tokens check that the users are who they claim to be and that they have access rights for that particular API call. </br>
- For example, when you log in to your email server, your email client uses authentication tokens for secure access.
2. `API keys` </br>
- `API` keys verify the program or application making the API call. They identify the application and ensure it has the access rights required to make the particular API call. </br>
- `API` keys are not as secure as tokens but they allow API monitoring in order to gather data on usage. You may have noticed a long string of characters and numbers in your browser URL when you visit different websites. This string is an API key the website uses to make internal API calls.
### How to create an API?
----
Due diligence and effort are required to build an API that other developers will want to work with and trust. These are the five steps required for high-quality API design:
1. `Plan the API `
- `API` specifications, like OpenAPI, provide the blueprint for your `API` design. It is better to think about different use cases in advance and ensure the `API` adheres to current `API` development standard </br>
2. `Build the API`
- `API` designers prototype `APIs` using boilerplate code. Once the prototype is tested, developers can customize it to internal specifications.
3. `Test the API`
- `API` testing is the same as software testing and must be done to prevent bugs and defects. `API` testing tools can be used to strength test the `API` against cyber attacks.
4. `Document the API `
- While `APIs` are self-explanatory, `API` documentation acts as a guide to improve usability. Well-documented APIs that offer a range of functions and use cases tend to be more popular in a service-oriented architecture.
5. `Market the API`
- Just as Amazon is an online marketplace for retail, `API` marketplaces exist for developers to buy and sell other `APIs`. Listing your `API` can allow you to monetize it.
### What is `API testing`?
----
`API testing` strategies are similar to other software testing methodologies. The main focus is on validating server responses. `API testing` includes:
- Making multiple requests to API endpoints for performance testing. </br>
- Writing unit tests for checking business logic and functional correctness. </br>
- Security testing by simulating system attacks. </br>
### How to write `API documentation`?
----
Writing comprehensive `API documentation` is part of the API management process. `API documentation` can be auto-generated using tools or written manually. Some best practices include:
- Writing explanations in simple, easy-to-read English. Documents generated by tools can become wordy and require editing.
- Using code samples to explain functionality.
- Maintaining the documentation so it is accurate and up-to-date.
- Aiming the writing style at beginners
- Covering all the problems the `API` can solve for the users.
### How to use an `API`?
----
The steps to implement a new `API` include:
1. Obtaining an API key. This is done by creating a verified account with the API provider.
2. Set up an HTTP API client. This tool allows you to structure API requests easily using the API keys received.
3. If you don’t have an API client, you can try to structure the request yourself in your browser by referring to the API documentation.
4. Once you are comfortable with the new API syntax, you can start using it in your code.
### What is an `API gateway`?
----
- An API Gateway is an API management tool for enterprise clients that use a broad range of back-end services. API gateways typically handle common tasks like user authentication, statistics, and rate management that are applicable across all API calls.
- Amazon API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale. It handles all the tasks involved in accepting and processing thousands of concurrent API calls, including traffic management, CORS support, authorization, and access control, throttling, monitoring, and API version management.
### What is `GraphQL`?
----
- GraphQL is a query language that was developed specifically for APIs. It prioritizes giving clients exactly the data they request and no more. It is designed to make APIs fast, flexible, and developer-friendly. As an alternative to REST, GraphQL gives front-end developers the ability to query multiple databases, microservices, and APIs with a single GraphQL endpoint. Organizations choose to build APIs with GraphQL because it helps them develop applications faster. Read more about GraphQL here.
- AWS AppSync is a fully managed service that makes it easy to develop GraphQL APIs by handling the heavy lifting of securely connecting to data sources like AWS DynamoDB, AWS Lambda, and more AWS AppSync can push real-time data updates over Websockets to millions of clients. For mobile and web applications, AppSync also provides local data access when devices go offline. Once deployed, AWS AppSync automatically scales GraphQL API execution engine up and down to meet API request volumes. |
<?php if ( !defined( 'ABSPATH' ) ) exit();
get_header( );
$id = get_the_ID();
$thumbnail = wp_get_attachment_image_url(get_post_thumbnail_id() , 'thumbnail' );
if ( $thumbnail == '') {
$thumbnail = \Elementor\Utils::get_placeholder_image_src();
}
$category = get_the_terms($id, 'cat_career');
$career_banner = get_post_meta( $id, 'ova_career_met_career_banner', true );
if ( $career_banner == '') {
$career_banner = \Elementor\Utils::get_placeholder_image_src();
}
$created_by = get_post_meta( $id, 'ova_career_met_created_by', true );
$venue = get_post_meta( $id, 'ova_career_met_venue', true );
$salary = get_post_meta( $id, 'ova_career_met_salary', true );
$working_from = get_post_meta( $id, 'ova_career_met_working_from', true );
$date_posted = get_the_date(get_option('date_format'),$id);
$expiration_date = get_post_meta( $id, 'ova_career_met_expiration_date', true );
$experience = get_post_meta( $id, 'ova_career_met_experience', true );
$gender = get_post_meta( $id, 'ova_career_met_gender', true );
$qualification = get_post_meta( $id, 'ova_career_met_qualification', true );
$link_contact = get_post_meta( $id, 'ova_career_met_link_contact_message', true );
$list_social = get_post_meta( $id, 'ova_career_met_group_icon', true );
// website
$website_url = get_post_meta( $id, 'ova_career_met_website_url', true );
if( str_contains( $website_url,'://' ) ) {
$website_name = substr($website_url, strpos($website_url, "//") + 2);
} else {
$website_name = '';
}
// Calculate days left to apply
$current_timestamp = time();
$expiration_date_timestamp = strtotime($expiration_date);
$days_left_to_apply = ceil( ($expiration_date_timestamp - $current_timestamp)/86400 ) ;
// social
$social = get_post_meta( $id, 'ova_career_met_group_social', true );
// link button apply
$link_apply = get_post_meta( $id, 'ova_career_met_link_apply_career', true );
$apply_target = apply_filters('ova_career_single_ft_apply_target','_blank');
// gallery
$career_gallery_ids = get_post_meta($id, 'ova_met_gallery_id', true) ? get_post_meta($id, 'ova_met_gallery_id', true) : '';
// map
$map = get_post_meta( $id, 'ova_career_met_map', true );
if ( ($map == '') || ($map['latitude'] == '') || ($map['longitude'] == '') ) {
$map = [];
$map['latitude'] = 39.177972;
$map['longitude'] = -100.36375;
}
// get variable for related career
$current_post_type = get_post_type($id);
$cat_ids = array();
if(!empty($category) && !is_wp_error($category)):
foreach ($category as $cat_id):
array_push($cat_ids, $cat_id->term_id);
endforeach;
endif;
?>
<div class="career_single_container">
<div class="career_banner">
<img src="<?php echo esc_url($career_banner);?>" alt="<?php the_title();?>">
</div>
<div class="row_site">
<div class="container_site">
<div class="ova_career_single">
<div class="main_content">
<div class="icon-heart">
<i aria-hidden="true" class="fas fa-heart"></i>
</div>
<div class="top-info">
<img src="<?php echo esc_url( $thumbnail ); ?>" alt="<?php the_title(); ?>" class="career-thumbnail">
<div class="right">
<h1 class="career-title">
<?php the_title();?>
</h1>
<div class="by-and-categories">
<div class="by">
<span class="text">
<?php esc_html_e( 'By', 'ova-career'); ?>
</span>
<span class="name">
<?php echo esc_html($created_by); ?>
</span>
<span class="text">
<?php esc_html_e( 'in', 'ova-career'); ?>
</span>
</div>
<div class="categories">
<span class="value">
<?php $category_first_link = get_term_link($category[0]->term_id);
if ( $category_first_link ) {
echo '<a href="'.esc_url( $category_first_link ).'" title="'.esc_attr($category[0]->name).'">'.$category[0]->name.'</a>';
}
?>
</span>
</div>
</div>
<div class="tag-wrapper">
<span class="tag from">
<?php echo esc_html($working_from); ?>
</span>
<span class="tag location">
<i aria-hidden="true" class="flaticon-infetech-placeholder"></i>
<?php echo esc_html($venue); ?>
</span>
<span class="tag salary">
<i aria-hidden="true" class="flaticon-new-dollar"></i>
<?php echo esc_html($salary); ?>
</span>
</div>
</div>
</div>
<div class="content">
<?php if( have_posts() ) : while( have_posts() ) : the_post();
the_content();
?>
<?php endwhile; endif; wp_reset_postdata(); ?>
</div>
<div class="share-social-icons">
<span class="text-share">
<?php esc_html_e('Share job Post:','ova-career'); ?>
</span>
<?php apply_filters( 'ova_share_social', get_the_permalink(), get_the_title() ); ?>
</div>
<!-- Gallery -->
<?php if ( !empty($career_gallery_ids) ) : ?>
<div class="career-gallery-wrapper">
<h4 class="heading">
<?php esc_html_e('Photo & Gallery','ova-career') ;?>
</h4>
<div class="career_gallery">
<?php foreach( $career_gallery_ids as $gallery_id ):
$gallery_alt = get_post_meta($gallery_id, '_wp_attachment_image_alt', true);
$gallery_title = get_the_title( $gallery_id );
$gallery_url = wp_get_attachment_image_url( $gallery_id, 'aovis_thumbnail' );
if ( ! $gallery_alt ) {
$gallery_alt = get_the_title( $gallery_id );
}
?>
<a class="gallery-fancybox"
data-src="<?php echo esc_url( $gallery_url ); ?>"
data-fancybox="career-gallery-fancybox"
data-caption="<?php echo esc_attr( $gallery_alt ); ?>">
<img src="<?php echo esc_url($gallery_url); ?>" alt="<?php echo esc_attr($gallery_alt); ?>" title="<?php echo esc_attr($gallery_title); ?>">
<div class="blur-bg">
<div class="icon">
<i aria-hidden="true" class="ovaicon ovaicon-plus-1"></i>
</div>
</div>
</a>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
<!-- Map -->
<?php if( $map ): ?>
<div class="career_map">
<div id="ova_career_admin_show_map" data-zoom="<?php esc_attr_e( get_theme_mod( 'ova_career_zoom_map_default', 17 ) ); ?>">
<div class="marker" data-lat="<?php echo esc_attr( $map['latitude'] ); ?>" data-lng="<?php echo esc_attr( $map['longitude'] ); ?>"></div>
</div>
</div>
<?php endif; ?>
<!-- related career -->
<?php
$query_args = array(
'tax_query' => array(
array(
'taxonomy' => 'cat_career',
'field' => 'term_id',
'terms' => $cat_ids
)
),
'post_type' => $current_post_type,
'post__not_in' => array($id),
'posts_per_page' => '3',
'orderby' => 'rand',
);
$related = new WP_Query( $query_args );
?>
<?php if ( apply_filters( 'ova_career_show_related', true ) ): ?>
<?php if( $related->have_posts() ) : ?>
<div class="career-related-wrapper">
<h4 class="heading heading-related-career">
<?php esc_html_e('Similar Jobs','ova-career') ;?>
</h4>
<?php while( $related->have_posts()): $related->the_post();
ovacareer_get_template( 'parts/item-career.php' );
endwhile; wp_reset_postdata(); ?>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
<!-- Sidebar -->
<div class="career_sidebar">
<div class="top-sidebar">
<h4 class="heading heading-sidebar">
<?php esc_html_e('Interested in this job?','ova-career') ;?>
</h4>
<div class="apply">
<?php if( $days_left_to_apply > 0 ) { ?>
<span class="days">
<?php echo esc_html($days_left_to_apply);?>
</span>
<span class="text">
<?php echo esc_html__('days left to apply','ova-career') ;?>
</span>
<?php } else { ?>
<span class="text">
<?php echo esc_html__('Application deadline has expired','ova-career') ;?>
</span>
<?php } ?>
</div>
<!-- Apply Button -->
<?php if( !empty( $link_apply ) ) : ?>
<a href="<?php echo esc_attr($link_apply);?>" target="<?php echo esc_attr($apply_target); ?>" class="button-apply">
<?php esc_html_e('Apply Now','ova-career') ;?>
</a>
<?php endif; ?>
</div>
<div class="middle-bottom-sidebar">
<h4 class="heading">
<?php esc_html_e('Overview','ova-career') ;?>
</h4>
<ul class="listing-info-bar">
<?php if(!empty($category)) { ?>
<li>
<i aria-hidden="true" class="flaticon-new-peace-sign"></i>
<span class="text">
<?php esc_html_e('Categories','ova-career') ;?>
</span>
<span class="details-content">
<?php
$arr_link = array();
foreach( $category as $cat ) {
$category_link = get_term_link($cat->term_id);
if ( $category_link ) {
$link = '<a href="'.esc_url( $category_link ).'" title="'.esc_attr($cat->name).'">'.$cat->name.'</a>';
array_push( $arr_link, $link );
}
}
if ( !empty( $arr_link ) && is_array( $arr_link ) ) {
echo join(', ', $arr_link);
}
?>
</span>
</li>
<?php } ?>
<li>
<i aria-hidden="true" class="flaticon-new-calendar"></i>
<span class="text">
<?php esc_html_e('Date Posted','ova-career') ;?>
</span>
<span class="details-content">
<?php echo esc_html($date_posted); ?>
</span>
</li>
<?php if(!empty($map['address'])) { ?>
<li>
<i aria-hidden="true" class="flaticon-infetech-placeholder"></i>
<span class="text">
<?php esc_html_e('Location','ova-career') ;?>
</span>
<span class="details-content">
<?php echo esc_html( $map['address'] ); ?>
</span>
</li>
<?php } ?>
<?php if(!empty($salary)) { ?>
<li>
<i aria-hidden="true" class="flaticon-new-money"></i>
<span class="text">
<?php esc_html_e('Offered Salary','ova-career') ;?>
</span>
<span class="details-content">
<?php echo esc_html( $salary ); ?>
</span>
</li>
<?php } ?>
<?php if(!empty($expiration_date)) { ?>
<li>
<i aria-hidden="true" class="flaticon-new-calendar"></i>
<span class="text">
<?php esc_html_e('Expiration date','ova-career') ;?>
</span>
<span class="details-content">
<?php echo esc_html( $expiration_date ); ?>
</span>
</li>
<?php } ?>
<?php if(!empty($experience)) { ?>
<li>
<i aria-hidden="true" class="flaticon-new-increase"></i>
<span class="text">
<?php esc_html_e('Experience','ova-career') ;?>
</span>
<span class="details-content">
<?php echo esc_html( $experience ); ?>
</span>
</li>
<?php } ?>
<?php if(!empty($gender)) { ?>
<li>
<i aria-hidden="true" class="ovaicon ovaicon-user-1"></i>
<span class="text">
<?php esc_html_e('Gender','ova-career') ;?>
</span>
<span class="details-content">
<?php echo esc_html( $gender ); ?>
</span>
</li>
<?php } ?>
<?php if(!empty($qualification)) { ?>
<li>
<i aria-hidden="true" class="flaticon-new-graduation"></i>
<span class="text">
<?php esc_html_e('Qualification','ova-career') ;?>
</span>
<span class="details-content">
<?php echo esc_html( $qualification ); ?>
</span>
</li>
<?php } ?>
</ul>
<!-- Website -->
<?php if( !empty( $website_url ) && !empty( $website_name ) ) : ?>
<a href="<?php echo esc_attr($website_url);?>" target="_blank" class="website">
<?php esc_html_e($website_name) ;?>
<i aria-hidden="true" class="flaticon-new-link"></i>
</a>
<?php endif; ?>
<!-- Link to Contact Message -->
<?php if( !empty( $link_contact ) ) : ?>
<a href="<?php echo esc_attr($link_contact);?>" target="_blank" class="message">
<?php echo esc_html__('Send us message','ova-career') ;?>
<i aria-hidden="true" class="flaticon-new-paper-plane"></i>
</a>
<?php endif; ?>
<?php if( ! empty( $list_social ) ) { ?>
<ul class="social">
<?php
foreach( $list_social as $social ){
$class_icon = isset( $social['ova_career_met_class_icon_social'] ) ? $social['ova_career_met_class_icon_social'] : '';
$link_social = isset( $social['ova_career_met_link_social'] ) ? $social['ova_career_met_link_social'] : '';
?>
<li>
<a href="<?php echo esc_url( $link_social ); ?>" target="_blank">
<i class="<?php echo esc_attr( $class_icon ); ?>"></i>
</a>
</li>
<?php } ?>
</ul>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
<?php get_footer( ); |
import React from "react";
import { BrowserRouter } from "react-router-dom";
import render from "Utils/render";
import BlogPageDisplay from "./Display";
import { BlogBannerInfo } from "Api/BlogBannerInfo";
import { BlogPost } from "Api/BlogPost";
import { mockImage } from "Utils/Image";
const mockPost = (content: string): BlogPost => ({
title: "astgfsdhgdsfgsd",
content,
description: "",
id: 213,
image: mockImage({
url: "https://labfaz-strapi-assets.s3.sa-east-1.amazonaws.com/Whats_App_Image_2020_12_19_at_17_23_28_439c4529a0.jpeg",
alternativeText: "Blog Banner Image",
}),
created_at: "2021-07-01T00:27:01.317Z",
})
describe("Post page", () => {
it("renders without exploding", () => {
const mockedData: BlogBannerInfo = {
title: "Blog",
subtitle: "LoremIpsum",
image: {
url:
"https://labfaz-strapi-assets.s3.sa-east-1.amazonaws.com/Whats_App_Image_2020_12_19_at_17_23_28_439c4529a0.jpeg",
alternativeText: "Blog Banner Image",
caption: "string",
width: 20,
height: 20,
ext: "jpeg",
},
};
expect(() =>
render(
<BrowserRouter>
<BlogPageDisplay data={mockedData} post={mockPost("")} />
</BrowserRouter>
)
).not.toThrow();
});
it("displays the data message", () => {
const mockedData: BlogBannerInfo = {
title: "Blog",
subtitle: "LoremIpsum",
image: {
url:
"https://labfaz-strapi-assets.s3.sa-east-1.amazonaws.com/Whats_App_Image_2020_12_19_at_17_23_28_439c4529a0.jpeg",
alternativeText: "Blog Banner Image",
caption: "string",
width: 20,
height: 20,
ext: "jpeg",
},
};
const { getAllByRole } = render(
<BrowserRouter>
<BlogPageDisplay data={mockedData} post={mockPost("")} />
</BrowserRouter>
);
expect(getAllByRole("heading", { level: 1 })[0]).toHaveTextContent("Blog");
expect(getAllByRole("heading", { level: 2 })[0]).toHaveTextContent("LoremIpsum");
});
}); |
"""shop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from products.views import index, products, add_product, details
from profiles.views import profiles, register, login_view, logout_view
from notes.views import notes, add_notes
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include("api.url", namespace="api")),
path("api/auth/", include("rest_framework.urls", namespace="rest_framework")),
path("profiles/", profiles, name="profiles"),
path("products/", products, name="products"),
path("", index, name="index"),
path("register/", register, name="register"),
path("add_product/", add_product, name="add_product"),
path("login/", login_view, name="login"),
path("logout/", logout_view, name="logout"),
path("notes/", notes, name="notes"),
path("add_notes/", add_notes, name="add_notes"),
path("details/<int:product_id>/", details, name="details"),
# path("cart/", cart, name="cart"),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
import "./OpenEscrow.sol";
import "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol";
contract OpenEscrowFactoryV0 {
OpenEscrow[] public contracts;
event EscrowCreated(
address indexed buyer,
address indexed seller,
ERC20 buyerToken,
uint256 buyerTokenAmount,
ERC20 sellerToken,
uint256 sellerTokenAmount
);
function createEscrow(
address payable buyer,
address payable seller,
ERC20 buyerToken,
uint256 buyerTokenAmount,
ERC20 sellerToken,
uint256 sellerTokenAmount
) public {
OpenEscrow escrow = new OpenEscrow(
buyer,
seller,
buyerToken,
buyerTokenAmount,
sellerToken,
sellerTokenAmount
);
contracts.push(escrow);
emit EscrowCreated(
buyer,
seller,
buyerToken,
buyerTokenAmount,
sellerToken,
sellerTokenAmount
);
}
function getDeployedEscrows() public view returns (OpenEscrow[] memory) {
return contracts;
}
} |
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
background: #000;
color: #fff;
font: 10px sans-serif;
}
.frame {
fill: none;
stroke: #999;
}
.axis text {
font: 10px sans-serif;
fill: #999;
}
.axis line,
.axis circle {
fill: none;
stroke: #777;
stroke-dasharray: 1,4;
}
.axis :last-of-type circle {
stroke: #333;
stroke-dasharray: none;
}
.line {
fill: none;
stroke: #4a8;
stroke-width: 1.5px;
}
.oldline {
fill: none;
stroke: #48a;
stroke-width: 1px;
}
</style>
<body>
<script src="/js/d3.min.js"></script>
<script src="/js/reconnecting-websocket.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
/*
var data = d3.range(0, 2 * Math.PI, .01).map(function(t) {
return [t, Math.sin(2 * t) * Math.cos(2 * t)];
});
*/
function mean(numbers) {
// mean of [3, 5, 4, 4, 1, 1, 2, 3] is 2.875
var total = 0,
i;
for (i = 0; i < numbers.length; i += 1) {
total += numbers[i];
}
return total / numbers.length;
}
function median(numbers) {
// median of [3, 5, 4, 4, 1, 1, 2, 3] = 3
var median = 0,
numsLen = numbers.length;
numbers.sort();
if (numsLen % 2 === 0) { // is even
// average of two middle numbers
median = (numbers[numsLen / 2 - 1] + numbers[numsLen / 2]) / 2;
} else { // is odd
// middle number only
median = numbers[(numsLen - 1) / 2];
}
return median;
}
var data = d3.range(0,270,1).map(function(t) { return [t, []]; });
var width = 960,
height = 700,
radius = Math.min(width, height) / 2 - 30;
var r = d3.scale.linear()
.domain([0, 150])
.range([0, radius]);
var line = d3.svg.line.radial()
.defined(function(d) { return d[1].length>0; })
.radius(function(d) { return r(mean(d[1])); })
.angle(function(d) { return ((d[0]-45)*(Math.PI/180)); });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ") rotate(-90)");
var gr = svg.append("g")
.attr("class", "r axis")
.selectAll("g")
.data(r.ticks(15).slice(1))
.enter().append("g");
gr.append("circle")
.attr("r", r);
gr.append("text")
.attr("y", function(d) { return -r(d) - 4; })
.attr("transform", "rotate(90) translate(10,10)")
.style("text-anchor", "middle")
.text(function(d) { return d; });
var ga = svg.append("g")
.attr("class", "a axis")
.selectAll("g")
.data(d3.range(0, 360, 30))
.enter().append("g")
.attr("transform", function(d) { return "rotate(" + d + ")"; });
ga.append("line")
.attr("x2", radius);
ga.append("text")
.attr("x", radius + 6)
.attr("dy", ".35em")
.style("text-anchor", function(d) { return d < 270 && d > 90 ? "end" : null; })
.attr("transform", function(d) { return d < 270 && d > 90 ? "rotate(180 " + (radius + 6) + ",0)" : null; })
.text(function(d) { return d + "°"; });
var irdar = [];
var stopped = true;
var waypoint = 0;
var dspeed = 0.02;
var aspeed = 0.02;
var m1prev = "-";
var m2prev = "-";
$(function(){
var ws;
var draw = function() {
if(d3.select("#wp"+waypoint)[0][0]==null) {
irdar[waypoint] = svg.append("path")
.datum(data)
.attr("class", "line")
.attr("id", "wp"+waypoint)
.attr("d", line);
} else {
irdar[waypoint]
.datum(data)
.attr("class", "line")
.attr("d", line);
}
}
draw();
var logger = function(msg){
var msgparts = $.parseJSON(msg);
if(msgparts.motors != undefined) {
if(m1prev!="-" || m2prev!="-") {
// moved
var dist = 0;
var angle = 0;
if(m1prev=="^" && m2prev=="^") dist = dspeed * -msgparts.t;
if(m1prev=="v" && m2prev=="v") dist = dspeed * msgparts.t;
if(m1prev=="^" && m2prev=="v") angle = aspeed * msgparts.t;
if(m1prev=="v" && m2prev=="^") angle = aspeed * -msgparts.t;
waypoint ++;
for(var wp=0; wp<waypoint; wp++) {
var history = (irdar[wp].attr("transform")==null) ? "" : " " + irdar[wp].attr("transform");
irdar[wp]
.attr("class", "oldline")
.attr("transform", "rotate("+angle+") translate("+dist+",0)" + history);
}
data = d3.range(0,270,1).map(function(t) { return [t, []]; });
} else {
}
m1prev = msgparts.motors.m1;
m2prev = msgparts.motors.m2;
}
if(msgparts.rangers != undefined) {
for(var r=0; r<msgparts.rangers.length; r++) {
//update(msgparts.rangers[r].f, msgparts.rangers[r].d);
if(data[msgparts.rangers[r].f]==undefined) data[msgparts.rangers[r].f] = [msgparts.rangers[r].f, []];
data[msgparts.rangers[r].f][1].push(msgparts.rangers[r].d);
}
draw();
}
//$("#log").html($("#log").html() + "<br />" + msg);
//$("#log").animate({ scrollTop: $('#log')[0].scrollHeight}, 100);
// $('#log').scrollTop($('#log')[0].scrollHeight);
}
var sender = function(k) {
ws.send(k);
}
ws = new ReconnectingWebSocket("ws://robincw.noip.me:12308/ws");
ws.onmessage = function(evt) {
logger(evt.data);
};
ws.onclose = function(evt) {
$("#log").text("Connection was closed...");
$("#thebutton #msg").prop('disabled', true);
};
ws.onopen = function(evt) { $("#log").text("Opening socket..."); };
var keysdown = {}
$(window).keydown(function(event) {
var k;
switch(event.which) {
case 189:
k='-';
break;
case 187:
k='=';
break;
default:
k=String.fromCharCode(event.which).toLowerCase();
}
if(keysdown[event.which] == null && k != 's') {
keysdown[event.which] = true;
sender(k);
}
});
$(window).keyup(function(event) {
keysdown[event.which] = null;
sender('s');
});
});
</script>
<h1>Map making robot</h1>
<table style="position: fixed; top: 0px; left: 0px; width: 64px; height: 64px;" cellspacing: "0" cellpadding: "0"><tr>
<td style="width: 20px; height: 20px" title="Scan 1 degree left">Q</td>
<td style="width: 20px; height: 20px; border: solid 1px #fff;" title="Drive forwards">W</td>
<td style="width: 20px; height: 20px" title="Scan 1 degree right">E</td>
<td style="width: 20px; height: 20px" id="dspeed">0.001</td>
</tr><tr>
<td style="width: 20px; height: 20px; border: solid 1px #fff;" title="Turn left">A</td>
<td style="width: 20px; height: 20px; border: solid 1px #fff;" title="Stop and scan">S</td>
<td style="width: 20px; height: 20px; border: solid 1px #fff;" title="Turn right">D</td>
<td style="width: 20px; height: 20px; border: solid 1px #fff;" title="Full scan">F</td>
</tr><tr>
<td style="width: 20px; height: 20px" title="Scan 10 degrees left">Z</td>
<td style="width: 20px; height: 20px; border: solid 1px #fff;" title="Drive backwards">X</td>
<td style="width: 20px; height: 20px" title="Scan 10 degrees right">C</td>
<td style="width: 20px; height: 20px" id="aspeed">0.001</td>
</tr>
</table> |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>后台管理系统 | 欢迎使用</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.7 -->
<link rel="stylesheet" href="../js/libs/AdminLTE-2.4.2/bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="../js/libs/AdminLTE-2.4.2/bower_components/font-awesome/css/font-awesome.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../js/libs/AdminLTE-2.4.2/dist/css/AdminLTE.css">
<link rel="stylesheet" href="../js/libs/AdminLTE-2.4.2/dist/css/skins/_all-skins.min.css">
<link rel="stylesheet" href="../js/libs/AdminLTE-2.4.2/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
</head>
<body>
<section class="content-header">
<h1>
<small>店铺管理</small>
</h1>
</section>
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box box-success">
<div class="box-header with-border">
<h3 class="box-title">修改</h3>
</div>
<form id="myForm" role="form" enctype="multipart/form-data">
<input type="hidden" id="id" name="id" value="${shop.id}"/>
<div class="box-body">
<div class="form-group">
<label for="name">店铺名称</label>
<input id="name" name="name" class="form-control" placeholder="店铺名称" maxlength="10" value="${shop.name }">
</div>
<div class="form-group">
<label for="file1">微信二维码</label>
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="${shop.qrcode }" alt="${shop.name }" onerror="this.src='../imgs/boxed-bg.jpg'">
</div>
</div>
</div>
<input id="file1" name="file1" type="file" accept="image/*" placeholder="微信二维码"/>
</div>
<div class="form-group">
<label for="file">店铺封面</label>
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="${shop.shopcover }" alt="${shop.name }" onerror="this.src='../imgs/boxed-bg.jpg'">
</div>
</div>
</div>
<input id="file" name="file" type="file" accept="image/*" placeholder="店铺封面"/>
</div>
<div class="form-group">
<label for="description">店铺描述</label>
<textarea id="description" name="description" class="form-control" rows="3" placeholder="店铺描述" maxlength="100">${shop.description }</textarea>
</div>
<div class="form-group">
<label for="location">店铺位置</label>
<input id="location" name="location" class="form-control" placeholder="店铺位置" maxlength="50" value="${shop.location }">
</div>
<div class="form-group">
<input type="hidden" id="lon" name="lon" value="${shop.lon }"/>
<input type="hidden" id="lat" name="lat" value="${shop.lat }"/>
<div id="container" class="col-sm-12" style="height:300px"></div>
</div>
<div class="form-group">
<label for="location">店主</label>
${admin.username }
<input id="adminid" name="adminid" type="hidden" value="${admin.id }">
</div>
<div class="form-group has-error">
<span class="help-block hidden"></span>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-success">提交</button>
<button type="button" class="btn btn-success" onclick="window.location.href='list'">返回</button>
</div>
</form>
</div>
</div>
</div>
</section>
<!-- jQuery 3 -->
<script src="../js/libs/AdminLTE-2.4.2/bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="../js/libs/AdminLTE-2.4.2/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- FastClick -->
<script src="../js/libs/AdminLTE-2.4.2/bower_components/fastclick/lib/fastclick.js"></script>
<script src="../js/libs/AdminLTE-2.4.2/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="../js/libs/AdminLTE-2.4.2/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="../js/libs/AdminLTE-2.4.2/dist/js/adminlte.js"></script>
<script src="../js/jquery.form.min.js"></script>
<script type="text/javascript">
$("#myForm").ajaxForm({
type: "post", //提交方式
dataType: "json", //数据类型
url: "edit", //请求url
//beforeSubmit: validate, // 提交前
success: function (data) { //提交成功的回调函数
if(data.status=='yes'){
window.location.href='list';
}else{
$(".help-block").html(data.message);
$(".help-block").removeClass("hidden");
}
}
});
function validate(){
}
</script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.4&key=49e9419b8d4734505992b6a69cfb9302"></script>
<script type="text/javascript">
$(function(){
var lon = $("#lon").val();
var lat = $("#lat").val();
var map = new AMap.Map('container',{
resizeEnable: true,
zoom: 15,
center: [lon, lat]
});
AMap.plugin(['AMap.ToolBar','AMap.Scale'],
function(){
map.addControl(new AMap.ToolBar({ position: 'LT'}));
map.addControl(new AMap.Scale({ position: 'LB'}));
}
);
var marker = new AMap.Marker({
map:map,
bubble:true
})
map.on('click',function(e){
marker.setPosition(e.lnglat);
$("#lon").val(e.lnglat.lng);
$("#lat").val(e.lnglat.lat);
AMap.service('AMap.Geocoder',function(){//回调函数
geocoder = new AMap.Geocoder({
city: "010"//城市,默认:“全国”
});
geocoder.getAddress(e.lnglat, function(status, result) {
if (status === 'complete' && result.info === 'OK') {
$("#location").val(result.regeocode.formattedAddress);
}else{
alert("获取地址失败");
}
});
})
})
map.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({buttonPosition: 'RB'});
map.addControl(geolocation);
if(!lat||!lon){
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
AMap.event.addListener(geolocation, 'error', onError); //返回定位出错信息
}
});
//解析定位结果
function onComplete(data) {
/* $("#lon").val(data.position.lng);
$("#lat").val(data.position.lat); */
}
//解析定位错误信息
function onError(data) {
alert('定位失败');
}
})
</script>
</body>
</html> |
### ADVENT OF CODE - DAY 1 ########################
#-- Libraries -------------------------
library(tidyverse)
#-- Load data ------------------------
#input <- read_table(here::here("2022", "day_01", "test_input_day01.txt"), col_names = "calories", skip_empty_rows = FALSE)
input <- read_csv(here::here("2022", "day_01", "input_day01.txt"),
col_names = "calories", skip_empty_rows = FALSE)
#-- Part 1 ------------------------
# How many Calories is the Elf carrying the most Calories carrying?
input |>
mutate(empty = ifelse(is.na(calories), 1, 0),
elf = cumsum(empty)) |>
drop_na() |>
group_by(elf) |>
summarise(total_calories = sum(calories)) |>
slice_max(total_calories) |>
pull(total_calories) |>
print()
#-- Part 2 ------------------------
# How many calories are carried by the Elves carrying the top 3 most calories?
input |>
mutate(empty = ifelse(is.na(calories), 1, 0),
elf = cumsum(empty)) |>
drop_na() |>
group_by(elf) |>
summarise(total_calories = sum(calories)) |>
slice_max(total_calories, n = 3) |>
summarise(total_calories = sum(total_calories)) |>
pull(total_calories) |>
print() |
import { useState } from "react";
import Link from "next/link";
import DropdownCaret from "./DropdownCaret";
interface DropdownProps {
content: {
text: string;
children: Array<{ text: string; link: string; sub?: any[] }>;
};
}
export default function Dropdown({ content }: DropdownProps | any) {
const [active, setActive] = useState(false);
return (
<div className="mx-2">
<div className="flex justify-center">
<div className="dropdown relative">
<button
onMouseEnter={() => setActive(true)}
className="px-2 ml-2 lg:px-4 py-2 font-medium text-xs leading-tight uppercase hover:text-blue-700 active:bg-red-800 active:shadow-lg active:text-white transition duration-150 ease-in-out flex z-50 items-center whitespace-nowrap"
type="button"
id="dropdownMenuButton1"
aria-expanded="false"
aria-label={`${content.text}`}
>
{content.text}
<DropdownCaret />
</button>
{active && (
<ul
className="min-w-max absolute bg-white text-base z-40 float-left py-2 list-none top-6 flex flex-col text-left rounded-lg shadow-lg mt-1 m-0 bg-clip-padding border-none"
aria-labelledby="dropdownMenuButton1"
onMouseLeave={() => setActive(false)}
>
{content.children.map((item: any) => {
return item.link ? (
<Link key={item.text} href={item.link} passHref>
<li>
<a
aria-label="dropdown"
className={`dropdown-item text-sm py-1 px-2 font-normal block w-full whitespace-nowrap bg-transparent text-gray-700 hover:bg-gray-100`}
href="#"
title={item.text}
>
{item.text}
</a>
</li>
</Link>
) : (
<a key={item.text} className="mx-2" title={item.text}>
{item.text}
</a>
);
})}
</ul>
)}
</div>
</div>
</div>
);
} |
package org.example.book;
public class Book implements Comparable{
private String title;
private String authorFirstName;
private String authorLastName;
private int pages;
public Book() {
this.title = "No title specified!";
this.authorFirstName = "No author first name specified!";
this.authorLastName = "No author last name specified!";
this.pages = 0;
}
public Book(String title, String authorFirsName, String authorLastName, int pages) {
this.title = title;
this.authorFirstName = authorFirsName;
this.authorLastName = authorLastName;
this.pages = pages;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthorFirsName() {
return authorFirstName;
}
public void setAuthorFirsName(String authorFirsName) {
this.authorFirstName = authorFirsName;
}
public String getAuthorLastName() {
return authorLastName;
}
public void setAuthorLastName(String authorLastName) {
this.authorLastName = authorLastName;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public String toString() {
return getTitle() + " (" + pages + " pages) " + " Written By: " + getAuthorFirsName() + " " + getAuthorLastName() + "\n";
}
@Override
public int compareTo(Object o) {
Book book = (Book) o;
return title.compareTo(book.getTitle());
}
public void printInfo() {
System.out.println("**** BOOK INFO ****");
System.out.println(this);
}
} |
import React, { useContext, useState } from "react";
import { FireBaseContext } from "../../Context/FireBase";
import {
updatePassword,
reauthenticateWithCredential,
EmailAuthProvider,
} from "firebase/auth";
import swal from "sweetalert";
const PasswordForm = () => {
const [newPassword, setNewPassword] = useState("");
const [CurrentPassword, setCurrentPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const { user } = useContext(FireBaseContext);
const credentials = user.providerData;
const checkpassword = ()=>{
if(newPassword==''||CurrentPassword==''||confirmPassword==''){
return true
}else{
return false
}
}
const handleChangePassword = async () => {
if (confirmPassword !== newPassword) {
setError("Password Not Matcing");
return;
}
const cred = EmailAuthProvider.credential(user.email, CurrentPassword);
console.log(cred);
await reauthenticateWithCredential(user, cred);
// // Update the password
try {
await updatePassword(user, newPassword);
swal({
icon: "success",
title: `Password Changed`,
}).then(() => {
setConfirmPassword("");
setCurrentPassword("");
setNewPassword("");
});
} catch (error) {
console.error("Error updating password:", error.message);
}
};
return (
<div >
<h5 className=" text-center m-0 mb-4 ">Change Password</h5>
<div className="row flex-column gap-2 align-items-center justify-content-center flex-wrap">
<div className=" row justify-content-between flex-wrap ">
<div className="col-5 " >
<label >Current Password:</label>
</div>
<div className="col-5 flex-fill">
<input
type="password"
value={CurrentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
/>
</div>
</div>
<div
className=" row justify-content-between flex-wrap"
>
<div className="col-5 ">
<label>New Password:</label>
</div>
<div className="col-5 flex-fill ">
<input
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
/>
</div>
</div>
<div className=" row justify-content-between flex-wrap">
<div className="col-5 ">
<label>Confirm Password:</label>
</div>
<div className="col-5 flex-fill">
<input
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
</div>
</div>
</div>
{error && <p style={{ color: "red" }}>{error}</p>}
<div className="w-100 d-flex justify-content-center align-items-center my-2 gap-2">
<span className={`text-danger ${checkpassword()?'d-block':'d-none'}`}>insert all data</span>
<button
className="border-0 bg-primary text-white rounded align-self-end "
disabled={checkpassword()}
onClick={handleChangePassword}
>
Change Password
</button>
</div>
</div>
);
};
export default PasswordForm; |
;;
;; ANSI Common Lisp 日本語訳
;; 4. 型とクラス
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; System Class FUNCTION
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@begin: 4.4.function!system-class
@name: function!system-class
@type: system-class
System Class `FUNCTION`
## {class-precedence-list}
{function!system-class:link},
{t!system-class:link}
## {description}
関数`function`とは、適切な数の引数を供給することで
実行されるコードを表現したオブジェクトです。
関数は、{function!special:link} {special-form}か、
関数への{coerce:link}か、
関数への{compile:link}によって生成されます。
関数は、{funcall:link}か{apply:link}か{multiple-value-call:link}の
第一引数として使用することによって直接起動できます。
## {compound-type-specifier-kind}
{specializing}
## {compound-type-specifier-syntax}
`function` [*arg-typespec* [*value-typespec*]]
```
arg-typespec ::= (typespec*
[&optional typespec*]
[&rest typespec]
[&key (keyword typespec)*])
```
## {compound-type-specifier-arguments}
*typespec* - 型指定子
*value-typespec* - 型指定子
## {compound-type-specifier-description}
リスト形式の{function!system-class:link}型指定子は
宣言でのみ使用することができ、区別されません。
この型の要素は、
*arg-typespec*によって指定された関数が受け付ける引数の型と、
*value-type*によって指定された返却値の型の集まりです。
引数の型のリストには、
`&optional`, `&rest`, `&key`, `&allow-other-keys`の印を
表すことができます。
この型指定子が提供する`&rest`は実際の各引数の型を表しており、
続く変数の型ではありません。
`&key`パラメーターはフォーム`(keyword type)`のリストとして
指定されなければなりません。
*keyword*は、呼び出しのときの実際の引数とし指定される
正当なキーワード名のシンボルである必要があります。
これは通常`KEYWORD`パッケージ内のシンボルですが、
どんなシンボルでも指定できます。
`&key`が{function!system-class:link}の型指定子のラムダリストに
与えられたときは、
その与えられたキーワードパラメーターは
`&allow-other-keys`が現れてないのであれば
徹底的に調査されます。
`&allow-other-keys`は、他のキーワード引数が実際に
指定されるかもしれないことを意味しており、
実際に指定されたときでも使用できます。
例えば、関数{make-list:link}の型は下記のように表すことができます。
```lisp
(function ((integer 0) &key (:initial-element t)) list)
```
*value-type*は、多値の型を示すために、
{values!type:link}型指定子を使うことができます。
下記の宣言フォームを考えます。
```lisp
(ftype (function (arg0-type arg1-type ...) val-type) f)
```
この宣言のスコープ内にある
全ての`(f arg0 arg1 ...)`フォームは
下記と同等になります。
```lisp
(the val-type (f (the arg0-type arg0) (the arg1-type arg1) ...))
```
これは、もし引数のどれかが指定された型と一致していないか、
返却値が指定した型と一致していなかったときの結果は未定義です。
とくに引数のどれかが正しく型と一致していないときは、
返却値が指定した型であるという保証はありません。
したがって、関数への{ftype:link}宣言は関数呼び出しの記述であり、
実際の関数定義に対するものではありません。
下記の宣言フォームを考えます。
```lisp
(type (function (arg0-type arg1-type ...) val-type) fn-valued-variable)
```
この宣言の解釈は次のようになります。
宣言のスコープ内では、もし`fn-valued-variable`の値が
指定した型の引数で呼ばれなかったときの結果は未定義です。
正しく呼び出されたときの返却値の型は`val-type`になるでしょう。
変数の型宣言がネストされたときは、
下記のように、暗黙的に型の共通部分が宣言されます。
- 次の2つの{ftype:link}宣言を考えます。
```lisp
(ftype (function (arg0-type1 arg1-type1 ...) val-type1) f)
(ftype (function (arg0-type2 arg1-type2 ...) val-type2) f)
```
もしこれらの宣言の両方に効果があるときは、
それらの宣言で囲まれた共通部分内では、
`f`の呼び出しは下記のような`f`の宣言であるかのように扱われます。
```lisp
(ftype (function ((and arg0-type1 arg0-type2) (and arg1-type1 arg1-type2 ...) ...)
(and val-type1 val-type2))
f)
```
これは、ひとつを無視するか、
あるいは全ての{ftype:link}を有効にするか、
どちらでも許されます。
- もし2つ(あるいはもっと)の型宣言が変数に対して効果を持っており、
それらは両方とも{function!system-class:link}の宣言であるとき、
それらの宣言は同じように結び付けられます。
@end |
import 'package:flutter/material.dart';
typedef IntValueSetter = void Function(int value);
class RangeSelectorForm extends StatelessWidget {
final GlobalKey<FormState> formKey;
final IntValueSetter minValueSetter;
final IntValueSetter maxValueSetter;
const RangeSelectorForm({
Key? key,
required this.formKey,
required this.minValueSetter,
required this.maxValueSetter,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RangeSelectorTextFormField(
labelText: "Minimum",
intValueSetter: minValueSetter,
),
const SizedBox(
height: 12,
),
RangeSelectorTextFormField(
labelText: "Maximum",
intValueSetter: maxValueSetter,
),
],
),
),
);
}
}
class RangeSelectorTextFormField extends StatelessWidget {
const RangeSelectorTextFormField({
Key? key,
required this.labelText,
required this.intValueSetter,
}) : super(key: key);
final String labelText;
final IntValueSetter intValueSetter;
@override
Widget build(BuildContext context) {
return TextFormField(
keyboardType: const TextInputType.numberWithOptions(
decimal: false,
signed: true,
),
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText: labelText,
),
validator: (value) {
if (value == null || int.tryParse(value) == null) {
return 'Must be an integer';
}
return null;
},
onSaved: (newValue) => intValueSetter(int.parse(newValue!)),
);
}
} |
<?php
namespace App;
use App\Traits\CoveringTrait;
use Illuminate\Database\Eloquent\Model;
/**
*/
class Torso extends Model
{
use CoveringTrait;
protected $fillable = [
'color', 'covering', 'pattern',
];
/**
* The available covering values
*
* @var array
*/
protected $coverings = ["skin", "feathers", "scales", "slime", "skin", "non-corporeal", "skeletonized", "fur", "spines", "skin", "fire", "water", "earth", "air"];
/**
* The main covering that will determine the allowable values for sub Coverings
*
* @var $mainCovering
*/
protected $mainCovering;
/**
* The actual applied levels of all coverings
*
* @var $coverings
*/
protected $appliedCoverings;
/**
* Value available for distribution
*
* @var $availVal
*/
protected $availVal = 80;
/**
* Associates torso with creature
*/
public function creature()
{
return $this->belongsTo('App\Creature', 'creature_id')->withDefault();
}
/**
* get the torso coloring
*
* @return mixed
*/
public function getRandomColor()
{
$colors = ["AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood","CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","DarkBlue","DarkCyan","DarkGoldenRod","DarkGray","DarkGrey","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","Darkorange","DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkSlateGrey","DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","FireBrick","FloralWhite","ForestGreen","Fuchsia","Gainsboro","GhostWhite","Gold","GoldenRod","Gray","Grey","Green","GreenYellow","HoneyDew","HotPink","IndianRed","Indigo","Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGoldenRodYellow","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon","MediumAquaMarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","Navy","OldLace","Olive","OliveDrab","Orange","OrangeRed","Orchid","PaleGoldenRod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple","Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown","SeaGreen","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","SlateGrey","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen"];
$color = $colors[mt_rand(0, count($colors)-1)];
return $color;
}
/**
* call the methods that will determine torso composition
*
* @return mixed
*/
public function getCoveringValues()
{
$this->getMainCovering();
$this->applyLevelsToCovering();
return $this->appliedCoverings;
}
/**
* get the torso external pattern
*
* @return mixed
*/
public function getRandomPattern()
{
$patterns = ["none", "stripes", "spotted", "none", "none"];
$pattern = $patterns[mt_rand(0, count($patterns)-1)];
return $pattern;
}
/**
* get a random torso composition
*
* @return mixed
*/
public function getRandomCovering()
{
return $this->coverings[mt_rand(0, count($this->coverings)-1)];
}
/**
* this is the main torso composition, this will have a higher value than others
*/
public function getMainCovering()
{
$this->mainCovering = $this->coverings[mt_rand(0, count($this->coverings)-1)];
}
/**
* this will set the varying torso composition levels
*/
public function applyLevelsToCovering()
{
$cover = [];
$cover[$this->mainCovering] = 20;
while ($this->availVal > 0) {
$cov = $this->getRandomCovering();
if ($cov !== $this->mainCovering) {
if ((isset($cover[$cov]) && $cover[$cov] < 15) || !isset($cover[$cov])) {
$val = $this->getVal();
$val = $this->disallowPointOverSpending($val);
$cover = $this->initializeNewEntities($cover, $cov);
if ($cover[$cov] + $val > 15) {
$val = $val - (($cover[$cov] + $val) - 15);
}
$cover[$cov] += $val;
$this->availVal -= $val;
}
}
}
$this->appliedCoverings = $cover;
}
/**
* get a random value for assigning to torso composition
*
* @return int
*/
public function getVal()
{
return mt_rand(1, 15);
}
/**
* do not allow points to be applied if the points are not available
*
* @param $val
*
* @return int
*/
protected function disallowPointOverSpending($val)
{
if ($val > $this->availVal) {
$val = $this->availVal;
}
return $val;
}
/**
* if the value has not been previously set, ensure that it is
*
* @param $cover
* @param $val
*
* @return mixed
*/
protected function initializeNewEntities($cover, $val)
{
if (!isset($cover[$val])) {
$cover[$val] = 0;
}
return $cover;
}
/**
* mutate to ensure an array is returned
*
* @param $value
*
* @return array
*/
public function getCovering($value)
{
return (array)$value;
}
} |
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClib.h>
DateTime now;
RTC_DS3231 rtc;
LiquidCrystal_I2C lcd(0x27,16,2);
void displayDate(void);
void displayTime(void);
void setup ()
{
Serial.begin(9600);
lcd.begin();
lcd.backlight();
if (! rtc.begin())
{
Serial.println("DS1307 RTC Module not Present");
while (1);
}
if (rtc.lostPower())
{
Serial.println("RTC power failure, resetting the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop ()
{
now = rtc.now();
displayDate();
displayTime();
}
void displayTime()
{
lcd.setCursor(0,0);
lcd.print("Time:");
lcd.print(now.hour());
lcd.print(':');
lcd.print(now.minute());
lcd.print(':');
lcd.print(now.second());
lcd.print(" ");
}
void displayDate()
{
lcd.setCursor(0,1);
lcd.print("Date:");
lcd.print(now.day());
lcd.print('/');
lcd.print(now.month());
lcd.print('/');
lcd.print(now.year());
} |
import ky from 'https://cdn.skypack.dev/ky?dts'
import {backgroundColor, createCard, createModal, fillSearchBar} from './js/modules.js'
const BASE_API_URL = 'https://pokeapi.co/api/v2'
const mainContainer = document.querySelector('.container.main')
const searchBarItemsContainer = document.querySelector('.autocomplete-box')
const searchBar = document.querySelector('#search-bar')
const regionSelect = document.querySelector('#region__select')
const primaryType = 0
const secondaryType = 1
async function getPokemons(){
const response = await ky.get(`${BASE_API_URL}/pokemon/?limit=150`).json()
const { results } = response
for(let i = 1 ; i<=results.length ; i++){
const data = await ky.get(`${BASE_API_URL}/pokemon/${i}/`).json()
const {sprites, types, id, name} = data
let fistType = types[primaryType].type.name
let secondType = (types.length>1) ? types[secondaryType].type.name : ""
let type = fistType+secondType
let card = createCard(sprites.other.home.front_default, id, name, fistType, secondType)
mainContainer.appendChild(card)
backgroundColor(type, card)
// card.style.display = 'none'
let item = fillSearchBar(sprites.other.home.front_default, id, name)
searchBarItemsContainer.appendChild(item)
searchBarItemsContainer.classList.add('not-show')
searchBar.addEventListener('keyup', filterItem)
card.addEventListener('click', showPokemonDetails)
}
}
function filterItem(){
const textValue = searchBar.value.split(" ").join("").toLowerCase()
searchBarItemsContainer.classList.remove('not-show')
let listItems = document.querySelectorAll('li')
listItems.forEach(element => {
let pokemonName = element.dataset.name
element.style.display='none'
if(pokemonName.indexOf(textValue) != -1 ){
element.style.display = 'flex'
}
if(textValue === ""){
searchBarItemsContainer.classList.add('not-show')
}
});
}
async function showPokemonDetails(){
const data = await ky.get(`${BASE_API_URL}/pokemon/${this.dataset.name}/`).json()
const {sprites, types, id, name} = data
let fistType = types[primaryType].type.name
let secondType = (types.length>1) ? types[secondaryType].type.name : ""
let type = fistType+secondType
let modal = createModal(id, name, sprites.other.home.front_default, type)
mainContainer.appendChild(modal)
modal.classList.add('modal--show')
modal.addEventListener('click', function(event){
if (
!event.target.matches(".modal-container") && !event.target.closest(".modal-container") // || event.target.closest(".modal-container")
) {
modal.classList.remove('modal--show')
modal.style.display = "none"
}
})
}
getPokemons() |
import torch
import torch.nn as nn
import numpy as np
import math
from torch.utils.checkpoint import checkpoint
from attention import Attention
import copy
from torch_butterfly import Butterfly
Sparse_Linear = Butterfly
class Embeddings(nn.Module):
def __init__(self, config):
super().__init__()
assert config["embedding_dim"] == config["transformer_dim"]
self.dim = config["embedding_dim"]
self.word_embeddings = nn.Embedding(config["vocab_size"], config["embedding_dim"])
torch.nn.init.normal_(self.word_embeddings.weight, std = 0.02)
self.position_embeddings = nn.Embedding(config["max_seq_len"], config["embedding_dim"])
torch.nn.init.normal_(self.position_embeddings.weight, std = 0.02)
self.dropout = torch.nn.Dropout(p = config["dropout_prob"])
def fixed_pos_emb(self, seq_len, device):
position = torch.arange(0, seq_len, device = device)[:, np.newaxis]
div_term = torch.exp(torch.arange(0, self.dim, 2, device = device) * -(math.log(10000.0) / self.dim))
pos_embed = torch.stack([torch.sin(position * div_term), torch.cos(position * div_term)], -1).reshape(seq_len, -1)
return pos_embed
def forward(self, input_ids):
batch_size, seq_len = input_ids.size()
X_token = self.word_embeddings(input_ids)
position_ids = torch.arange(seq_len, dtype = torch.long, device = input_ids.device)[None, :].repeat(batch_size, 1)
X_pos = self.position_embeddings(position_ids)
X = X_token + X_pos
X = self.dropout(X)
return X
class Transformer(nn.Module):
def __init__(self, config, idx):
super().__init__()
#if ((config["fabnet_att_layer"]<0) or ((config["num_layers"]-idx) > config["fabnet_att_layer"])):
# print ("a", config["num_layers"]-(idx+1))
# print ("b", config["fabnet_att_layer"])
if ((config["fabnet_att_layer"]<0) or ((config["num_layers"]-(idx+1)) < config["fabnet_att_layer"])):
self.attn_type = config["attn_type"]
else:
self.attn_type = "softmax"
self.norm1 = nn.LayerNorm(config["transformer_dim"])
att_config = copy.deepcopy(config)
att_config["attn_type"] = self.attn_type
print (self.attn_type)
self.mha = Attention(att_config)
self.dropout1 = torch.nn.Dropout(p = config["dropout_prob"])
self.norm2 = nn.LayerNorm(config["transformer_dim"])
if config["is_butterfly"] and self.attn_type != "softmax":
Linear = Sparse_Linear
else:
Linear = nn.Linear
self.mlpblock = nn.Sequential(
Linear(config["transformer_dim"], config["transformer_hidden_dim"]),
nn.GELU(),
torch.nn.Dropout(p = config["dropout_prob"]),
Linear(config["transformer_hidden_dim"], config["transformer_dim"]),
torch.nn.Dropout(p = config["dropout_prob"])
)
def forward(self, X, mask):
if self.attn_type == "fft":
X = (self.mha(self.norm1(X), mask)) + X
X = self.mlpblock(self.norm2(X)) + X
else:
X = self.dropout1(self.mha(self.norm1(X), mask)) + X
X = self.mlpblock(self.norm2(X)) + X
return X
class Model(nn.Module):
def __init__(self, config):
super().__init__()
self.num_layers = config["num_layers"]
self.tied_weights = config["tied_weights"]
self.embeddings = Embeddings(config)
if self.tied_weights:
self.transformer = Transformer(config)
else:
for idx in range(self.num_layers):
setattr(self, f"transformer_{idx}", Transformer(config, idx))
self.norm = nn.LayerNorm(config["transformer_dim"])
def forward(self, input_ids, mask = None):
X = self.embeddings(input_ids)
if mask is None:
mask = torch.ones_like(input_ids)
if self.tied_weights:
for idx in range(self.num_layers):
X = self.transformer(X, mask)
else:
for idx in range(self.num_layers):
X = getattr(self, f"transformer_{idx}")(X, mask)
X = self.norm(X) * mask[:, :, None]
return X |
package com.sorune.photogram.Security.Service;
import com.sorune.photogram.Security.Entity.User;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@AllArgsConstructor
public class UserPrincipal implements UserDetails {
private User user;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
this.user.getPermissionList().forEach(p ->{
GrantedAuthority authority = new SimpleGrantedAuthority(p);
authorities.add(authority);
});
this.user.getRoleList().forEach(p->{
GrantedAuthority authority = new SimpleGrantedAuthority(p);
authorities.add(authority);
});
return authorities;
}
@Override
public String getPassword() {
return this.user.getPassword();
}
@Override
public String getUsername() {
return this.user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return this.user.isActive();
}
} |
import { Fragment } from "react";
import classNames from "classnames";
import { Disclosure, Menu, Transition } from "@headlessui/react";
import { BellIcon, MenuIcon, XIcon } from "@heroicons/react/outline";
const navigation = [
{ name: "Dashboard", href: "#", current: true },
{ name: "Settings", href: "#", current: false },
];
export const MobileShell = () => {
return (
<>
<div className="min-h-full">
<div className="pb-32 bg-gray-800">
<Disclosure as="nav" className="bg-gray-800">
{({ open }) => (
<>
<div className="mx-auto max-w-7xl sm:px-6 lg:px-8">
<div className="border-b border-gray-700">
<div className="flex items-center justify-between h-16 px-4 sm:px-0">
<div className="flex items-center">
<div className="hidden md:block">
<div className="flex items-baseline space-x-4">
{navigation.map((item) => (
<a
key={item.name}
href={item.href}
className={classNames(
item.current
? "bg-gray-900 text-white"
: "text-gray-300 hover:bg-gray-700 hover:text-white",
"px-3 py-2 rounded-md text-sm font-medium"
)}
aria-current={item.current ? "page" : undefined}
>
{item.name}
</a>
))}
</div>
</div>
</div>
<div className="hidden md:block">
<div className="flex items-center ml-4 md:ml-6">
<button
type="button"
className="p-1 text-gray-400 bg-gray-800 rounded-full hover:text-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white"
>
<span className="sr-only">View notifications</span>
<BellIcon className="w-6 h-6" aria-hidden="true" />
</button>
{/* Profile dropdown */}
<Menu as="div" className="relative ml-3">
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
></Transition>
</Menu>
</div>
</div>
<div className="flex -mr-2 md:hidden">
{/* Mobile menu button */}
<Disclosure.Button className="inline-flex items-center justify-center p-2 text-gray-400 bg-gray-800 rounded-md hover:text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white">
<span className="sr-only">Open main menu</span>
{open ? (
<XIcon
className="block w-6 h-6"
aria-hidden="true"
/>
) : (
<MenuIcon
className="block w-6 h-6"
aria-hidden="true"
/>
)}
</Disclosure.Button>
</div>
</div>
</div>
</div>
<Disclosure.Panel className="border-b border-gray-700 md:hidden">
<div className="px-2 py-3 space-y-1 sm:px-3">
{navigation.map((item) => (
<Disclosure.Button
key={item.name}
as="a"
href={item.href}
className={classNames(
item.current
? "bg-gray-900 text-white"
: "text-gray-300 hover:bg-gray-700 hover:text-white",
"block px-3 py-2 rounded-md text-base font-medium"
)}
aria-current={item.current ? "page" : undefined}
>
{item.name}
</Disclosure.Button>
))}
</div>
<div className="pt-4 pb-3 border-t border-gray-700">
<div className="flex items-center px-5">
<button
type="button"
className="flex-shrink-0 p-1 ml-auto text-gray-400 bg-gray-800 rounded-full hover:text-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white"
>
<span className="sr-only">View notifications</span>
<BellIcon className="w-6 h-6" aria-hidden="true" />
</button>
</div>
</div>
</Disclosure.Panel>
</>
)}
</Disclosure>
<header className="py-10">
<div className="px-4 mx-auto max-w-7xl sm:px-6 lg:px-8">
<h1 className="text-3xl font-bold text-white">Mobile app</h1>
</div>
</header>
</div>
<main className="-mt-32">
<div className="px-4 pb-12 mx-auto max-w-7xl sm:px-6 lg:px-8">
{/* Replace with your content */}
<div className="px-5 py-6 bg-white rounded-lg shadow sm:px-6">
<div className="border-4 border-gray-200 border-dashed rounded-lg h-96" />
</div>
{/* /End replace */}
</div>
</main>
</div>
</>
);
}; |
#ifndef CSTRING_H
#define CSTRING_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
// functions returning an int return 0 on failure and 1 on success
#define STRING_RETURN_IF_NULL(ptr) if(ptr == NULL) return STRING_ERROR
#define STRING_ERROR 0
#define STRING_SUCCESS 1
static const size_t string_npos = -1;// (~(size_t)0) one is left for the null term char
static const size_t _string_max_size = string_npos-1;
typedef struct
{
size_t _null_char;
size_t size;
size_t capacity;
char* data;
} _string;
typedef _string string[1];
// declarations
static inline int string_assign_c(string dest, size_t n, char c);
static inline size_t _min(size_t a, size_t b)
{
return a < b ? a : b;
}
static inline void _string_set_props(string dest, size_t size, size_t capacity)
{
dest->size = size;
dest->capacity = capacity;
dest->data[size] = 0;
dest->_null_char = size+1;
}
static inline int _string_assign(string dest, const char* str, size_t str_len)
{
if (str_len <= dest->capacity)
{
dest->size = str_len;
memcpy(dest->data, str, str_len);
dest->data[str_len] = 0;
dest->_null_char = str_len+1;
return STRING_SUCCESS;
}
dest->data = realloc(dest->data, str_len+1);
STRING_RETURN_IF_NULL(dest->data);
_string_set_props(dest, str_len, str_len);
memcpy(dest->data, str, dest->size);
return STRING_SUCCESS;
}
static inline int _string_append(string dest, const char* src, size_t src_len)
{
if(src_len == 0) return STRING_SUCCESS;
const size_t min = _min(dest->size, dest->_null_char);
const size_t new_len = min + src_len;
if (dest->capacity >= new_len)
{
memcpy(&dest->data[min], src, src_len);
dest->size = new_len;
dest->data[dest->size] = 0;
dest->_null_char = new_len+1;
return STRING_SUCCESS;
}
dest->data = realloc(dest->data, new_len+1);
STRING_RETURN_IF_NULL(dest->data);
memcpy(&dest->data[min], src, src_len);
_string_set_props(dest, new_len, new_len);
return STRING_SUCCESS;
}
static inline size_t _string_find(const string dest, const char* str, size_t str_len, size_t pos)
{
if (str_len == 0) return 0;
if (str_len > dest->size) return string_npos;
size_t off = pos;
for (size_t i = off; i < dest->size; ++i)
{
if(dest->data[i] == str[0])
{
for (size_t k = 0; k < str_len && k+i < dest->size; ++k)
{
if(k == str_len-1 && dest->data[k+i] == str[k])
return i;
off = k;
}
i += off;
}
}
return string_npos;
}
static inline void _string_reset(string s)
{
s->_null_char = 0;
s->size = 0;
s->capacity = 0;
s->data = NULL;
}
// public api
static inline void string_create_empty(string dest)
{
_string_reset(dest);
}
static inline int string_create(string dest, const char* str)
{
const size_t str_len = strlen(str);
assert(str_len > 0 && "strlen(str) must be greater than 0 use string_create_empty for an empty string");
_string_reset(dest);
return _string_assign(dest, str, str_len);
}
static inline int string_create_s(string dest, const string src)
{
assert(src->size > 0 && "strlen(str) must be greater than 0 use string_create_empty for an empty string");
_string_reset(dest);
return _string_assign(dest, src->data, src->size);
}
static inline int string_create_c(string dest, size_t n, char c)
{
assert(n > 0 && "n must be greater than 0 use string_create_empty for an empty string");
_string_reset(dest);
return string_assign_c(dest, n, c);
}
static inline void string_free(string src)
{
if (src->data != NULL)
free(src->data);
_string_reset(src);
}
static inline int string_assign(string s, const char* str)
{
return _string_assign(s, str, strlen(str));
}
static inline int string_assign_s(string dest, const string src)
{
return _string_assign(dest, src->data, src->size);
}
static inline int string_assign_c(string dest, size_t n, char c)
{
if (n <= dest->capacity)
{
memset(dest->data, c, n);
dest->size = n;
dest->_null_char = n+1;
dest->data[n] = 0;
return STRING_SUCCESS;
}
dest->data = realloc(dest->data, n+1);
STRING_RETURN_IF_NULL(dest->data);
memset(dest->data, c, n);
_string_set_props(dest, n, n);
if(c == 0) dest->_null_char = 0;
return STRING_SUCCESS;
}
static inline int string_append(string dest, const char* src)
{
return _string_append(dest, src, strlen(src));
}
static inline int string_append_s(string dest, const string src)
{
return _string_append(dest, src->data, src->size);
}
static inline int string_append_c(string dest, size_t n, char c)
{
const size_t min = _min(dest->size, dest->_null_char);
const size_t new_len = min + n;
if (new_len <= dest->capacity)
{
memset(&dest->data[min], c, n);
dest->size = new_len;
dest->_null_char = new_len+1;
dest->data[n] = 0;
return STRING_SUCCESS;
}
dest->data = realloc(dest->data, n+1);
STRING_RETURN_IF_NULL(dest->data);
memset(&dest->data[min], c, n);
_string_set_props(dest, new_len, new_len);
return STRING_SUCCESS;
}
static inline int string_resize_c(string dest, size_t new_size, char c)
{
if (new_size <= dest->capacity)
{
dest->size = new_size;
dest->data[dest->size] = 0;
dest->_null_char = new_size+1;
return STRING_SUCCESS;
}
dest->data = realloc(dest->data, new_size+1);
STRING_RETURN_IF_NULL(dest->data);
memset(&dest->data[dest->size], c, new_size - dest->size);
if (c == 0)
dest->_null_char = dest->size;
else
dest->_null_char = new_size + 1;
dest->size = new_size;
dest->capacity = new_size;
dest->data[dest->size] = 0;
return STRING_SUCCESS;
}
static inline int string_resize(string dest, size_t new_size)
{
return string_resize_c(dest, new_size, 0);
}
static inline int string_shrink_to_fit(string dest)
{
if (dest->size == dest->capacity)
return STRING_SUCCESS;
dest->data = realloc(dest->data, dest->size + 1);
STRING_RETURN_IF_NULL(dest->data);
dest->capacity = dest->size;
dest->_null_char = dest->size+1;
return STRING_SUCCESS;
}
static inline int string_reserve(string dest, size_t n)
{
if (n== dest->size) return STRING_SUCCESS;
if (n < dest->size) return string_shrink_to_fit(dest);
dest->data = realloc(dest->data, n+1);
STRING_RETURN_IF_NULL(dest->data);
dest->capacity = n;
memset(dest->data, 0, n - dest->size);
return STRING_SUCCESS;
}
static inline int string_push_back(string dest, char c)
{
return string_append_c(dest, 1, c);
}
static inline int string_pop_back(string dest)
{
if (dest->size == 0) return STRING_ERROR;
--dest->size;
dest->data[dest->size] = 0;
--dest->_null_char;
return STRING_SUCCESS;
}
static inline void string_swap(string s1, string s2)
{
_string tmp = { ._null_char = s1->_null_char, .size = s1->size, .capacity = s1->capacity, .data = s1->data };
s1->_null_char = s2->_null_char;
s1->capacity = s2->capacity;
s1->size = s2->size;
s1->data = s2->data;
s2->_null_char = tmp._null_char;
s2->capacity = tmp.capacity;
s2->size = tmp.size;
s2->data = tmp.data;
}
static inline void string_erase(string dest, size_t pos, size_t len)
{
assert(pos < dest->size && "pos must be lest than string_size(dest)");
if (len + pos >= dest->size)
{
dest->data[pos] = 0;
dest->size = 0;
dest->_null_char = 0;
return;
}
memmove(&dest->data[pos], &dest->data[pos+len], dest->size-pos-len);
dest->size -= len;
dest->_null_char = dest->size+1;
dest->data[dest->size] = 0;
}
static inline size_t string_find_c(const string s, char c, size_t pos)
{
for (size_t i = pos; i < s->size; ++i)
if(s->data[i] == c) return i;
return string_npos;
}
static inline int string_compare(const string s, const char* str) { return strcmp(s->data, str) == 0; }
static inline int string_compare_s(const string s1, const string s2) { return strcmp(s1->data, s2->data) == 0; }
static inline size_t string_find(const string s, const char* str, size_t pos) { return _string_find(s, str, strlen(str), pos); }
static inline size_t string_find_s(const string s1, const string s2, size_t pos) { return _string_find(s1, s2->data, s2->size, pos); }
static inline size_t string_find_n(const string s, const char* str, size_t pos, size_t n) { return _string_find(s, str, n, pos); }
static inline int string_empty(const string s) { return s->size == 0; }
static inline void string_clear(string dest) { dest->size = 0; dest->data[0] = 0; dest->_null_char = 0; }
static inline char* string_data(const string s) { return s->data; }
static inline const char* string_cstr(const string s) { return s->data; }
static inline size_t string_max_size() { return _string_max_size; }
static inline size_t string_size(const string s) { return s->size; }
static inline size_t string_length(const string s) { return s->size; }
static inline size_t string_capacity(const string s) { return s->capacity; }
static inline char string_at(const string s, size_t idx) { return s->data[idx]; }
static inline char string_front(const string s) { return s->data[0]; }
static inline char string_back(const string s) { return s->data[s->size-1]; }
static inline void string_print(const string s)
{
printf("s: %zu c: %zu nc: %zu %s\n", s[0].size, s[0].capacity, s->_null_char, s[0].data);
puts(s->data);
}
#endif |
<%= form_with(model: company) do |form| %>
<% if company.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(company.errors.count, "error") %> prohibited this company from being saved:</h2>
<ul>
<% company.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content %>
</div>
<div class="field">
<%= form.label :concept %>
<%= form.text_area :concept %>
</div>
<div class="field">
<%= form.label :media %>
<%= form.text_area :media %>
</div>
<div class="field">
<%= form.label :benefits %>
<%= form.text_area :benefits %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %> |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace="对应Dao的全限定名"
-->
<mapper namespace="com.itheima.mapper.UserMapper">
<!--
SQL片段:提高代码的重用性
-->
<sql id="SQL_SELECT">
SELECT id,username,sex,birthday,address FROM USER
</sql>
<!--
查询指定ID的用户信息
parameterType="可写可不写,能自动识别,即便写错了也能自动识别"
如果入参是集合类型,则写集合类型中对应的对象的类型 List<T> [Object]
-->
<select id="findUserForeach" parameterType="int" resultType="User">
<!--
SELECT * FROM USER WHERE ID IN(1,2,23)
1)用户如果输入的ID个数为0,则SELECT * FROM USER
2)用户输入的ID个数不为0,则按照下面步骤来:
a.sql=SELECT * FROM USER
b.sql=sql+WHERE ID IN(
c.ids.foreach->循环
for (int id : ids) {
sql+=id+",";
最后一次不需要加,号
}
d.sql+=);
-->
<!--SELECT id,username,sex,birthday,address FROM USER-->
<!--
引用SQL片段
-->
<include refid="SQL_SELECT" />
<!--
foreach:循环指定参数
collection="要循环的目标参数"
如果入参为数组,则直接写array
如果入参为List,则直接写list
如果入参为Map,则直接写[key]
item="id":表示定义id变量接收当前被循环的数据
open="":foreach执行之前,先执行open中的字符拼接,如果foreach中拼接的字符为空字符串,则此处也不拼接
separator=",":分隔符
close=")":foreach中执行拼接完成之后,最后需要拼接的字符
-->
<foreach collection="array" item="id" open="WHERE ID IN (" close=")" separator=",">
#{id}
</foreach>
</select>
<!--
where
根据用户输入的信息搜索用户
-->
<select id="findUserWhere" parameterType="User" resultType="User">
SELECT id,username,sex,birthday,address FROM user
<where>
<!--
根据用户输入的信息搜索用户
1)判断用户名是否为空,不为空,则拼接SQL语句查询用户信息
test="判断条件"
-->
<if test="username!=null and username!=''">
AND username LIKE #{username}
</if>
<!--
地址:需要根据用户输入的地址搜索
2)如果用户输入的地址不为空,则需要根据地址搜索
-->
<if test="address!=null and address!=''">
AND address=#{address}
</if>
</where>
</select>
<!--
if条件判断搜索
根据用户输入的信息搜索用户
-->
<select id="findUserIf" parameterType="User" resultType="User">
SELECT id,username,sex,birthday,address FROM user WHERE 1=1
<!--
根据用户输入的信息搜索用户
1)判断用户名是否为空,不为空,则拼接SQL语句查询用户信息
test="判断条件"
-->
<if test="username!=null and username!=''">
AND username LIKE #{username}
</if>
<!--
地址:需要根据用户输入的地址搜索
2)如果用户输入的地址不为空,则需要根据地址搜索
-->
<if test="address!=null and address!=''">
AND address=#{address}
</if>
</select>
</mapper> |
// React
import React,{useState,FormEvent,useEffect} from 'react';
import { useNavigate, Link } from "react-router-dom";
import { isObject } from 'lodash';
// Style
import "./Subs.css";
// images
import imagem from "../assets/img/image 2.jpg";
import logo from "../assets/img/Type=Colored negative.svg";
import Login from './Login';
const Subs = () => {
const [firstName,setfirstName] = useState<string>("");
const [lastName,setLastName] = useState<string>("");
const [birthDate,setBirthDate] = useState<string>("");
const [city,setCity] = useState<string>("");
const [country,setCountry] = useState<string>("");
const [email, setEmail] = useState<string>("");
const [confirmPassword, setconfirmPassword] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [error, setError] = useState<string>("");
const [isLoading, setIsLoading] = useState(false);
const navigate = useNavigate();
interface User {
firstName: string;
email: string;
lastName: string;
birthDate: string;
city: string;
country: string;
password: string;
confirmPassword?: string;
}
const HandleSub = (e:FormEvent) => {
e.preventDefault();
if (!email || !confirmPassword|| !password || !firstName || !lastName || !birthDate || !city || !country) {
setError("* Fill out all the fields");
return;
} else if (password !== confirmPassword) {
setError("* The passwords do not match");
return;
}
const signup = async (user: User) => {
setIsLoading(true);
try {
const response = await fetch("https://latam-challenge-2.deta.dev/api/v1/users/sign-up", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(user),
});
const data = await response.json();
if (response.status === 201) {
alert("success!!");
navigate("/Login");
} else if (response.status === 400) {
alert("User with required email already exists. Please sign in!");
} else if (response.status === 404) {
alert("Not found.");
} else {
alert("Something went wrong.");
}
} catch (error) {
console.log(error);
alert("Sorry, an error has occurred. Please try again later.");
}
finally {
setIsLoading(false);
}
};
signup({firstName,lastName,city,country,birthDate,email,password,confirmPassword});
}
return (
<div>
<div className="body-ls">
<div className="form-e">
<h1 className="titulo">Welcome,</h1>
<p className="sub-titulo">Please, register to continue</p>
{isLoading && <h2 className='load'>Carregando...</h2>}
{error && <div className="errou">{error}</div>}
<form onSubmit={HandleSub} className="formul">
<label><span className="span">First name</span><input className="btn-form" type="text" placeholder='Your first name' value={firstName} onChange={(e) => [setfirstName(e.target.value), setError("")]}/></label>
<label><span className="span">Last name</span><input className="btn-form" type="text" placeholder='Your last name' value={lastName} onChange={(e) => [setLastName(e.target.value), setError("")]}/></label>
<label><span className="span">Birth date</span><input className="btn-form" type="number" placeholder='MM/DD/YYYY' value={birthDate} onChange={(e) => [setBirthDate(e.target.value), setError("")]}/></label>
<label><span className="span">Country</span><input className="btn-form" type="text" placeholder='Your Country' value={country} onChange={(e) => [setCountry(e.target.value), setError("")]}/></label>
<label><span className="span">City</span><input className="btn-form" type="text" placeholder='Your City' value={city} onChange={(e) => [setCity(e.target.value), setError("")]}/></label>
<label><span className="span">E-mail</span><input className="btn-form" type="email" placeholder='A valid e-mail here' value={email} onChange={(e) => [setEmail(e.target.value), setError("")]}/></label>
<label><span className="span">password</span><input className="btn-form" type="password" minLength={6} placeholder='Your password' value={password} onChange={(e) => [setPassword(e.target.value), setError("")]}/></label>
<label><span className="span">password</span><input className="btn-form" type="password" placeholder='Comfirm your password' value={confirmPassword} onChange={(e) => [setconfirmPassword(e.target.value), setError("")]}/></label>
<button type="submit" className="btn-button">Register Now</button>
</form>
</div>
<div className="img-d">
<Link to="https://www.youtube.com/watch?v=ZNC-RNE0sdc" target="_blank"><img src={logo} alt="logo" id="imgm-0"/></Link>
<img src={imagem} alt="Imagem Principal" id="imgm-1"/>
</div>
</div>
</div>
)
}
export default Subs |
<!doctype html>
<html lang="en" class="h-100">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.84.0">
<title>GO IT, HOME WORK 13</title>
<link rel="icon" href="{{ url_for('static', path='/favicon.ico') }}">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
@media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="{{ url_for('static', path='/cover.css') }}" rel="stylesheet">
</head>
<body class="d-flex h-100 text-center text-white bg-dark">
<div class="cover-container-sd d-flex w-100 h-100 p-3 mx-auto flex-column" style="amax-width: 72em;">
<header class="mb-auto">
<div>
<h3 class="float-md-start mb-0">GoIT WEB</h3>
<nav class="nav nav-masthead justify-content-center float-md-end">
<a class="nav-link active" aria-current="page" href="#">Home</a>
<a class="nav-link" target="_blank" href="https://github.com/lexxai/goit_python_web_hw_13/">Features</a>
<a class="nav-link" target="_blank" href="https://github.com/lexxai/goit_python_web_hw_13">Contact</a>
</nav>
</div>
</header>
<main class="px-3">
<h1>{{tilte}}</h1>
<div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button>
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button>
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="3" aria-label="Slide 4"></button>
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="4" aria-label="Slide 5"></button>
<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="5" aria-label="Slide 6"></button>
</div>
<div class="carousel-inner" style="padding: 50px; height: 250px;">
<div class="carousel-item active">
<h4>Мета цього домашнього завдання</h4>
<p class="lead">
У цьому домашньому завданні ми продовжуємо доопрацьовувати застосунок REST API із домашнього [ <a target="_blank" href="https://github.com/lexxai/goit_python_web_hw_12">завдання 12</a> ]
</p>
</div>
<div class="carousel-item">
<h4>Завдання:</h4>
<p class="lead">
Реалізуйте механізм верифікації електронної пошти зареєстрованого користувача
</p>
</div>
<div class="carousel-item">
<h4>Завдання:</h4>
<p class="lead">
Обмежуйте кількість запитів до своїх маршрутів контактів. Обов’язково обмежте швидкість - створення контактів для користувача.
</p>
<p class="lead">
Увімкніть CORS для свого REST API.
</p>
</div>
<div class="carousel-item">
<h4>Завдання:</h4>
<p class="lead">
Реалізуйте можливість оновлення аватара користувача. Використовуйте сервіс Cloudinary.
</p>
</div>
<div class="carousel-item">
<h4> Загальні вимоги:</h4>
<p class="lead">
- Усі змінні середовища повинні зберігатися у файлі .env. Всередині коду не повинно бути конфіденційних даних у «чистому» вигляді.<br>
- Для запуску всіх сервісів і баз даних у застосунку використовується Docker Compose.
</p>
</div>
<div class="carousel-item">
<h4>Дотаково</h4>
<p class="lead">
У цьому домашньому завданні необхідно доопрацювати застосунок Django із домашнього завдання 10.<br>
2.1. Реалізуйте механізм скидання паролю для зареєстрованого користувача.<br>
2.2. Усі змінні середовища повинні зберігатися у файлі .env та використовуватися у файлі settings.py.
</p>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev">
<span class="carousel-control-prev-icon" style="margin-right: 150px;" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next">
<span class="carousel-control-next-icon" style="margin-left: 150px;" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<a href="docs/" class="btn btn-lg btn-secondary fw-bold border-white bg-white">API DOC</a>
<a href="static/client/index.html" class="btn btn-lg btn-secondary fw-bold border-white bg-white">JavaScript Web Client</a>
</main>
<footer class="mt-auto text-white-50">
<p><a class="btn btn-sm btn-success bg-transparent border-0"" href="https://github.com/lexxai" target="_blank">Goit WEB 15. ©lexxai</a></p>
</footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</body>
</html> |
*if_lua.txt* For Vim version 7.3. 最近更新: 2010年7月
VIM 参 考 手 册 by Luis Carvalho
译者: Willis
http://vimcdoc.sf.net
Vim 的 Lua 接口 *lua* *Lua*
1. 命令 |lua-commands|
2. vim 模块 |lua-vim|
3. 缓冲区用户数据 |lua-buffer|
4. 窗口用户数据 |lua-window|
{Vi 没有任何以上的命令}
仅当 Vim 编译时加入 |+lua| 特性时 Lua 接口才可用。
1. 命令 *lua-commands*
*:lua*
:[range]lua {chunk}
执行 Lua 语言块 {chunk}。{Vi 无此功能}
示例:
>
:lua print("Hello, Vim!")
:lua local curbuf = vim.buffer() curbuf[7] = "line #7"
<
:[range]lua << {endmarker}
{script}
{endmarker}
执行 Lua 脚本 {script}。{Vi 无此功能}
注意: 如果编译时没有加入 Lua 特性,此命令不能工作。要
避免错误,见 |script-here|。
{endmarker} 之前_不能_有任何空白。如果 "<<" 之后的 {endmarker} 省略,{script}
之后必须加上句号 '.',就像 |:append| 和 |:insert| 命令那样。
这种形式的 |:lua| 命令主要用于在 Vim 脚本中嵌入 Lua 代码。
示例:
>
function! CurrentLineInfo()
lua << EOF
local linenr = vim.window().line
local curline = vim.buffer()[linenr]
print(string.format("Current line [%d] has %d chars",
linenr, #curline))
EOF
endfunction
<
*:luado*
:[range]luado {body} 在 [range] 行范围的每行执行 Lua 函数
"function (line) {body} end",其中,函数参数是每行的文
本,结尾的 <EOL> 不计。函数返回值为字符串时用来替代当
前行的文本。缺省的 [range] 是整个文件: "1,$"。
{Vi 无此功能}
示例:
>
:luado return string.format("%s\t%d", line:reverse(), #line)
:lua require"lpeg"
:lua -- balanced parenthesis grammar:
:lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
:luado if bp:match(line) then return "-->\t" .. line end
<
*:luafile*
:[range]luafile {file}
执行 Lua {file} 文件中的脚本. {Vi 无此功能}
整个参数用作单个文件名。
示例:
>
:luafile script.lua
:luafile %
<
以上的命令都可执行一段 Lua 代码块 (chunk),或从命令行 (:lua 和 :luado),或从文
件 (:luafile),并可给出行范围 [range]。和 Lua 解释器类似,每个代码块都有自己的
作用域,所以命令之间只有全局变量可以共享。Lua 缺省库中 "table"、"string"、
"math"、和 "package" 可用,而 "io" 和 "debug" 不可用,"os" 只提供以下函数:
"date"、"clock"、"time"、"difftime" 和 "getenv"。此外,Lua 的 "print" 函数的输
出重定向到 Vim 消息区,参数以空格而不是制表符分隔。
Lua 使用 "vim" 模块 (见 |lua-vim|) 来对 Vim 发出指令以及对缓冲区
(|lua-buffer|) 和窗口 (|lua-window|) 进行管理。不过在 |sandbox| 中执行命令时,
修改缓冲区内容、打开新缓冲区和改变光标位置的过程收到限制。
2. vim 模块 *lua-vim*
Lua 通过 "vim" 模块和 Vim 进行接口。输入行范围的首末行分别存入 "vim.firstline"
和 "vim.lastline"。该模块也包含一些对缓冲区、窗口以及当前行查询的例程、Vim 调
用和命令执行,以及其它各种操作。
vim.isbuffer(value) 如果 "value" 是缓冲区用户数据,返回 'true'。否
则返回 'false' (见 |lua-buffer|)。
vim.buffer([arg]) 如果 "arg" 是数值,返回缓冲区列表中编号为
"arg" 的缓冲区。如果 "arg" 为字符串,返回完整
明或简短名为 "arg" 的缓冲区。这两种情况下,如
果找不到缓冲区,返回 'nil'。此外,如果
"toboolean(arg)" 为 'true',返回缓冲区列表的首
个缓冲区,否则返回当前缓冲区。
vim.iswindow(value) 如果 "value" 是窗口用户数据,返回 'true'。否则
返回 'false' (见 |lua-window|)。
vim.window([arg]) 如果 "arg" 是数值,返回编号为 "arg" 的窗口,如
果找不到,返回 'nil'。此外,如果
"toboolean(arg)" 为 'true',返回首个窗口,否则
返回当前窗口。
vim.command({cmd}) 执行 vim (ex 模式) 命令 {cmd}。
示例: >
:lua vim.command"set tw=60"
:lua vim.command"normal ddp"
<
vim.eval({expr}) 计算表达式 {expr} (见 |expression|),把结果转
化为 Lua 格式并返回。Vim 字符串和数值被直接转
为响应的 Lua 字符串和数值类型。Vim 列表和字典
被转化为 Lua 表 (列表成为以整数为键的表)。
示例: >
:lua tw = vim.eval"&tw"
:lua print(vim.eval"{'a': 'one'}".a)
<
vim.line() 返回当前行 (没有结尾的 <EOL>),Lua 字符串。
vim.beep() 鸣笛。
vim.open({fname}) 为文件 {fname} 打开新缓冲区并返回之。注意 并不
把该缓冲区设为当前缓冲区。
3. 缓冲区用户数据 *lua-buffer*
缓冲区用户数据代表 vim 的缓冲区。缓冲区用户数据 "b" 包含以下属性和方法:
属性
----------
o "b()" 设置 "b" 为当前缓冲区。
o "#b" 是缓冲区 "b" 的行数。
o "b[k]" 代表行号 k: "b[k] = newline" 把第 "k" 行替换为字符串
"newline",还有 "b[k] = nil" 删除第 "k" 行。
o "b.name" 包含缓冲区 "b" 的简短名 (只读)。
o "b.fname" 包含缓冲区 "b" 的完整名 (只读)。
o "b.number" 包含缓冲区 "b" 在缓冲区列表的位置 (只读)。
方法
-------
o "b:insert(newline"[, pos]")" 在缓冲区 "pos" (可选) 位置插入
"newline" 字符串。"pos" 缺省值为 "#b + 1"。如果 "pos == 0",
"newline" 将成为缓冲区的首行。
o "b:next()" 返回缓冲区列表中 "b" 的下一个缓冲区。
o "b:previous()" 返回缓冲区列表 "b" 的前一个缓冲区。
o "b:isvalid()" 如果缓冲区 "b" 对应 "真正的" (内存没有释放的) Vim 缓
冲区时,返回 'true' (布尔值)。
示例:
>
:lua b = vim.buffer() -- 当前缓冲区
:lua print(b.name, b.number)
:lua b[1] = "first line"
:lua b:insert("FIRST!", 0)
:lua b[1] = nil -- 删除首行
:lua for i=1,3 do b:insert(math.random()) end
:3,4lua for i=vim.lastline,vim.firstline,-1 do b[i] = nil end
:lua vim.open"myfile"() -- 打开缓冲区,设为当前缓冲区
function! ListBuffers()
lua << EOF
local b = vim.buffer(true) -- 列表中的首个缓冲区
while b ~= nil do
print(b.number, b.name, #b)
b = b:next()
end
vim.beep()
EOF
endfunction
<
4. 窗口用户数据 *lua-window*
窗口对象代表 vim 窗口。窗口用户数据 "w" 有以下属性和方法:
属性
----------
o "w()" 设置 "w" 为当前窗口。
o "w.buffer" 返回窗口 "w" 对应的缓冲区 (只读)。
o "w.line" 返回窗口 "w" 的光标行位置。
o "w.col" 返回窗口 "w" 的光标列位置。
o "w.width" 代表窗口 "w" 的宽度。
o "w.height" 代表窗口 "w" 的高度。
方法
-------
o "w:next()" 返回 "w" 的下一个窗口。
o "w:previous()" 返回 "w" 的前一个窗口。
o "w:isvalid()" 如果窗口 "w" 对应 "真正的" (内存没有释放的) Vim 窗
口,返回 'true' (布尔值)。
示例:
>
:lua w = vim.window() -- 当前窗口
:lua print(w.buffer.name, w.line, w.col)
:lua w.width = w.width + math.random(10)
:lua w.height = 2 * math.random() * w.height
:lua n,w = 0,vim.window(true) while w~=nil do n,w = n + 1,w:next() end
:lua print("有 " .. n .. " 个窗口")
<
vim:tw=78:ts=8:ft=help:norl: |
<?php
namespace App\Http\Controllers;
use App\Models\Sijil;
use Illuminate\Http\Request;
use App\Models\Paper;
use \Bkwld\Cloner\Cloneable;
use DB;
use App\Models\Peserta;
use Illuminate\Support\Facades\File;
use Auth;
use App\Models\Role;
use App\Models\User;
use Laratrust\Models\LaratrustRole;
use PDF;
use RealRashid\SweetAlert\Facades\Alert;
class SijilController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('/sijil/index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function createsijil()
{
return view('/sijil/createsijil');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function storesijil(Request $request)
{
$sijils = $request->all();
$sijils['user_id'] = auth()->id();
Sijil::create($sijils);
if ($sijils) {
Alert::success('Berjaya', 'Maklumat telah disimpan');
return redirect()->route('list.sijil');
}
else {
Alert::error('Gagal', 'Cuba lagi');
return back();
}
}
/**
* Display the specified resource.
*
* @param \App\Models\Sijil $sijil
* @return \Illuminate\Http\Response
*/
public function showsijil(Sijil $sijil)
{
$user = Auth::user();
if (auth()->id() <= 2) {
$sijils = Sijil::with('children')->whereNull('task_id')
->orderBy('id', 'desc')
->paginate(3);
}
else {
$sijils = Sijil::where('user_id', $user->id)
->with('children')
->whereNull('task_id')
->orderBy('id', 'desc')
->paginate(3);
//$posts = Post::all();
}
return view ('/sijil/listsijil', compact('user', 'sijils'))->with('i', (request()->input('page', 1) - 1) * 3);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Sijil $sijil
* @return \Illuminate\Http\Response
*/
public function editsijil($id)
{
$data = Sijil::find($id);
return view ('/sijil/editsijil', ['data'=>$data]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Sijil $sijil
* @return \Illuminate\Http\Response
*/
public function updatesijil(Request $request, Sijil $sijil)
{
$data=Sijil::find($request->id);
$data['user_id'] = auth()->id();
$data->username = $request['username'];
$data->program = $request['program'];
$data->tempat = $request['tempat'];
$data->anjuran = $request['anjuran'];
$data->tarikhA = $request['tarikhA'];
$data->tarikhB = $request['tarikhB'];
$data->jawatansain = $request['jawatansain'];
$data->jabatansain = $request['jabatansain'];
$data->logopath = $request['logopath'];
$data->sainpath = $request['sainpath'];
$data->jsijil = $request['jsijil'];
$data->save();
if ($data) {
Alert::success('Berjaya', 'Maklumat telah dikemaskini');
return redirect()->route('list.sijil');
}
else {
Alert::error('Gagal', 'Cuba lagi');
return back();
}
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Sijil $sijil
* @return \Illuminate\Http\Response
*/
public function deletesijil($id)
{
$sijils = Sijil::find($id);
$sijils != null;
$sijils->children()->delete();
$sijils->delete();
if ($sijils) {
Alert::success('Berjaya', 'Maklumat sijil dan peserta berkaitan telah dihapus');
return redirect('/sijil/listsijil');
}
else {
Alert::error('Gagal', 'Cuba lagi');
return back();
}
}
public function searchsijil(Request $request)
{
$search = $request->input('search');
$sijils = Sijil::query()
->Where('ic', 'LIKE', "%{$search}%")
->orWhere('kodsekolah', 'LIKE', "%{$search}%")
->orderBy('id', 'asc')
->paginate(5);
return view('/sijil/search', compact('sijils'))->with('i', (request()->input('page', 1) - 1) * 5);
}
public function pdf($id)
{
$data = Sijil::find($id);
$pdf = PDF::loadView('/sijil/pdf', ['data'=>$data])->setOptions(['isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true]);
return $pdf->download('sijilJPNMelaka.pdf');
}
} |
/************************/
/* Burak Demirci */
/* 141044091 */
/************************/
//CPU Class tanimlanmasi
#include <iostream>
#include <string>
#include "Memory.h"
using namespace std;
#ifndef CPU_H
#define CPU_H
class CPU
{
public:
//Constructor fonksiyon baslangicta register degerlerini sifirlar
CPU(const int option);
//PC'yi getirir
int getPC()const;
//Programin bitip bitmedigini kontroleder
int halted();
//PC degerini ve Registerlerin degerini yazdirir
const void print();
//Gelen kodu isleyen fonksiyon
void execute(string Str, Memory &myMemory);
//PC degerini degistirmeye yarayan fonksiyon
void setPC(const int newPC);
//Verilen adresli registerin degerini getirir
int getRegister(const int adress)const;
//Verilen keye gore regadres li registere islem yapar
void setRegister(const char key, const int regadres , const int eleman);
//Gelen string icerisindeki bilginin integer bir sayi olup olmadigini kontrol eder
int NumberCheck(const string Temp);
//Halt flag degerini degistirir
inline void setHlt()
{
hlt=1;
}
//Halt flag degerini dondurur
inline int getHlt()
{
return hlt;
}
//Option icin getter
inline const int getOption()
{
return option;
}
private:
//NumberCheck fonksiyonuna yardimci fonksiyon
int Power(int num,const int pow);
//HLT icin kullanilan flag
int hlt= 0;
//Mainde kullanilan dongudeki hangi satirda islem yaptigini tutar
int PC = 1;
//Registerlerimiz
int R[5];
//Option degiskeni
int option;
};
#endif //CPU_H |
// Blake W Hausafus 2023 bwhausafus@dmacc.edu
#include <iomanip>
#include <iostream>
#include <string>
#include <random>
#include "node.cpp"
using namespace std;
class doubly_linked_list{
public:
node* first;
node* last;
int size;// total items in a list
doubly_linked_list(){// constructor
this->first = nullptr;
this->last = nullptr;
this->size = 0;
}
void create_node(shirt* item){// creates new node
node* inv_node;
if (this->size == 0){// if list is empty
inv_node = new node(nullptr, item, nullptr);
this->first = inv_node;
this->last = inv_node;
this->size++;
}
else{
inv_node = new node(last, item, nullptr);
last->add_invnext(inv_node);
this->last = inv_node;
this->size++;
}
}
node* get_last(){
return this->last;
}
node* get_first(){
return this->first;
}
int get_size(){
return this->size;
}
void print_all(){
node* inv_node = first;
int count = 1;
while (inv_node != nullptr){
cout << count << ": \n";
cout << "Collar: " <<inv_node->inv_item->get_collar() << "\n";
cout << "Cuff: " <<inv_node->inv_item->get_cuff() << "\n";
cout << "Placket: " <<inv_node->inv_item->get_placket() << "\n";
cout << "Color: " <<inv_node->inv_item->get_color() << "\n";
cout << "Price: $" <<inv_node->inv_item->get_price() << "\n";
cout << "\n";
inv_node = inv_node->inv_next;// go to next node
count++;// increment count
}
}
void populate(int n, float rand_min, float rand_max){//populate an empty list
if (this->size == 0){
for(int i = 0; i < n; i++){
random_device randomizer;// RNG
uniform_real_distribution<float> dist(rand_min, rand_max);
float ramdom_num = ceil(dist(randomizer)* 100.0) / 100.0;// Round to the nearest 100th
shirt* new_shirt;
if (i % 10 == 9){
new_shirt = new shirt("Point Collar", "Barrel Cuff", "Traditional", "White", 25 + ramdom_num);
}
else if (i % 10 == 8){
new_shirt = new shirt("Spread Collar", "Barrel Cuff", "Traditional", "White", 25 + ramdom_num);
}
else if (i % 10 == 7){
new_shirt = new shirt("Spread Collar", "Barrel Cuff", "Traditional", "Blue", 15 + ramdom_num);
}
else if (i % 10 == 6){
new_shirt = new shirt("Wing Collar", "French Cuff", "French", "White", 65 + ramdom_num);
}
else if (i % 10 == 5){
new_shirt = new shirt("Point Collar", "French Cuff", "Traditional", "White", 20 + ramdom_num);
}
else if (i % 10 == 4){
new_shirt = new shirt("Wing Collar", "French Cuff", "French", "White", 60 + ramdom_num);
}
else if (i % 10 == 3){
new_shirt = new shirt("Point Collar", "French Cuff", "French", "Red", 70 + ramdom_num);
}
else if (i % 10 == 2){
new_shirt = new shirt("Point Collar", "Barrel Cuff", "Traditional", "Blue", 20 + ramdom_num);
}
else if (i % 10 == 1){
new_shirt = new shirt("Spread Collar", "Barrel Cuff", "Traditional", "Blue", 20 + ramdom_num);
}
else {
new_shirt = new shirt("Point Collar", "Barrel Cuff", "Traditional", "Red", 25 + ramdom_num);
}
this->create_node(new_shirt);
}
cout << "Done! \n";
}
else{
cout << "Error: This list is already populated! \n";
}
}
void node_analytics(node* selected_node){
node* inv_node = first;
// total number of similar shirts
int similar_total_collar = 0;
int similar_total_cuff = 0;
int similar_total_placket = 0;
int similar_total_color = 0;
// total prices
float price_total_collar = 0;
float price_total_cuff = 0;
float price_total_placket = 0;
float price_total_color = 0;
// average prices
float price_average_collar = 0;
float price_average_cuff = 0;
float price_average_placket = 0;
float price_average_color = 0;
while (inv_node != nullptr){// Collect data
if (inv_node->inv_item->get_collar() == selected_node->inv_item->get_collar()){
price_total_collar += inv_node->inv_item->get_price();
similar_total_collar++;
}
if (inv_node->inv_item->get_cuff() == selected_node->inv_item->get_cuff()){
price_total_cuff += inv_node->inv_item->get_price();
similar_total_cuff++;
}
if (inv_node->inv_item->get_placket() == selected_node->inv_item->get_placket()){
price_total_placket += inv_node->inv_item->get_price();
similar_total_placket++;
}
if (inv_node->inv_item->get_color() == selected_node->inv_item->get_color()){
price_total_color += inv_node->inv_item->get_price();
similar_total_color++;
}
inv_node = inv_node->inv_next;// go to next node
}
if (similar_total_collar > 0){
price_average_collar = price_total_collar / similar_total_collar;// Calculate average
if(selected_node->inv_item->get_price() <= price_average_collar)
{cout << "$" << setprecision(2) << price_average_collar - selected_node->inv_item->get_price() << " below average price for " << selected_node->inv_item->get_collar() << "\n";}
else{cout << "$" << setprecision(2) << selected_node->inv_item->get_price() - price_average_collar << " above average price for " << selected_node->inv_item->get_collar() << "\n";}
}
if (similar_total_cuff > 0){
price_average_cuff = price_total_cuff / similar_total_cuff;// Calculate average
if(selected_node->inv_item->get_price() <= price_average_cuff)
{cout << "$" << setprecision(2) << price_average_cuff - selected_node->inv_item->get_price() << " below average price for " << selected_node->inv_item->get_cuff() << "\n";}
else{cout << "$" << setprecision(2) << selected_node->inv_item->get_price() - price_average_cuff << " above average price for " << selected_node->inv_item->get_cuff() << "\n";}
}
if (similar_total_placket > 0){
price_average_placket = price_total_placket / similar_total_placket;// Calculate average
if(selected_node->inv_item->get_price() <= price_average_placket)
{cout << "$" << setprecision(2) << price_average_placket - selected_node->inv_item->get_price() << " below average price for " << selected_node->inv_item->get_placket() << " plackets \n";}
else{cout << "$" << setprecision(2) << selected_node->inv_item->get_price() - price_average_placket << " above average price for " << selected_node->inv_item->get_placket() << " plackets \n";}
}
if (similar_total_color > 0){
price_average_color = price_total_color / similar_total_color;// Calculate average
if(selected_node->inv_item->get_price() <= price_average_color)
{cout << "$" << setprecision(2) << price_average_color - selected_node->inv_item->get_price() << " below average price for " << selected_node->inv_item->get_color() << "\n";}
else{cout << "$" << setprecision(2) << selected_node->inv_item->get_price() - price_average_color << " above average price for " << selected_node->inv_item->get_color() << "\n";}
}
else{
cout << "Error: Insufficient data! \n";
}
}
void display_main_menu(){
char response = '?';
int response_number = -255;
bool response_number_flag = true;// reset response_number_flag
while (response != 'A' or response != 'a' or response != 'B' or response != 'b' or response != 'C' or response != 'c' or response != 'D' or response != 'd' or response != 'E' or response != 'e'){
cout << "A) Quit \n"
<< "B) Display all \n"
<< "C) Populate List\n"
<< "D) Analytics Menu \n"
<< "E) Create New Shirt \n";
cin >> response;
if (response == 'A' or response == 'a'){// Quit
abort();
}
else if (response == 'B' or response == 'b'){// Display all
if (this->size > 0){
this->print_all();
this->display_main_menu();
}
else{// Don't display if list is empty.
cout << "Error: This list is empty! \n";
this->display_main_menu();
}
}
else if (response == 'C' or response == 'c'){// Populate List
while(response_number <= 0 and response_number_flag == true){// Don't accept negative numbers or 0s
cout << "How many? \n";
cin >> response_number;
if (cin.good() and response_number > 0){// Makes sure it can read the user input
this->populate(response_number, 0.03, 10);
response_number_flag = false;
this->display_main_menu();
}
else{
cin.clear();// clear input
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Error: Invalid input! \n";
response_number_flag = true;
}
}
}
else if (response == 'D' or response == 'd'){// Analytics Menu
if (this->size > 0){
this->display_analytics_menu(1, this->first);
}
else{// Don't open if list is empty.
cout << "Error: This list is empty! \n";
this->display_main_menu();
}
}
else if (response == 'E' or response == 'e'){// Create New Shirt
shirt* new_shirt;
string new_collar;
string new_cuff;
string new_placket;
string new_color;
float new_price = -1;
cout << "\n Collar: ";
cin >> new_collar;
cout << "\n Cuff: ";
cin >> new_cuff;
cout << "\n Placket: ";
cin >> new_placket;
cout << "\n Color: ";
cin >> new_color;
while (new_price <= 0 and response_number_flag == true){// Don't accept negative numbers or 0s
cout << "\n Price: $";
cin >> new_price;
if (cin.good() and new_price > 0){// Makes sure it can read the user input
new_shirt = new shirt(new_collar, new_cuff, new_placket, new_color, new_price);
this->create_node(new_shirt);// add shirt to list
response_number_flag = false;
this->display_main_menu();
}
else{
cin.clear();// clear input
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Error: Invalid input! \n";
response_number_flag = true;
}
}
}
}
}
void display_analytics_menu(int count, node* start){
char response = '?';
node* inv_node = start;
cout << count << ": \n";// Display current item
cout << "Collar: " <<inv_node->inv_item->get_collar() << "\n";
cout << "Cuff: " <<inv_node->inv_item->get_cuff() << "\n";
cout << "Placket: " <<inv_node->inv_item->get_placket() << "\n";
cout << "Color: " <<inv_node->inv_item->get_color() << "\n";
cout << "Price: $" <<inv_node->inv_item->get_price() << "\n";
cout << "\n";
while (response != 'A' or response != 'a' or response != 'B' or response != 'b' or response != 'C' or response != 'c' or response != 'D' or response != 'd'){
cout << "A) Main Menu \n"
<< "B) Previous \n"
<< "C) Analyze\n"
<< "D) Next \n";
cin >> response;
if (response == 'A' or response == 'a'){// Main Menu
this->display_main_menu();
}
else if (response == 'B' or response == 'b'){// Previous
if(inv_node->inv_prev != nullptr){
count--;// decrement count
this->display_analytics_menu(count, inv_node->inv_prev);// go to previous node
}
else{
count = this->size;// adjust count
this->display_analytics_menu(count, this->last);// loop around
}
}
else if (response == 'C' or response == 'c'){// Analyze
this->node_analytics(inv_node);
}
else if (response == 'D' or response == 'd'){// Next
if(inv_node->inv_next != nullptr){
count++;// increment count
this->display_analytics_menu(count, inv_node->inv_next);// go to next node
}
else{
count = 1;// reset count
this->display_analytics_menu(count, this->first);// loop around
}
}
}
}
}; |
import { useForm } from 'react-hook-form';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { loginUser, loginSelector } from './loginSlice';
import { useEffect } from 'react';
import '../../App.css';
export function Login() {
const { register, handleSubmit, error } = useForm();
const dispatch = useDispatch();
const navigate = useNavigate();
const { loading, userInfo } = useSelector(loginSelector);
const onSubmit = (data) => {
dispatch(loginUser(data));
};
useEffect(() => {
if (userInfo) {
navigate('/');
}
});
return (
<div className="login-wrap">
<form onSubmit={handleSubmit(onSubmit)}>
{error && { error }}
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-input"
{...register('email')}
required
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-input"
{...register('password')}
required
/>
</div>
<button type="submit" className="button" disabled={loading}>
{loading ? 'loading...' : 'Login'}
</button>
</form>
</div>
);
} |
<form (ngSubmit)="onSubmitProject()" [formGroup]="proyectoForm">
<div class="modal-content">
<div class="text-center text-bg-rosa">
<h5 class="fs-3">Proyectos</h5>
</div>
<div class="container text-start">
<div class="row my-1">
<div class="col-6 col-sm-6 col-md-3 mb-2">
<label for="image" class="form-label">Imagen del Proyecto</label>
</div>
<div class="col-6 col-sm-6 col-md-9 mb-2">
<input class="form-control" type="url" id="image" name="image" formControlName="image">
</div>
<div class="col-6 col-sm-6 col-md-3 mb-2">
<label for="name" class="form-label">Nombre del Proyecto</label>
</div>
<div class="col-6 col-sm-6 col-md-9 mb-2">
<textarea class="form-control" type="text" id="name" rows="1" name="name" required formControlName="name"></textarea>
<div *ngIf="proyectoForm.get('name')?.touched && proyectoForm.get('name')?.errors?.['required']" class="alert alert-danger">Este campo es requerido</div>
</div>
<div class="col-6 col-sm-6 col-md-3 mb-2">
<label for="date" class="form-label">Fecha de Realización</label>
</div>
<div class="col-6 col-sm-6 col-md-9 mb-2">
<textarea class="form-control" type="text" id="date" rows="1" required name="date" formControlName="date"></textarea>
<div *ngIf="proyectoForm.get('date')?.touched && proyectoForm.get('date')?.errors?.['required']" class="alert alert-danger">Este campo es requerido</div>
</div>
<div class="col-6 col-sm-6 col-md-3 mb-2">
<label for="description" class="form-label">Descripción del Proyecto</label>
</div>
<div class="col-6 col-sm-6 col-md-9 mb-2">
<textarea class="form-control" type="text" id="description" rows="1" required name="description" formControlName="description"></textarea>
<div *ngIf="proyectoForm.get('description')?.touched && proyectoForm.get('description')?.errors?.['required']" class="alert alert-danger">Este campo es requerido</div>
</div>
<div class="col-6 col-sm-6 col-md-3">
<label for="url" class="form-label">Enlace del Proyecto</label>
</div>
<div class="col-6 col-sm-6 col-md-9">
<textarea class="form-control" type="url" id="url" rows="1" required name="url" formControlName="url"></textarea>
<div *ngIf="proyectoForm.get('url')?.touched && proyectoForm.get('url')?.errors?.['required']" class="alert alert-danger">Este campo es requerido</div>
</div>
</div>
</div>
<div class="modal-footer text-bg-rosa ">
<button type="submit" class="btn btn-primary" [disabled]="proyectoForm.invalid">Agregar</button>
</div>
</div>
</form> |
/* Auth Builder Widget */
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_starter/models/models.dart';
import 'package:flutter_starter/services/auth_service.dart';
import 'package:flutter_starter/services/services.dart';
import 'package:provider/provider.dart';
class AuthWidgetBuilder extends StatelessWidget {
const AuthWidgetBuilder({Key key, @required this.builder}) : super(key: key);
final Widget Function(BuildContext, AsyncSnapshot<User>) builder;
@override
Widget build(BuildContext context) {
final authService = Provider.of<AuthService>(context, listen: false);
return StreamBuilder<User>(
stream: authService.user,
builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
final User user = snapshot.data;
if (user != null) {
/*
* For any other Provider services that rely on user data can be
* added to the following MultiProvider list.
* Once a user has been detected, a re-build will be initiated.
*/
return MultiProvider(providers: [
Provider<User>.value(value: user),
StreamProvider<UserModel>.value(
initialData: UserModel(),
value: AuthService().streamFirestoreUser(user))
], child: builder(context, snapshot));
}
return builder(context, snapshot);
},
);
}
} |
// To parse this JSON data, do
//
// final roomsHotelsModels = roomsHotelsModelsFromJson(jsonString);
import 'dart:convert';
RoomsHotelsModels roomsHotelsModelsFromJson(String str) => RoomsHotelsModels.fromJson(json.decode(str));
String roomsHotelsModelsToJson(RoomsHotelsModels data) => json.encode(data.toJson());
class RoomsHotelsModels {
Data data;
dynamic userContext;
RoomsHotelsModels({
this.data,
this.userContext,
});
factory RoomsHotelsModels.fromJson(Map<String, dynamic> json) => RoomsHotelsModels(
data: Data.fromJson(json["data"]),
userContext: json["userContext"],
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
"userContext": userContext,
};
}
class Data {
String status;
dynamic message;
List<RecommendedEntry> recommendedEntries;
dynamic roomRecommendations;
String searchId;
String pricingRuleDescription;
RoomDisplayInfo roomDisplayInfo;
bool isReschedule;
bool isInventoryContainPayAtHotel;
VariantContexts variantContexts;
Layout layout;
String bookmarkInventoryId;
dynamic userTagContext;
dynamic worryFreeNotificationText;
dynamic failedStatusReason;
bool showResponseAfterLogin;
dynamic communicationBanner;
List<AvailableInventoryTag> availableInventoryTags;
RoomListBanners roomListBanners;
DataContexts contexts;
bool reschedule;
bool inventoryContainPayAtHotel;
Data({
this.status,
this.message,
this.recommendedEntries,
this.roomRecommendations,
this.searchId,
this.pricingRuleDescription,
this.roomDisplayInfo,
this.isReschedule,
this.isInventoryContainPayAtHotel,
this.variantContexts,
this.layout,
this.bookmarkInventoryId,
this.userTagContext,
this.worryFreeNotificationText,
this.failedStatusReason,
this.showResponseAfterLogin,
this.communicationBanner,
this.availableInventoryTags,
this.roomListBanners,
this.contexts,
this.reschedule,
this.inventoryContainPayAtHotel,
});
factory Data.fromJson(Map<String, dynamic> json) => Data(
status: json["status"],
message: json["message"],
recommendedEntries: List<RecommendedEntry>.from(json["recommendedEntries"].map((x) => RecommendedEntry.fromJson(x))),
roomRecommendations: json["roomRecommendations"],
searchId: json["searchId"],
pricingRuleDescription: json["pricingRuleDescription"],
roomDisplayInfo: RoomDisplayInfo.fromJson(json["roomDisplayInfo"]),
isReschedule: json["isReschedule"],
isInventoryContainPayAtHotel: json["isInventoryContainPayAtHotel"],
variantContexts: VariantContexts.fromJson(json["variantContexts"]),
layout: Layout.fromJson(json["layout"]),
bookmarkInventoryId: json["bookmarkInventoryId"],
userTagContext: json["userTagContext"],
worryFreeNotificationText: json["worryFreeNotificationText"],
failedStatusReason: json["failedStatusReason"],
showResponseAfterLogin: json["showResponseAfterLogin"],
communicationBanner: json["communicationBanner"],
availableInventoryTags: List<AvailableInventoryTag>.from(json["availableInventoryTags"].map((x) => AvailableInventoryTag.fromJson(x))),
roomListBanners: RoomListBanners.fromJson(json["roomListBanners"]),
contexts: DataContexts.fromJson(json["contexts"]),
reschedule: json["reschedule"],
inventoryContainPayAtHotel: json["inventoryContainPayAtHotel"],
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"recommendedEntries": List<dynamic>.from(recommendedEntries.map((x) => x.toJson())),
"roomRecommendations": roomRecommendations,
"searchId": searchId,
"pricingRuleDescription": pricingRuleDescription,
"roomDisplayInfo": roomDisplayInfo.toJson(),
"isReschedule": isReschedule,
"isInventoryContainPayAtHotel": isInventoryContainPayAtHotel,
"variantContexts": variantContexts.toJson(),
"layout": layout.toJson(),
"bookmarkInventoryId": bookmarkInventoryId,
"userTagContext": userTagContext,
"worryFreeNotificationText": worryFreeNotificationText,
"failedStatusReason": failedStatusReason,
"showResponseAfterLogin": showResponseAfterLogin,
"communicationBanner": communicationBanner,
"availableInventoryTags": List<dynamic>.from(availableInventoryTags.map((x) => x.toJson())),
"roomListBanners": roomListBanners.toJson(),
"contexts": contexts.toJson(),
"reschedule": reschedule,
"inventoryContainPayAtHotel": inventoryContainPayAtHotel,
};
}
class AvailableInventoryTag {
Name name;
String displayName;
String description;
String shortDescription;
AvailableInventoryTag({
this.name,
this.displayName,
this.description,
this.shortDescription,
});
factory AvailableInventoryTag.fromJson(Map<String, dynamic> json) => AvailableInventoryTag(
name: nameValues.map[json["name"]],
displayName: json["displayName"],
description: json["description"],
shortDescription: json["shortDescription"],
);
Map<String, dynamic> toJson() => {
"name": nameValues.reverse[name],
"displayName": displayName,
"description": description,
"shortDescription": shortDescription,
};
}
enum Name { FREE_CANCELLATION, FREE_BREAKFAST, LARGE_BED }
final nameValues = EnumValues({
"FREE_BREAKFAST": Name.FREE_BREAKFAST,
"FREE_CANCELLATION": Name.FREE_CANCELLATION,
"LARGE_BED": Name.LARGE_BED
});
class DataContexts {
dynamic metasearchToken;
dynamic encryptedAccessCode;
DataContexts({
this.metasearchToken,
this.encryptedAccessCode,
});
factory DataContexts.fromJson(Map<String, dynamic> json) => DataContexts(
metasearchToken: json["metasearchToken"],
encryptedAccessCode: json["encryptedAccessCode"],
);
Map<String, dynamic> toJson() => {
"metasearchToken": metasearchToken,
"encryptedAccessCode": encryptedAccessCode,
};
}
class Layout {
String detail;
String card;
bool useNewRoomMappingLayout;
Layout({
this.detail,
this.card,
this.useNewRoomMappingLayout,
});
factory Layout.fromJson(Map<String, dynamic> json) => Layout(
detail: json["detail"],
card: json["card"],
useNewRoomMappingLayout: json["useNewRoomMappingLayout"],
);
Map<String, dynamic> toJson() => {
"detail": detail,
"card": card,
"useNewRoomMappingLayout": useNewRoomMappingLayout,
};
}
class RecommendedEntry {
List<RoomList> roomList;
RecommendedEntry({
this.roomList,
});
factory RecommendedEntry.fromJson(Map<String, dynamic> json) => RecommendedEntry(
roomList: List<RoomList>.from(json["roomList"].map((x) => RoomList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"roomList": List<dynamic>.from(roomList.map((x) => x.toJson())),
};
}
class RoomList {
String hotelRoomId;
String providerId;
String name;
List<String> roomImages;
String description;
String originalDescription;
BedDescription bedDescription;
String maxOccupancy;
String baseOccupancy;
String maxChildOccupancy;
String maxChildAge;
String numExtraBeds;
String numChargedRooms;
String numRemainingRooms;
String numBreakfastIncluded;
bool isBreakfastIncluded;
bool isWifiIncluded;
bool isRefundable;
bool hasLivingRoom;
bool extraBedIsIncluded;
dynamic size;
RateDisplay rateDisplay;
RateDisplay originalRateDisplay;
RateDisplay strikethroughRateDisplay;
dynamic propertyCurrencyRateDisplay;
dynamic propertyCurrencyOriginalRateDisplay;
dynamic rescheduleRateDisplay;
dynamic isCashback;
RateInfo rateInfo;
dynamic extraBedRate;
dynamic vatInvoice;
RoomCancellationPolicy roomCancellationPolicy;
dynamic roomReschedulePolicy;
dynamic extraBedSummaries;
bool promoFlag;
RoomListContexts contexts;
List<dynamic> amenitiesExcluded;
List<String> amenitiesIncluded;
AmenitiesByCategory amenitiesByCategory;
List<dynamic> roomHighlightFacilityDisplay;
dynamic promoIds;
HotelPromoType hotelPromoType;
LabelDisplayData labelDisplayData;
List<BedroomSummary> hotelBedType;
BedArrangements bedArrangements;
dynamic hotelRoomSizeDisplay;
String hotelRoomType;
dynamic smokingPreferences;
RateType rateType;
dynamic ccGuaranteeRequirement;
dynamic additionalCharges;
dynamic propertyCurrencyAdditionalCharges;
String loyaltyAmount;
HotelLoyaltyDisplay hotelLoyaltyDisplay;
AccomLoyaltyEligibilityStatus accomLoyaltyEligibilityStatus;
dynamic checkInInstruction;
dynamic walletPromoDisplay;
List<ImageWithCaption> imageWithCaptions;
String caption;
String inventoryName;
List<Name> inventoryTags;
ExtraBedSearchSummary extraBedSearchSummary;
dynamic extraBedRateSummary;
ChildOccupancyPolicyDisplay childOccupancyPolicyDisplay;
dynamic disabilitySupport;
dynamic bookingPolicy;
bool isBookable;
dynamic inventoryLabelDisplay;
dynamic supportedAddOns;
InventoryLabels inventoryLabels;
dynamic cashback;
bool breakfastIncluded;
bool wifiIncluded;
bool refundable;
RoomList({
this.hotelRoomId,
this.providerId,
this.name,
this.roomImages,
this.description,
this.originalDescription,
this.bedDescription,
this.maxOccupancy,
this.baseOccupancy,
this.maxChildOccupancy,
this.maxChildAge,
this.numExtraBeds,
this.numChargedRooms,
this.numRemainingRooms,
this.numBreakfastIncluded,
this.isBreakfastIncluded,
this.isWifiIncluded,
this.isRefundable,
this.hasLivingRoom,
this.extraBedIsIncluded,
this.size,
this.rateDisplay,
this.originalRateDisplay,
this.strikethroughRateDisplay,
this.propertyCurrencyRateDisplay,
this.propertyCurrencyOriginalRateDisplay,
this.rescheduleRateDisplay,
this.isCashback,
this.rateInfo,
this.extraBedRate,
this.vatInvoice,
this.roomCancellationPolicy,
this.roomReschedulePolicy,
this.extraBedSummaries,
this.promoFlag,
this.contexts,
this.amenitiesExcluded,
this.amenitiesIncluded,
this.amenitiesByCategory,
this.roomHighlightFacilityDisplay,
this.promoIds,
this.hotelPromoType,
this.labelDisplayData,
this.hotelBedType,
this.bedArrangements,
this.hotelRoomSizeDisplay,
this.hotelRoomType,
this.smokingPreferences,
this.rateType,
this.ccGuaranteeRequirement,
this.additionalCharges,
this.propertyCurrencyAdditionalCharges,
this.loyaltyAmount,
this.hotelLoyaltyDisplay,
this.accomLoyaltyEligibilityStatus,
this.checkInInstruction,
this.walletPromoDisplay,
this.imageWithCaptions,
this.caption,
this.inventoryName,
this.inventoryTags,
this.extraBedSearchSummary,
this.extraBedRateSummary,
this.childOccupancyPolicyDisplay,
this.disabilitySupport,
this.bookingPolicy,
this.isBookable,
this.inventoryLabelDisplay,
this.supportedAddOns,
this.inventoryLabels,
this.cashback,
this.breakfastIncluded,
this.wifiIncluded,
this.refundable,
});
factory RoomList.fromJson(Map<String, dynamic> json) => RoomList(
hotelRoomId: json["hotelRoomId"],
providerId: json["providerId"],
name: json["name"],
roomImages: List<String>.from(json["roomImages"].map((x) => x)),
description: json["description"],
originalDescription: json["originalDescription"],
bedDescription: bedDescriptionValues.map[json["bedDescription"]],
maxOccupancy: json["maxOccupancy"],
baseOccupancy: json["baseOccupancy"],
maxChildOccupancy: json["maxChildOccupancy"],
maxChildAge: json["maxChildAge"],
numExtraBeds: json["numExtraBeds"],
numChargedRooms: json["numChargedRooms"],
numRemainingRooms: json["numRemainingRooms"],
numBreakfastIncluded: json["numBreakfastIncluded"],
isBreakfastIncluded: json["isBreakfastIncluded"],
isWifiIncluded: json["isWifiIncluded"],
isRefundable: json["isRefundable"],
hasLivingRoom: json["hasLivingRoom"],
extraBedIsIncluded: json["extraBedIsIncluded"],
size: json["size"],
rateDisplay: RateDisplay.fromJson(json["rateDisplay"]),
originalRateDisplay: RateDisplay.fromJson(json["originalRateDisplay"]),
strikethroughRateDisplay: RateDisplay.fromJson(json["strikethroughRateDisplay"]),
propertyCurrencyRateDisplay: json["propertyCurrencyRateDisplay"],
propertyCurrencyOriginalRateDisplay: json["propertyCurrencyOriginalRateDisplay"],
rescheduleRateDisplay: json["rescheduleRateDisplay"],
isCashback: json["isCashback"],
rateInfo: RateInfo.fromJson(json["rateInfo"]),
extraBedRate: json["extraBedRate"],
vatInvoice: json["vatInvoice"],
roomCancellationPolicy: RoomCancellationPolicy.fromJson(json["roomCancellationPolicy"]),
roomReschedulePolicy: json["roomReschedulePolicy"],
extraBedSummaries: json["extraBedSummaries"],
promoFlag: json["promoFlag"],
contexts: RoomListContexts.fromJson(json["contexts"]),
amenitiesExcluded: List<dynamic>.from(json["amenitiesExcluded"].map((x) => x)),
amenitiesIncluded: List<String>.from(json["amenitiesIncluded"].map((x) => x)),
amenitiesByCategory: AmenitiesByCategory.fromJson(json["amenitiesByCategory"]),
roomHighlightFacilityDisplay: List<dynamic>.from(json["roomHighlightFacilityDisplay"].map((x) => x)),
promoIds: json["promoIds"],
hotelPromoType: HotelPromoType.fromJson(json["hotelPromoType"]),
labelDisplayData: json["labelDisplayData"] == null ? null : LabelDisplayData.fromJson(json["labelDisplayData"]),
hotelBedType: List<BedroomSummary>.from(json["hotelBedType"].map((x) => bedroomSummaryValues.map[x])),
bedArrangements: BedArrangements.fromJson(json["bedArrangements"]),
hotelRoomSizeDisplay: json["hotelRoomSizeDisplay"],
hotelRoomType: json["hotelRoomType"],
smokingPreferences: json["smokingPreferences"],
rateType: rateTypeValues.map[json["rateType"]],
ccGuaranteeRequirement: json["ccGuaranteeRequirement"],
additionalCharges: json["additionalCharges"],
propertyCurrencyAdditionalCharges: json["propertyCurrencyAdditionalCharges"],
loyaltyAmount: json["loyaltyAmount"],
hotelLoyaltyDisplay: HotelLoyaltyDisplay.fromJson(json["hotelLoyaltyDisplay"]),
accomLoyaltyEligibilityStatus: accomLoyaltyEligibilityStatusValues.map[json["accomLoyaltyEligibilityStatus"]],
checkInInstruction: json["checkInInstruction"],
walletPromoDisplay: json["walletPromoDisplay"],
imageWithCaptions: List<ImageWithCaption>.from(json["imageWithCaptions"].map((x) => ImageWithCaption.fromJson(x))),
caption: json["caption"],
inventoryName: json["inventoryName"],
inventoryTags: List<Name>.from(json["inventoryTags"].map((x) => nameValues.map[x])),
extraBedSearchSummary: ExtraBedSearchSummary.fromJson(json["extraBedSearchSummary"]),
extraBedRateSummary: json["extraBedRateSummary"],
childOccupancyPolicyDisplay: ChildOccupancyPolicyDisplay.fromJson(json["childOccupancyPolicyDisplay"]),
disabilitySupport: json["disabilitySupport"],
bookingPolicy: json["bookingPolicy"],
isBookable: json["isBookable"],
inventoryLabelDisplay: json["inventoryLabelDisplay"],
supportedAddOns: json["supportedAddOns"],
inventoryLabels: json["inventoryLabels"] == null ? null : InventoryLabels.fromJson(json["inventoryLabels"]),
cashback: json["cashback"],
breakfastIncluded: json["breakfastIncluded"],
wifiIncluded: json["wifiIncluded"],
refundable: json["refundable"],
);
Map<String, dynamic> toJson() => {
"hotelRoomId": hotelRoomId,
"providerId": providerId,
"name": name,
"roomImages": List<dynamic>.from(roomImages.map((x) => x)),
"description": description,
"originalDescription": originalDescription,
"bedDescription": bedDescriptionValues.reverse[bedDescription],
"maxOccupancy": maxOccupancy,
"baseOccupancy": baseOccupancy,
"maxChildOccupancy": maxChildOccupancy,
"maxChildAge": maxChildAge,
"numExtraBeds": numExtraBeds,
"numChargedRooms": numChargedRooms,
"numRemainingRooms": numRemainingRooms,
"numBreakfastIncluded": numBreakfastIncluded,
"isBreakfastIncluded": isBreakfastIncluded,
"isWifiIncluded": isWifiIncluded,
"isRefundable": isRefundable,
"hasLivingRoom": hasLivingRoom,
"extraBedIsIncluded": extraBedIsIncluded,
"size": size,
"rateDisplay": rateDisplay.toJson(),
"originalRateDisplay": originalRateDisplay.toJson(),
"strikethroughRateDisplay": strikethroughRateDisplay.toJson(),
"propertyCurrencyRateDisplay": propertyCurrencyRateDisplay,
"propertyCurrencyOriginalRateDisplay": propertyCurrencyOriginalRateDisplay,
"rescheduleRateDisplay": rescheduleRateDisplay,
"isCashback": isCashback,
"rateInfo": rateInfo.toJson(),
"extraBedRate": extraBedRate,
"vatInvoice": vatInvoice,
"roomCancellationPolicy": roomCancellationPolicy.toJson(),
"roomReschedulePolicy": roomReschedulePolicy,
"extraBedSummaries": extraBedSummaries,
"promoFlag": promoFlag,
"contexts": contexts.toJson(),
"amenitiesExcluded": List<dynamic>.from(amenitiesExcluded.map((x) => x)),
"amenitiesIncluded": List<dynamic>.from(amenitiesIncluded.map((x) => x)),
"amenitiesByCategory": amenitiesByCategory.toJson(),
"roomHighlightFacilityDisplay": List<dynamic>.from(roomHighlightFacilityDisplay.map((x) => x)),
"promoIds": promoIds,
"hotelPromoType": hotelPromoType.toJson(),
"labelDisplayData": labelDisplayData == null ? null : labelDisplayData.toJson(),
"hotelBedType": List<dynamic>.from(hotelBedType.map((x) => bedroomSummaryValues.reverse[x])),
"bedArrangements": bedArrangements.toJson(),
"hotelRoomSizeDisplay": hotelRoomSizeDisplay,
"hotelRoomType": hotelRoomType,
"smokingPreferences": smokingPreferences,
"rateType": rateTypeValues.reverse[rateType],
"ccGuaranteeRequirement": ccGuaranteeRequirement,
"additionalCharges": additionalCharges,
"propertyCurrencyAdditionalCharges": propertyCurrencyAdditionalCharges,
"loyaltyAmount": loyaltyAmount,
"hotelLoyaltyDisplay": hotelLoyaltyDisplay.toJson(),
"accomLoyaltyEligibilityStatus": accomLoyaltyEligibilityStatusValues.reverse[accomLoyaltyEligibilityStatus],
"checkInInstruction": checkInInstruction,
"walletPromoDisplay": walletPromoDisplay,
"imageWithCaptions": List<dynamic>.from(imageWithCaptions.map((x) => x.toJson())),
"caption": caption,
"inventoryName": inventoryName,
"inventoryTags": List<dynamic>.from(inventoryTags.map((x) => nameValues.reverse[x])),
"extraBedSearchSummary": extraBedSearchSummary.toJson(),
"extraBedRateSummary": extraBedRateSummary,
"childOccupancyPolicyDisplay": childOccupancyPolicyDisplay.toJson(),
"disabilitySupport": disabilitySupport,
"bookingPolicy": bookingPolicy,
"isBookable": isBookable,
"inventoryLabelDisplay": inventoryLabelDisplay,
"supportedAddOns": supportedAddOns,
"inventoryLabels": inventoryLabels == null ? null : inventoryLabels.toJson(),
"cashback": cashback,
"breakfastIncluded": breakfastIncluded,
"wifiIncluded": wifiIncluded,
"refundable": refundable,
};
}
enum AccomLoyaltyEligibilityStatus { USER_NOT_ELIGIBLE }
final accomLoyaltyEligibilityStatusValues = EnumValues({
"USER_NOT_ELIGIBLE": AccomLoyaltyEligibilityStatus.USER_NOT_ELIGIBLE
});
class AmenitiesByCategory {
List<Amenity> freebies;
List<Amenity> amenities;
List<Amenity> bathroom;
AmenitiesByCategory({
this.freebies,
this.amenities,
this.bathroom,
});
factory AmenitiesByCategory.fromJson(Map<String, dynamic> json) => AmenitiesByCategory(
freebies: List<Amenity>.from(json["freebies"].map((x) => Amenity.fromJson(x))),
amenities: List<Amenity>.from(json["amenities"].map((x) => Amenity.fromJson(x))),
bathroom: List<Amenity>.from(json["bathroom"].map((x) => Amenity.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"freebies": List<dynamic>.from(freebies.map((x) => x.toJson())),
"amenities": List<dynamic>.from(amenities.map((x) => x.toJson())),
"bathroom": List<dynamic>.from(bathroom.map((x) => x.toJson())),
};
}
class Amenity {
String name;
String iconUrl;
Amenity({
this.name,
this.iconUrl,
});
factory Amenity.fromJson(Map<String, dynamic> json) => Amenity(
name: json["name"],
iconUrl: json["iconUrl"],
);
Map<String, dynamic> toJson() => {
"name": name,
"iconUrl": iconUrl,
};
}
class BedArrangements {
BedroomSummary bedroomSummary;
String numOfBedroom;
List<Bedroom> bedrooms;
BedArrangements({
this.bedroomSummary,
this.numOfBedroom,
this.bedrooms,
});
factory BedArrangements.fromJson(Map<String, dynamic> json) => BedArrangements(
bedroomSummary: bedroomSummaryValues.map[json["bedroomSummary"]],
numOfBedroom: json["numOfBedroom"],
bedrooms: List<Bedroom>.from(json["bedrooms"].map((x) => Bedroom.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"bedroomSummary": bedroomSummaryValues.reverse[bedroomSummary],
"numOfBedroom": numOfBedroom,
"bedrooms": List<dynamic>.from(bedrooms.map((x) => x.toJson())),
};
}
enum BedroomSummary { THE_1_GING_FULL, THE_1_GING_C_KING, THE_2_GING_X_2 }
final bedroomSummaryValues = EnumValues({
"1 giường cỡ king": BedroomSummary.THE_1_GING_C_KING,
"1 giường Full": BedroomSummary.THE_1_GING_FULL,
"2 giường (x 2)": BedroomSummary.THE_2_GING_X_2
});
class Bedroom {
List<Default> defaultArrangement;
List<dynamic> alternativeArrangement;
Arrangements arrangements;
Bedroom({
this.defaultArrangement,
this.alternativeArrangement,
this.arrangements,
});
factory Bedroom.fromJson(Map<String, dynamic> json) => Bedroom(
defaultArrangement: List<Default>.from(json["defaultArrangement"].map((x) => Default.fromJson(x))),
alternativeArrangement: List<dynamic>.from(json["alternativeArrangement"].map((x) => x)),
arrangements: Arrangements.fromJson(json["arrangements"]),
);
Map<String, dynamic> toJson() => {
"defaultArrangement": List<dynamic>.from(defaultArrangement.map((x) => x.toJson())),
"alternativeArrangement": List<dynamic>.from(alternativeArrangement.map((x) => x)),
"arrangements": arrangements.toJson(),
};
}
class Arrangements {
List<Default> arrangementsDefault;
Arrangements({
this.arrangementsDefault,
});
factory Arrangements.fromJson(Map<String, dynamic> json) => Arrangements(
arrangementsDefault: List<Default>.from(json["default"].map((x) => Default.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"default": List<dynamic>.from(arrangementsDefault.map((x) => x.toJson())),
};
}
class Default {
BedName bedName;
String total;
String bedIcon;
Default({
this.bedName,
this.total,
this.bedIcon,
});
factory Default.fromJson(Map<String, dynamic> json) => Default(
bedName: bedNameValues.map[json["bedName"]],
total: json["total"],
bedIcon: json["bedIcon"],
);
Map<String, dynamic> toJson() => {
"bedName": bedNameValues.reverse[bedName],
"total": total,
"bedIcon": bedIcon,
};
}
enum BedName { GING_FULL, GING_C_KING, GING_X_2 }
final bedNameValues = EnumValues({
"giường cỡ king": BedName.GING_C_KING,
"giường Full": BedName.GING_FULL,
"giường (x 2)": BedName.GING_X_2
});
enum BedDescription { FULL, KING, TWIN }
final bedDescriptionValues = EnumValues({
"Full": BedDescription.FULL,
"King": BedDescription.KING,
"Twin": BedDescription.TWIN
});
class ChildOccupancyPolicyDisplay {
ChildPolicyEligibility childPolicyEligibility;
dynamic shortChildPolicyDisplayString;
dynamic fullChildPolicyDisplayString;
ChildOccupancyPolicyDisplay({
this.childPolicyEligibility,
this.shortChildPolicyDisplayString,
this.fullChildPolicyDisplayString,
});
factory ChildOccupancyPolicyDisplay.fromJson(Map<String, dynamic> json) => ChildOccupancyPolicyDisplay(
childPolicyEligibility: ChildPolicyEligibility.fromJson(json["childPolicyEligibility"]),
shortChildPolicyDisplayString: json["shortChildPolicyDisplayString"],
fullChildPolicyDisplayString: json["fullChildPolicyDisplayString"],
);
Map<String, dynamic> toJson() => {
"childPolicyEligibility": childPolicyEligibility.toJson(),
"shortChildPolicyDisplayString": shortChildPolicyDisplayString,
"fullChildPolicyDisplayString": fullChildPolicyDisplayString,
};
}
class ChildPolicyEligibility {
ChildPolicyStatus childPolicyStatus;
String numberOfEligibleChild;
ChildPolicyEligibility({
this.childPolicyStatus,
this.numberOfEligibleChild,
});
factory ChildPolicyEligibility.fromJson(Map<String, dynamic> json) => ChildPolicyEligibility(
childPolicyStatus: childPolicyStatusValues.map[json["childPolicyStatus"]],
numberOfEligibleChild: json["numberOfEligibleChild"],
);
Map<String, dynamic> toJson() => {
"childPolicyStatus": childPolicyStatusValues.reverse[childPolicyStatus],
"numberOfEligibleChild": numberOfEligibleChild,
};
}
enum ChildPolicyStatus { FREE }
final childPolicyStatusValues = EnumValues({
"FREE": ChildPolicyStatus.FREE
});
class RoomListContexts {
String availToken;
String searchId;
bool newroomdataavailable;
String inventoryRateKey;
String bookingId;
String numRooms;
String numAdults;
String numChildren;
List<dynamic> childAges;
String numInfants;
RoomListContexts({
this.availToken,
this.searchId,
this.newroomdataavailable,
this.inventoryRateKey,
this.bookingId,
this.numRooms,
this.numAdults,
this.numChildren,
this.childAges,
this.numInfants,
});
factory RoomListContexts.fromJson(Map<String, dynamic> json) => RoomListContexts(
availToken: json["availToken"],
searchId: json["searchId"],
newroomdataavailable: json["NEWROOMDATAAVAILABLE"],
inventoryRateKey: json["inventoryRateKey"],
bookingId: json["bookingId"],
numRooms: json["numRooms"],
numAdults: json["numAdults"],
numChildren: json["numChildren"],
childAges: List<dynamic>.from(json["childAges"].map((x) => x)),
numInfants: json["numInfants"],
);
Map<String, dynamic> toJson() => {
"availToken": availToken,
"searchId": searchId,
"NEWROOMDATAAVAILABLE": newroomdataavailable,
"inventoryRateKey": inventoryRateKey,
"bookingId": bookingId,
"numRooms": numRooms,
"numAdults": numAdults,
"numChildren": numChildren,
"childAges": List<dynamic>.from(childAges.map((x) => x)),
"numInfants": numInfants,
};
}
class ExtraBedSearchSummary {
dynamic maxExtraBeds;
dynamic numExtraBedIncluded;
dynamic extraBedRateDisplay;
dynamic propertyCurrencyExtraBedRateDisplay;
ExtraBedSearchSummary({
this.maxExtraBeds,
this.numExtraBedIncluded,
this.extraBedRateDisplay,
this.propertyCurrencyExtraBedRateDisplay,
});
factory ExtraBedSearchSummary.fromJson(Map<String, dynamic> json) => ExtraBedSearchSummary(
maxExtraBeds: json["maxExtraBeds"],
numExtraBedIncluded: json["numExtraBedIncluded"],
extraBedRateDisplay: json["extraBedRateDisplay"],
propertyCurrencyExtraBedRateDisplay: json["propertyCurrencyExtraBedRateDisplay"],
);
Map<String, dynamic> toJson() => {
"maxExtraBeds": maxExtraBeds,
"numExtraBedIncluded": numExtraBedIncluded,
"extraBedRateDisplay": extraBedRateDisplay,
"propertyCurrencyExtraBedRateDisplay": propertyCurrencyExtraBedRateDisplay,
};
}
class HotelLoyaltyDisplay {
Display display;
String amount;
HotelLoyaltyDisplay({
this.display,
this.amount,
});
factory HotelLoyaltyDisplay.fromJson(Map<String, dynamic> json) => HotelLoyaltyDisplay(
display: displayValues.map[json["display"]],
amount: json["amount"],
);
Map<String, dynamic> toJson() => {
"display": displayValues.reverse[display],
"amount": amount,
};
}
enum Display { STRONG_NHN_FONT_COLOR_1_BA0_E2_0_IM_FONT_STRONG }
final displayValues = EnumValues({
"<strong>Nhận <font color=\"#1ba0e2\">0 điểm</font></strong>": Display.STRONG_NHN_FONT_COLOR_1_BA0_E2_0_IM_FONT_STRONG
});
class HotelPromoType {
PromoType promoType;
String promoDescription;
HotelPromoType({
this.promoType,
this.promoDescription,
});
factory HotelPromoType.fromJson(Map<String, dynamic> json) => HotelPromoType(
promoType: promoTypeValues.map[json["promoType"]],
promoDescription: json["promoDescription"] == null ? null : json["promoDescription"],
);
Map<String, dynamic> toJson() => {
"promoType": promoTypeValues.reverse[promoType],
"promoDescription": promoDescription == null ? null : promoDescription,
};
}
enum PromoType { SALE }
final promoTypeValues = EnumValues({
"SALE": PromoType.SALE
});
class ImageWithCaption {
Caption caption;
String url;
dynamic width;
dynamic height;
String thumbnailUrl;
String assetOrder;
ImageWithCaption({
this.caption,
this.url,
this.width,
this.height,
this.thumbnailUrl,
this.assetOrder,
});
factory ImageWithCaption.fromJson(Map<String, dynamic> json) => ImageWithCaption(
caption: json["caption"] == null ? null : captionValues.map[json["caption"]],
url: json["url"],
width: json["width"],
height: json["height"],
thumbnailUrl: json["thumbnailUrl"],
assetOrder: json["assetOrder"],
);
Map<String, dynamic> toJson() => {
"caption": caption == null ? null : captionValues.reverse[caption],
"url": url,
"width": width,
"height": height,
"thumbnailUrl": thumbnailUrl,
"assetOrder": assetOrder,
};
}
enum Caption { GUESTROOM_VIEW, GUESTROOM, BATHROOM, FEATURED_IMAGE }
final captionValues = EnumValues({
"Bathroom": Caption.BATHROOM,
"Featured Image": Caption.FEATURED_IMAGE,
"Guestroom": Caption.GUESTROOM,
"Guestroom View": Caption.GUESTROOM_VIEW
});
class InventoryLabels {
LabelDisplayData roomRecommendation;
InventoryLabels({
this.roomRecommendation,
});
factory InventoryLabels.fromJson(Map<String, dynamic> json) => InventoryLabels(
roomRecommendation: json["ROOM_RECOMMENDATION"] == null ? null : LabelDisplayData.fromJson(json["ROOM_RECOMMENDATION"]),
);
Map<String, dynamic> toJson() => {
"ROOM_RECOMMENDATION": roomRecommendation == null ? null : roomRecommendation.toJson(),
};
}
class LabelDisplayData {
String iconId;
String shortDescription;
String longDescription;
bool overrideProviderLabel;
String iconUrl;
String shortFormattedDescription;
String longFormattedDescription;
String backgroundColor;
LabelDisplayData({
this.iconId,
this.shortDescription,
this.longDescription,
this.overrideProviderLabel,
this.iconUrl,
this.shortFormattedDescription,
this.longFormattedDescription,
this.backgroundColor,
});
factory LabelDisplayData.fromJson(Map<String, dynamic> json) => LabelDisplayData(
iconId: json["iconId"],
shortDescription: json["shortDescription"],
longDescription: json["longDescription"],
overrideProviderLabel: json["overrideProviderLabel"],
iconUrl: json["iconUrl"],
shortFormattedDescription: json["shortFormattedDescription"],
longFormattedDescription: json["longFormattedDescription"],
backgroundColor: json["backgroundColor"] == null ? null : json["backgroundColor"],
);
Map<String, dynamic> toJson() => {
"iconId": iconId,
"shortDescription": shortDescription,
"longDescription": longDescription,
"overrideProviderLabel": overrideProviderLabel,
"iconUrl": iconUrl,
"shortFormattedDescription": shortFormattedDescription,
"longFormattedDescription": longFormattedDescription,
"backgroundColor": backgroundColor == null ? null : backgroundColor,
};
}
class RateDisplay {
BaseFare baseFare;
BaseFare fees;
BaseFare taxes;
BaseFare totalFare;
String numOfDecimalPoint;
RateDisplay({
this.baseFare,
this.fees,
this.taxes,
this.totalFare,
this.numOfDecimalPoint,
});
factory RateDisplay.fromJson(Map<String, dynamic> json) => RateDisplay(
baseFare: BaseFare.fromJson(json["baseFare"]),
fees: BaseFare.fromJson(json["fees"]),
taxes: BaseFare.fromJson(json["taxes"]),
totalFare: BaseFare.fromJson(json["totalFare"]),
numOfDecimalPoint: json["numOfDecimalPoint"],
);
Map<String, dynamic> toJson() => {
"baseFare": baseFare.toJson(),
"fees": fees.toJson(),
"taxes": taxes.toJson(),
"totalFare": totalFare.toJson(),
"numOfDecimalPoint": numOfDecimalPoint,
};
}
class BaseFare {
Currency currency;
String amount;
BaseFare({
this.currency,
this.amount,
});
factory BaseFare.fromJson(Map<String, dynamic> json) => BaseFare(
currency: currencyValues.map[json["currency"]],
amount: json["amount"],
);
Map<String, dynamic> toJson() => {
"currency": currencyValues.reverse[currency],
"amount": amount,
};
}
enum Currency { VND }
final currencyValues = EnumValues({
"VND": Currency.VND
});
class RateInfo {
dynamic savings;
List<FeeElement> fees;
List<FeeElement> taxes;
List<dynamic> surcharges;
RateInfo({
this.savings,
this.fees,
this.taxes,
this.surcharges,
});
factory RateInfo.fromJson(Map<String, dynamic> json) => RateInfo(
savings: json["savings"],
fees: List<FeeElement>.from(json["fees"].map((x) => FeeElement.fromJson(x))),
taxes: List<FeeElement>.from(json["taxes"].map((x) => FeeElement.fromJson(x))),
surcharges: List<dynamic>.from(json["surcharges"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"savings": savings,
"fees": List<dynamic>.from(fees.map((x) => x.toJson())),
"taxes": List<dynamic>.from(taxes.map((x) => x.toJson())),
"surcharges": List<dynamic>.from(surcharges.map((x) => x)),
};
}
class FeeElement {
FeeDescription description;
String amount;
FeeElement({
this.description,
this.amount,
});
factory FeeElement.fromJson(Map<String, dynamic> json) => FeeElement(
description: feeDescriptionValues.map[json["description"]],
amount: json["amount"],
);
Map<String, dynamic> toJson() => {
"description": feeDescriptionValues.reverse[description],
"amount": amount,
};
}
enum FeeDescription { SERVICE_FEE, TAX }
final feeDescriptionValues = EnumValues({
"Service Fee": FeeDescription.SERVICE_FEE,
"Tax": FeeDescription.TAX
});
enum RateType { PAY_NOW }
final rateTypeValues = EnumValues({
"PAY_NOW": RateType.PAY_NOW
});
class RoomCancellationPolicy {
CancellationPolicyLabel cancellationPolicyLabel;
String cancellationPolicyString;
String providerCancellationPolicyString;
bool freeCancel;
bool refundable;
List<CancellationPolicyInfo> cancellationPolicyInfos;
List<AdditionalCancellationPolicyInfo> additionalCancellationPolicyInfo;
RoomCancellationPolicy({
this.cancellationPolicyLabel,
this.cancellationPolicyString,
this.providerCancellationPolicyString,
this.freeCancel,
this.refundable,
this.cancellationPolicyInfos,
this.additionalCancellationPolicyInfo,
});
factory RoomCancellationPolicy.fromJson(Map<String, dynamic> json) => RoomCancellationPolicy(
cancellationPolicyLabel: cancellationPolicyLabelValues.map[json["cancellationPolicyLabel"]],
cancellationPolicyString: json["cancellationPolicyString"],
providerCancellationPolicyString: json["providerCancellationPolicyString"] == null ? null : json["providerCancellationPolicyString"],
freeCancel: json["freeCancel"],
refundable: json["refundable"],
cancellationPolicyInfos: json["cancellationPolicyInfos"] == null ? null : List<CancellationPolicyInfo>.from(json["cancellationPolicyInfos"].map((x) => CancellationPolicyInfo.fromJson(x))),
additionalCancellationPolicyInfo: json["additionalCancellationPolicyInfo"] == null ? null : List<AdditionalCancellationPolicyInfo>.from(json["additionalCancellationPolicyInfo"].map((x) => additionalCancellationPolicyInfoValues.map[x])),
);
Map<String, dynamic> toJson() => {
"cancellationPolicyLabel": cancellationPolicyLabelValues.reverse[cancellationPolicyLabel],
"cancellationPolicyString": cancellationPolicyString,
"providerCancellationPolicyString": providerCancellationPolicyString == null ? null : providerCancellationPolicyString,
"freeCancel": freeCancel,
"refundable": refundable,
"cancellationPolicyInfos": cancellationPolicyInfos == null ? null : List<dynamic>.from(cancellationPolicyInfos.map((x) => x.toJson())),
"additionalCancellationPolicyInfo": additionalCancellationPolicyInfo == null ? null : List<dynamic>.from(additionalCancellationPolicyInfo.map((x) => additionalCancellationPolicyInfoValues.reverse[x])),
};
}
enum AdditionalCancellationPolicyInfo { ROOM_TYPE_POLICY_INFO, HOTEL_LOCAL_TIME_POLICY_INFO }
final additionalCancellationPolicyInfoValues = EnumValues({
"hotelLocalTimePolicyInfo": AdditionalCancellationPolicyInfo.HOTEL_LOCAL_TIME_POLICY_INFO,
"roomTypePolicyInfo": AdditionalCancellationPolicyInfo.ROOM_TYPE_POLICY_INFO
});
class CancellationPolicyInfo {
AppliedDateInfoDescription appliedDateInfoDescription;
AppliedDate appliedStartDate;
AppliedDate appliedEndDate;
PolicyInfoDetail policyInfoDetail;
CancellationPolicyInfo({
this.appliedDateInfoDescription,
this.appliedStartDate,
this.appliedEndDate,
this.policyInfoDetail,
});
factory CancellationPolicyInfo.fromJson(Map<String, dynamic> json) => CancellationPolicyInfo(
appliedDateInfoDescription: appliedDateInfoDescriptionValues.map[json["appliedDateInfoDescription"]],
appliedStartDate: AppliedDate.fromJson(json["appliedStartDate"]),
appliedEndDate: AppliedDate.fromJson(json["appliedEndDate"]),
policyInfoDetail: PolicyInfoDetail.fromJson(json["policyInfoDetail"]),
);
Map<String, dynamic> toJson() => {
"appliedDateInfoDescription": appliedDateInfoDescriptionValues.reverse[appliedDateInfoDescription],
"appliedStartDate": appliedStartDate.toJson(),
"appliedEndDate": appliedEndDate.toJson(),
"policyInfoDetail": policyInfoDetail.toJson(),
};
}
enum AppliedDateInfoDescription { THE_13_THG_1220190500, THE_14_THG_1220191500, HOTEL_CHECK_IN_DATE_INFO }
final appliedDateInfoDescriptionValues = EnumValues({
"hotelCheckInDateInfo": AppliedDateInfoDescription.HOTEL_CHECK_IN_DATE_INFO,
"13-thg 12-2019, 05:00": AppliedDateInfoDescription.THE_13_THG_1220190500,
"14-thg 12-2019, 15:00": AppliedDateInfoDescription.THE_14_THG_1220191500
});
class AppliedDate {
MonthDayYear monthDayYear;
HourMinute hourMinute;
AppliedDate({
this.monthDayYear,
this.hourMinute,
});
factory AppliedDate.fromJson(Map<String, dynamic> json) => AppliedDate(
monthDayYear: MonthDayYear.fromJson(json["monthDayYear"]),
hourMinute: HourMinute.fromJson(json["hourMinute"]),
);
Map<String, dynamic> toJson() => {
"monthDayYear": monthDayYear.toJson(),
"hourMinute": hourMinute.toJson(),
};
}
class HourMinute {
String hour;
String minute;
HourMinute({
this.hour,
this.minute,
});
factory HourMinute.fromJson(Map<String, dynamic> json) => HourMinute(
hour: json["hour"],
minute: json["minute"],
);
Map<String, dynamic> toJson() => {
"hour": hour,
"minute": minute,
};
}
class MonthDayYear {
String month;
String day;
String year;
MonthDayYear({
this.month,
this.day,
this.year,
});
factory MonthDayYear.fromJson(Map<String, dynamic> json) => MonthDayYear(
month: json["month"],
day: json["day"],
year: json["year"],
);
Map<String, dynamic> toJson() => {
"month": month,
"day": day,
"year": year,
};
}
class PolicyInfoDetail {
PolicyInfoDetailFee fee;
Type type;
PolicyInfoDetailDescription description;
PolicyInfoDetail({
this.fee,
this.type,
this.description,
});
factory PolicyInfoDetail.fromJson(Map<String, dynamic> json) => PolicyInfoDetail(
fee: PolicyInfoDetailFee.fromJson(json["fee"]),
type: typeValues.map[json["type"]],
description: policyInfoDetailDescriptionValues.map[json["description"]],
);
Map<String, dynamic> toJson() => {
"fee": fee.toJson(),
"type": typeValues.reverse[type],
"description": policyInfoDetailDescriptionValues.reverse[description],
};
}
enum PolicyInfoDetailDescription { FREE_CANCELLATION_POLICY_INFO, CANCELLATION_FEE_POLICY_INFO, FULL_CHARGE_POLICY_INFO }
final policyInfoDetailDescriptionValues = EnumValues({
"cancellationFeePolicyInfo": PolicyInfoDetailDescription.CANCELLATION_FEE_POLICY_INFO,
"freeCancellationPolicyInfo": PolicyInfoDetailDescription.FREE_CANCELLATION_POLICY_INFO,
"fullChargePolicyInfo": PolicyInfoDetailDescription.FULL_CHARGE_POLICY_INFO
});
class PolicyInfoDetailFee {
BaseFare currencyValue;
String numOfDecimalPoint;
PolicyInfoDetailFee({
this.currencyValue,
this.numOfDecimalPoint,
});
factory PolicyInfoDetailFee.fromJson(Map<String, dynamic> json) => PolicyInfoDetailFee(
currencyValue: BaseFare.fromJson(json["currencyValue"]),
numOfDecimalPoint: json["numOfDecimalPoint"],
);
Map<String, dynamic> toJson() => {
"currencyValue": currencyValue.toJson(),
"numOfDecimalPoint": numOfDecimalPoint,
};
}
enum Type { FREE_CANCELLATION, CANCELLATION_FEE_APPLIES, FULL_CHARGE }
final typeValues = EnumValues({
"CANCELLATION_FEE_APPLIES": Type.CANCELLATION_FEE_APPLIES,
"FREE_CANCELLATION": Type.FREE_CANCELLATION,
"FULL_CHARGE": Type.FULL_CHARGE
});
enum CancellationPolicyLabel { T_PHNG_NY_KHNG_C_HON_TIN, MIN_PH_HY_PHNG_N_13_THG_122019 }
final cancellationPolicyLabelValues = EnumValues({
"Miễn phí hủy phòng đến 13-thg 12-2019": CancellationPolicyLabel.MIN_PH_HY_PHNG_N_13_THG_122019,
"Đặt phòng này không được hoàn tiền.": CancellationPolicyLabel.T_PHNG_NY_KHNG_C_HON_TIN
});
class RoomDisplayInfo {
String finalPriceInfo;
String finalPriceInfoPerRoom;
String finalPriceInfoRoomDetail;
RoomDisplayInfo({
this.finalPriceInfo,
this.finalPriceInfoPerRoom,
this.finalPriceInfoRoomDetail,
});
factory RoomDisplayInfo.fromJson(Map<String, dynamic> json) => RoomDisplayInfo(
finalPriceInfo: json["finalPriceInfo"],
finalPriceInfoPerRoom: json["finalPriceInfoPerRoom"],
finalPriceInfoRoomDetail: json["finalPriceInfoRoomDetail"],
);
Map<String, dynamic> toJson() => {
"finalPriceInfo": finalPriceInfo,
"finalPriceInfoPerRoom": finalPriceInfoPerRoom,
"finalPriceInfoRoomDetail": finalPriceInfoRoomDetail,
};
}
class RoomListBanners {
RoomRecommendation roomRecommendation;
RoomListBanners({
this.roomRecommendation,
});
factory RoomListBanners.fromJson(Map<String, dynamic> json) => RoomListBanners(
roomRecommendation: RoomRecommendation.fromJson(json["ROOM_RECOMMENDATION"]),
);
Map<String, dynamic> toJson() => {
"ROOM_RECOMMENDATION": roomRecommendation.toJson(),
};
}
class RoomRecommendation {
String iconUrl;
String description;
String formattedDescription;
String backgroundColor;
RoomRecommendation({
this.iconUrl,
this.description,
this.formattedDescription,
this.backgroundColor,
});
factory RoomRecommendation.fromJson(Map<String, dynamic> json) => RoomRecommendation(
iconUrl: json["iconUrl"],
description: json["description"],
formattedDescription: json["formattedDescription"],
backgroundColor: json["backgroundColor"],
);
Map<String, dynamic> toJson() => {
"iconUrl": iconUrl,
"description": description,
"formattedDescription": formattedDescription,
"backgroundColor": backgroundColor,
};
}
class VariantContexts {
bool isCollapseAll;
String roomImprovementDisplay;
bool isNewLayout;
bool isExpandAllRooms;
bool isShowChevron;
bool haspromolabel;
VariantContexts({
this.isCollapseAll,
this.roomImprovementDisplay,
this.isNewLayout,
this.isExpandAllRooms,
this.isShowChevron,
this.haspromolabel,
});
factory VariantContexts.fromJson(Map<String, dynamic> json) => VariantContexts(
isCollapseAll: json["isCollapseAll"],
roomImprovementDisplay: json["roomImprovementDisplay"],
isNewLayout: json["isNewLayout"],
isExpandAllRooms: json["isExpandAllRooms"],
isShowChevron: json["isShowChevron"],
haspromolabel: json["HASPROMOLABEL"],
);
Map<String, dynamic> toJson() => {
"isCollapseAll": isCollapseAll,
"roomImprovementDisplay": roomImprovementDisplay,
"isNewLayout": isNewLayout,
"isExpandAllRooms": isExpandAllRooms,
"isShowChevron": isShowChevron,
"HASPROMOLABEL": haspromolabel,
};
}
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
} |
import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";
import Home from "../views/Home.vue";
import ItemView from "../components/ItemView.vue";
import Form from "../components/Form.vue";
Vue.use(VueRouter);
const routes: Array<RouteConfig> = [
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/listitem/page",
name: "ItemView",
component: ItemView,
},
{
path: "/form",
name: "Form",
component: Form,
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
});
export default router; |
using Nop.Web.Framework.Mvc.ModelBinding;
using Nop.Web.Framework.Models;
using Nop.Web.Areas.Admin.Models.Orders;
namespace Nop.Web.Areas.Admin.Models.Settings
{
/// <summary>
/// Represents an order settings model
/// </summary>
public partial record OrderSettingsModel : BaseNopModel, ISettingsModel
{
#region Ctor
public OrderSettingsModel()
{
ReturnRequestReasonSearchModel = new ReturnRequestReasonSearchModel();
ReturnRequestActionSearchModel = new ReturnRequestActionSearchModel();
}
#endregion
#region Properties
public int ActiveStoreScopeConfiguration { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.IsReOrderAllowed")]
public bool IsReOrderAllowed { get; set; }
public bool IsReOrderAllowed_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.MinOrderSubtotalAmount")]
public decimal MinOrderSubtotalAmount { get; set; }
public bool MinOrderSubtotalAmount_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.MinOrderSubtotalAmountIncludingTax")]
public bool MinOrderSubtotalAmountIncludingTax { get; set; }
public bool MinOrderSubtotalAmountIncludingTax_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.MinOrderTotalAmount")]
public decimal MinOrderTotalAmount { get; set; }
public bool MinOrderTotalAmount_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.AutoUpdateOrderTotalsOnEditingOrder")]
public bool AutoUpdateOrderTotalsOnEditingOrder { get; set; }
public bool AutoUpdateOrderTotalsOnEditingOrder_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.AnonymousCheckoutAllowed")]
public bool AnonymousCheckoutAllowed { get; set; }
public bool AnonymousCheckoutAllowed_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.CheckoutDisabled")]
public bool CheckoutDisabled { get; set; }
public bool CheckoutDisabled_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.TermsOfServiceOnShoppingCartPage")]
public bool TermsOfServiceOnShoppingCartPage { get; set; }
public bool TermsOfServiceOnShoppingCartPage_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.TermsOfServiceOnOrderConfirmPage")]
public bool TermsOfServiceOnOrderConfirmPage { get; set; }
public bool TermsOfServiceOnOrderConfirmPage_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.OnePageCheckoutEnabled")]
public bool OnePageCheckoutEnabled { get; set; }
public bool OnePageCheckoutEnabled_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab")]
public bool OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab { get; set; }
public bool OnePageCheckoutDisplayOrderTotalsOnPaymentInfoTab_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.DisableBillingAddressCheckoutStep")]
public bool DisableBillingAddressCheckoutStep { get; set; }
public bool DisableBillingAddressCheckoutStep_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.DisableOrderCompletedPage")]
public bool DisableOrderCompletedPage { get; set; }
public bool DisableOrderCompletedPage_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.DisplayPickupInStoreOnShippingMethodPage")]
public bool DisplayPickupInStoreOnShippingMethodPage { get; set; }
public bool DisplayPickupInStoreOnShippingMethodPage_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.AttachPdfInvoiceToOrderPlacedEmail")]
public bool AttachPdfInvoiceToOrderPlacedEmail { get; set; }
public bool AttachPdfInvoiceToOrderPlacedEmail_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.AttachPdfInvoiceToOrderPaidEmail")]
public bool AttachPdfInvoiceToOrderPaidEmail { get; set; }
public bool AttachPdfInvoiceToOrderPaidEmail_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.AttachPdfInvoiceToOrderCompletedEmail")]
public bool AttachPdfInvoiceToOrderCompletedEmail { get; set; }
public bool AttachPdfInvoiceToOrderCompletedEmail_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.ReturnRequestsEnabled")]
public bool ReturnRequestsEnabled { get; set; }
public bool ReturnRequestsEnabled_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.ReturnRequestsAllowFiles")]
public bool ReturnRequestsAllowFiles { get; set; }
public bool ReturnRequestsAllowFiles_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.ReturnRequestNumberMask")]
public string ReturnRequestNumberMask { get; set; }
public bool ReturnRequestNumberMask_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.NumberOfDaysReturnRequestAvailable")]
public int NumberOfDaysReturnRequestAvailable { get; set; }
public bool NumberOfDaysReturnRequestAvailable_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.ActivateGiftCardsAfterCompletingOrder")]
public bool ActivateGiftCardsAfterCompletingOrder { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.DeactivateGiftCardsAfterCancellingOrder")]
public bool DeactivateGiftCardsAfterCancellingOrder { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.DeactivateGiftCardsAfterDeletingOrder")]
public bool DeactivateGiftCardsAfterDeletingOrder { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.CompleteOrderWhenDelivered")]
public bool CompleteOrderWhenDelivered { get; set; }
public string PrimaryStoreCurrencyCode { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.OrderIdent")]
public int? OrderIdent { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.CustomOrderNumberMask")]
public string CustomOrderNumberMask { get; set; }
public bool CustomOrderNumberMask_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.ExportWithProducts")]
public bool ExportWithProducts { get; set; }
public bool ExportWithProducts_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.AllowAdminsToBuyCallForPriceProducts")]
public bool AllowAdminsToBuyCallForPriceProducts { get; set; }
public bool AllowAdminsToBuyCallForPriceProducts_OverrideForStore { get; set; }
[NopResourceDisplayName("Admin.Configuration.Settings.Order.DeleteGiftCardUsageHistory")]
public bool DeleteGiftCardUsageHistory { get; set; }
public bool DeleteGiftCardUsageHistory_OverrideForStore { get; set; }
public ReturnRequestReasonSearchModel ReturnRequestReasonSearchModel { get; set; }
public ReturnRequestActionSearchModel ReturnRequestActionSearchModel { get; set; }
#endregion
}
} |
import React from "react";
import { ThemeContext } from "../contexts/ThemeContext";
import { AuthContext } from "../contexts/AuthContext";
class Navbar extends React.Component {
render() {
return (
<AuthContext.Consumer>{(authContext) => (
<ThemeContext.Consumer>{(themeContext) => {
const { isDarkTheme, darkTheme, lightTheme } = themeContext;
const { isLoggedIn, changeAuthStatus } = authContext;
const theme = isDarkTheme ? darkTheme : lightTheme;
return (
<nav style={{ background: theme.background, color: theme.text, height: '120px' }}>
<h2 style={{ textAlign: 'center' }} className="ui centered header">To Do List</h2>
<p style={{textAlign: 'center'}} onClick={ changeAuthStatus }>{ isLoggedIn ? 'Logged in' : 'Loggen out' }</p>
<div className="ui three buttons">
<button className="ui button">Overview</button>
<button className="ui button">Contact</button>
<button className="ui button">Support</button>
</div>
</nav>
)
}}
</ThemeContext.Consumer>
)}
</AuthContext.Consumer>
)
}
}
export default Navbar; |
---
title: "\"In 2024, Superior Animation Suites Top 3D Modelers\""
date: 2024-06-04T04:06:05.763Z
updated: 2024-06-05T04:06:05.763Z
tags:
- screen-recording
- ai video
- ai audio
- ai auto
categories:
- ai
- screen
description: "\"This Article Describes In 2024, Superior Animation Suites: Top 3D Modelers\""
excerpt: "\"This Article Describes In 2024, Superior Animation Suites: Top 3D Modelers\""
keywords: "\"Anime Master Tools,3D Design Software,Pro Animators Suite,High-End Modeler,Top Animator Apps,Premium Animation Software,Leading Modeling Packs\""
thumbnail: https://thmb.techidaily.com/eeef901d1f6e0f72044944aeb5612974e0f0cbfc3a23bf93996d4e40618dadce.jpeg
---
## Superior Animation Suites: Top 3D Modelers
Using software like [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) for editing your videos ready for uploading or release is fast and effective but first you have to get your files ready to import. We will be talking about 3d model creation today which is the first step in 3D animation creation. There are many options out there with their own advantages and drawbacks as well as price points and additional support via tutorials and in some cases assets to help speed up the creation process.
In every case you can always just buy ready-made models for your animations but in doing that you lose the option and the flexibility to have a completely custom asset with the ability to alter when needed.
There are many steps to creating that perfect video and in time you will have your preferred method. We call this our workflow. Achieving a comfortable workflow is one of the most important and influential processes you will undergo as a creative artist, this is due to the fact even with the best ideas and all the drive in the world, if you struggle to translate that into a 3d model then it stays in your head and no one will see it.
With this in mind let's look at some of the options available to us and how we can use them for this first most important step in our creative process. Remember to pick one that does not limit your creativity and gives you the tools you need to translate thought into visualization.
## ZBrush by MAXON

Zbrush is what is considered an industry standard 3D modeling software and is one of the most used by many leading studios. This is a paid software with different versions meeting different needs depending on what you feel you need. You can create impressive 3d models with very high levels of detail without overusing your computer resources resulting in a stable and fluid working process. Zbrush is very powerful with many features, too many features to highlight in this guide but as an overview some features that can improve your process are:
* You can import or create alphas easily for micro detailing.
* There is a live boolean to create unique items within your sculpts.
* It's very easy to use the Zremesher to create a new clean topology of your sculptures.
Dynamesh lets you work and retopo as you go so the sculpt retains detail.
* Work with multiple levels of divisions at the same time with the Sub Divide tools.
This is just a tiny scratch on the surface of what ZBrush can do. There are all the tools you need within this software to create an amazing jaw dropping model for your videos but this is a paid software which is important to remember when making the decision to go with this one as you will need animation and rigging software as well as in some cases a UV editor. Another thing to remember is system requirements depending on your setup. Minimum system requirements are as follows:
**For Windows:**
* 64-bit Windows 10 or 11 .
* Core 2 Duo or AMD equivalent with SSE2 technology or better.
* 4GB of ram with a strong recommendation for 6GB or more.
* 8GB of free hard drive space.
* A graphics card with OpenGL 3.3 or higher and Vulkan 1.1 or higher.
* Monitor with 32-bit color and a resolution of 1280x1024.
* Mouse or Wacom compatible (WinTab API) pen tablet.
**For Mac:**
* Mac OSX: 10.14 or above
* Everything else is the same as above.
Zbrush runs the same on Windows and Mac so there is no advantage over the other and the only real elements that you need to consider is your CPU and your RAM, A faster CPU with more cores will make this program run more stable and 16GB or RAM or more will also help with stability so if your running an older computer this will still work but you may be limited to pixel count but that is true for all 3D creation software.
## Autodesk Maya

This guide wouldn't be complete without introducing Maya, Maya is another industry standard for modeling but also offers animation and rigging tools meaning this covers a lot more ground that some of the other 3D modeling software.
Maya is very powerful but for this guide I will only be talking about the 3D modeling creation tools as I feel other topics need their own space but that said I think it is important to mention this is a complete workflow from creation to the exportation of your movie file into Filmora ready for editing and uploading to your audience.
Again this software has a list of features that is simply too large to cover so i will highlight some useful features for your creative process.
* Polygon modeling lets you create 3D models based on vertexes, edges and faces.
* Nurbs modeling lets you create 3d models from geometric primitives and drawn curves
* Sculpting tools allows you to create organic sculpts
* Subdivision workflow for better performance in higher pixel counts
* Built in UV editing
* Orthopedic viewport so you can check dimensions from whichever side you need
Again we are only scratching the surface of what Maya can do. Maya is capable of creating hyper realistic hard surface and organic models for use within animation and also provides all the tools needed to get a perfect rendering. Again system performance is important to consider when choosing software and the minimum requirements are as follows:
* Windows 10 or 11, macOS x or above and linux but see website for compatibility.
* 64-bit Intel or AMD multi-core processor with SSE4.2, M series Mac under rosetta 2.
* 8GB of RAM but 16GB or more is recommended.
* 7GB free disk space for the install.
* Three-button mouse.
* Graphics card please see website for compatibility
This is a paid software and can be expensive so please consider this when choosing your desired workflow but also consider that this is a complete workflow right up to importing your video file into Filmora so the price may be justified compared to multiple software. Another thing to consider is you can mostly get the desired results you want without the use of a drawing tablet cutting even more cost.
## 3DCoat 2022

3DCoat was first released in 2007 and has released constant updates inline with the 3D art community needs. Being a smaller team of developers it's quite impressive what they have achieved as this is a fully featured 3D art software capable of creating very nice detailed models. When used with the likes of Daz 3D, Keyshot or similar animation software you can easily create the animation you are planning. This is not a full workflow but it is very close to one and the team are constantly releasing updates so one day it might be. You have the ability to UV your models as well as texture, paint and sculpt all within one program and this has one of the most impressive live retopo tools around called voxel modeling mode. Key features are as follows:
* Easy texturing and PBR with the use of smart materials and a HDRL viewport.
* Voxel sculpting with complex boolean operations and adaptive dynamic tessellation.
* Classic polygonal modeling is fully supported and also supports splines and joints.
* Auto-retopology with user-defined edge loops but also fast and easy manual tools.
* Professional tools for creating and editing UV-sets.
* Native global uniform unwrapping algorithms.
* PBR and HDRL rendering for concept exporting.
* Use of scripts for repetitive actions.
* And many more.
This is paid software but with many options to buy as well as unlimited learning period which you will have to take into consideration when you are deciding to take this in your workflow. And again another consideration is your hardware and 3DCoat is complex due to the complexity of their software , as a point of reference there website states they consider a Surface Pro as the minimal hardware needed to use there software, minimum system specs are as follows:
* 64-Bit Windows 7/8/10/11, macOS 10.13 High Sierra or higher, Linux Ubuntu 20.04+
* CPU m3 1.00 GHz,
* 4GB RAM
* Intel HD Graphics 615
* This will allow painting textures up to 2K and sculpting up to 1 million triangles
What makes 3DCoat a good choice is the fact they have unlimited learning allowing you to journey into sculpting without putting any money in to start and in confection with other software it is very powerful.
## Blender

So now it's time to talk about Blender, the Blender institute set off with one main goal in mind and that was to put powerful tools for use with 3D and CG in the hands of artists in the form of free/open-source software. This is commendable and they have in large achieved what they set out to do, not only can you sculpt or model in Blender you can also rig and animate and add VFX to your projects.
It's impressive to see what you can do with free software and you will be able to achieve very good results. What you miss out on in the form of automation tools and boutique brushes and toolsets this makes up for in an ever-expanding community driven tutorials and guides. With this being free it doesn't make sense to not have this installed even if you have a different workflow due to the ability to expand with new skills that may work their way into your daily task. Key features are as follows:
* Render with impressive results thanks to cycles,
* An extensive toolset for modeling, curves and retopology
* Sculpting tools provide the power and flexibility needed in several stages of production
* Designed for animation in mind
* Push the boundaries of story art by drawing in a 3d environment
* Powerful post FX and VFX tools like object motion tracking
* Fully customisable UI and controles
* Python API means every tool can be customized and scripted
Blender is complex software and due to this some functions require different hardware specs but as a rule the higher the CPU speed and cores plus the more RAM you have the more you can do at any given time. With this said the minimum system requirements are as follows@
* Windows 8.1,10 and 11, macOS 10.13 and above and Linux supported
* 64-Bit quad core CPU with SSE2 support
* 8GB RAM
* Full HD display
* Mouse, trackpad or pen+tablet
* Graphics card with 2GB VRAM, OpenGL 4.3 support
Blender receives regular updates and is supported by community scripts and content and is becoming a new go to tool for 3D artists in all industries and backgrounds making it a real contender when picking a workflow.
**From Desktop to Portable**
There are lots of options and this list is in no way stating what you may already use is not good enough, this is just what is being used in the industry and is more accessible to a starter or someone who works from home and doesn't want to spend thousands upfront for their software.
That being said there is more than just the desktop workflow and some people lead busy lifestyles and are always on the move. This is where I would like to introduce the portable workflow. Due to the fact the Ipad Pro is considered a must have for portable creativity and with recent releases there has never been a better time to start i will be showing Ipad compatible apps.
## Forger by Maxon

Forger is released as a standalone app or part of the Maxon one. Forger gives you all the tools needed to create sculptures and models on the go which you can be proud of. Designed by artists for artists the features are quite large considering this is running on an ipad and with the seamlessness of importing and exporting to and from software such as cinema 4D this can be worked into your workflow very easily. One feature of Forger that people like to talk about is the ability to use your ipad camera and view your model in the real world using augmented reality.
Some of the key features of Forger but not limited to are as follows:
* Multi-resolution mesh sculpting via catmull0clark mesh subdivisions.
* Volume-based quad-dominant remeshing.
* Sculpt in layers.
* Sculpt with a mask with the ability to clear, invert, blur, grow and shrink your masks.
* Ability to close holes in existing meshes
* Simple auto-generation of mesh UVs.
* Symmetrical sculpting based on axis of choice
* Ability to reapply symmetry to topologically symmetrical meshes.
Forger is very powerful and don't let the fact it's on an ipad make you think it's inferior to the bigger desktop software as this is very capable of getting the results you are looking for. It just takes a bit of researching and a different learning curve. Due to the fact it is on an ipad the system requirements are easier to achieve, minimum system requirements are as follows
* IOS 15 or later
* Ipad pro or current model ipad
A note from the developers, the more complex the model being sculpted, the more RAM required. While there is no screen size requirement, as anticipated the bigger the better when it comes to sculpting workspace.
## Nomad Sculpt

Nomad Sculpt is another contender offering powerful tools that artists can use to sculpt outstanding models for your animations. With a fixed price payment once you buy this you get regular updates and added features meaning you can buy with the confidence you will always have the best tools available. Nomad has a growing community of tutors giving guides and tutorials to get your desired results so no matter your experience Nomad is accessible to you. With the use of voxel remeshing and boolean you can experiment all you like and with the added history feature you can always undo and retrace your steps creating a non destructive workflow and piece of mind. Some of the key features of Nomad are as follows:
* Industry standard sculpting tools like clay, flatten, smooth, mask and cutting tools.
* Stroke parameters can be customized with falloff, alphas and pencil pressure.
* Vertex painting with color, roughness and metalness.
* Work with layers for non destructive modeling.
* Multiresolution sculpting for flexibility.
* Voxel remeshing allows to quickly get uniform levels of detail.
* Dynamic topology even with multiple layers.
* PBR rendering by default with lighting and shadows and switchable matcaps
* Post-processing , screen space reflection, depth of field, ambient occlusion and more
* Customisable user interface
Again due to being an app the system requirements are open to more users but unlike forger as of the writing of this Nomad is also available on Android giving people more options when choosing. System requirements are as follows:
* Iphone iOS 12.0 or later.
* Ipad iPADOS 12.0 or later.
* Ipod iOS 12.0 or later
* Android 4.4 and up.
## Procreate

Procreate gets an honorable mention here due to the recent update that added the ability to paint in 3D directly onto your imported OBJ’s. This is a very cool feature as you can paint on different maps directly onto your model and get the exact results you wanted, the prerequisite for this is your OBJ needs to have UV’s already applied when you import into procreate and also this is limited to only three maps as of writing this, they have started they are going to advancing this feature in upcoming updates. Procreate also allows you to use augmented reality to view your models in the real world. Compatibility is as follows:
* Ipad iPadOS 14.4 or later.
## Conclusion
As you can see there are many options and these are just a few or the ever expanding list out there but hopefully this has given you a good starting point with some of the leading industry tools to gain the results you wish. Depending on your setup and space you may lean towards desktop or laptop sculpting or you may be on the move a lot and find the portable option best meets your needs. Either way there is software out there for you to create that perfect sculpt and create the animation you have in your mind. Filmora is very powerful at editing your scenes together ready for uploading and with this guide you will soon be making scene after scene.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit)
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<span class="atpl-alsoreadstyle">Also read:</span>
<div><ul>
<li><a href="https://some-skills.techidaily.com/new-the-9gag-pathway-to-piling-up-popular-memes/"><u>[New] The 9GAG Pathway to Piling Up Popular Memes</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-unveiling-the-art-of-converting-still-images-into-engaging-videos-with-pixiz/"><u>2024 Approved Unveiling the Art of Converting Still Images Into Engaging Videos with Pixiz</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-the-pinnacle-guide-to-uncomplicated-online-live-streams/"><u>[New] The Pinnacle Guide to Uncomplicated Online Live Streams</u></a></li>
<li><a href="https://some-skills.techidaily.com/the-ultimate-handbook-for-swapping-music-libraries-for-2024/"><u>The Ultimate Handbook for Swapping Music Libraries for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-the-art-of-crafting-dynamic-luts/"><u>In 2024, The Art of Crafting Dynamic LUTs</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-tips-for-a-smooth-transition-into-vr-worlds/"><u>[New] Tips for a Smooth Transition Into VR Worlds</u></a></li>
<li><a href="https://some-skills.techidaily.com/transform-your-trip-diary-into-haul-video-hype-for-2024/"><u>Transform Your Trip Diary Into Haul Video Hype for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/updated-the-exclusive-list-of-elite-christian-streaming-services/"><u>[Updated] The Exclusive List of Elite Christian Streaming Services</u></a></li>
<li><a href="https://some-skills.techidaily.com/the-ultimate-picart-technique-for-clean-images-for-2024/"><u>The Ultimate PicArt Technique for Clean Images for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/updated-the-top-25-mobile-editors-for-dji-filmmaking/"><u>[Updated] The Top 25 Mobile Editors for DJi Filmmaking</u></a></li>
<li><a href="https://some-skills.techidaily.com/updated-techniques-to-procure-free-visual-frame-videos/"><u>[Updated] Techniques to Procure Free Visual Frame Videos</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-streamlining-your-room-for-oculus-vr/"><u>In 2024, Streamlining Your Room for Oculus VR</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-the-veritable-value-of-voice-podcasters-earnings-analysis/"><u>In 2024, The Veritable Value of Voice Podcasters’ Earnings Analysis</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-the-cream-of-the-crop-top-8-sites-for-rich-3d-and-text/"><u>2024 Approved The Cream of the Crop Top 8 Sites for Rich 3D & Text</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-unveiling-the-superior-video-compression-in-av1/"><u>In 2024, Unveiling the Superior Video Compression in AV1</u></a></li>
<li><a href="https://some-skills.techidaily.com/the-essential-price-matrix-top-cloud-storage-firms-for-2024/"><u>The Essential Price Matrix Top Cloud Storage Firms for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-ultimate-playlist-of-scores-for-clips/"><u>In 2024, Ultimate Playlist of Scores for Clips</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-tips-and-tricks-for-effortless-finding-exceptional-pexel-images/"><u>2024 Approved Tips and Tricks for Effortless Finding Exceptional Pexel Images</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-television-or-projector-for-peak-4k-performance/"><u>In 2024, Television or Projector for Peak 4K Performance?</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-top-drone-shopping-mistakes-and-how-to-dodge-them/"><u>2024 Approved Top Drone Shopping Mistakes and How to Dodge Them</u></a></li>
<li><a href="https://some-skills.techidaily.com/timing-duration-for-a-20mb-high-definition-video-for-2024/"><u>Timing Duration for a 20Mb High-Definition Video for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/updated-prime-20-opening-melodies-in-animation/"><u>[Updated] Prime 20 Opening Melodies in Animation</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-unveiling-the-art-of-chromatic-mastery-in-video-editing-11-steps/"><u>In 2024, Unveiling the Art of Chromatic Mastery in Video Editing (11 Steps)</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-unleash-creativity-free-premiere-pro-2023-templates/"><u>2024 Approved Unleash Creativity Free Premiere Pro 2023 Templates</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-the-editors-edge-insider-strategies-to-supercharge-your-photos/"><u>2024 Approved The Editor's Edge Insider Strategies to Supercharge Your Photos</u></a></li>
<li><a href="https://some-skills.techidaily.com/top-6-choices-prime-microphones-for-dynamic-online-broadcasts-for-2024/"><u>Top 6 Choices Prime Microphones for Dynamic Online Broadcasts for 2024</u></a></li>
<li><a href="https://some-skills.techidaily.com/2024-approved-unlocking-window-11s-best-kept-secrets-for-maximum-productivity/"><u>2024 Approved Unlocking WINDOW 11'S Best-Kept Secrets for Maximum Productivity</u></a></li>
<li><a href="https://some-skills.techidaily.com/new-ultimate-compilation-best-gopro-cases-for-action-seekers/"><u>[New] Ultimate Compilation Best GoPro Cases for Action Seekers</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-unveiling-the-best-lipos-a-drone-buyers-bible/"><u>In 2024, Unveiling the Best LiPos - A Drone Buyer's Bible</u></a></li>
<li><a href="https://some-skills.techidaily.com/in-2024-unleashing-the-full-power-of-apple-podcasts-downloads/"><u>In 2024, Unleashing the Full Power of Apple Podcasts Downloads</u></a></li>
<li><a href="https://desktop-recording.techidaily.com/effortlessly-integrating-obs-into-your-mac-step-by-step-guide-for-2024/"><u>Effortlessly Integrating OBS Into Your Mac Step by Step Guide for 2024</u></a></li>
<li><a href="https://techidaily.com/how-do-i-reset-my-tecno-spark-20-proplus-phone-without-technical-knowledge-drfone-by-drfone-reset-android-reset-android/"><u>How do I reset my Tecno Spark 20 Pro+ Phone without technical knowledge? | Dr.fone</u></a></li>
<li><a href="https://ai-vdieo-software.techidaily.com/updated-experience-the-thrill-top-10-movie-trailer-apps-for-ios/"><u>Updated Experience the Thrill Top 10 Movie Trailer Apps for iOS</u></a></li>
<li><a href="https://youtube-clips.techidaily.com/youtube-treasures-the-ultimate-list-for-endless-screen-time/"><u>YouTube Treasures The Ultimate List for Endless Screen Time</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/new-avi-video-editing-made-easy-top-trimming-tools-for-every-platform/"><u>New AVI Video Editing Made Easy Top Trimming Tools for Every Platform</u></a></li>
<li><a href="https://unlock-android.techidaily.com/how-to-unlock-a-network-locked-vivo-y200e-5g-phone-by-drfone-android/"><u>How to Unlock a Network Locked Vivo Y200e 5G Phone?</u></a></li>
<li><a href="https://ai-live-streaming.techidaily.com/new-a-detailed-guide-to-stream-to-instagram-with-an-rtmp-for-2024/"><u>New A Detailed Guide To Stream to Instagram With an RTMP for 2024</u></a></li>
<li><a href="https://video-screen-grab.techidaily.com/new-clan-the-challenge-best-games-similar-to-ghost-of-tsushima/"><u>[New] Clan the Challenge Best Games Similar to Ghost of Tsushima</u></a></li>
<li><a href="https://ai-driven-video-production.techidaily.com/2024-approved-unleash-your-creativity-a-comprehensive-guide-to-using-wax-for-free-video-editing/"><u>2024 Approved Unleash Your Creativity A Comprehensive Guide to Using Wax for Free Video Editing</u></a></li>
<li><a href="https://ai-editing-video.techidaily.com/1713954042187-new-2024-approved-best-8-online-gif-to-apng-converters/"><u>New 2024 Approved | Best 8 Online GIF to APNG Converters</u></a></li>
<li><a href="https://youtube-video-recordings.techidaily.com/updated-download-youtube-gallery-files-instantly/"><u>[Updated] Download YouTube Gallery Files Instantly</u></a></li>
<li><a href="https://facebook-videos.techidaily.com/new-2024-approved-mastering-social-media-finding-youtube-content-on-fb/"><u>[New] 2024 Approved Mastering Social Media Finding YouTube Content on FB</u></a></li>
<li><a href="https://location-fake.techidaily.com/5-easy-ways-to-change-location-on-youtube-tv-on-honor-magic-vs-2-drfone-by-drfone-virtual-android/"><u>5 Easy Ways to Change Location on YouTube TV On Honor Magic Vs 2 | Dr.fone</u></a></li>
<li><a href="https://sound-tweaking.techidaily.com/streamlining-your-workflow-our-selection-of-the-6-best-automatic-transcription-programs/"><u>Streamlining Your Workflow Our Selection of the 6 Best Automatic Transcription Programs</u></a></li>
<li><a href="https://screen-activity-recording.techidaily.com/in-2024-premier-5-web-video-capture-tech/"><u>In 2024, Premier 5 Web Video Capture Tech</u></a></li>
<li><a href="https://tiktok-video-recordings.techidaily.com/updated-in-2024-accelerating-filming-on-tiktok-for-real-time-results/"><u>[Updated] In 2024, Accelerating Filming on TikTok for Real-Time Results</u></a></li>
<li><a href="https://discord-videos.techidaily.com/updated-2024-approved-explore-discords-colored-palette-with-over-7-free-emoji-resources/"><u>[Updated] 2024 Approved Explore Discord's Colored Palette with Over 7 FREE Emoji Resources</u></a></li>
<li><a href="https://tiktok-videos.techidaily.com/2024-approved-top-10-freely-downloadable-apps-for-tiktok-video-editing-on-mac/"><u>2024 Approved Top 10 Freely Downloadable Apps for TikTok Video Editing on Mac</u></a></li>
<li><a href="https://screen-mirror.techidaily.com/in-2024-overview-of-the-best-nubia-z50-ultra-screen-mirroring-app-drfone-by-drfone-android/"><u>In 2024, Overview of the Best Nubia Z50 Ultra Screen Mirroring App | Dr.fone</u></a></li>
<li><a href="https://fix-guide.techidaily.com/simple-solutions-to-fix-android-systemui-has-stopped-error-for-infinix-hot-30-5g-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Simple Solutions to Fix Android SystemUI Has Stopped Error For Infinix Hot 30 5G | Dr.fone</u></a></li>
<li><a href="https://screen-recording.techidaily.com/immersive-escapades-documented-the-experts-guide-to-capturing-vr-games/"><u>Immersive Escapades Documented The Expert's Guide to Capturing VR Games</u></a></li>
<li><a href="https://video-capture.techidaily.com/2024-approved-how-to-ensure-accurate-game-saves-with-fbx-recorder/"><u>2024 Approved How to Ensure Accurate Game Saves with FBX Recorder</u></a></li>
<li><a href="https://facebook-video-content.techidaily.com/2024-approved-global-gala-of-greatest-video-views/"><u>2024 Approved Global Gala of Greatest Video Views</u></a></li>
<li><a href="https://remote-screen-capture.techidaily.com/in-2024-essential-screen-capture-tips-for-mi-11-users/"><u>In 2024, Essential Screen Capture Tips for Mi 11 Users</u></a></li>
<li><a href="https://extra-guidance.techidaily.com/seamless-transition-turning-mac-videos-into-discs-for-2024/"><u>Seamless Transition Turning Mac Videos Into Discs for 2024</u></a></li>
<li><a href="https://extra-tips.techidaily.com/2024-approved-create-powerful-biz-decks-with-no-cost-templates/"><u>2024 Approved Create Powerful Biz Decks with No-Cost Templates</u></a></li>
</ul></div> |
import React, { createContext , useState } from 'react';
import { PRODUCTS } from '../products';
export const ShopContext = createContext(null);
const getDefaultCart = () => {
let cart = {};
for (let i =1; i<PRODUCTS.length +1; i++){
cart[i] = 0;
}
return cart;
}
export const ShopContextProvider = (props) => {
const [cartItems , setCartItems] = useState(getDefaultCart());
const getTotalCartAmount = () =>{
let totalAmount = 0;
for(const item in cartItems){
if(cartItems[item] > 0){
let itemInfo = PRODUCTS.find((product)=> product.id === Number(item));
totalAmount += cartItems[item] * itemInfo.price;
}
}
return totalAmount;
}
const addToCart = (itemId) => {
setCartItems ((prev) => ({...prev,[itemId]:prev[itemId] + 1 }))
}
const removeToCart = (itemId) => {
setCartItems ((prev) => ({...prev,[itemId]:prev[itemId] - 1 }))
}
const updateCartItemCount = (newAmount, itemId) => {
setCartItems((prev) => ({...prev, [itemId]: newAmount}));
}
const contextValue = {cartItems, addToCart, removeToCart, updateCartItemCount, getTotalCartAmount}
return (
<ShopContext.Provider value={contextValue}>{props.children}</ShopContext.Provider>
)
} |
import {
Injectable,
Inject,
forwardRef,
ForbiddenException,
HttpException
} from '@nestjs/common';
import { PerformerService } from 'src/modules/performer/services';
import { Model } from 'mongoose';
import { ObjectId } from 'mongodb';
import { EntityNotFoundException } from 'src/kernel';
import { v4 as uuidv4 } from 'uuid';
import { ConversationService } from 'src/modules/message/services';
import { SubscriptionService } from 'src/modules/subscription/services/subscription.service';
import { UserDto } from 'src/modules/user/dtos';
import { RedisService } from 'nestjs-redis';
import { RequestService } from './request.service';
import { SocketUserService } from '../../socket/services/socket-user.service';
import {
PRIVATE_CHAT,
PUBLIC_CHAT,
defaultStreamValue,
BroadcastType
} from '../constant';
import { IStream, StreamDto } from '../dtos';
import { StreamModel } from '../models';
import { STREAM_MODEL_PROVIDER } from '../providers/stream.provider';
import {
StreamOfflineException,
StreamServerErrorException
} from '../exceptions';
import { TokenNotEnoughtException } from '../exceptions/token-not-enought';
export const REDIS_PERFORMER_PUBLIC_STREAM = 'performer_public_streams';
export const REDIS_PERFORMER_PRIVATE_STREAM = 'performer_private_streams';
@Injectable()
export class StreamService {
constructor(
@Inject(forwardRef(() => PerformerService))
private readonly performerService: PerformerService,
@Inject(STREAM_MODEL_PROVIDER)
private readonly streamModel: Model<StreamModel>,
private readonly conversationService: ConversationService,
private readonly socketUserService: SocketUserService,
private readonly subscriptionService: SubscriptionService,
private readonly requestService: RequestService,
private readonly redisService: RedisService
) {
this.resetPerformerLivestreamList();
}
public async findById(id: string | ObjectId): Promise<StreamModel> {
const stream = await this.streamModel.findOne({ _id: id });
if (!stream) {
throw new EntityNotFoundException();
}
return stream;
}
public async findBySessionId(sessionId: string): Promise<StreamModel> {
const stream = await this.streamModel.findOne({ sessionId });
if (!stream) {
throw new EntityNotFoundException();
}
return stream;
}
public async findByPerformerId(
performerId: string | ObjectId,
payload?: Partial<StreamDto>
): Promise<StreamModel> {
const stream = await this.streamModel.findOne({ performerId, ...payload });
return stream;
}
public async getSessionId(
performerId: string | ObjectId,
type: string
): Promise<string> {
let stream = await this.streamModel.findOne({ performerId, type });
if (!stream) {
const data: IStream = {
sessionId: uuidv4(),
performerId,
type
};
stream = await this.streamModel.create(data);
}
return stream.sessionId;
}
public async goLive(performerId: ObjectId) {
let stream = await this.streamModel.findOne({
performerId,
type: PUBLIC_CHAT
});
if (!stream) {
const data: IStream = {
sessionId: uuidv4(),
performerId,
type: PUBLIC_CHAT
};
stream = await this.streamModel.create(data);
}
let conversation = await this.conversationService.findOne({
type: 'stream_public',
performerId
});
if (!conversation) {
conversation = await this.conversationService.createStreamConversation(
new StreamDto(stream)
);
}
const data = {
...defaultStreamValue,
streamId: stream._id,
name: stream._id,
description: '',
type: BroadcastType.LiveStream,
status: 'finished'
};
const result = await this.requestService.create(data);
if (result.status) {
throw new StreamServerErrorException({
message: result.data?.data?.message,
error: result.data,
status: result.data?.status
});
}
return { conversation, sessionId: stream._id };
}
public async joinPublicChat(performerId: string | ObjectId) {
const stream = await this.streamModel.findOne({
performerId,
type: PUBLIC_CHAT
});
if (!stream) {
throw new EntityNotFoundException();
}
if (!stream.isStreaming) {
throw new StreamOfflineException();
}
return { sessionId: stream._id };
}
public async requestPrivateChat(
user: UserDto,
performerId: string | ObjectId
) {
const performer = await this.performerService.findById(performerId);
if (!performer) {
throw new EntityNotFoundException();
}
const subscribed = await this.subscriptionService.checkSubscribed(
performerId,
user._id
);
if (!subscribed) {
throw new HttpException('Please subscribe model to send private request', 403);
}
if (user.balance < performer.privateChatPrice) {
throw new TokenNotEnoughtException();
}
const isOnline = await this.socketUserService.isOnline(performer._id);
if (!isOnline) {
throw new HttpException(`${performer.username} is offline`, 400);
}
const data: IStream = {
sessionId: uuidv4(),
performerId,
userIds: [user._id],
type: PRIVATE_CHAT,
isStreaming: true
};
const stream = await this.streamModel.create(data);
const recipients = [
{ source: 'performer', sourceId: new ObjectId(performerId) },
{ source: 'user', sourceId: user._id }
];
const conversation = await this.conversationService.createStreamConversation(
new StreamDto(stream),
recipients
);
const {
username, email, avatar, _id, balance
} = user;
await this.socketUserService.emitToUsers(
performerId,
'private-chat-request',
{
user: {
username, email, avatar, _id, balance
},
streamId: stream._id,
conversationId: conversation._id
}
);
return { conversation, sessionId: stream.sessionId };
}
public async accpetPrivateChat(id: string, performerId: ObjectId) {
const conversation = await this.conversationService.findById(id);
if (!conversation) {
throw new EntityNotFoundException();
}
const recipent = conversation.recipients.find(
(r) => r.sourceId.toString() === performerId.toString()
&& r.source === 'performer'
);
if (!recipent) {
throw new ForbiddenException();
}
const stream = await this.findById(conversation.streamId);
if (!stream && stream.performerId !== performerId) {
throw new EntityNotFoundException();
}
if (!stream.isStreaming) {
throw new StreamOfflineException();
}
return { conversation, sessionId: stream.sessionId };
}
public async getToken() {
return null;
}
public async addPerformerLivestreamList(performerId: string | ObjectId, publicOrPrivate = 'public') {
const room = publicOrPrivate === 'public' ? REDIS_PERFORMER_PUBLIC_STREAM : REDIS_PERFORMER_PRIVATE_STREAM;
const redisClient = this.redisService.getClient();
await redisClient.sadd(room, performerId.toString());
}
public async removePerformerLivestreamList(performerId) {
const redisClient = this.redisService.getClient();
await Promise.all([
redisClient.srem(REDIS_PERFORMER_PRIVATE_STREAM, performerId.toString()),
redisClient.srem(REDIS_PERFORMER_PUBLIC_STREAM, performerId.toString())
]);
}
// apply single instance only!!
public async resetPerformerLivestreamList() {
const redisClient = this.redisService.getClient();
await Promise.all([
redisClient.del(REDIS_PERFORMER_PRIVATE_STREAM),
redisClient.del(REDIS_PERFORMER_PUBLIC_STREAM)
]);
}
public async checkPerformerStreaming(performerId) {
const redisClient = this.redisService.getClient();
const [hasPublic, hasPrivate] = await Promise.all([
redisClient.sismember(REDIS_PERFORMER_PUBLIC_STREAM, performerId.toString()),
redisClient.sismember(REDIS_PERFORMER_PRIVATE_STREAM, performerId.toString())
]);
if (hasPublic) return 'public';
if (hasPrivate) return 'private';
return null;
}
} |
#ifndef VM_MNGR_H
#define VM_MNGR_H
#include "../include/type.h"
#include "pm_mngr.h"
#include "../Lib/util.h"
#include "./../cpu/idt.h"
* One way to create the mapping table between the virtual pages
* and physcial memory blocks is to generate an array of integers
* where the array index is represents the virtual page number
* while the value of that integer is the physcial address of the
* frame address and attributions of that page.
*
* +----------------------------------------+
* | Frame Addr (20 bits) | Attrib |
* +----------------------------------------+
* .
* .
* .
* +----------------------------------------+
* | Frame Addr (20 bits) | Attrib |
* +----------------------------------------+
* | Frame Addr (20 bits) | Attrib |
* +----------------------------------------+
*
* Considering the supported memory by i386 system is 4GB and that
* one page is 4KB in size, it's easy to calculate that the array
* needs to contain 1M integers, which consumes 4MB size of memory.
*
* If you got a 4GB memory, then it would not be painful to spare
* 4MB, but what if the memory size is much smaller, for example,
* the i386 system emulated by QEMU by default comes with only
* 128M memory. Therefore, to minimize the cost of storing the
* mapping table, i386 system adopts a 2-layer mapping scheme,
* where the first layer is the page directory table and
* the second layer are the page tables.
*
* The page directory, which by itself is also a page,
* stores 1K entries with each points a page table, then a page
* table, which is also a page contains 1K entries, withe each
* points to a page, whose physical entity is called a frame in
* the physical memory that occupies 4KB.
*
* This scheme determined by the system not the software becasue
* eventually, the virtual address will be sent to the MMU to be
* translated into physcial address. How MMU interprets the address
* is decided by hardware manufactures.
*
* For the i386 system in particular, after the paging is enabled,
* MMU interpret the virtual in the following way:
*
* 31 22 21 12 11 0
* +----------------------------------------+
* | dir index | page index | page offset | Linear Addr
* +----------------------------------------+
* | | | Frame
* | | | +----------------------------+
* | | +------------------------> | Physical address |
* | | | |
* | | Page Table | |
* | +------------- + +------------+ +----------------------------+
* | | | | ^
* | Page Dir | +------------+ |
* | +------------+ | | | |
* | | | | +------------+ |
* | +------------+ +---> | | ----------+
* +---> | | ---+ +------------+
* +------------+ | | |
* | | | +------------+
* +------------+ | ^
* | | | |
* +------------+ | |
* | |
* +--------------+
*
* This way, the entire 4GB address space can be covered with the
* advantage that if a page table has no entries, it can be freed
* and it's present flag unset in the page directory.
*
* When is a page table to have no entries? A page table has no
* entries when there isn't enough physical memory to allocate,
* leaving many page tables unused and whereby having no entries,
* for example, when the entire physical memory is 128M, which
* requires at total 128M/4K = 32K pages only and other pages
* could all be freed.
/**
* Some functions that help manipulate the 32-bit virtual addresses
*/
/**
* Retrieve the page directory index given a virtual (linear) address
*/
int va_get_dir_index(uint32_t va);
/**
* Retrieve the page table index given a virtual (linear) address
*/
int va_get_page_index(uint32_t va);
/**
* Retrieve the page table offset given a virtual (linear) address
*/
int va_get_page_offset(uint32_t va);
*
*
* Page table entry format:
*
* (Refer to 80386 manual page 100 of 421)
*
* Bit
* --------------------------------
* 0
* Present (in memory) Flag
* 0
* --------------------------------
* 1
* Read/ Write Flag
* 0 : Read only
* 1 : Writable
* 1
* --------------------------------
* 2
* Operation Mode
* 0 : Kernel
* 1 : User
* 2
* --------------------------------
* 3
* 0,0
* 4
* --------------------------------
* 5
* Access Flag (SET BY PROCESSOR)
* 0 : Page has not been accessed (read from or written to)
* 1 : Page has been accessed
* 5
* --------------------------------
* 6
* Dirty Flag (SET BY PROCESSOR)
* 0 : Page has not been written to
* 1 : Page has been written to
* 6
* --------------------------------
* 7
* 0,0
* 8
* --------------------------------
* 9
* Available for use
* 11
* --------------------------------
* 12
* Frame Address
*
* Physical memory (4G)
* #Frames = ---------------------- = 1M
* Page Size (4K)
*
* => 20 bits
* 31
* --------------------------------
*
* In conclusion, each page is 4K, each page table has 1K entries
* and each page directory also has 1K entries. Therefore,
* the total virtual memory size is 4KB * 1K * 1K = 4GB.
*
/**
* Below provides an abstract interface for the management of Page Table Entries
*/
#define PAGE_PRESENT 0b00000000000000000000000000000001
#define PAGE_WRITABLE 0b00000000000000000000000000000010
#define PAGE_USER 0b00000000000000000000000000000100
#define PAGE_ACCESSED 0b00000000000000000000000000100000 // Not used by page_add_attrib() becasue it is set by the processor, it is used by page_is_accessed()
#define PAGE_DIRTY 0b00000000000000000000000001000000 // Not used by page_add_attrib() becasue it is set by the processor, it is used by page_is_dirty()
#define PAGE_FRAME_ADDR_MASK 0b11111111111111111111000000000000
/**
* Set certain bits in the PTE to add attributes to a page
*/
void page_add_attrib(uint32_t* ptr_to_pte, int attrib);
/**
* Clear certain bits in the PTE to delete attributes of a page
*/
void page_del_attrib(uint32_t* ptr_to_pte, int attrib);
/**
* Install frame addess field in the PTE to assign a physical memory for a page
*/
void page_install_frame_addr(uint32_t* ptr_to_pte, uint32_t frame_addr);
/**
* Test if the page is present (in the main memory)
* Returns TRUE if present, or 0 if not
*/
int page_is_present(uint32_t pte);
/**
* Test if the page is used by the user
* Returns TRUE if used by the user, or 0 if used by kernel
*/
int page_is_user(uint32_t pte);
/**
* Test if the page is has been accessed
* Returns TRUE if accessed, or 0 if not
*/
int page_is_accessed(uint32_t pte);
/**
* Test if the page is has been marked as dirty
* Returns TRUE if dirty, or 0 if not
*/
int page_is_dirty(uint32_t pte);
/**
* Test if the page is has been marked as dirty
* Returns the physical address of the frame
*/
uint32_t page_get_frame_addr(uint32_t pte);
#define KERNEL_PD_BASE 0x501000
/**
* This global veriable does the job of recording the current page directory in use
* which is stored in the PDBR (Page Directory Base Register - cr3). With this, we
* can fetch the current page directory address easily without having to read it out
* from cr3 using a separate routing coded in raw assambly instructions.
*/
/**
* Load the page directory address to PDBR
*/
void vm_mngr_load_pd(uint32_t pd_physical_addr);
/**
* Assign physical memory to a page
* Returns the frame address of the page if successful or 0 if not
*/
uint32_t vm_mngr_alloc_frame(uint32_t* ptr_to_pte);
/**
* Free the physical memory allocated for the page
*/
void vm_mngr_free_frame(uint32_t* ptr_to_pte);
/**
* Map the physical address to the virtual address on a 4K basis (1 block at a time)
*/
void vm_mngr_map_segmentation(uint32_t pa, uint32_t va);
/**
* 1. Identity map the kernel so that the execution of the current code won't be affacted when enabling the paging
* 2. Map the kernel to 3GB virtual to make a higher half kernel
* 3. Set up the kernel address space
*/
void vm_mngr_init();
void vm_mngr_higher_kernel_map(uint32_t pd_pa, uint32_t va, uint32_t pa, uint32_t attrib);
void vm_mngr_higher_kernel_unmap(uint32_t pd_pa, uint32_t va);
uint32_t* vm_mngr_map_frame(uint32_t pa);
void vm_mngr_unmap_frame(uint32_t *va);
void flush_tlb();
void invalidate_tlb_ent(uint32_t va);
#endif |
package com.example.and103_assignmentht.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.and103_assignmentht.R;
import java.util.ArrayList;
import android.content.Context;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder>{
private Context context;
private ArrayList<String> list;
public ImageAdapter(Context context, ArrayList<String> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public ImageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ImageAdapter.ViewHolder holder, int position) {
String url = list.get(position);
String newUrl = url.replace("localhost", "10.0.2.2");
Glide.with(context)
.load(newUrl)
.thumbnail(Glide.with(context).load(R.drawable.baseline_broken_image_24))
.into(holder.img);
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView img;
public ViewHolder(@NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
}
}
} |
package com.rescu.wave
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.Toast
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
import com.rescu.wave.models.Agency
import kotlinx.android.synthetic.main.activity_register_agency.addressET
import kotlinx.android.synthetic.main.activity_register_agency.btnRegister
import kotlinx.android.synthetic.main.activity_register_agency.districtET
import kotlinx.android.synthetic.main.activity_register_agency.emailET
import kotlinx.android.synthetic.main.activity_register_agency.phoneET
class RegisterAgencyActivity : BaseActivity() {
private val mFireStore = FirebaseFirestore.getInstance()
val data1= arrayOf("National Disaster Relief Force (NDRF)","Research and Analysis Wing (RAW)","Police Force","Ambulance Unit")
val data2= arrayOf("Uttar Pradesh","Madhya Pradesh","Jharkhand","Jammu and Kashmir")
val data3= arrayOf("Less than 10","10 to 50","50 to 100","More than 100")
val data4= arrayOf("Less than 2","2 to 5","5 to 10","10 to 20 ","More than 20")
lateinit var autocompleteTV1:AutoCompleteTextView
lateinit var autocompleteTV2:AutoCompleteTextView
lateinit var autocompleteTV3:AutoCompleteTextView
lateinit var autocompleteTV4:AutoCompleteTextView
lateinit var adapter1:ArrayAdapter<String>
lateinit var adapter2:ArrayAdapter<String>
lateinit var adapter3:ArrayAdapter<String>
lateinit var adapter4:ArrayAdapter<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register_agency)
var email : String = intent.getStringExtra("email").toString()
val password : String = intent.getStringExtra("password").toString()
// Initialise variables for agency info
var type : String
var phone : Long = 0
var location : String
var employeeCount : String
var vehicleCount : String
val validNumber = Regex("^[+]?[0-9]{1,10}\$")
val validNumber2 = Regex("^[+]"+"91"+"[+]?[0-9]{1,10}$")
autocompleteTV1=findViewById(R.id.drop1)
autocompleteTV2=findViewById(R.id.drop2)
autocompleteTV3=findViewById(R.id.drop3)
autocompleteTV4=findViewById(R.id.drop4)
adapter1 = ArrayAdapter<String>(this, R.layout.agency_list,data1)
adapter2 = ArrayAdapter<String>(this, R.layout.agency_list,data2)
adapter3 = ArrayAdapter<String>(this, R.layout.agency_list,data3)
adapter4 = ArrayAdapter<String>(this, R.layout.agency_list,data4)
autocompleteTV1.setAdapter(adapter1)
autocompleteTV2.setAdapter(adapter2)
autocompleteTV3.setAdapter(adapter3)
autocompleteTV4.setAdapter(adapter4)
autocompleteTV1.onItemClickListener = AdapterView.OnItemClickListener{
adapterView, view, i, l ->
val itemSelected = adapterView.getItemAtPosition(i).toString()
}
autocompleteTV2.onItemClickListener = AdapterView.OnItemClickListener{
adapterView, view, i, l ->
val itemSelected = adapterView.getItemAtPosition(i).toString()
}
autocompleteTV3.onItemClickListener = AdapterView.OnItemClickListener{
adapterView, view, i, l ->
val itemSelected = adapterView.getItemAtPosition(i).toString()
}
autocompleteTV4.onItemClickListener = AdapterView.OnItemClickListener{
adapterView, view, i, l ->
val itemSelected = adapterView.getItemAtPosition(i).toString()
}
emailET.setText(email)
btnRegister.setOnClickListener {
type = autocompleteTV1.text.toString()
location = addressET.text.toString().trim() + ", " + districtET.text.toString().trim() + ", " + autocompleteTV2.text.toString()
employeeCount = autocompleteTV3.text.toString()
vehicleCount = autocompleteTV4.text.toString()
email = emailET.text.toString().trim()
val phoneText = phoneET.text.toString().replace(" ", "")
if(phoneText.matches(validNumber) or phoneText.matches(validNumber2)) {
phone = phoneText.toLong()
}
it.hideKeyboard()
if (validateForm(type, phone, email, location)) {
showProgressDialog("Uploading information")
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email,password).addOnCompleteListener(
OnCompleteListener<AuthResult> { task ->
hideProgressDialog()
if(task.isSuccessful){
val firebaseUser: FirebaseUser = task.result!!.user!!
val firebaseEmail = firebaseUser.email!!
val agency = Agency(firebaseUser.uid, type, firebaseEmail, "", phone, location, employeeCount, vehicleCount)
mFireStore.collection("agencies")
.document(getCurrentUserID())
.set(agency, SetOptions.merge())
Toast.makeText(this,
"Registered successfully as " + type,Toast.LENGTH_LONG).show()
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
} else{
Toast.makeText(this, task.exception!!.message, Toast.LENGTH_LONG).show()
}
}
)
}
}
}
private fun validateForm(type: String, phone: Long, email: String, location: String) : Boolean {
return when {
TextUtils.isEmpty(type)->{
showErrorSnackbar("Please enter the type of agency")
false
}
TextUtils.isEmpty(phone.toString())->{
showErrorSnackbar("Please enter the organization phone number")
false
}
TextUtils.equals(phone.toString(), "0")->{
showErrorSnackbar("Please enter the organization phone number")
false
}
TextUtils.isEmpty(email)->{
showErrorSnackbar("Please enter the organization email")
false
}
TextUtils.equals(location, ", , ")->{
showErrorSnackbar("Please enter the address of your agency")
false
}
else->{
true
}
}
}
} |
import { IUserSchema } from 'entities/User';
import { ILoginSchema } from 'features/AuthByUsername';
import {
AnyAction, CombinedState, EnhancedStore, Reducer, ReducersMapObject,
} from '@reduxjs/toolkit';
import { IProfileSchema } from 'entities/Profile';
import { AxiosInstance } from 'axios';
import { To } from '@remix-run/router';
import { NavigateOptions } from 'react-router';
export interface IGlobalStateSchema {
user: IUserSchema,
// Async reducers
login?: ILoginSchema
profile?: IProfileSchema
}
export type GlobalStateSchemaKey = keyof IGlobalStateSchema
export interface IReducerManager {
getReducerMap: () => ReducersMapObject<IGlobalStateSchema>,
reduce: (state: IGlobalStateSchema, action: AnyAction) => CombinedState<IGlobalStateSchema>,
add: (key: GlobalStateSchemaKey, reducer: Reducer) => void
remove: (key: GlobalStateSchemaKey) => void
}
export interface IStoreWithReducerManager extends EnhancedStore<IGlobalStateSchema> {
reducerManager: IReducerManager
}
interface IThunkExtra {
api: AxiosInstance,
navigate?: (to: To, options?: NavigateOptions) => void,
}
export interface IThunkOptions<T> {
rejectValue: T
extra: IThunkExtra
state: IGlobalStateSchema
} |
// set up vuetify with theme and icons
// Vuetify
import "vuetify/styles";
import { ThemeDefinition, createVuetify } from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
import { fa } from "vuetify/iconsets/fa";
import { aliases, mdi } from "vuetify/lib/iconsets/mdi";
// make sure to also import the coresponding css
import "@mdi/font/css/materialdesignicons.css"; // Ensure you are using css-loader
import "@fortawesome/fontawesome-free/css/all.css"; // Ensure your project is capable of handling css files
const myAllBlackTheme: ThemeDefinition = {
dark: false,
colors: {
background: "#000000",
surface: "#000000",
primary: "#000000",
"primary-darken-1": "#000000",
secondary: "#000000",
"secondary-darken-1": "#000000",
error: "#000000",
info: "#000000",
success: "#000000",
warning: "#000000",
},
};
export const vuetify = createVuetify({
theme: {
defaultTheme: "myAllBlackTheme",
themes: {
myAllBlackTheme,
},
},
icons: {
defaultSet: "mdi",
aliases,
sets: {
mdi,
fa,
},
},
components,
directives,
}); |
import "./App.css";
import { useState, useEffect, useRef } from "react";
import axios from "axios";
import { uniq } from "lodash";
const url = `http://127.0.0.1:8000/game`;
function App() {
const [selectedAgent, setSelectedAgent] = useState("0");
const [goldCoins, setGoldCoins] = useState([]);
const [agentImage, setAgentImage] = useState("Aki.png");
const [cost, setCost] = useState(0);
const [selectedMap, setSelectedMap] = useState("map1");
const [mapContent, setMapContent] = useState("");
const [agentPosition, setAgentPosition] = useState({ x: 0, y: 0 });
const [visitedCoins, setVisitedCoins] = useState([]);
const [dataAgent, setDataAgent] = useState({
agent: [],
agentIndex1: "",
putanje: [],
zlatnici: [],
opisPutanja: [],
zbir: "",
});
const [opisi, setOpisi] = useState([]);
const [isPaused, setIsPaused] = useState(true);
const [step, setStep] = useState(0);
const [showSteps, setShowSteps] = useState(false);
const [isGameOver, setIsGameOver] = useState(false);
const [isGameInterrupted, setIsGameInterrupted] = useState(false);
const animationTimeoutRef = useRef();
const currentStepRef = useRef(0);
const buttonRef = useRef(null);
const [isStepByStepMode, setIsStepByStepMode] = useState(false);
const [currentSimulationStep, setCurrentSimulationStep] = useState(0);
function changeAgent(agentIndex, agentImg) {
setSelectedAgent(agentIndex);
setAgentImage(agentImg);
setVisitedCoins([]);
setStep(0);
setOpisi([]);
setIsGameOver(false);
setIsGameInterrupted(false);
setGoldCoins([]);
setCost(0);
setAgentPosition({ x: 0, y: 0 });
setIsStepByStepMode(false);
}
const handleMapChange = (event) => {
setSelectedMap(event.target.value);
setVisitedCoins([]);
setStep(0);
setOpisi([]);
setIsGameOver(false);
setIsGameInterrupted(false);
setGoldCoins([]);
setCost(0);
setAgentPosition({ x: 0, y: 0 });
setIsStepByStepMode(false);
};
useEffect(() => {
fetch(`maps/${selectedMap}.txt`)
.then((response) => response.text())
.then((text) => {
setMapContent(text);
const lines = text.split("\n");
const coins = lines.map((line) => {
const parts = line.split(",").map(Number);
return { x: parts[0], y: parts[1] };
});
setGoldCoins(coins);
});
}, [selectedMap]);
///Enter dogadjaj
useEffect(() => {
const handleKeyDown = (event) => {
if (event.key === "Enter") {
setIsGameInterrupted(true);
if (animationTimeoutRef.current) {
clearTimeout(animationTimeoutRef.current);
}
setIsGameOver(true);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [goldCoins]);
useEffect(() => {
if (isGameInterrupted) {
console.log("Igra je prekinuta.");
completeGame();
setIsGameInterrupted(false);
}
}, [isGameInterrupted]);
const completeGame = () => {
const newVisitedCoins = goldCoins.map((_, index) => true);
setVisitedCoins(newVisitedCoins);
if (goldCoins.length > 0) {
const startPosition = goldCoins[0];
setAgentPosition({
x: startPosition.x - startPosition.x,
y: startPosition.y - startPosition.y,
});
}
setStep(goldCoins.length);
setOpisi(dataAgent.opisPutanja);
setCost(dataAgent.zbir);
setIsGameOver(true);
setIsGameInterrupted(false);
};
const handleSubmit = async () => {
setOpisi([]);
setCost(0);
setIsPaused(false);
setVisitedCoins([]);
setIsGameOver(false);
setIsStepByStepMode(false);
setCurrentSimulationStep(0);
setIsGameInterrupted(false);
setStep(0);
const data = {
mapContent: mapContent,
agentIndex: selectedAgent,
};
try {
const response = await axios.post(url, data);
setDataAgent(response.data.data);
dataAgent.opisPutanja = response.data.data.opisPutanja;
dataAgent.agent = response.data.data.agent;
dataAgent.agent.shift();
animateAgent(response.data.data.agent);
if (buttonRef.current) {
buttonRef.current.blur();
}
} catch (error) {
console.error("Došlo je do greške:", error);
}
};
/// razmak dogadjaj
useEffect(() => {
const handleKeyDown = (event) => {
event.preventDefault();
if (event.key === " ") {
setIsPaused((prev) => {
if (!prev) {
clearTimeout(animationTimeoutRef.current);
} else {
animateAgent(dataAgent.agent, currentStepRef.current - 1);
}
return !prev;
});
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isPaused, dataAgent]);
///S događaj
useEffect(() => {
const handleKeyDown = (event) => {
event.preventDefault();
if (isGameOver) {
return;
}
if (event.key === "s") {
setIsStepByStepMode((prev) => {
if (prev === false) {
clearTimeout(animationTimeoutRef.current);
} else if (prev === true) {
animateAgent(dataAgent.agent, currentStepRef.current - 1);
}
return !prev;
});
setShowSteps(!showSteps);
} else if (isStepByStepMode && event.key === "ArrowRight") {
// Logika za korak unapred
const nextStep = Math.min(
currentSimulationStep + 1,
dataAgent.agent.length - 1
);
animateAgent(dataAgent.agent, nextStep);
setCurrentSimulationStep(nextStep);
setStep(step + 1);
} else if (isStepByStepMode && event.key === "ArrowLeft") {
// Logika za korak unazad
const prevStep = Math.max(currentSimulationStep - 1, 0);
setCurrentSimulationStep(prevStep);
animateAgent(dataAgent.agent, prevStep);
setStep(step - 1);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [isStepByStepMode, currentSimulationStep, dataAgent]);
useEffect(() => {
if (isStepByStepMode) {
animateAgent(dataAgent.agent, currentSimulationStep);
}
}, [isStepByStepMode, currentSimulationStep, dataAgent]);
const animateAgent = (path, startStep = 0) => {
const moveAgent = (index) => {
currentStepRef.current = index;
if (index < path.length) {
if (path[index] < goldCoins.length) {
const nextPosition = goldCoins[path[index]];
if (nextPosition && "x" in nextPosition && "y" in nextPosition) {
createAgentAnimation(agentPosition, nextPosition);
setVisitedCoins((prev) => ({ ...prev, [path[index - 1]]: true }));
setAgentPosition({
x: nextPosition.x - goldCoins[0].x,
y: nextPosition.y - goldCoins[0].y,
});
let i = index;
const opis1 = dataAgent.opisPutanja[i];
if (!isStepByStepMode) {
setStep(step + 1);
}
setOpisi((opis) => [...opis, opis1]);
const delovi = opis1.split(":");
delovi[1] = delovi[1].trim();
if (!isNaN(delovi[1])) {
setCost((prev) => prev + parseFloat(delovi[1]));
}
if (index === path.length - 1) {
// Kada agent dođe do poslednjeg zlatnika
setIsGameOver(true);
}
currentStepRef.current = index + 1;
if (!isStepByStepMode) {
animationTimeoutRef.current = setTimeout(() => {
moveAgent(index + 1);
}, 2500);
}
} else {
console.error("Nevalidna pozicija zlatnika", nextPosition);
}
} else {
console.error("Indeks je van granica niza 'goldCoins'", path[index]);
}
}
if (index === path.length) {
setIsGameOver(true);
}
};
if (!isStepByStepMode) {
moveAgent(startStep);
} else {
moveAgent(currentSimulationStep);
}
};
const createAgentAnimation = (fromPosition, toPosition) => {
const keyframes = `
@keyframes moveAgent {
from {
left: ${fromPosition.x}px;
top: ${fromPosition.y}px;
}
to {
left: ${toPosition.x - goldCoins[0].x}px;
top: ${toPosition.y - goldCoins[0].y}px;
}
}
`;
const styleSheet = document.styleSheets[0];
if (styleSheet.cssRules.length > 0) {
styleSheet.deleteRule(0);
}
styleSheet.insertRule(keyframes, 0);
};
return (
<div className="App">
<h1 className="naziv">PUTNIK IGRA</h1>
<div className="agents">
<h1 className="izaberiAgenta">
AGENTI:
</h1>
<div
className={selectedAgent === "0" ? "selected-agent" : "agent"}
onClick={() => changeAgent("0", "Aki.png")}
>
<img src="Aki.png" alt="" />
<h3>Aki</h3>
</div>
<div
className={selectedAgent === "1" ? "selected-agent" : "agent"}
onClick={() => changeAgent("1", "Jocke.png")}
>
<img src="Jocke.png" alt="" />
<h3>Jocke</h3>
</div>
<div
className={selectedAgent === "2" ? "selected-agent" : "agent"}
onClick={() => changeAgent("2", "Uki.png")}
>
<img src="Uki.png" alt="" />
<h3>Uki</h3>
</div>
<div
className={selectedAgent === "3" ? "selected-agent" : "agent"}
onClick={() => changeAgent("3", "Micko.png")}
>
<img src="Micko.png" alt="" />
<h3>Micko</h3>
</div>
<div className="mapSelection">
<label htmlFor="mapSelection" ><b> MAPE: </b></label>
<select onChange={handleMapChange}>
<option value="map1">prva</option>
<option value="map2">druga</option>
<option value="map3">treca</option>
</select>
</div>
</div>
<div className="dugme">
<button ref={buttonRef} onClick={handleSubmit}>
ODABERI AGENTA I MAPU I PUSTI IGRU
</button>
</div>
<div className="mapa">
<div className="terrain">
<img src="terrain.png" alt="Terrain" />
{goldCoins.map((coin, index) => (
<div
key={index}
className="goldCoin"
style={{
left: coin.x + "px",
top: coin.y + "px",
backgroundColor: visitedCoins[index] ? "transparent" : "yellow",
color: visitedCoins[index] ? "red" : "black",
}}
>
{index === 0 ? (
<>
<img
className="slAgent"
src={agentImage}
alt="Agent"
style={{
position: "absolute",
left: agentPosition.x + "px",
top: agentPosition.y + "px",
animation: "moveAgent 2s",
transition: "all 2s",
}}
/>
<p>{index}</p>
</>
) : (
<p>{index}</p>
)}
</div>
))}
{showSteps && (
<p className="koraci">
Step: {step}/{goldCoins.length}
</p>
)}
{isPaused && visitedCoins.length !== goldCoins.length && (
<p className="pauza">PAUSED</p>
)}
{isGameOver && <p className="pauza">GAME OVER</p>}
</div>
<div className="data">
<h2>=====Steps=====</h2>
<div className="opisiPutanja">
{uniq(opisi).map((opis, index) => (
<div className="opis" key={index}>
{opis}
</div>
))}
</div>
<div>
<h2>
Cost:{" "}
{uniq(opisi)
.map((opis) => +opis.split(":")[1])
.reduce((a, b) => a + b, 0)}
</h2>
</div>
</div>
</div>
</div>
);
}
export default App; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.