text
stringlengths 184
4.48M
|
|---|
import React, { useContext, useEffect, useState } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import {
StructuredListWrapper,
StructuredListHead,
StructuredListRow,
StructuredListCell,
StructuredListBody,
ModalWrapper,
Loading,
InlineNotification,
} from "carbon-components-react";
import { ImageReference24 } from "@carbon/icons-react";
import { gql, useQuery, useMutation } from "@apollo/client";
import { GlobalContext } from "../../../../App.jsx";
const getImagesItems = (images = []) => {
const flattenImages = images.reduce((pre, cur) => {
const { attachment = {}, ...rest } = cur;
return [
...pre,
{
...rest,
attachmentId: attachment.id,
attachmentUid: attachment.uid,
cloudId: attachment.cloudId,
url: attachment.url,
}
];
}, []);
return flattenImages;
};
const Images = () => {
const ctx = useContext(GlobalContext);
const navigate = useNavigate();
const { user } = ctx;
const { uid } = useParams();
// getting the item for the images
const GET_REFERENCE_QUERY = gql`
query getOneReference (
$uid: String!
) {
getReference (
getOneReferenceInput: {
uid: $uid
}
) {
referenceAttachments {
main
version
attachment {
id
uid
cloudId
type
url
}
}
}
}
`;
const {
loading: referenceQueryLoading,
// error: referenceQueryError,
data: referenceQueryData,
} = useQuery(GET_REFERENCE_QUERY, {
variables: {
uid,
},
});
// define the state
const [images, setImages] = useState([]);
const [shouldClosePopUp, setShouldClosePopUp] = useState(false);
const [deletingImage, setDeletingImage] = useState(false);
// check if the user is logged in
// if not, redirect to login page
useEffect(() => {
if (!user) {
return navigate("/");
}
if (referenceQueryData) {
setImages(getImagesItems(referenceQueryData?.getReference?.referenceAttachments));
}
}, [user, navigate, referenceQueryData]);
// delete the image
const DELETE_REFERENCE_IMAGE_MUTATION = gql`
mutation deleteReferenceImage (
$referenceUid: String!
$attachmentUid: String!
) {
deleteReferenceImage (
deleteReferenceImageInput: {
referenceUid: $referenceUid,
attachmentUid: $attachmentUid
}
) {
id,
uid,
sku,
name,
description
}
}
`;
const [
deleteReferenceImage,
{
// data: deleteReferenceImageData,
// loading: deletingReferenceImageLoading,
error: deletingReferenceImageError,
}
] = useMutation(DELETE_REFERENCE_IMAGE_MUTATION);
const deleteImage = async (attachmentUid) => {
setDeletingImage(true);
await deleteReferenceImage({
variables: {
referenceUid: uid,
attachmentUid,
},
});
setImages(images.filter(image => image.attachmentUid !== attachmentUid));
setShouldClosePopUp(true);
setShouldClosePopUp(false);
setDeletingImage(false);
};
return (
<div className="bx--grid bx--grid--full-width bx--grid--no-gutter category_images-page">
<div className="bx--row category_images-page__r1">
<div className="bx--col-lg-16">
<div style={{ marginBottom: "1rem" }}>
<Link to={"/references"}>Back</Link>
<span> | </span>
<Link to={`/references/${uid}/images/create`}>Create image</Link>
</div>
{
referenceQueryLoading &&
<div style={{ width: "100%" }}>
<Loading
style={{ display: "table", margin: "0 auto" }}
description="Active loading indicator" withOverlay={false}
/>
</div>
}
{
referenceQueryData &&
<StructuredListWrapper ariaLabel="Structured list">
<StructuredListHead>
<StructuredListRow
head
tabIndex={0}
>
<StructuredListCell head>
Main image
</StructuredListCell>
<StructuredListCell head>
Version
</StructuredListCell>
<StructuredListCell head>
Show
</StructuredListCell>
</StructuredListRow>
</StructuredListHead>
<StructuredListBody>
{images.map((image, index) => (
<StructuredListRow tabIndex={0} key={index}>
<StructuredListCell>
{String(image.main)}
</StructuredListCell>
<StructuredListCell>
{image.version || "none"}
</StructuredListCell>
<StructuredListCell>
<ModalWrapper
renderTriggerButtonIcon={() => <ImageReference24 />}
buttonTriggerClassName="category_images-page__trigger-button"
triggerButtonKind="primary"
modalHeading="Image"
modalLabel="Label"
danger={true}
shouldCloseAfterSubmit={shouldClosePopUp}
preventCloseOnClickOutside={true}
handleSubmit={() => deleteImage(image.attachmentUid)}
primaryButtonText="Delete"
primaryButtonDisabled={deletingImage}
>
{
deletingReferenceImageError &&
<InlineNotification
kind="error"
iconDescription="close button"
subtitle={<span>{deletingReferenceImageError.message}</span>}
title="Uups!"
/>
}
<img
src={image.url}
alt="Carbon illustration"
/>
</ModalWrapper>
</StructuredListCell>
</StructuredListRow>
))}
</StructuredListBody>
</StructuredListWrapper>
}
</div>
</div>
</div>
);
};
export default Images;
|
import SwiftUI
import DesignComponents
struct WeatherSearchView<ViewModel: WeatherSearchViewModel>: View {
let componentsFactory: ComponentsFactory
@StateObject var viewModel: ViewModel
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationStack {
ZStack {
Colors.primaryBackgroundColor.ignoresSafeArea()
switch viewModel.state {
case .idle:
WeatherSearchIdleView(
componentsFactory: componentsFactory,
translations: viewModel.translations
)
.padding(.horizontal, 16)
case .loading:
WeatherSearchLoadingView()
case .error:
WeatherSearchErrorView(
componentsFactory: componentsFactory,
translations: viewModel.translations
)
.padding(.horizontal, 16)
case .empty:
WeatherSearchEmptyView(
componentsFactory: componentsFactory,
translations: viewModel.translations
)
.padding(.horizontal, 16)
case .data(let locations):
WeatherSearchDataView(
componentsFactory: componentsFactory,
locations: locations
) { location in
viewModel.locationTapped(location)
}
}
}
.navigationTitle(viewModel.translations.title)
.searchable(text: $viewModel.searchText)
.toolbar {
DismissButtonView(
componentsFactory: componentsFactory,
title: viewModel.translations.buttonTitle,
action: viewModel.dismissTapped
)
}
.onReceive(viewModel.dismissPublisher) { _ in
dismiss()
}
}
}
}
|
import { SubmitHandler, useForm } from "react-hook-form";
import { api } from "../../services/api";
import { ActionButton } from "../ActionButton";
import { Container, ButtonContainer } from "./styles";
interface DriverInfoProps {
name: string;
cnh: string;
address: string;
email: string;
phone: string;
licensePlate: string;
model: string;
year: string;
carMaker: string;
}
export function DriverInfo({
name,
cnh,
address,
email,
phone,
licensePlate,
model,
year,
carMaker
}: DriverInfoProps) {
const { register, handleSubmit } = useForm<DriverInfoProps>({
defaultValues: {
name: name,
cnh: cnh,
address: address,
email: email,
phone: phone,
licensePlate: licensePlate,
model: model,
year: year,
carMaker: carMaker
}
});
const onSubmit: SubmitHandler<DriverInfoProps> = async data => {
const driver = {
"cnh": data.cnh,
"name": data.name,
"address": data.address,
"email": data.email,
"phone": data.phone,
"licensePlate": data.licensePlate,
"model": data.model,
"year": data.year,
"carMaker": data.carMaker
}
const response = await api.patch(`drivers/${cnh}`, driver);
return response.data;
}
async function deleteDriver() {
console.log('entrou')
return await api.delete(`drivers/${cnh}`);
}
return (
<Container>
<h1>{name}</h1>
<form id="form" onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="cnh">Número da CNH</label>
<input defaultValue={cnh} placeholder="Digite o número da sua CNH" {...register("cnh")} />
</div>
<div>
<label htmlFor="name">Nome</label>
<input defaultValue={name} placeholder="Digite seu nome" {...register("name")} />
</div>
<div>
<label htmlFor="address">Endereço</label>
<input defaultValue={address} placeholder="Digite o seu endereço" {...register("address")} />
</div>
<div>
<label htmlFor="email">Email</label>
<input defaultValue={email} placeholder="Digite o seu email" type="email" {...register("email")} />
</div>
<div>
<label htmlFor="phone">Número do telefone</label>
<input defaultValue={phone} placeholder="Digite seu telefone" {...register("phone")} />
</div>
<div>
<label htmlFor="licensePlate">Placa do Carro</label>
<input defaultValue={licensePlate} placeholder="Digite o número da sua placa" {...register("licensePlate")} />
</div>
<div>
<label htmlFor="model">Modelo do Carro</label>
<input defaultValue={model} placeholder="Digite o modelo do seu carro" {...register("model")} />
</div>
<div>
<label htmlFor="year">Ano do Carro</label>
<input defaultValue={year} placeholder="Digite o ano do seu carro" {...register("year")} />
</div>
<div>
<label htmlFor="carMaker">Fabricante</label>
<input defaultValue={carMaker} placeholder="Digite o fabricante do seu carro" {...register("carMaker")} />
</div>
<ButtonContainer>
<ActionButton buttonTitle="editar" type="submit" />
<ActionButton buttonTitle="apagar" onClick={() => deleteDriver()} />
</ButtonContainer>
</form>
</Container>
);
}
|
import analyzeArray from "./analyzeArray";
test("result is an object with 4 required properties", () => {
expect(analyzeArray([1, 2])).toEqual(
expect.objectContaining({
average: expect.any(Number),
min: expect.any(Number),
max: expect.any(Number),
length: expect.any(Number),
})
);
});
test("[1]", () => {
expect(analyzeArray([1])).toEqual({
average: 1,
min: 1,
max: 1,
length: 1,
});
});
test("[1,2,3]", () => {
expect(analyzeArray([1, 2, 3])).toEqual({
average: 2,
min: 1,
max: 3,
length: 3,
});
});
test("[80,77,88,95,68]", () => {
expect(analyzeArray([80, 77, 88, 95, 68])).toEqual({
average: 81.6,
min: 68,
max: 95,
length: 5,
});
});
|
package com.n3wt0n.bbrm;
import java.util.Random;
import net.phys2d.raw.World;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.XMLPackedSheet;
import com.n3wt0n.G2DP.Entity;
import com.n3wt0n.G2DP.SoundWrapper;
public class Crate extends Entity {
private XMLPackedSheet sheet;
private Image initialImage;
protected int spriteNumber;
protected float xRender, yRender;
protected String currentState = "Init State";
protected int rotationAngle = 10;
protected boolean canJump = true;
public Crate(World world, int x, int y, int width, int height, float mass,
String name, SoundWrapper swrap) throws SlickException {
super(world, x, y, width, height, mass, name, swrap);
super.setSoundWrapper(swrap);
super.setFacingRight(true);
sheet = new XMLPackedSheet("media/images/creatures.png",
"media/images/creatures.png.xml");
Random rand = new Random(System.currentTimeMillis());
spriteNumber = 1+rand.nextInt(3);
init(sheet.getSprite("SmallCrate0" + spriteNumber + ".png"));
}
public void init(Image image) throws SlickException {
super.setImage(image);
initialImage = image;
}
public void flipBaseImage() {
// The static image that the hero is initialised as.
// It's important that the image is a "right facing" image.
// If it's not, then flip it using this method.
initialImage = initialImage.getFlippedCopy(true, false);
}
public void flipImage() {
// The method used for flipping the base image, so the hero can face
// left.
setImage(getImage().getFlippedCopy(true, false));
}
@Override
public void render(GameContainer gc, Graphics g) throws SlickException {
getImage().drawCentered(xRender, yRender);
}
@Override
public void preUpdate(int delta) {
// super.preUpdate(delta);
float theRot = getBody().getRotation();
getImage().setRotation((float) Math.toDegrees(theRot));
xRender = getBody().getPosition().getX();
yRender = getBody().getPosition().getY();
}
public String getState() {
return currentState;
}
public void setImage(String name) {
setImage(sheet.getSprite(name));
}
public int getSpriteNumber() {
return spriteNumber;
}
}
|
import React, {useState} from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import delRecipeAction from '../../config/redux/actions/delRecipeAction';
import {useDispatch} from 'react-redux';
function ModalDelRecipe({id}) {
const dispatch = useDispatch();
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const handleSubmit = (e) => {
e.preventDefault();
dispatch(delRecipeAction(id, setShow));
};
return (
<>
<Button variant="white" onClick={handleShow} className="mr-2">
Delete Recipe
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Delete</Modal.Title>
</Modal.Header>
<form onSubmit={handleSubmit}>
<Modal.Body>
<h3 className="text-danger text-center">Sure wanna delete this product? This action are permanent</h3>
</Modal.Body>
<Modal.Footer>
<Button variant="dark" onClick={handleClose}>
Close
</Button>
<Button type="submit" variant="warning">
Delete
</Button>
</Modal.Footer>
</form>
</Modal>
</>
);
}
export default ModalDelRecipe;
|
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UsersController extends Controller
{
public function create(Request $request){
// validate the form before submission
$request->validate([
'name' => 'required',
'email' => 'required | email',
'password' => 'required'
]);
// print_r($request->all()); // display the data in the form of assciative array
$data = new User();
$data->name = $request['name'];
$data->email = $request['email'];
$data->password = $request['password'];
$data->save();
return redirect('/userinfo');
}
public function userinfo(){
$userinfo = User::all(); // fetching data from database using model
// dd($userinfo); //prints the data in the form of array
$user_records = compact('userinfo');
return view('userinfo')->with($user_records);
}
public function userdel($id){
// echo $id;
$data = User::find($id);
// dd($data);
if(!is_null($data)){
$data->delete();
return redirect('/userinfo');
}else{
return redirect('/userinfo');
}
}
public function useredit($id){
$editdata = User::find($id);
// dd($editdata);
return view ('edituser')->with(compact('editdata'));
}
public function upd($id, Request $request){
$userdata = User::find($id);
$userdata->name = $request['name'];
$userdata->email = $request['email'];
$userdata->password = $request['password'];
$userdata->save();
return redirect ('/userinfo');
}
}
|
import React, { createContext, useState, useContext } from 'react';
// Define the shape of the user state
interface UserState {
user: any; // Define the type for user data
login: (userData: any) => void;
logout: () => void;
}
// Create the authentication context with a default value
const AuthContext = createContext<UserState>({
user: null,
login: () => {},
logout: () => {}
});
// Custom hook to consume the authentication context
export const useAuth = () => useContext(AuthContext);
// Provider component to wrap your application and provide the context
export const AuthProvider= ({ children} :any) => {
const [user, setUser] = useState<any>(null);
const login = (userData: any) => setUser(userData);
const logout = () => setUser(null);
// Value provided by the context
const value = {
user,
login,
logout
};
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
};
|
import React, {
ChangeEvent,
InputHTMLAttributes,
DetailedHTMLProps,
HTMLAttributes,
} from 'react'
import s from './SuperRadio.module.css'
import {logDOM} from '@testing-library/react';
type DefaultRadioPropsType = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
// тип пропсов обычного спана
type DefaultSpanPropsType = DetailedHTMLProps<
HTMLAttributes<HTMLSpanElement>,
HTMLSpanElement
>
type SuperRadioPropsType = Omit<DefaultRadioPropsType, 'type'> & {
options?: any[]
onChangeOption?: (option: any) => void
spanProps?: DefaultSpanPropsType // пропсы для спана
}
const SuperRadio: React.FC<SuperRadioPropsType> = ({
id,
name,
className,
options,
value,
onChange,
onChangeOption,
spanProps,
...restProps
}) => {
const onChangeCallback = (e: ChangeEvent<HTMLInputElement>) => {
onChange?.(e)
onChangeOption?.(+e.currentTarget.value)
}
const finalRadioClassName = s.radio + (className ? ' ' + className : '')
const spanClassName = s.span + (spanProps?.className ? ' ' + spanProps.className : '')
// console.log(value);
// console.log(options?.map(option => option.id === value));
const mappedOptions: any[] = options
? options.map((option) => (
<label key={name + '-' + option.id} className={s.label}>
<input
id={id + '-input-' + option.id}
className={finalRadioClassName}
type={'radio'}
name={name}
checked={option.id === value}
value={option.id}
// name, checked, value делают студенты
onChange={onChangeCallback}
{...restProps}
/>
<span
id={id + '-span-' + option.id}
{...spanProps}
className={spanClassName}
>
{option.value}
</span>
</label>
))
: []
return <div className={s.options}>{mappedOptions}</div>
}
export default SuperRadio
|
<template>
<div class="app-container">
<!-- 搜索 -->
<el-card>
<el-form
:inline="true"
:model="listQuery"
label-width="100px"
size="mini"
class="demo-form-inline"
>
<!-- <el-form-item label="用户信息:">
<el-input
v-model="listQuery.userinfo"
placeholder="请输入姓名/手机号"
class="filter-item"
clearable
size="mini"
@keyup.enter.native="handleFilter"
/>
</el-form-item> -->
<el-form-item label="日期:">
<el-date-picker
v-model="listQuery.querydate"
type="daterange"
value-format="yyyy-MM-dd"
:unlink-panels="true"
start-placeholder="开始时间"
end-placeholder="结束时间"
>
</el-date-picker>
</el-form-item>
<el-form-item label="类型:">
<el-radio-group
v-model="listQuery.type"
size="mini"
@change="selectStatus"
>
<!-- 1 添加 2 修改 3 删除 -->
<el-radio-button label>全部</el-radio-button>
<el-radio-button label="1">添加</el-radio-button>
<el-radio-button label="2">修改</el-radio-button>
<el-radio-button label="3">删除</el-radio-button>
<el-radio-button label="4">导出</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item>
<el-button
v-waves
size="mini"
type="primary"
class="starh_button"
@click="handleFilter"
>搜索</el-button
>
</el-form-item>
</el-form>
</el-card>
<!-- 列表 -->
<el-card style="margin-top: 20px">
<el-table
:key="tableKey"
v-loading="listLoading"
:data="list"
border
fit
highlight-current-row
style="width: 100%"
>
<el-table-column label="编号" type="index" align="center" width="80">
</el-table-column>
<el-table-column
label="操作"
align="center"
prop="title"
sortable
min-width="180px"
:show-overflow-tooltip="true"
/>
<el-table-column
label="账号"
align="center"
prop="op"
sortable
min-width="120px"
>
</el-table-column>
<el-table-column
label="操作类型"
align="center"
prop="type"
sortable
width="120"
>
<template slot-scope="{ row }">
<el-tag :type="row.type | typeFilter" size="small" effect="dark">{{
row.type | statusFilter
}}</el-tag>
</template>
</el-table-column>
<el-table-column
label="操作时间"
:show-overflow-tooltip="true"
align="center"
min-width="120px"
>
<template slot-scope="{ row }">
<span>{{ row.create_time }}</span>
</template>
</el-table-column>
<!-- <el-table-column label="操作" align="center" min-width="220">
<template slot-scope="{ row }">
<el-button type="primary" size="mini" @click="handleEdit(row)"
>编辑</el-button
>
<el-button type="warning" size="mini" @click="handledelorder(row)"
>删除</el-button
>
<el-button
type="danger"
:disabled="row.price <= 0 || row.status != 1"
size="mini"
@click="handleDel(row)"
>退款</el-button
>
</template>
</el-table-column> -->
</el-table>
</el-card>
<pagination
v-show="total > 0"
:total="total"
:page.sync="listQuery.page"
:limit.sync="listQuery.pageSize"
@pagination="getList"
/>
</div>
</template>
<script>
import { getLog } from "@/api/log";
import waves from "@/directive/waves"; // waves directive 123
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { getToken } from "@/utils/auth.js";
export default {
name: "getLog",
components: {
Pagination,
},
directives: {
waves,
},
filters: {
freeFilter(status) {
const statusMap = {
1: "免费",
2: "付费",
};
return statusMap[status];
},
sheheFilter(status) {
const statusMap = {
1: "需要",
2: "不需要",
};
return statusMap[status];
},
payFilter(status) {
// 1 公众号支付 2 余额支付 3 免费赠送 4 优惠券
const statusMap = {
1: "微信支付",
2: "余额支付",
3: "免费赠送",
4: "优惠券",
};
return statusMap[status];
},
// 状态: 1 自动,2 手动
// 1 添加 2 修改 3 删除
statusFilter(status) {
const statusMap = {
1: "添加",
2: "修改",
3: "删除",
4: "导出",
};
return statusMap[status];
},
// 状态: 1 自动,2 手动
topFilter(status) {
const statusMap = {
1: "已置顶",
2: "未置顶",
};
return statusMap[status];
},
// 状态颜色
typeFilter(status) {
const statusMap = {
1: "success",
2: "warning",
3: "info",
4: "danger",
5: "warning",
6: "success",
7: "info",
8: "danger",
};
return statusMap[status];
},
},
data() {
return {
dialoguploadorderVisible: false,
area_cardoptions: [],
autosize: { minRows: 10, maxRows: 30 },
iscoverloading: false,
isvideoloading: false,
uploadorderfileList: [],
headers: "",
dataObj: {
token: "",
key: "",
domain: "designvideo",
config: {
useCdnDomain: true,
},
},
baseUrl: "",
tableKey: 0,
list: null,
total: 0,
is_edit: false,
listLoading: false,
table: true,
status: "全部",
disabled: "false",
listQuery: {
page: 1,
type: "",
pageSize: 10,
querydate: "",
},
adverlist: [],
uploadform: {
card_id: "",
},
//导入文件
SelectCardlist: [],
dialogFormVisible: false,
dialogAddFormVisible: false,
imageloading: false,
};
},
watch: {
dialogAddFormVisible(newV, onlv) {
if (!newV) {
this.is_edit = false;
}
},
},
created() {
this.getList();
this.getSelectCard();
},
methods: {
handlenewherf(id) {
window.open("http://api.skyorange.cn/mpqq?id=" + id);
},
selectStatus() {
this.getList();
},
clipboardSuccess() {
this.$message({
message: "复制成功,请手机微信打开",
type: "success",
duration: 1500,
});
},
// 获取地点列表
getList() {
this.listLoading = true;
console.log(123);
getLog(this.listQuery).then((response) => {
this.listLoading = false;
let list = response.data.result;
this.list = list.map((item) => {
item["receive_time"] = parseTime(item["receive_time"]);
item["start_time"] = parseTime(item["start_time"]);
item["time_out"] = parseTime(item["time_out"]);
return item;
});
this.total = response.data.pageInfo.total;
});
},
handlestate() {
this.listQuery.title = this.listQuery.title || "";
this.getList();
},
//筛选过滤
handleFilter() {
this.getList();
},
},
};
</script>
|
package com.sunilos.spring;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* It will be used for JPA configuration
*
* @author Sunil Sahu
*
*/
// @Configuration
// @EnableTransactionManagement
public class JPAConfig {
@Autowired
private DriverManagerDataSource datasource = null;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(datasource);
em.setPackagesToScan(new String[] { "com.sunilos.spring" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
em.setJpaProperties(properties);
return em;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
|
import { createSlice } from "@reduxjs/toolkit";
import type { CartProductsType } from "@/clientComps/HomeState";
import type { PayloadAction } from "@reduxjs/toolkit";
import { RootState } from "@/store/store";
// function to get the carts from localstarage
const getInitialCartProducts = (): CartProductsType[] => {
if (typeof window !== "undefined") {
const localStorageCartProducts = localStorage.getItem("cart_products");
if (localStorageCartProducts !== null) {
return JSON.parse(localStorageCartProducts) as CartProductsType[];
} else {
return []
}
}
else {
return []
}
}
const getInitialTotal = (): number=> {
if (typeof window !== "undefined") {
const localStorageCartProducts = localStorage.getItem("total");
if (localStorageCartProducts !== null) {
return JSON.parse(localStorageCartProducts) as number;
} else {
return 0
}
}
else {
return 0
}
}
// cart initial state
const initialState = {
cartProducts: getInitialCartProducts(),
total: getInitialTotal(),
};
// slice for cart actions
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
addToCart: (state, action: PayloadAction<CartProductsType>) => {
state.cartProducts.push(action.payload);
const newTotal =
state.total + (action.payload.price * action.payload.quantity);
state.total = newTotal;
// checking if we are in a server component, if we aren't we store the data to local storage
if (typeof window !== "undefined") {
localStorage.setItem(
"cart_products",
JSON.stringify(state.cartProducts)
);
localStorage.setItem("total", JSON.stringify(state.total));
}
},
removeFromCart: (state, action: PayloadAction<CartProductsType>) => {
const filteredResult = state.cartProducts.filter(
(product) => product.id !== action.payload.id
);
state.cartProducts = filteredResult;
const newTotal =
state.total - (action.payload.price * action.payload.quantity);
state.total = newTotal;
// checking if we are in a server component, if we aren't we store the data to local storage
if (typeof window !== "undefined") {
localStorage.setItem(
"cart_products",
JSON.stringify(state.cartProducts)
);
localStorage.setItem("total", JSON.stringify(state.total));
}
},
addToSpecificCartProductQuantity: (state, action: PayloadAction<CartProductsType>) => {
const filteredResult = state.cartProducts.find(product => product.id === action.payload.id);
if (filteredResult) {
filteredResult.quantity += 1
state.total += filteredResult.price;
}
if (typeof window !== "undefined") {
localStorage.setItem(
"cart_products",
JSON.stringify(state.cartProducts)
);
localStorage.setItem("total", JSON.stringify(state.total));
}
},
subtractFromSpecificCartProductQuantity: (state, action: PayloadAction<CartProductsType>) => {
const filteredResult = state.cartProducts.find(
(product) => product.id === action.payload.id
);
if (filteredResult && filteredResult.quantity > 1) {
filteredResult.quantity -= 1;
state.total -= filteredResult.price;
}
if (typeof window !== "undefined") {
localStorage.setItem(
"cart_products",
JSON.stringify(state.cartProducts)
);
localStorage.setItem("total", JSON.stringify(state.total));
}
},
resetCart: (state) => {
state.cartProducts = [];
state.total = 0;
if (typeof window !== "undefined") {
localStorage.setItem(
"cart_products",
JSON.stringify(state.cartProducts)
);
localStorage.setItem("total", JSON.stringify(state.total));
}
}
},
});
export const { addToCart, removeFromCart, addToSpecificCartProductQuantity, subtractFromSpecificCartProductQuantity ,resetCart } =
cartSlice.actions;
// Other code such as selectors can use the imported `RootState` type
export const selectCart = (state: RootState) => state.cart.cartProducts;
export const selectCartTotal = (state: RootState) => state.cart.total;
export default cartSlice.reducer;
|
Что выведет программа? Объяснить вывод программы. Объяснить как работают defer’ы и их порядок вызовов.
```go
package main
import (
"fmt"
)
func test() (x int) {
defer func() {
x++
}()
x = 1
return
}
func anotherTest() int {
var x int
defer func() {
x++
}()
x = 1
return x
}
func main() {
fmt.Println(test())
fmt.Println(anotherTest())
}
```
Ответ:
```
defer - интсрумент отложенного вызова в языке го. defer позволяет отложить выполнение функции до того момента
как окружающая функция завершится. Так же стоит обратить внимание, что x подсчитывается до начала выполнения отложенной
операции. return x возвращает значение в момент вызова, defer запускается после return, но возвращаемое значение
вычисляется до выполнения оперции defer.
Значение, возвращаемое функцией anotherTest(), остается неизменным, несмотря на то что x увеличивается в defer.
В Go, функция может иметь именованные`test` или безымянные`anotherTest()`(или анонимные) возвращаемые значения.
Именованные возвращаемые значения могут быть изменены отложенными вызовами (defer), что и проиходит в test()
```
|
//
// ServiceAgreementsFilter.swift
// KarhooUISDK
//
// Created by Aleksander Wedrychowski on 16/06/2022.
// Copyright © 2022 Flit Technologies Ltd. All rights reserved.
//
import Foundation
import KarhooSDK
extension QuoteListFilters {
enum ServiceAgreements: String, QuoteListFilter, CaseIterable {
case freeCancelation = "free_cancellation"
case freeWatingTime = "free_waiting_time"
var filterCategory: QuoteListFilters.Category { .serviceAgreements }
var localizedString: String {
switch self {
case .freeCancelation:
return UITexts.Quotes.freeCancellation
case .freeWatingTime:
return UITexts.Quotes.freeWaitingTime
}
}
func conditionMet(for quote: Quote) -> Bool {
switch self {
case .freeCancelation:
return quote.serviceLevelAgreements?.serviceCancellation.type != .other(value: nil)
case .freeWatingTime:
return (quote.serviceLevelAgreements?.serviceWaiting.minutes ?? 0) > 0
}
}
}
}
|
package com.iuh.busgoo.entity;
import java.io.Serializable;
import java.time.LocalDate;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.iuh.busgoo.secirity.CustomUserDetail;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import lombok.Data;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Data
public class AbstractEntity implements Serializable{
private static final long serialVersionUID = 1L;
@CreatedDate
private LocalDate createdDate;
@CreatedBy
private String createdBy;
@LastModifiedDate
private LocalDate lastModifiedDate;
@LastModifiedBy
private String lastModifiedBy;
@PrePersist
protected void onCreate() {
createdDate = LocalDate.now();
createdBy = getCurrentUser();
}
@PreUpdate
protected void onUpdate() {
lastModifiedDate = LocalDate.now();
lastModifiedBy = getCurrentUser();
}
public String getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
CustomUserDetail currentUser = (CustomUserDetail) authentication.getPrincipal();
return currentUser.getAccount().getUser().getUserCode();
}
return "anonymous"; // Trả về một giá trị mặc định nếu không có ai được xác thực
}
}
|
---
created: 2024-06-10T13:59
updated: 2024-06-10T18:16
tags:
- TypeScript
- TypeScript/Generic
---
# Problem
```ts file:20.1-maybe.problem.ts
import { Equal, Expect } from "../helpers/type-utils";
type Maybe = unknown;
type tests = [
Expect<Equal<Maybe<string>, string | null | undefined>>,
Expect<Equal<Maybe<number>, number | null | undefined>>,
Expect<Equal<Maybe<boolean>, boolean | null | undefined>>,
Expect<Equal<Maybe<null>, null | undefined>>,
];
```
# Solution
```ts file:20.1-maybe.solution.ts fold
import { Equal, Expect } from "../helpers/type-utils";
type Maybe<T> = T | null | undefined;
type tests = [
Expect<Equal<Maybe<string>, string | null | undefined>>,
Expect<Equal<Maybe<number>, number | null | undefined>>,
Expect<Equal<Maybe<boolean>, boolean | null | undefined>>,
Expect<Equal<Maybe<null>, null | undefined>>,
];
```
|
import {signal} from '@preact/signals';
import type {ModContext, ModStorage} from 'melvor';
import type {TypedKeys} from 'mod-util/typed-keys';
import type {FunctionComponent} from 'preact/compat';
import {memo} from 'preact/compat';
import {useCallback, useMemo} from 'preact/hooks';
import {EMPTY_ARR} from '../../lib/util.mjs';
import useRefreshingRef from '../hooks/use-refreshing-ref.mjs';
export const enum ConfigCheckboxKey {
RM_WORKFLOW_ON_COMPLETE = 'rmWorkflowOnComplete',
}
interface Props {
configKey: ConfigCheckboxKey;
/** @default accountStorage */
storage?: TypedKeys<ModContext, ModStorage>;
}
const Component: FunctionComponent<Props> = ({children, configKey, storage}) => {
const checked$ = useMemo(() => signal(Boolean(ctx[storage!].getItem(configKey))), EMPTY_ARR);
const storageRef = useRefreshingRef(storage!);
const keyRef = useRefreshingRef(configKey);
const onInput = useCallback((e: Event) => {
const checked = (e.target as HTMLInputElement).checked;
const store = ctx[storageRef.current!];
if (checked) {
store.setItem(keyRef.current!, 1);
} else {
store.removeItem(keyRef.current!);
}
checked$.value = checked;
}, EMPTY_ARR);
return (
<label>
<input type={'checkbox'}
class={'mr-1'}
checked={checked$.value}
onChange={onInput}/>
<span class={'font-weight-normal'}>{children}</span>
</label>
);
};
Component.defaultProps = {storage: 'accountStorage'};
if (!process.env.PRODUCTION) {
Component.displayName = 'ConfigCheckbox';
}
export const ConfigCheckbox = memo(Component);
|
# Autore: Maurizio Paolini (2005)
# Licenza: GPL
#
# seguono alcune costruzioni basate sullo scripting python
# di 'kig' e l'interfaccia 'pykig.py' di Daniele Zambelli
# per operare con il modello del semipiano di Poincare'
#
# Le costruzioni particolari ottenute possono essere utilizzate
# per ottenere delle macro
#
# ROTAZIONE:
# la rotazione nel semipiano di Poincare' non e' ottenuta
scriptsegment='''def calc( arg1, arg2 ):
# Construct the hyperbolic segment (arc) connecting the two points
a=arg1.coordinate();
b=arg2.coordinate();
ax=a.x
ay=a.y
if ay < 0:
return InvalidObject()
bx=b.x
by=b.y
if by < 0:
return InvalidObject()
asq=ax*ax + ay*ay
bsq=bx*bx + by*by
den = 2*(bx - ax)
if den == 0:
return Segment(a,b)
x = (bsq - asq)/den
c = Coordinate(x,0)
rsq = asq + x*x - 2*x*ax
r = sqrt (rsq)
if rsq > 100000000*asq:
return Segment(a,b)
alfa = atan2(ay, ax-x)
beta = atan2(by, bx-x)
return Arc(c,r,alfa,beta-alfa)
'''
def HyperbolicSegment ( a, b ):
return PythonScript (scriptsegment, [a, b])
scriptline='''def calc( arg1, arg2 ):
# Construct the hyperbolic line (semicircle) through two points
a=arg1.coordinate();
b=arg2.coordinate();
ax=a.x
ay=a.y
if ay < 0:
return InvalidObject()
bx=b.x
by=b.y
if by < 0:
return InvalidObject()
asq=ax*ax + ay*ay
bsq=bx*bx + by*by
den = 2*(bx - ax)
if den == 0:
return Ray(Coordinate(ax,0.),b)
x = (bsq - asq)/den
c = Coordinate(x,0)
rsq = asq + x*x - 2*x*ax
r = sqrt (rsq)
if rsq > 100000*asq:
return Ray(Coordinate(ax,0.),b)
alfa = atan2(ay, ax-x)
beta = atan2(by, bx-x)
return Arc(c,r,0.,atan2(0.,-1.))
'''
def HyperbolicLine ( a, b ):
return PythonScript (scriptline, [a, b])
scriptcircle='''def calc( arg1, arg2 ):
# Construct the hyperbolic circle centered in arg1 through arg2
a=arg1.coordinate();
b=arg2.coordinate();
ax=a.x
ay=a.y
if ay < 0:
return InvalidObject()
bx=b.x
by=b.y
if by <= 0:
return InvalidObject()
asq=ax*ax + ay*ay
bsq=bx*bx + by*by
den = 2*(bx - ax)
num2 = bsq - asq - den*bx
dby2 = num2/by
dy = by - dby2/2.
d = Coordinate(ax,dy)
r2 = sqrt( den*den + dby2*dby2 )
return Circle(d,r2/2.)
'''
def HyperbolicCircle ( a, b ):
return PythonScript (scriptcircle, [a, b])
scriptlinebyvector='''def calc( arg1, arg2 ):
# Construct the hyperbolic line through arg1 and direction arg2
a=arg1.coordinate()
dir=arg2.dir()
ax=a.x
ay=a.y
if ay < 0:
return InvalidObject()
dirx=dir.x
diry=dir.y
cx=ax + ay*diry/dirx
r = sqrt ((cx-ax)*(cx-ax) + ay*ay)
c = Coordinate(cx,0.)
return Arc(c,r,0.,atan2(0.,-1.))
'''
scriptlineend1='''def calc( arg1 ):
# Construct the first endpoint of a line
if arg1.inherits( Ray.stype() ):
ld = arg1.data()
return Point( ld.a )
return Point (arg1.secondEndPoint())
'''
scriptlineend2='''def calc( arg1 ):
# Construct the second endpoint of a line
if arg1.inherits( Ray.stype() ):
return InvalidObject()
return Point (arg1.firstEndPoint())
'''
scriptsegmentdir1='''def calc( arg1, arg2 ):
# Construct the vector tangent in A to the hyp segment AB
# A (arg1) and B (arg2) are the two endpoints
a=arg1.coordinate();
b=arg2.coordinate();
ax=a.x
ay=a.y
if ay < 0:
return InvalidObject()
bx=b.x
by=b.y
if by < 0:
return InvalidObject()
asq=ax*ax + ay*ay
bsq=bx*bx + by*by
den = 2*(bx - ax)
if den == 0:
return Segment(a,b)
cx = (bsq - asq)/den
dirort = Coordinate( ay, cx - ax)
dirortnorm = dirort.length()
if den < 0:
dirortnorm = -dirortnorm
return Vector (a, a + dirort/dirortnorm)
'''
scriptcirclelineradical='''def calc( arg1, arg2 ):
if arg2.inherits( Ray.stype() ):
# by now...
line = Ray.data()
return Line(line)
a = arg1.center()
ax = a.x
ay = a.y
#return Point (a)
r1sq = arg1.squareRadius()
c = arg2.center()
cx = c.x
r2 = arg2.radius()
r2sq = r2*r2
dirx = ax - cx
diry = ay
if c.y != 0:
return InvalidObject()
num = r2sq - r1sq
dirsq = dirx*dirx + diry*diry
lam = num/(2*dirsq)
#lam = (ax*ax + ay*ay - cx*cx - r1sq + r2sq)/(2*((ax - cx)*(ax - cx) + ay*ay))
#lam = 0.5
mx = (ax + cx)/2
my = ay/2
dir = Coordinate(dirx, diry)
point = Coordinate (mx + lam*dirx, my + lam*diry)
dirort = Coordinate (-diry, dirx)
return Line (point, point + dirort)
#return Point (a)
'''
assoluto = Line(Point(-1.,0.,internal=True),Point(1.,0.,internal=True))
#
# ROTAZIONE del punto B attorno ad A di angolo "Angle".
# basata su una riflessione attorno all'asse verticale per A
# seguita da una inversione circolare rispetto ad un cerchio
# passante per A e centro sull'asse delle ascisse costruito in
# modo che l'angolo che forma in A rispetto all'asse verticale
# sia la meta' dell'angolo "Angle".
#
def HyperbolicRotation (B, A, Angle):
reflectionaxis = Orthogonal (assoluto, A, HIDDEN)
Breflected = AxialSymmetry (B, reflectionaxis, HIDDEN)
projection = LineLineIntersection (reflectionaxis, assoluto, HIDDEN)
rotatedprojection = Rotate (projection, A, Angle, HIDDEN)
# angleatA = Angle (projection, A, rotatedprojection)
# ... non proseguo in questo modo perche' al momento pykig non
# permette di costruire la bisettrice
pushdown = Vector (A, projection, HIDDEN)
pusheddown = Translate (rotatedprojection, pushdown, HIDDEN)
ltangent = Line (A, pusheddown, HIDDEN)
ortoline = Orthogonal (ltangent, A, HIDDEN)
inversioncenter = LineLineIntersection (ortoline, assoluto, HIDDEN)
inversioncircle = Circle (inversioncenter, A, HIDDEN)
return InvertPoint (Breflected, inversioncircle)
|
/*
* ************************************************************************************************
* * © 2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved. *
* ************************************************************************************************
*/
package com.qualcomm.qti.libraries.upgrade.data;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* A class to store the different states of a device for an ongoing upgrade process.
*/
public final class DeviceState {
/**
* The current step the device is at.
*/
private final AtomicReference<ResumePoint> resumePoint = new AtomicReference<>(ResumePoint.START);
/**
* To know if messages can be sent to the device.
*/
private final AtomicBoolean isTransportConnected = new AtomicBoolean(false);
/**
* To know the upgrade protocol version supported by the device.
*/
private final AtomicInteger protocolVersion = new AtomicInteger(0);
/**
* To know if the device supports silent commit.
*/
private final AtomicBoolean silentCommitSupport = new AtomicBoolean(false);
/**
* Empty constructor to build a new instance of this class.
*/
public DeviceState() {
}
/**
* To get the current step the device is at for the upgrade.
*/
public ResumePoint getResumePoint() {
return resumePoint.get();
}
/**
* To update the upgrade step the device is at.
*/
public void setResumePoint(ResumePoint point) {
this.resumePoint.set(point);
}
/**
* To know if messages can be sent to a device.
*/
public boolean isTransportConnected() {
return isTransportConnected.get();
}
/**
* To update the state of messages as processable.
* This method compares the expected state to the current value prior to set it.
* It returns True if the operation was successful: it means that the current value was the
* expected value and the current value is now the new value.
*/
public boolean setIsTransportConnected(boolean expected, boolean value) {
return isTransportConnected.compareAndSet(expected, value);
}
/**
* To know the upgrade protocol supported by the device.
*/
public int getProtocolVersion() {
return protocolVersion.get();
}
/**
* To set the upgrade protocol version that is supported by the device.
*/
public void setProtocolVersion(int version) {
protocolVersion.set(version);
}
/**
* To know if silent commit is supported by the device.
*/
public boolean isSilentCommitSupported() {
return silentCommitSupport.get();
}
/**
* To set the support of silent commit by the device.
*/
public void setSilentCommitSupport(boolean supported) {
silentCommitSupport.set(supported);
}
/**
* To reset all the states of a device.
*/
public void reset() {
setResumePoint(ResumePoint.START);
setIsTransportConnected(isTransportConnected(), false);
setProtocolVersion(0);
setSilentCommitSupport(false);
}
}
|
import React from 'react';
import Modal from '../UI/Modal/Modal';
import { IShipping } from '../../interfaces/shipping';
import styles from './ModalShippingDetails.module.scss';
import moment from 'moment';
import Currency from '../UI/Currency/Currency';
import ShippingDetail from './ShippingDetail';
import Button from '../UI/Button/Button';
type ModalShippingDetailsProps = {
data: IShipping | undefined;
show: boolean;
setShow: React.Dispatch<React.SetStateAction<boolean>>;
footer?: React.ReactNode;
};
export default function ModalShippingDetails({
data,
show,
setShow,
footer,
}: ModalShippingDetailsProps) {
return (
<Modal
className={styles.content__container}
show={show}
setShow={setShow}
footer={footer}
header={
<div className={`${styles.header}`}>
<Button variant='transparent' onClick={() => setShow(false)}>
X
</Button>
<h2 className={`${styles.title}`}>Shipping Details</h2>
</div>
}
>
<div>
<div className={`${styles.content__title}`}>
<h3>Recipient</h3>
</div>
<div className={`${styles.recipient}`}>
<h3>{data ? data.address.recipient_name : '-'}</h3>
<p className={`${styles.phone}`}>
{data ? data.address.recipient_phone : '-'}
</p>
</div>
<div>{data ? data.address.full_address : null}</div>
<div className={`${styles.content__title} ${styles.card__details}`}>
<h3>Details</h3>
</div>
<div className={`${styles.content__item}`}>
<p className={`${styles.content__item__title}`}>Order Date</p>
<p>{data ? moment(data.date).format('LL') : '-'}</p>
</div>
{data ? <ShippingDetail title='Size' data={data.size} /> : null}
{data ? <ShippingDetail title='Category' data={data.category} /> : null}
{data && data.add_on.length != 0 ? (
<ShippingDetail title='Add Ons' data={data.add_on} />
) : null}
<div className={`${styles.content__item}`}>
<p className={`${styles.content__item__title}`}>Total Cost</p>
<Currency
locales='en-ID'
currency='IDR'
value={data ? data.payment.total_cost : 0}
/>
</div>
{data && data.payment.status ? (
<>
<div className={`${styles.content__item}`}>
<p className={`${styles.content__item__title}`}>Total Discount</p>
<Currency
locales='en-ID'
currency='IDR'
value={data.payment.total_discount*-1}
/>
</div>
<div className={`${styles.content__item}`}>
<p className={`${styles.content__item__title}`}>Total Paid</p>
<Currency
locales='en-ID'
currency='IDR'
value={data.payment.record.amount*-1}
/>
</div>
</>
) : null}
</div>
</Modal>
);
}
|
import {MigrationInterface, QueryRunner, Table, TableColumn, TableForeignKey} from "typeorm";
export class createSensorDevice1623352139547 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(new Table({
name: 'SensorDevice',
columns:[
{
name: 'id',
type: 'integer',
unsigned: true,
isPrimary: true,
isGenerated: true,
generationStrategy: 'increment'
},
{
name:'key',
type: 'varchar'
},
{
name:'label',
type: 'varchar'
},
{
name:'description',
type: 'varchar'
}
]
}))
await queryRunner.addColumn("SensorDevice", new TableColumn({
name: "user_id",
type: "int"
}));
await queryRunner.createForeignKey("SensorDevice", new TableForeignKey({
columnNames: ["user_id"],
referencedColumnNames: ["id"],
referencedTableName: "User",
onDelete: "CASCADE"
}));
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('SensorDevice');
}
}
|
#include <iostream>
#include <vector>
#include <chrono>
int elementary_operations = 0;
void shellSort(std::vector<int>& arr) {
int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1};
elementary_operations += 1; // =
const int n = arr.size();
elementary_operations += 1; // =
for (int gap : gaps) {
elementary_operations += 1; // обращение к элементам массива
for (int i = gap; i < n; ++i) {
elementary_operations += 3; // = < ++
const int temp = arr[i];
elementary_operations += 1; // =
int j = i;
elementary_operations += 1; // =
for (; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
elementary_operations += 10; // = >= > && - -= и обращения к элементам массива
}
arr[j] = temp;
elementary_operations += 2; // = и обращение к элементам массива
}
}
}
int main(int argc, char* argv[]) {
std::vector<int> data;
for (int i = 2; i < argc; ++i) {
data.emplace_back(std::stoi(argv[i]));
}
auto start = std::chrono::high_resolution_clock::now();
shellSort(data);
auto elapsed = std::chrono::high_resolution_clock::now() - start;
int64_t nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count();
std::cout << nanoseconds << "\n";
int data_size = argc - 2;
for (int i = 0; i < data_size; ++i) {
std::cout << data[i] << "\t";
}
std::cout << elementary_operations;
return 0;
}
|
---
icon: material/store
---
# Gestionar proveedoras
Desde esta pantalla podrás gestionar las entidades proveedoras relacionadas con el Mercado que gestionas.
## Ver detalles de la proveedora
Para ver en detalle una proveedora, haz click en la fila de la proveedora que quieres consultar. Esto te llevará a otra
pantalla donde se muestran los detalles principales de la proveedora. Además desde esta pantalla podrás editar los datos
de la proveedora y añadir una ventaja.
## :fontawesome-solid-plus: Añadir proveedora
Haciendo click en el botón "Añadir nueva" accederás a la pantalla para añadir una nueva entidad proveedora.
En esta pantalla se te pedirán varios datos referentes a la proveedora divididas en las siguientes secciones:
### Información de la entidad
- Foto de perfil
- Nombre
- Email
- NIF/CIF/Pasaporte
- Número de socia
- Dirección postal
- Descripción
- Categorías a las que pertenece. [Ver cómo gestionar categorías](categorias.md)
- Número de personas trabajadoras
### Galería
- Fotografías de la proveedora
### Geolocalización
- Usa el mapa interactivo para colocar el pin en la localización donde se encuentra la proveedora.
Esta localización será visible en el mapa general de proveedoras.
### Visibilidad
- Oculta en listado público
- Activa
### Redes sociales
- Enlaces de la entidad a distintas redes sociales, incluyendo enlace a la página web.
/// admonition | Redes sociales admitidas
type: info
Actualmente, las redes sociales admitidas son: Facebook, Fediverso, Instagram, LinkedIn, Pinterest,
Telegram, TikTok, Whatsapp, X, Youtube.
///
### Crear usuaria asociada a la proveedora
{ align=right width=50% loading=lazy}
Cuando creamos una entidad proveedora tenemos la opción de crear paralelamente una cuenta de usuaria.
Si seleccionas esta opción, se enviará automáticamente un correo a la dirección de email de la proveedora,
desde el cual podrá crear una contraseña para acceder a la aplicación móvil.
Si no seleccionamos la opción podremos enviar el mail de prerregistro más adelante.
Una vez rellenados los campos obligatorios, pulsa el botón "Crear entidad" para crear la entidad proveedoras.
## :fontawesome-solid-pen: Editar proveedora
Para editar una proveedora puedes hacer click en la fila correspondiente a la usuaria que se quiera editar, o haciendo
click en el icono :material-pencil:.
En esta pantalla podrás modificar la información de la proveedora y pulsar el botón "Guardar cambios" cuando estés satisfecha.
## :material-basket: Consultar ofertas de la proveedora
Para consultar las ofertas de una provedora puedes hacer click en el icono :material-basket: que se encuentra en la fila
de la provedora de la que quieres consultar las ofertas.
## :fontawesome-solid-trash: Eliminar proveedora
Para eliminar una proveedora ponte en contacto con el equipo de administración.
|
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="@color/white"
tools:context=".Authentication.RegistrationActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Регистрация"
android:textColor="@color/black"
android:textSize="40dp"
android:layout_marginTop="30dp"
android:textStyle="bold">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Зарегистрируйте новый аккаунт"
android:textColor="@color/black"
android:textSize="16dp"
android:textStyle="bold">
</TextView>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/tit_phone"
style="@style/Widget.Material3.TextInputEditText.OutlinedBox"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:hint="Введите свое ФИО"
app:boxBackgroundMode="outline"
app:endIconMode="clear_text">
<EditText
android:id="@+id/text_fio"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
android:maxLines="1">
</EditText>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/tit_fio"
style="@style/Widget.Material3.TextInputEditText.OutlinedBox"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:hint="Введите номер телефона"
app:boxBackgroundMode="outline"
app:endIconMode="clear_text">
<com.santalu.maskara.widget.MaskEditText
android:id="@+id/text_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:mask="+7 ___ ___ __ __"
app:maskCharacter="_"
android:inputType="number"
android:maxLines="1">
</com.santalu.maskara.widget.MaskEditText>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/tit_email"
style="@style/Widget.Material3.TextInputEditText.OutlinedBox"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:hint="E-mail"
app:boxBackgroundMode="outline"
app:endIconMode="clear_text"
app:helperText="">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/text_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:maxLines="1">
</com.google.android.material.textfield.TextInputEditText>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/tit_password"
style="@style/Widget.Material3.TextInputEditText.OutlinedBox.Dense"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:hint="Пароль"
app:boxBackgroundMode="outline"
app:counterEnabled="true"
app:counterMaxLength="20"
app:endIconMode="password_toggle">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/text_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="20"
android:inputType="textPassword">
</com.google.android.material.textfield.TextInputEditText>
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/regUser"
android:layout_width="330dp"
android:layout_height="50dp"
android:text="Зарегистрировать"
android:textSize="18dp"
android:textStyle="bold"
android:layout_gravity="center"
android:textColor="@color/white"
android:background="@drawable/gradient"
android:layout_marginTop="10dp"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp">
</Button>
<TextView
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Есть аккаунт? Войдите"
android:textColor="@color/black"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:textSize="18dp"
android:textStyle="bold">
</TextView>
</LinearLayout>
|
<script>
import Flatpickr from "svelte-flatpickr"
import "flatpickr/dist/flatpickr.css"
import "@spectrum-css/inputgroup/dist/index-vars.css"
import "@spectrum-css/textfield/dist/index-vars.css"
import "@spectrum-css/picker/dist/index-vars.css"
import { createEventDispatcher } from "svelte"
import { uuid } from "../../helpers"
export let id = null
export let disabled = false
export let error = null
export let enableTime = true
export let value = null
export let placeholder = null
export let appendTo = undefined
export let timeOnly = false
const dispatch = createEventDispatcher()
const flatpickrId = `${uuid()}-wrapper`
let open = false
let flatpickr, flatpickrOptions, isTimeOnly
$: isTimeOnly = !timeOnly && value ? !isNaN(new Date(`0-${value}`)) : timeOnly
$: flatpickrOptions = {
element: `#${flatpickrId}`,
enableTime: isTimeOnly || enableTime || false,
noCalendar: isTimeOnly || false,
altInput: true,
altFormat: isTimeOnly ? "H:i" : enableTime ? "F j Y, H:i" : "F j, Y",
wrap: true,
appendTo,
disableMobile: "true",
}
const handleChange = event => {
const [dates] = event.detail
let newValue = dates[0]
if (newValue) {
newValue = newValue.toISOString()
}
// if time only set date component to today
if (timeOnly) {
const todayDate = new Date().toISOString().split("T")[0]
newValue = `${todayDate}T${newValue.split("T")[1]}`
}
dispatch("change", newValue)
}
const clearDateOnBackspace = event => {
if (["Backspace", "Clear", "Delete"].includes(event.key)) {
dispatch("change", null)
flatpickr.close()
}
}
const onOpen = () => {
open = true
document.addEventListener("keyup", clearDateOnBackspace)
}
const onClose = () => {
open = false
document.removeEventListener("keyup", clearDateOnBackspace)
// Manually blur all input fields since flatpickr creates a second
// duplicate input field.
// We need to blur both because the focus styling does not get properly
// applied.
const els = document.querySelectorAll(`#${flatpickrId} input`)
els.forEach(el => el.blur())
}
const parseDate = val => {
if (!val) {
return null
}
let date
let time = new Date(`0-${val}`)
// it is a string like 00:00:00, just time
if (timeOnly || (typeof val === "string" && !isNaN(time))) {
date = time
} else if (val instanceof Date) {
// Use real date obj if already parsed
date = val
} else if (isNaN(val)) {
// Treat as date string of some sort
date = new Date(val)
} else {
// Treat as numerical timestamp
date = new Date(parseInt(val))
}
time = date.getTime()
if (isNaN(time)) {
return null
}
// By rounding to the nearest second we avoid locking up in an endless
// loop in the builder, caused by potentially enriching {{ now }} to every
// millisecond.
return new Date(Math.floor(time / 1000) * 1000)
}
</script>
{#key isTimeOnly}
<Flatpickr
bind:flatpickr
value={parseDate(value)}
on:open={onOpen}
on:close={onClose}
options={flatpickrOptions}
on:change={handleChange}
element={`#${flatpickrId}`}
>
<div
id={flatpickrId}
class:is-disabled={disabled}
class:is-invalid={!!error}
class="flatpickr spectrum-InputGroup spectrum-Datepicker"
class:is-focused={open}
aria-readonly="false"
aria-required="false"
aria-haspopup="true"
>
<div
on:click={flatpickr?.open}
class="spectrum-Textfield spectrum-InputGroup-textfield"
class:is-disabled={disabled}
class:is-invalid={!!error}
>
{#if !!error}
<svg
class="spectrum-Icon spectrum-Icon--sizeM spectrum-Textfield-validationIcon"
focusable="false"
aria-hidden="true"
>
<use xlink:href="#spectrum-icon-18-Alert" />
</svg>
{/if}
<input
data-input
type="text"
{disabled}
class="spectrum-Textfield-input spectrum-InputGroup-input"
{placeholder}
{id}
{value}
/>
</div>
<button
type="button"
class="spectrum-Picker spectrum-Picker--sizeM spectrum-InputGroup-button"
tabindex="-1"
{disabled}
class:is-invalid={!!error}
on:click={flatpickr?.open}
>
<svg
class="spectrum-Icon spectrum-Icon--sizeM"
focusable="false"
aria-hidden="true"
aria-label="Calendar"
>
<use xlink:href="#spectrum-icon-18-Calendar" />
</svg>
</button>
</div>
</Flatpickr>
{/key}
{#if open}
<div class="overlay" on:mousedown|self={flatpickr?.close} />
{/if}
<style>
.spectrum-Textfield-input {
pointer-events: none;
}
.spectrum-Textfield:not(.is-disabled):hover {
cursor: pointer;
}
.flatpickr {
width: 100%;
overflow: hidden;
}
.flatpickr .spectrum-Textfield {
width: 100%;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 999;
}
:global(.flatpickr-calendar) {
font-family: "Source Sans Pro", sans-serif;
}
</style>
|
// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.0 < 0.9.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract WarriorsOfUkraine is ERC1155, Ownable, ReentrancyGuard {
using Strings for uint256;
string public name = "Warriors Of Ukraine";
string public symbol = "WOU";
string public baseURI = "ipfs://QmbZvhhxXDDm9BqRfGqM4bFS8htGnQSBFWaUGWmxTkkjCo/";
uint private counter;
uint public supply;
uint256 public constant PRICE = 0.05 ether;
uint32 public constant ARTWORK = 24;
uint32 public constant SUPPLY_MAX = 12001;
constructor() ERC1155(baseURI) {
for (uint i=1; i<26; i++) {
_mint(msg.sender, i, 1, "");
}
}
function mint(uint32 quantity) external payable nonReentrant {
require(quantity > 0, "Quantity needs to be more than 0.");
require(msg.value >= PRICE * quantity, "Insufficient eth sent.");
require(supply + quantity <= SUPPLY_MAX, "Exceeds the maximum allowed supply.");
supply += quantity;
uint i;
for (i=0; i<quantity; i++) {
uint tkId = (counter % ARTWORK) + 1; // Equal distribution.
_mint(msg.sender, tkId, 1, "");
counter++;
}
}
function mintForAddress(
address to,
uint32 id,
uint32 quantity
) external onlyOwner {
supply += quantity;
_mint(to, id, quantity, "");
}
function batchMintForAddress(
address[] calldata to,
uint32 id,
uint256[] calldata quantity
) external onlyOwner {
uint i;
for (i=0; i<quantity.length; i++) {
supply += quantity[i];
_mint(to[i], id, quantity[i], "");
}
}
function setURI(string memory _uri) external onlyOwner {
baseURI = _uri;
}
function uri(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseURI, _tokenId.toString(), ".json"));
}
function withdraw() external onlyOwner {
payable(address(0x165CD37b4C644C2921454429E7F9358d18A45e14)).transfer(address(this).balance * 95/100); // 95% to Ukraine Crypto Wallet.
payable(msg.sender).transfer(address(this).balance); // Remaining 5% to the Artists.
}
}
|
#include "main_menu.hpp"
#include "imgui/imgui.h"
#include "sokol/sokol_app.h"
#include <math.h>
#include <filesystem>
#include <stdio.h>
#include "util.hpp"
void show_file_list(MainMenu *main_menu, ImVec2 size)
{
if (ImGui::BeginListBox("##File List", size)) {
int i = 0;
for (auto &file : main_menu->files) {
if (ImGui::Selectable(file.c_str(), main_menu->file_selected == i)) {
main_menu->file_selected = i;
}
i++;
}
ImGui::EndListBox();
}
}
void synchronize_file_list(MainMenu *main_menu)
{
main_menu->file_selected = 0;
main_menu->files = {};
for (const auto &entry : std::filesystem::directory_iterator(main_menu->directory_path)) {
main_menu->files.push_back(entry.path().filename().generic_string());
}
}
std::string get_selected_file_filename(MainMenu *main_menu)
{
return main_menu->files[main_menu->file_selected];
}
void remove_selected_file(MainMenu *main_menu)
{
if (main_menu->files.size() > 0) {
std::filesystem::remove(main_menu->directory_path / get_selected_file_filename(main_menu));
synchronize_file_list(main_menu);
}
}
void create_file(MainMenu *main_menu, const char *filename)
{
if (filename[0] == 0) {
return;
}
auto path = (main_menu->directory_path / filename).string();
FILE *f = fopen(path.c_str(), "wb");
fclose(f);
synchronize_file_list(main_menu);
}
void open_selected_file(MainMenu *main_menu, OpenProject *project)
{
project->path = (main_menu->directory_path / get_selected_file_filename(main_menu)).string();
project->is_open = true;
}
void host_selected_file(MainMenu *main_menu, OpenProject *project)
{
open_selected_file(main_menu, project);
project->host_name = main_menu->host_name;
project->hosting_type = HostingType::HOST;
}
void join_selected_ip(MainMenu *main_menu, OpenProject *project)
{
project->host_name = main_menu->host_name;
project->hosting_type = HostingType::JOIN;
}
MainMenu MainMenu::init(std::filesystem::path directory_path)
{
MainMenu menu = {};
menu.directory_path = directory_path;
synchronize_file_list(&menu);
return menu;
}
bool MainMenu::show(OpenProject *project)
{
bool opened = false;
center_next_window({400, 300});
if (ImGui::Begin("Main Menu v1")) {
show_file_list(this, {200, 240});
float y = 45;
ImGui::SetCursorPos({230, y});
ImGui::SetNextItemWidth(150);
ImGui::InputTextWithHint("##Host", "Host", this->host_name, MENU_STRING_SIZE);
y += 40;
ImGui::SetCursorPos({230, y});
ImGui::SetNextItemWidth(150);
ImGui::InputTextWithHint("##File Name", "File Name", this->file_name, MENU_STRING_SIZE);
y += 40;
ImGui::SetCursorPos({230, y});
if (ImGui::Button("Host", {150/2-5, 30})) {
host_selected_file(this, project);
opened = true;
}
ImGui::SetCursorPos({230+150/2+5, y});
if (ImGui::Button("Join", {150/2-5, 30})) {
join_selected_ip(this, project);
opened = true;
}
y += 40;
ImGui::SetCursorPos({230, y});
if (ImGui::Button("Create", {150, 30})) {
create_file(this, this->file_name);
this->file_name[0] = 0;
}
y += 40;
ImGui::SetCursorPos({230, y});
if (ImGui::Button("Open", {150, 30})) {
open_selected_file(this, project);
opened = true;
}
y += 40;
ImGui::SetCursorPos({230, y});
if (ImGui::Button("Remove", {150, 30})) {
remove_selected_file(this);
}
}
ImGui::End();
return opened;
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Moq;
using System.Text;
using UserApi.Controllers;
using UserApi.Models;
using UserApi.Service;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace LoginUnitTest
{
public class LoginTest
{
Mock<ILoginService> _loginMockService;
public LoginTest()
{
_loginMockService = new Mock<ILoginService>();
}
[Fact]
public void LoginFails_ByEmptyField()
{
UserLogin user = new UserLogin()
{
emailid = "",
password = ""
};
_loginMockService.Setup(x =>x.LoginDb(user.emailid,user.password)).Returns("User field is empty");
var loginController=new LoginController(_loginMockService.Object);
var errorResult = loginController.Login(user);
Assert.IsType<BadRequestObjectResult>(errorResult);
var data = errorResult as BadRequestObjectResult;
Assert.Equal("User field is empty", data.Value);
}
[Fact]
public void LoginFails_ByInvalidEmailFormat()
{
UserLogin user = new UserLogin()
{
emailid = "brin123.com",
password = "test123"
};
_loginMockService.Setup(x => x.LoginDb(user.emailid, user.password)).Returns("Invalid email format");
var loginController = new LoginController(_loginMockService.Object);
var errorResult = loginController.Login(user);
Assert.IsType<BadRequestObjectResult>(errorResult);
var data = errorResult as BadRequestObjectResult;
Assert.Equal("Invalid email format", data.Value);
}
[Fact]
public void LogicFails_ByIncorrectCredentials()
{
UserLogin user = new UserLogin()
{
emailid = "kas123@gmail.com",
password = "password"
};
_loginMockService.Setup(x => x.LoginDb(user.emailid, user.password)).Returns("Invalid Username or Password");
var loginController = new LoginController(_loginMockService.Object);
var errorResult = loginController.Login(user);
Assert.IsType<BadRequestObjectResult>(errorResult);
var data = errorResult as BadRequestObjectResult;
Assert.Equal("Invalid Username or Password", data.Value);
}
[Fact]
public void LoginSuccess()
{
UserLogin user = new UserLogin()
{
emailid= "kas123@gmail.com",
password= "acb@123"
};
_loginMockService.Setup(x => x.LoginDb(user.emailid, user.password)).Returns("Login Success");
var loginController = new LoginController(_loginMockService.Object);
var errorResult = loginController.Login(user);
Assert.IsType<OkObjectResult>(errorResult);
var data=errorResult as OkObjectResult;
Assert.Equal("Login Success", data.Value);
}
}
}
|
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var lat;
var lng
function getValue(data){
fetch("reques_api.php?location="+data.value)
.then((resp) => resp.json())
.then(function (data) {
document.getElementById("places").innerHTML = ""
lat = data.lat
lng = data.lng
setTimeout(initMap(lat,lng),1000)
})
.catch(function (error) {
console.log(error);
});
}
function initMap(lat,lng) {
var pyrmont = { lat:lat, lng:lng };
const map = new google.maps.Map(document.getElementById("map"), {
center: pyrmont,
zoom: 17,
mapId: "8d193001f940fde3",
});
// Create the places service.
const service = new google.maps.places.PlacesService(map);
let getNextPage;
const moreButton = document.getElementById("more");
moreButton.onclick = function () {
moreButton.disabled = true;
if (getNextPage) {
getNextPage();
}
};
// Perform a nearby search.
service.nearbySearch(
{ location: pyrmont, radius: 500, type: ['atm'] },
(results, status, pagination) => {
if (status !== "OK" || !results) return;
console.log(results)
addPlaces(results, map);
moreButton.disabled = !pagination || !pagination.hasNextPage;
if (pagination && pagination.hasNextPage) {
getNextPage = () => {
// Note: nextPage will call the same handler function as the initial call
pagination.nextPage();
};
}
}
);
}
function addPlaces(places, map) {
const placesList = document.getElementById("places");
for (const place of places) {
if (place.geometry && place.geometry.location) {
const image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25),
};
new google.maps.Marker({
map,
icon: image,
title: place.name,
position: place.geometry.location,
});
const li = document.createElement("li");
const p = document.createElement("p");
li.textContent = place.name;
p.textContent = place.vicinity;
placesList.appendChild(li,p);
li.addEventListener("click", () => {
map.setCenter(place.geometry.location);
});
}
}
}
|
---
product-area: projects
navigation-topic: update-work-in-a-project
title: Percentage van voltooiing weergeven en bijwerken voor taken
description: U kunt het percentage van voltooiing van een taak bijwerken om de vooruitgang aan te geven die u op de taak hebt gemaakt om het te voltooien.
author: Alina
feature: Work Management
exl-id: e53bca4d-1ed3-4e4d-8a35-217529a246dc
source-git-commit: b02c81873d84946f8db54bcf9a1a464de38781de
workflow-type: tm+mt
source-wordcount: '552'
ht-degree: 0%
---
# Percentage van voltooiing weergeven en bijwerken voor taken
U kunt het percentage van voltooiing van een taak bijwerken om de vooruitgang aan te geven die u op de taak hebt gemaakt om het te voltooien.
## Toegangsvereisten
<!--drafted for P&P:
<table style="table-layout:auto">
<col>
<col>
<tbody>
<tr>
<td role="rowheader">Adobe Workfront plan*</td>
<td> <p>Any</p> </td>
</tr>
<tr>
<td role="rowheader">Adobe Workfront license*</td>
<td> <p>Current license: Standard</p>
Or
<p>Legacy license: Work or higher</p>
</td>
</tr>
<tr>
<td role="rowheader">Access level configurations*</td>
<td> <p>Edit access to Tasks</p> <p><b>NOTE</b>
If you still don't have access, ask your Workfront administrator if they set additional restrictions in your access level. For information on how a Workfront administrator can modify your access level, see <a href="../../../administration-and-setup/add-users/configure-and-grant-access/create-modify-access-levels.md" class="MCXref xref">Create or modify custom access levels</a>.</p> </td>
</tr>
<tr>
<td role="rowheader">Object permissions</td>
<td> <p>Manage permissions to the task</p> <p>For information on requesting additional access, see <a href="../../../workfront-basics/grant-and-request-access-to-objects/request-access.md" class="MCXref xref">Request access to objects </a>.</p> </td>
</tr>
</tbody>
</table>
-->
U moet de volgende toegang hebben om taken handmatig bij te werken:
<table style="table-layout:auto">
<col>
<col>
<tbody>
<tr>
<td role="rowheader">Adobe Workfront-abonnement*</td>
<td> <p>Alle</p> </td>
</tr>
<tr>
<td role="rowheader">Adobe Workfront-licentie*</td>
<td> <p>Werk of hoger</p> </td>
</tr>
<tr>
<td role="rowheader">Configuraties op toegangsniveau*</td>
<td> <p>Toegang tot taken bewerken</p> <p><b>OPMERKING</b>
Als u nog steeds geen toegang hebt, vraagt u de Workfront-beheerder of deze aanvullende beperkingen op uw toegangsniveau instelt. Voor informatie over hoe een beheerder van Workfront uw toegangsniveau kan wijzigen, zie <a href="../../../administration-and-setup/add-users/configure-and-grant-access/create-modify-access-levels.md" class="MCXref xref">Aangepaste toegangsniveaus maken of wijzigen</a>.</p> </td>
</tr>
<tr>
<td role="rowheader">Objectmachtigingen</td>
<td> <p>Rechten voor de taak beheren</p> <p>Voor informatie over het aanvragen van aanvullende toegang raadpleegt u <a href="../../../workfront-basics/grant-and-request-access-to-objects/request-access.md" class="MCXref xref">Toegang tot objecten aanvragen </a>.</p> </td>
</tr>
</tbody>
</table>
*Neem contact op met uw Workfront-beheerder om te weten te komen welk plan, licentietype of toegang u hebt.
## Gebieden waar u het percentage van voltooiing van een taak kunt bijwerken
U kunt het voltooide percentage voor een taak op een van de volgende gebieden bijwerken:
* **In een takenlijst**: U kunt het voltooide percentage van een taak bijwerken wanneer de kolom Percentage voltooid wordt weergegeven.\
Zie voor meer informatie over inline bewerken [Items inline bewerken in een lijst in Adobe Workfront](../../../workfront-basics/navigate-workfront/use-lists/inline-edit-objects.md).
* **In de milestone-weergave**: U kunt het percentage bijwerken voltooide van een taak wanneer het gebruiken van de mening van de Mijlpaal op een projectlijst of een projectrapport. Zie voor meer informatie [De milestone-weergave gebruiken](../../../reports-and-dashboards/reports/reporting-elements/use-milestone-view.md).
* **Terwijl u de taak bijwerkt**: U kunt de optie voor het percentage van een taak bijwerken wanneer u een update aan de taak toevoegt.
>[!IMPORTANT]
>
>Deze optie wordt alleen weergegeven nadat u de optie Percentage tonen hebt ingeschakeld.\
>Ga als volgt te werk om het percentage van de volledige updatebalk voor taken in te schakelen:
>
>1. Ga naar de **Hoofd** menu>uw naam>**Meer** pictogram naast uw naam >**Bewerken** > selecteren **Percentage volledig tonen bij updatestatus**.\
> >
* **In de taakkoptekst**: U kunt het percentage van een taak bijwerken in de taakkoptekst. Zie voor meer informatie [Taken bewerken](../../tasks/manage-tasks/edit-tasks.md).

## Overwegingen bij het bijwerken van het percentage voltooide taken
* Wanneer u een taak markeert als 100% voltooid, wordt de taakstatus bijgewerkt naar Voltooid.
* De volgende scenario's bestaan voor oudertaken:
* U kunt niet het percentage bijwerken volledig van een oudertaak aan 100% wanneer de Summiere Wijze van de Voltooiing van het project aan Automatisch wordt geplaatst en de subtaken niet worden voltooid.
* U kunt het percentage volledig van een oudertaak aan 100% bijwerken wanneer de Summiere Wijze van de Voltooiing van het project aan Handboek wordt geplaatst en subtaken worden voltooid of onvolledig.
Zie voor meer informatie [Projecten bewerken](../manage-projects/edit-projects.md).
## Het percentage van een taak bijwerken
1. Ga naar een van de volgende gebieden in Workfront:
* Een takenlijst
* Een lijst met projecten en past de Mijlpaal-weergave toe
* Een taak, door tot de taakpagina toegang te hebben
1. Zoek de **Percentage voltooid** veld voor de taak waarvan het percentage is voltooid dat u wilt bijwerken.
1. Klik in het veld Percentage voltooid en typ een getal tussen 0 en 100
of
Klik en sleep de **Percentage voltooid** bar aan het noodzakelijke aantal om te wijzen op hoeveel van de taak u voltooide.
>[!NOTE]
>
>Als u aangeeft dat 100% van de taak is voltooid, wordt de status van de taak ook bijgewerkt naar Voltooien.
1. Druk op Enter op het toetsenbord om het volledige percentage op te slaan.
|
<script setup lang="ts">
import { onMounted, inject } from 'vue'
// Basic UI Stuff
import InputDialog from './components/InputDialog.vue'
import Clipboard from './components/Clipboard.vue'
import Modal from './components/Modal.vue'
import SimpleAction from './components/SimpleAction.vue'
import Menu from './components/Menu.vue'
import ProgressBar from './components/ProgressBar.vue'
import ProgressCircle from './components/ProgressCircle.vue'
import KbdAction from './components/KbdAction.vue'
import Instruction from './components/Instruction.vue'
import Incidators from './components/Incidators.vue'
import Compass from './components/Compass.vue'
import VehicleIndicators from './components/VehicleIndicators.vue'
import Context from './components/Context.vue'
import Notifications from './components/Notifications.vue'
// Minigames
import CombinationMinigame from './components/CombinationMinigame.vue'
import MemoryMinigame from './components/MemoryMinigame.vue'
import PasswordMinigame from './components/PasswordMinigame.vue'
import SquareMinigame from './components/SquareMinigame.vue'
import KeysMinigame from './components/KeysMinigame.vue'
import VAR from './components/VAR.vue'
import PathMinigame from './components/PathMinigame.vue'
import { useApp } from './stores/app'
import { useLocale } from './stores/locale'
import { useAxios } from '@vueuse/integrations/useAxios'
import { resource } from '@/utils'
const app = useApp()
const locale = useLocale()
const emitter: any = inject('emitter')
const events: { [key: string]: Function } = {
setLocale: (strings: string) => {
locale.setLocale(strings)
},
uiShown: (event: any) => {
if (event.shown !== undefined) {
app.shown = event.shown
}
if (event.partiallyShown !== undefined) {
app.partiallyShown = event.partiallyShown
}
},
toggleIndicators: (event: any) => {
app.hudForcefullyHidden = event.hide
},
updateTheme: (event: any) => {
app.updateTheme(event.theme)
},
isMinimapShown: (event: any) => {
app.isMinimapShown = event.isShown
},
overrideLocaleKeys: (event: any) => {
locale.overrideLocaleKeys(event)
},
}
onMounted(() => {
window.addEventListener('message', handleMessage)
if (!import.meta.env.DEV) {
locale.initLocale()
app.updateSafezoneSettings()
app.initializeTheme()
}
})
function handleMessage(event: any) {
if (event.data.isOpen) {
for (const item in app.apps) {
//@ts-ignore
if (app.apps[item]) {
useAxios(`https://${resource()}/openCheckCallback`, {
method: 'POST',
data: {
app: item,
isOpen: true,
},
})
return
}
}
useAxios(`https://${resource()}/openCheckCallback`, {
method: 'POST',
data: {
isOpen: false,
},
})
return
}
if (event.data.event && events[event.data.event]) {
events[event.data.event](event.data.data)
return
}
const { app: toOpen, show, data }: { app: string; toOpen: string; show: boolean; data: any } = event.data
if (!toOpen) return
if (!(toOpen in app.apps)) return
let type = show ? 'open' : 'close'
if (typeof show === 'string') {
type = show
}
emitter.emit(`${toOpen}:${type}`, data ?? {})
}
</script>
<template>
<main class="absolute inset-0 grid place-items-center bg-transparent" :style="[app.getSafezoneStyles ?? `inset-0`]" v-show="app.shown">
<Clipboard />
<Modal />
<SimpleAction />
<Menu />
<ProgressBar />
<ProgressCircle />
<KbdAction />
<Instruction />
<InputDialog />
<CombinationMinigame />
<MemoryMinigame />
<PasswordMinigame />
<SquareMinigame />
<KeysMinigame />
<VAR />
<PathMinigame />
<Incidators />
<Compass />
<VehicleIndicators />
<Context />
<Notifications />
</main>
</template>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>Three.js - Lots of Objects - Slow</title>
<style>
html,
body {
height: 100%;
margin: 0;
}
#c {
width: 100%;
height: 100%;
display: block;
}
</style>
</head>
<body>
<canvas id="c"></canvas>
</body>
<script type="importmap">
{
"imports": {
"three": "../../../three.js/build/three.module.js",
"three/addons/": "../../../three.js/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from './three.js/build/three.module.js';
import { OrbitControls } from './three.js/examples/jsm/controls/OrbitControls.js';
async function loadFile(url) {
const req = await fetch(url);
return req.text();
}
function parseData(text) {
const data = [];
const settings = { data };
let max;
let min;
// split into lines
text.split('\n').forEach((line) => {
// split the line by whitespace
const parts = line.trim().split(/\s+/);
if (parts.length === 2) {
// only 2 parts, must be a key/value pair
settings[parts[0]] = parseFloat(parts[1]);
} else if (parts.length > 2) {
// more than 2 parts, must be data
const values = parts.map((v) => {
const value = parseFloat(v);
if (value === settings.NODATA_value) {
return undefined;
}
max = Math.max(max === undefined ? value : max, value);
min = Math.min(min === undefined ? value : min, value);
return value;
});
data.push(values);
}
});
return Object.assign(settings, { min, max });
}
function drawData(file) {
const { min, max, data, ncols, nrows } = file;
const range = max - min;
const ctx = document.querySelector('canvas').getContext('2d');
// 新建一个和网格数据尺寸相等的canvas
ctx.canvas.width = ncols;
ctx.canvas.height = nrows;
// 但是以两倍大小绘制防止太小
ctx.canvas.style.width = px(ncols * 2);
ctx.canvas.style.height = px(nrows * 2);
// 用黑灰色填充
ctx.fillStyle = '#444';
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// 绘制数据点
data.forEach((row, latNdx) => {
row.forEach((value, lonNdx) => {
if (value === undefined) {
return;
}
const amount = (value - min) / range;
const hue = 1;
const saturation = 1;
const lightness = amount;
ctx.fillStyle = hsl(hue, saturation, lightness);
ctx.fillRect(lonNdx, latNdx, 1, 1);
});
});
}
function px(v) {
return `${v | 0}px`;
}
function hsl(h, s, l) {
return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
}
loadFile('./static/data/demographic data in a grid format/gpw_v4_basic_demographic_characteristics_rev11_atotpopbt_2010_cntm_1_deg.asc')
.then(parseData)
.then(drawData)
</script>
</html>
|
import { NavLink } from 'react-router-dom';
// @ts-ignore
import Services from '../assets/svg/services.svg?component';
// @ts-ignore
import Seller from '../assets/svg/seller.svg?component';
// @ts-ignore
import Buyer from '../assets/svg/buyer.svg?component';
// @ts-ignore
import Profile from '../assets/svg/profile.svg?component';
// @ts-ignore
import Escrows from '../assets/svg/escrow.svg?component';
import InitiateEscrow from '../pages/InitiateEscrow';
import RegisterSeller from '../pages/RegisterSeller';
import RegisterBuyer from '../pages/RegisterBuyer';
function NavItem({ to, label }: { to: string; label: string }) {
let IconComponent;
switch (to) {
case '/services':
IconComponent = Services;
break;
case '/sellers':
IconComponent = Seller;
break;
case '/sellers/create':
IconComponent = RegisterSeller;
break;
case '/buyers':
IconComponent = Buyer;
break;
case '/buyers/create':
IconComponent = RegisterBuyer;
break;
case '/escrows':
IconComponent = Escrows;
break;
case '/escrows/create':
IconComponent = InitiateEscrow;
break;
case '/profile':
IconComponent = Profile;
break;
default:
IconComponent = <div></div>;
break;
}
const regularCls =
'pl-4 py-2 text-gray-700 hover:text-indigo-700 transition w-full cursor-pointer text-[16px]';
const activeCls =
'pl-4 py-2 text-indigo-700 hover:text-indigo-700 transition w-full cursor-pointer font-semibold text-[16px]';
return (
<NavLink
to={to}
className={(props) => {
return !props.isActive ? regularCls : activeCls;
}}
>
<div className='flex items-center justify-start'>
<div className='w-1/6 flex items-center justify-center'>
<IconComponent />
</div>
<span className='ml-2 flex-1'>{label}</span>
</div>
</NavLink>
);
}
export default NavItem;
|
require "rails_helper"
RSpec.describe "artpieces#show", type: :request do
let(:params) { {} }
subject(:make_request) do
jsonapi_get "/api/v1/artpieces/#{artpiece.id}", params: params
end
describe "basic fetch" do
let!(:artpiece) { create(:artpiece) }
it "works" do
expect(ArtpieceResource).to receive(:find).and_call_original
make_request
expect(response.status).to eq(200)
expect(d.jsonapi_type).to eq("artpieces")
expect(d.id).to eq(artpiece.id)
end
end
end
|
<template>
<view class="home">
<custom-head-bar :foldState="foldState" id="customHeadBar"></custom-head-bar>
<view class="wrapper">
<view class="search">
<car-search></car-search>
</view>
<view class="scrollLayout">
<view class="rightScroll">
<scroll-view @scroll="rightScrollEnt" :scroll-top="ScrollValue" scroll-y scroll-with-animation
class="sContent">
<view class="productView">
<view class="proitem">
<view class="swiper">
<car-swiper></car-swiper>
</view>
<view class="grid">
<car-grid></car-grid>
</view>
<view class="commo">
<commodity :dataList='commodityList'></commodity>
</view>
<view class="loadmore">
<u-loadmore bg-color="rgb(240, 240, 240)" :status="loadStatus"
@loadmore="addRandomData"></u-loadmore>
</view>
</view>
</view>
</scroll-view>
</view>
</view>
</view>
</view>
</template>
<script>
import {
mapMutations,
mapGetters
} from "vuex";
import Commodity from '../../components/commodity/commodity.vue';
export default {
data() {
return {
navSing: 0,
ScrollValue: 0,
HitArr: [],
foldState: false,
commodityList: [{
id: 1,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/01.jpg",
name: "Java In A Nutshell桌面快速参考",
pprice: "30",
oprice: "189",
discount: "5.2"
},
{
id: 2,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/02.jpg",
name: "通往夏天的隧道",
pprice: "45",
oprice: "125",
discount: "5.2"
},
{
id: 3,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/03.jpg",
name: "Goodbye, Eri",
pprice: "35",
oprice: "125",
discount: "5.2"
},
{
id: 4,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/04.jpg",
name: "用Python自动化繁琐的工作",
pprice: "25",
oprice: "80",
discount: "5.2"
},
{
id: 6,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/07.jpg",
name: "置身事内",
pprice: "18",
oprice: "35",
discount: "5.2"
},
{
id: 5,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/05.jpg",
name: "C程序设计语言",
pprice: "45",
oprice: "120",
discount: "5.2"
},
{
id: 7,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/06.jpg",
name: "Sql用于数据分析",
pprice: "45",
oprice: "75",
discount: "5.2"
},
{
id: 9,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/09.jpg",
name: "Spy X Family, Vol. 1",
pprice: "42",
oprice: "84",
discount: "5.2"
},
{
id: 10,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/10.jpg",
name: "研究生高分论文写作(第四版)",
pprice: "12",
oprice: "35",
discount: "5.2"
},
{
id: 8,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/08.jpg",
name: "漫长的等待",
pprice: "32",
oprice: "54",
discount: "5.2"
},
{
id: 11,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/11.jpg",
name: "Java网络编程",
pprice: "49",
oprice: "149",
discount: "5.2"
},
{
id: 12,
imgUrl: "https://mp-06cb9cdc-8c7c-46a3-9e40-23b4c64fd8a3.cdn.bspapp.com/book/12.png",
name: "前端开发实战",
pprice: "20",
oprice: "50",
discount: "5.2"
},
]
}
},
components: {
Commodity,
},
onLoad() {
this.getHeightArr().then(() => {
// 达到高度后
});
},
computed: {},
methods: {
...mapMutations(["setFoldState"]),
//点击导航条
clickNav(index) {
if (this.navSing == index) return;
this.navSing = index;
if (this.timeout) {
clearTimeout(this.timeout);
}
this.timeout = setTimeout(() => {
this.ScrollValue = this.HitArr[index];
}, 100)
},
// 获取滚动条内容高度
getHeightArr() {
return new Promise((resolve) => {
let selectorQuery = uni.createSelectorQuery();
let customHeadBar;
//获取自定义导航高度
selectorQuery
.select("#customHeadBar")
.boundingClientRect((rects) => {
customHeadBar = rects.height;
})
.exec();
// 滚到区域的节点组
selectorQuery
.selectAll(".productView")
.boundingClientRect((rects) => {
this.HitArr = rects.map((item) => item.top - customHeadBar - 40);
})
.exec();
});
},
// 监听滚动条的改变
rightScrollEnt(e) {
let scrollTop = Math.ceil(e.detail.scrollTop);
let sing = this.HitArr.findIndex((value, index, arr) => scrollTop >= value && scrollTop < arr[index +
1])
this.navSing = sing;
if (scrollTop > 100) {
this.setFoldState(false)
}
if (scrollTop > 300) {
this.setFoldState(true)
}
},
},
};
</script>
<style lang="scss" scoped>
.home {
height: 100vh;
display: flex;
flex-direction: column;
.wrapper {
overflow: hidden;
background: #fff;
border-radius: 10px 10px 0 0;
margin-top: -10px;
padding: relative;
z-index: 2;
.search {
padding: 10rpx;
margin-top: 5rpx;
}
.scrollLayout {
padding-top: 5rpx;
height: calc(100% - 100rpx);
@include flex-box();
.rightScroll {
height: 100%;
flex: 1;
position: relative;
.productView {
.proitem {
.swiper {}
.grid {
padding-top: 5rpx;
}
.commo {
padding: 10rpx 30rpx;
}
.loadmore {
padding-bottom: 85rpx;
}
}
}
}
.sContent {
height: 109%;
}
}
}
}
</style>
|
import React from "react";
import Modal from "./Modal";
import Button from "../components/Button";
import Input from "../components/Input";
const LoginModal = ({ open, handleClose }) => {
const [state, setState] = React.useState({ email: "", password: "" });
const handleChange = (event) =>
setState({ ...state, [event.target.name]: event.target.value });
return (
<Modal
title="Login"
id="alert-dialog-title"
descID="alert-dialog-description"
open={open}
handleClose={handleClose}
>
<Input
type="email"
name="email"
value={state.email}
placeholder="Email"
handleChange={handleChange}
/>
<Input
type="password"
name="password"
value={state.password}
placeholder="Password"
handleChange={handleChange}
/>
<Button
label="login"
classname="w-full text-center uppercase text-white bg-[dodgerblue] mt-3 hover:opacity-80 p-2 rounded-md sm:p-3 font-semibold"
/>
<p className="mt-3 text-[#070707] text-center">
Don't have an account?{" "}
<span className="font-semibold text-[dodgerblue] cursor-pointer underline">
Signup
</span>
</p>
</Modal>
);
};
export default LoginModal;
|
// import java.util.*;
// class Pen{
// String color;
// String type;
// public void write(){
// System.out.println("Writing...");
// }
// public void printColor(){
// System.out.println(this.color);
// }
// }
// class Student{
// String name;
// int age;
// public void printInfo(){
// System.out.println(this.name);
// System.out.println(this.age);
// }
// // Student(String name , int age){
// // this.name = name;
// // this.age = age;
// // }
// // COPY CONSTRUCTOR
// Student(Student s2){
// this.name = s2.name;
// this.age = s2.age;
// }
// Student(){
// }
// }
// public class oops{
// public static void main(String[] args){
// // Pen p = new Pen();
// // p.color = "blue";
// // p.type = "ballpoint";
// // p.write();
// // Pen p1 = new Pen();
// // p1.color = "red";
// // p1.type = "gel";
// // p.printColor();
// // p1.printColor();
// Student s1 = new Student();
// s1.name = "Rohan";
// s1.age = 20;
// //s1.printInfo();
// Student s2 = new Student(s1);
// s2.printInfo();
// }
// }
// import java.util.*;
// class Student{
// String name;
// int age;
// // Polymorphism
// public void printInfo(String name){
// System.out.println(name);
// }
// public void printInfo(int age){
// System.out.println(age);
// }
// public void printInfo(String name , int age ){
// System.out.println(name + " " + age);
// }
// }
// public class oops{
// public static void main(String[] args){
// Student s1 = new Student();
// s1.name = "Rohan";
// s1.age = 20;
// s1.printInfo(s1.name , s1.age);
// }
// }
// Inheritance
// import java.util.*;
// class Shape{
// String color;
// }
// class Triangle extends Shape {
// }
// public class oops{
// public static void main(String[] args){
// Triangle t1 = new Triangle();
// t1.color = "red";
// System.out.println(t1.color);
// }
// }
// Single Level Inheritance
import java.util.*;
class Shape{
public void area(){
System.out.println("Area of shape");
}
}
class Triangle extends Shape {
public void area(int l , int h){
System.out.println(1/2*l*h);
}
}
// Hirerchal Inheritance
class circle extends Shape{
public void area(int r){
System.out.println(3.14*r*r);
}
}
// Multi Level Inheritance
// class EquilateralTriangle extends Triangle{
// public void area(int l , int h){
// System.out.println(1/2*l*h);
// }
// }
public class oops{
public static void main(String[] args){
Triangle t1 = new Triangle();
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePacientesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pacientes', function (Blueprint $table) {
$table->increments('id');
$table->string('nombres');
$table->string('apellido_pat');
$table->string('apellido_mat');
$table->string('rut')->unique();
$table->string('dv');
$table->string('direccion');
$table->string('correo')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('pacientes');
}
}
|
import 'package:bookly/core/utils/styles.dart';
import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
const CustomButton({
super.key,
required this.backgroundColor,
required this.textColor,
this.borderRadius,
this.textStyle,
required this.text,
this.onPressed,
});
final Color backgroundColor;
final Color textColor;
final String text;
final BorderRadius? borderRadius;
final TextStyle? textStyle;
final void Function()? onPressed;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 44,
child: TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
foregroundColor: Colors.black,
backgroundColor: backgroundColor,
shape: RoundedRectangleBorder(
borderRadius: borderRadius ?? BorderRadius.circular(16),
),
),
child: Text(
text,
style: textStyle ?? Styles.numTextStyle18R,
),
),
);
}
}
|
"use client";
import { loadData } from "@/components/actions/codeblockActions";
import { CodeBlock, PageParms } from "@/components/assets/CommonType";
import DeleteButton from "@/components/assets/DeleteButton";
import Rating from "@/components/assets/Rating";
import { db } from "@/db";
import Link from "next/link";
import { useEffect, useState } from "react";
import { FidgetSpinner } from "react-loader-spinner";
export default function Home({ params }: PageParms) {
const [data, setData] = useState<CodeBlock | null>();
const [notification, setNotification] = useState(false);
useEffect(() => {
loadData(parseInt(params.id)).then((response) => {
setData(response);
});
}, []);
const toastNotification = (show: boolean) => {
if (show) {
setNotification(true);
setTimeout(() => {
setNotification(false);
}, 3000);
}
};
return (
<div>
<div className="lg:flex lg:items-center lg:justify-between">
<div className="min-w-0 flex">
<h3 className="font-bold leading-7 text-gray-900 sm:truncate sm:text-lg sm:tracking-tight">
Code Block Details
</h3>
</div>
{notification && (
<>
<div className="absolute flex origin-center m-96">
<div className="flex items-center bg-green-500 border-l-4 border-green-700 py-2 px-3 shadow-md mb-2">
<div className="text-green-500 rounded-full bg-white mr-3">
<svg
width="1.8em"
height="1.8em"
viewBox="0 0 16 16"
className="bi bi-check"
fill="currentColor"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
d="M10.97 4.97a.75.75 0 0 1 1.071 1.05l-3.992 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.236.236 0 0 1 .02-.022z"
/>
</svg>
</div>
<div className="text-white max-w-xs ">Rating updated</div>
</div>
</div>
</>
)}
<div className="mt-5 flex lg:ml-4 lg:mt-0 gap-4">
<Link href={`/blocks/${data?.id}/edit`}>
<svg
className="h-8 w-8 text-red-500"
viewBox="0 0 24 24"
stroke-width="2"
stroke="currentColor"
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
>
<path stroke="none" d="M0 0h24v24H0z" />{" "}
<path d="M9 7 h-3a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2 -2v-3" />{" "}
<path d="M9 15h3l8.5 -8.5a1.5 1.5 0 0 0 -3 -3l-8.5 8.5v3" />{" "}
<line x1="16" y1="5" x2="19" y2="8" />
</svg>
</Link>
<DeleteButton id={data?.id} />
<Link href="/">
<svg
className="h-8 w-8 text-red-400"
width="24"
height="24"
viewBox="0 0 24 24"
stroke-width="2"
stroke="currentColor"
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
>
<path stroke="none" d="M0 0h24v24H0z" />
<path d="M9 13l-4 -4l4 -4m-4 4h11a4 4 0 0 1 0 8h-1" />
</svg>
</Link>
</div>
</div>
{data && (
<div className="mt-6 border-t border-gray-100">
<dl className="divide-y divide-gray-100">
<div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0">
<dt className="text-sm font-medium leading-6 text-gray-900">
Title
</dt>
<dd className="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
{data?.title}
</dd>
</div>
<div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0">
<dt className="text-sm font-medium leading-6 text-gray-900">
Code
</dt>
<dd className="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0 max-w-24">
{data?.code}
</dd>
</div>
<div className="px-4 py-6 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-0">
<dt className="text-sm font-medium leading-6 text-gray-900">
Rating
</dt>
<dd className="mt-1 text-sm leading-6 text-gray-700 sm:col-span-2 sm:mt-0">
<Rating
rating={data?.rating}
id={data?.id}
notify={toastNotification}
/>
</dd>
</div>
</dl>
</div>
)}
{!data && (
<div className="flex justify-center mt-11">
<FidgetSpinner />
</div>
)}
</div>
);
}
|
package service
import (
"v-helper/internal/model"
"gorm.io/gorm"
)
type ArticleService struct {
db *gorm.DB
}
func NewArticleService(db *gorm.DB) *ArticleService {
return &ArticleService{db: db}
}
func (s *ArticleService) CreateArticle(article model.Article) error {
return s.db.Create(&article).Error
}
func (s *ArticleService) GetAllArticles() ([]model.Article, error) {
var articles []model.Article
if err := s.db.Find(&articles).Error; err != nil {
return nil, err
}
return articles, nil
}
func (s *ArticleService) GetArticleByID(id uint) (model.Article, error) {
var article model.Article
if err := s.db.First(&article, id).Error; err != nil {
return article, err
}
return article, nil
}
func (s *ArticleService) GetArticlesByUserID(userID uint) ([]model.Article, error) {
var articles []model.Article
if err := s.db.Where("user_id = ?", userID).Find(&articles).Error; err != nil {
return nil, err
}
return articles, nil
}
func (s *ArticleService) UpdateArticleByID(id uint, article model.Article) error {
return s.db.Model(&article).Where("id = ?", id).Updates(article).Error
}
func (s *ArticleService) DeleteArticleByID(id uint) error {
return s.db.Where("id = ?", id).Delete(&model.Article{}).Error
}
|
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<style>
.col-flex {
height: 400px;
display: flex;
flex-direction: column;
flex-wrap: wrap;
align-content: stretch;
}
.col-flex>* {
flex: 1 1 200px;
width: 320px;
}
.group {
display: flex;
align-items: stretch;
}
.group + .group {
margin-top: 2px;
}
.group-points {
margin-left: 5px;
border-left: 1px double #c0c0c0;
display: flex;
flex-direction: column;
justify-content: center;
}
.group-slots {
flex-basis: 190px;
}
.slot {
text-align: right;
}
.slot__player {
display: inline-block;
width: 50px;
}
input[type="number"] {
width: 40px;
}
/* always show the arrows on active number inputs and hide the arrows on disabled inputs */
/* Chrome, Safari, Edge, Opera */
input[type=number]:not(:disabled)::-webkit-outer-spin-button,
input[type=number]:not(:disabled)::-webkit-inner-spin-button {
opacity: 1;
}
/* Firefox */
input[type=number]:disabled {
-moz-appearance: textfield;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
let max;
// The code in this function runs when the page is loaded.
$(document).ready(function () {
google.script.run
.withSuccessHandler(showProjects)
.withFailureHandler(showError)
.listProjects();
});
function showMessage(msg, element) {
const span = $(`<span id="message" class="gray">${msg}</span>`);
$(element).after(span);
}
function removeMessage() {
$('#message').remove();
}
function showError(msg, element) {
const div = $(`<div id="error" class="error">${msg}</div>`);
$(element).after(div);
}
function removeError() {
$('#error').remove();
}
function showProjects({ projects, maxContribution }) {
max = maxContribution;
$('#projects').empty();
if (projects.length === 0) {
$('#projects').text('no project found');
}
const doms = projects.map((project, id) => {
const slots = project.slots.map((slot) => {
if (!slot) {
return '';
}
return `<div class="slot">
<label for="prj-${id}-${slot.slotId}">${slot.title}</label>
<input id="prj-${id}-${slot.slotId}" type="number" name="project-slots" min="${slot.points}" max="6" value="${slot.points}"
data-project-id="${id}" data-project-name="${project.name}" data-slot-id="${slot.slotId}" data-group-id="${slot.groupId}"
${!slot.activeForCurrentPlayer && "disabled"} />
<span>/6點</span>
<span class="slot__player">${slot.player ? `(${slot.player})` : '' }</span>
</div>`;
});
const groupIdsMap = project.slots.reduce((map, slot) => {
if (slot && !map[slot.groupId]) {
map[slot.groupId] = {
current: slot.groupCurrentPoints,
goal: slot.groupGoalPoints,
};
}
return map;
}, {});
const groups = Object.keys(groupIdsMap).map(groupId => {
const { current, goal } = groupIdsMap[groupId];
const slotsBelongToGroup = slots.filter((slot, index) => String(project.slots[index].groupId) === String(groupId));
return `<div class="group" data-group-id="${groupId}">
<div class="group-slots">
${slotsBelongToGroup.reduce((d, s) => d + s, '')}
</div>
<div class="group-points small">
<div>
合計
<span class="group-points__current">${current || 0}</span> / <span class="group-points__goal">${goal}</span> 點
</div>
</div>
</div>`;
});
const displaySlots = groups.length === 0 ? slots : groups;
const title = project.name ? `[${project.type}] ${project.name} (${project.owner})` : '沒有專案卡';
return $(`<div>
<b id="project-${id}">${title}</b>
${displaySlots.reduce((d, s) => d + s, '')}
</div>`);
});
$('#projects').append(doms);
$('#projects').append('<div class="block">\
<div class="block" id="count"></div>\
<button id="reset">重置貢獻</button>\
<button class="blue" id="contribute">貢獻專案</button>\
</div>');
$('#count').text(`還剩下${maxContribution}點`);
function calculateGroupContributionPoints() {
const $group = $(this);
const $slots = $group.children('.group-slots').children('.slot')
.children('input[type="number"]');
const points = $slots.map((_, element) => element.value).get().map(Number);
const current = points.reduce((a, b) => a + b, 0);
const $groupPoints = $group.children('.group-points').children('div');
const $current = $groupPoints.children('span.group-points__current');
$current.text(current);
const $goal = $groupPoints.children('span.group-points__goal');
const goal = Number($goal.text());
if (current > goal) {
$groupPoints.addClass('error');
} else {
$groupPoints.removeClass('error');
}
}
$('#reset').click(function () {
$('input[type="number"]:not(:disabled)').each(function () {
$(this).val($(this).prop('min'));
});
// reset group contribution points
const $groups = $('div.group');
$groups.each(calculateGroupContributionPoints);
$('#count').text(`還剩下${maxContribution}點`).removeClass('current');
$('#contribute').prop('disabled', false);
});
$('#contribute').click(contribute);
$('input[type="number"]:not(:disabled)').change(function () {
const $group = $(this).parents('.group');
calculateGroupContributionPoints.call($group);
let cnt = 0;
$('input[type="number"]:not(:disabled)').each(function () {
cnt += ($(this).val() - $(this).prop('min'));
});
if (maxContribution - cnt >= 0) {
$('#count').text(`還剩下${maxContribution - cnt}點`).removeClass('current');
$('#contribute').prop('disabled', false);
} else {
$('#count').text(`用超過${-(maxContribution - cnt)}點`).addClass('current');
$('#contribute').prop('disabled', true);
}
});
}
function contribute() {
removeError();
showMessage('處理中...', this);
// disable the button
this.disabled = true;
const contributionList = [];
let count = 0;
$('input[type="number"]:not(:disabled)').each(function () {
const $this = $(this);
const points = $this.val() - $this.prop('min');
if (points > 0) {
const project = $this.data('project-name');
const slotId = $this.data('slot-id');
contributionList.push({ project, slotId, points });
count += points;
}
});
if (count > max) {
throw new Error('超過分配點數上限!');
}
google.script.run
.withSuccessHandler(
function (result, el) {
removeMessage();
google.script.host.close();
el.disabled = false;
})
.withFailureHandler(
function (error, el) {
removeMessage();
showError(error, el);
el.disabled = false;
})
.withUserObject(this)
.contribute(contributionList);
}
</script>
</head>
<body>
<div class="block">
<div class="col-flex" id="projects">Loading...</div>
</div>
</body>
</html>
|
package com.iivetradertube.toptendownliader;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.StringReader;
import java.util.ArrayList;
/**
* Created by alejandrovelez on 7/23/16.
*/
public class ParseApps {
private String xmlData;
private ArrayList<Application>applications;
public ParseApps(String xmlData) {
this.xmlData = xmlData;
applications = new ArrayList<Application>();
}
public ArrayList<Application> getApplications() {
return applications;
}
public boolean process(){
boolean status = true;
Application currentRecord = null;
boolean inEntry = false;
String textValue = "";
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(this.xmlData));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT){
String tagName = xpp.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
//Log.d("ParseApplication", "Starting tag for"+ tagName);
if(tagName.equalsIgnoreCase("entry")){
inEntry = true;
currentRecord = new Application();
} break;
case XmlPullParser.TEXT:
textValue = xpp.getText();
break;
case XmlPullParser.END_TAG:
//Log.d("ParseApplication", "Ending tag for" + tagName);
if(inEntry){
if(tagName.equalsIgnoreCase("entry")){
applications.add(currentRecord);
inEntry = false;
}else if(tagName.equalsIgnoreCase("name")){
currentRecord.setName(textValue);
}else if(tagName.equalsIgnoreCase("artist")){
currentRecord.setArtist(textValue);
}else if(tagName.equalsIgnoreCase("releaseDate")){
currentRecord.setReleaseDate(textValue);
}
}
break;
default:
//Nothing elese to do.
}
eventType = xpp.next();
}
} catch(Exception e){
status = false;
e.printStackTrace();
}
for(Application app : applications){
Log.d("ParseApplications", "****************");
Log.d("ParseApplications", "Name: " + app.getName());
Log.d("ParseApplications", "Artist" + app.getArtist());
Log.d("ParseApplications", "ReleaseDate: "+ app.getReleaseDate());
}
return true;
}
}
|
import { Suspense } from "react";
import { Link, Route, Switch } from "react-router-dom";
// Components
import { NoMatch } from "./components/NoMatch";
import { Loading } from "../components/Loading";
import { PublicPage } from "../components/PublicPage";
import { PrivatePage } from "../components/PrivatePage";
import { ProtectedPage } from "../components/ProtectedPage";
// Utilities
import { lazy } from "react";
// Pages
const LazyUsersPage = lazy(() =>
import(/* webpackChunkName: "UsersPage" */ "./pages/Users/users.page")
);
const LazyAboutUsPage = lazy(() =>
import(/* webpackChunkName: "AboutUsPage" */ "./pages/AboutUs/about-us.page")
);
const LazyAuthPage = lazy(() =>
import(/* webpackChunkName: "AuthPage" */ "./pages/Auth/auth.page")
);
const LazyDashboardPage = lazy(() =>
import(
/* webpackChunkName: "DashboardPage" */ "./pages/Dashboard/dashboard.page"
)
);
export function RootPage() {
return (
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
<li>
<Link to="/auth/login">Login</Link>
</li>
</ul>
</nav>
<Suspense fallback={<Loading />}>
<Switch>
<ProtectedPage path="/auth" component={LazyAuthPage} />
<PrivatePage path="/about" component={LazyAboutUsPage} />
<PrivatePage path="/users" component={LazyUsersPage} />
<PrivatePage path="/dashboard" component={LazyDashboardPage} />
<PublicPage path="/" exact>
Home
</PublicPage>
<PublicPage path="*">
<NoMatch />
</PublicPage>
</Switch>
</Suspense>
</div>
);
}
|
#include "main.h"
/**
* binary_to_uint - converts a binary number to an unsigned int
* @b: pointer to string of 0 and 1 chars
*
* Return: the converted number; 0 if there is one or more chars
* in string b that is not 0 or 1; 0 if b is NULL
*/
unsigned int binary_to_uint(const char *b)
{
int i;
unsigned int sum = 0;
if (b == NULL)
return (0);
for (i = 0; b[i] ; i++)
{
if (b[i] < 48 || b[i] > 49)
return (0);
sum = 2 * sum + (b[i] - '0');
}
return (sum);
}
|
# 2155. All Divisions With the Highest Score of a Binary Array
#### You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n)
#### into two arrays (possibly empty) numsleft and numsright:
#### numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - 1 (inclusive).
#### If i == 0, numsleft is empty, while numsright has all the elements of nums.
#### If i == n, numsleft has all the elements of nums, while numsright is empty.
#### The division score of an index i is the sum of the number of 0's in numsleft and the number of 1's in numsright.
#### Return all distinct indices that have the highest possible division score. You may return the answer in any order.
##### Example 1:
##### Input: nums = [0,0,1,0]
##### Output: [2,4]
##### Example 2:
##### Input: nums = [0,0,0]
##### Output: [3]
```
class Solution {
public List<Integer> maxScoreIndices(int[] nums) {
int rightNum = 0;
for(int i:nums){
if(i == 1){
rightNum++;
}
}
int leftNum = 0;
int max = Integer.MIN_VALUE;
for(int i = 0; i <= nums.length-1; i++){
int temp = rightNum + leftNum;
max = Math.max(max, temp);
if(nums[i] == 0){
leftNum++;
}else{
rightNum--;
}
nums[i] = temp;
}
max = Math.max(max, leftNum);
List<Integer> list = new ArrayList<>();
for(int i = 0; i <= nums.length-1 ; i++){
if(nums[i] == max){
list.add(i);
}
}
if(leftNum == max){
list.add(nums.length);
}
return list;
}
}
```

|
package com.example.orderservice.domain.entity;
import com.example.modulecommon.domain.entity.AggregateRoot;
import com.example.modulecommon.domain.valueobject.*;
import com.example.orderservice.domain.exception.OrderDomainException;
import com.example.orderservice.domain.valueobject.OrderItemId;
import com.example.orderservice.domain.valueobject.StreetAddress;
import com.example.orderservice.domain.valueobject.TrackingId;
import lombok.Getter;
import java.util.List;
import java.util.UUID;
@Getter
public class Order extends AggregateRoot<OrderId> {
private final CustomerId customerId;
private final RestaurantId restaurantId;
private final StreetAddress deliveryAddress;
private final Money price;
private final List<OrderItem> items;
private TrackingId trackingId;
private OrderStatus orderStatus;
private List<String> failureMessages;
public static final String FAILURE_MESSAGE_DELIMITER = ",";
public void initOrder() {
setId(OrderId.of(UUID.randomUUID()));
trackingId = new TrackingId(UUID.randomUUID());
orderStatus = OrderStatus.PENDING;
initOrderItems();
}
public void validateOrder() {
validateInitOrder();
validateTotalPrice();
validateItemsPrice();
}
public void pay() {
if (orderStatus != OrderStatus.PENDING) {
throw new OrderDomainException("Order is not in correct state for pay operation!");
}
orderStatus = OrderStatus.PAID;
}
public void approve() {
if (orderStatus != OrderStatus.PAID) {
throw new OrderDomainException("Order is not in correct state for approve operation!");
}
orderStatus = OrderStatus.APPROVED;
}
public void initCancel(List<String> failureMessages) {
if (orderStatus != OrderStatus.PAID) {
throw new OrderDomainException("Order is not in correct state for initCancel operation!");
}
orderStatus = OrderStatus.CANCELLING;
updateFailureMessages(failureMessages);
}
private void updateFailureMessages(List<String> failureMessages) {
if(this.failureMessages != null && failureMessages != null) {
this.failureMessages.addAll(failureMessages.stream().filter(message -> !message.isEmpty()).toList());
}
if(this.failureMessages == null) {
this.failureMessages = failureMessages;
}
}
public void cancel(List<String> failureMessages) {
if(!(orderStatus == OrderStatus.CANCELLING || orderStatus == OrderStatus.PENDING)) {
throw new OrderDomainException("Order is not in correct state for cancel operation!");
}
orderStatus = OrderStatus.CANCELLED;
}
private void validateItemsPrice() {
Money orderItemsTotal = items.stream().map((orderItem -> {
validateItemPrice(orderItem);
return orderItem.getSubTotal();
})).reduce(Money.ZERO, Money::add);
if(!price.equals(orderItemsTotal)) {
throw new OrderDomainException("Total price: " + price.getAmount()
+ " is not equal to orderItems total: "+orderItemsTotal.getAmount()+"!");
}
}
private void validateItemPrice(OrderItem orderItem) {
if(!orderItem.isPriceValid()){
throw new OrderDomainException("Order item price: " + orderItem.getPrice().getAmount() +
" is not valid for product " + orderItem.getProduct().getId().getValue());
}
}
private void validateTotalPrice() {
if (price == null || !price.isGreaterThanZero()) {
throw new OrderDomainException("Total price must be greater than zero!");
}
}
private void validateInitOrder() {
if (orderStatus != null || getId() != null) {
throw new OrderDomainException("Order is not in correct state for initialization!");
}
}
private void initOrderItems() {
long itemId = 1;
for (OrderItem orderItem : items) {
orderItem.initOrderItem(super.getId(), new OrderItemId(itemId++));
}
}
private Order(Builder builder) {
super.setId(builder.orderId);
customerId = builder.customerId;
restaurantId = builder.restaurantId;
deliveryAddress = builder.deliveryAddress;
price = builder.price;
items = builder.items;
trackingId = builder.trackingId;
orderStatus = builder.orderStatus;
failureMessages = builder.failureMessages;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private OrderId orderId;
private CustomerId customerId;
private RestaurantId restaurantId;
private StreetAddress deliveryAddress;
private Money price;
private List<OrderItem> items;
private TrackingId trackingId;
private OrderStatus orderStatus;
private List<String> failureMessages;
private Builder() {
}
public Builder orderId(OrderId id) {
this.orderId = id;
return this;
}
public Builder customerId(CustomerId customerId) {
this.customerId = customerId;
return this;
}
public Builder restaurantId(RestaurantId restaurantId) {
this.restaurantId = restaurantId;
return this;
}
public Builder deliveryAddress(StreetAddress deliveryAddress) {
this.deliveryAddress = deliveryAddress;
return this;
}
public Builder price(Money price) {
this.price = price;
return this;
}
public Builder items(List<OrderItem> items) {
this.items = items;
return this;
}
public Builder trackingId(TrackingId trackingId) {
this.trackingId = trackingId;
return this;
}
public Builder orderStatus(OrderStatus orderStatus) {
this.orderStatus = orderStatus;
return this;
}
public Builder failureMessages(List<String> failureMessages) {
this.failureMessages = failureMessages;
return this;
}
public Order build() {
return new Order(this);
}
}
}
|
---
tagsSlotOptions:
- value: alice
name: Alice C.
image: /images/avatars/photos/7.jpg
- value: erik
name: Erik K.
image: /images/avatars/photos/8.jpg
- value: melany
name: Melany W.
image: /images/avatars/photos/25.jpg
- value: tara
name: Tara S.
image: /images/avatars/photos/13.jpg
- value: mary
name: Mary L.
image: /images/avatars/photos/5.jpg
- value: irina
name: Irina V.
image: /images/avatars/photos/23.jpg
- value: jonathan
name: Jonathan K.
image: /images/avatars/photos/32.jpg
tagsSlotValue: []
---
### User tags
You can combine the `mode="tags"` with a custom template. This way you can
show custom tag elements with an image inside. The tag shape inherits from
the select class modifier.
<!--code-->
```vue
<script setup lang="ts">
const tagsSlotValue = []
const tagsSlotOptions = [
{
value: 'alice',
name: 'Alice Carasca',
image: '/images/avatars/photos/7.jpg',
},
{
value: 'erik',
name: 'Erik Kovalsky',
image: '/images/avatars/photos/8.jpg',
},
{
value: 'melany',
name: 'melany Wallace',
image: '/images/avatars/photos/25.jpg',
},
{
value: 'tara',
name: 'Tara Svenson',
image: '/images/avatars/photos/13.jpg',
},
{
value: 'mary',
name: 'Mary Lebowski',
image: '/images/avatars/photos/5.jpg',
},
{
value: 'irina',
name: 'Irina Vierbovsky',
image: '/images/avatars/photos/23.jpg',
},
{
value: 'jonathan',
name: 'Jonathan Krugger',
image: '/images/avatars/photos/32.jpg',
},
]
</script>
<template>
<V-Field class="is-image-tags">
<V-Control>
<Multiselect
v-model="tagsSlotValue"
mode="tags"
placeholder="Select employees"
track-by="name"
label="name"
:search="true"
:options="tagsSlotOptions"
:max-height="145"
>
<template #tag="{ option, remove, disabled }">
<div class="multiselect-tag is-user">
<img :src="option.image" />
{{ option.name }}
<i
v-if="!disabled"
@click.prevent
@mousedown.prevent.stop="remove(option)"
/>
</div>
</template>
</Multiselect>
</V-Control>
</V-Field>
</template>
```
<!--/code-->
<!--example-->
<div class="columns">
<div class="column is-4">
<V-Field class="is-image-tags">
<V-Control>
<Multiselect
v-model="frontmatter.tagsSlotValue"
mode="tags"
placeholder="Select employees"
trackBy="name"
label="name"
:search="true"
:options="frontmatter.tagsSlotOptions"
:max-height="145"
>
<template v-slot:tag="{ option, remove, disabled }">
<div class="multiselect-tag is-user">
<img :src="option.image">
{{ option.name }}
<i
v-if="!disabled"
@click.prevent
@mousedown.prevent.stop="remove(option)"
/>
</div>
</template>
</Multiselect>
</V-Control>
</V-Field>
</div>
<div class="column is-4">
<V-Field class="is-image-tags is-curved-select">
<V-Control>
<Multiselect
v-model="frontmatter.tagsSlotValue"
mode="tags"
placeholder="Select employees"
trackBy="name"
label="name"
:search="true"
:options="frontmatter.tagsSlotOptions"
:max-height="145"
>
<template v-slot:tag="{ option, remove, disabled }">
<div class="multiselect-tag is-user">
<img :src="option.image">
{{ option.name }}
<i
v-if="!disabled"
@click.prevent
@mousedown.prevent.stop="remove(option)"
/>
</div>
</template>
</Multiselect>
</V-Control>
</V-Field>
</div>
<div class="column is-4">
<V-Field class="is-image-tags is-rounded-select">
<V-Control>
<Multiselect
v-model="frontmatter.tagsSlotValue"
mode="tags"
placeholder="Select employees"
trackBy="name"
label="name"
:search="true"
:options="frontmatter.tagsSlotOptions"
:max-height="145"
>
<template v-slot:tag="{ option, remove, disabled }">
<div class="multiselect-tag is-user">
<img :src="option.image">
{{ option.name }}
<i
v-if="!disabled"
@click.prevent
@mousedown.prevent.stop="remove(option)"
/>
</div>
</template>
</Multiselect>
</V-Control>
</V-Field>
</div>
</div>
<!--/example-->
|
<?php
namespace App\Http\Controllers\Admin;
use Carbon\Carbon;
use App\Models\Course;
use App\Models\SchoolYear;
use Illuminate\Http\Request;
use App\Enums\RecordTypeEnum;
use App\Models\StudentGrades;
use Illuminate\Http\Response;
use App\Models\PreviousSchool;
use App\Models\StudentProfile;
use Barryvdh\DomPDF\Facade\Pdf;
use App\Enums\AcademicStatusEnum;
use App\Enums\AdmissionStatusEnum;
use App\Models\DocumentsSubmitted;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Gate;
use App\Observers\StudentActionObserver;
use Yajra\DataTables\Facades\DataTables;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(Request $request)
{
abort_if(Gate::denies('student_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');
if ($request->ajax()) {
$query = StudentProfile::with(['course', 'honor'])
->when($request->has('course') && $request->course, function ($query) use ($request) {
$query->whereHas('course', function ($query) use ($request) {
$query->whereIn('cour_id', explode(",", $request->course));
});
})->when($request->has('academic_status') && $request->academic_status, function ($query) use ($request) {
$query->whereIn('stud_academicStatus', explode(",", $request->academic_status));
})->when($request->has('admission_type') && $request->admission_type, function ($query) use ($request) {
$query->whereIn('stud_admissionType', explode(",", $request->admission_type));
})->when($request->has('admission_year') && $request->admission_year, function ($query) use ($request) {
$query->whereIn('stud_yearOfAdmission', explode(",", $request->admission_year));
})->when($request->has('record_type') && $request->record_type, function ($query) use ($request) {
$query->whereIn('stud_recordType', explode(",", $request->record_type));
})->when($request->has('honorable_dismissed') && $request->honorable_dismissed, function ($query) use ($request) {
$query->where('stud_isHonorableDismissed', $request->honorable_dismissed);
})->when($request->has('created_at') && $request->created_at, function ($query) use ($request) {
$query->whereBetween('stud_createdAt', explode(",", $request->created_at));
})->when($request->has('updated_at') && $request->updated_at, function ($query) use ($request) {
$query->whereBetween('stud_createdAt', explode(",", $request->updated_at));
})->when($request->has('archived_at') && $request->archived_at, function ($query) use ($request) {
$query->whereBetween('archived_at', explode(",", $request->archived_at));
})->when($request->has('show_archived') && $request->show_archived == "1", function ($query) use ($request) {
$query->onlyArchived();
})->when($request->has('show_archived') && $request->show_archived == "1", function ($query) use ($request) {
$query->onlyArchived();
})->when(!$request->has('show_archived') || $request->has('show_archived') && $request->show_archived == "0", function ($query) use ($request) {
$query->withoutArchived();
});
$table = Datatables::eloquent($query)
->addColumn('full_name', function ($row) {
return $row->full_name;
})
->addColumn('course_code', function ($row) {
return $row->course->cour_code;
})
->addColumn('remarks', function ($row) {
$hasHonor = $row->honor && $row->stud_academicStatus == AcademicStatusEnum::GRADUATED ? sprintf('<span data-bs-toggle="tooltip" data-bs-placement="right" data-bs-custom-class="tooltip-dark" title="%s"><i class="fa-duotone fa-file-certificate text-warning fs-4"></i></span>', $row->honor->honor_name) : "";
return $row->stud_isHonorableDismissed ? sprintf('%s <span data-bs-toggle="tooltip" data-bs-placement="right" data-bs-custom-class="tooltip-dark" title="%s"><i class="fa-duotone fa-arrow-right-from-bracket ms-2 text-danger fs-4"></i></span>', $hasHonor, __('Honorable Dismissed')) : "";
})
->addColumn('actions', function ($row) {
$viewGate = 'student_show';
$editGate = 'student_edit';
$archiveGate = 'student_archive';
$docuEvalGate = 'student_generate_document_evaluation';
$scholasticGate = 'student_generate_scholastic_data';
$unarchiveGate = 'student_archive_unarchive';
$resource = 'student';
$viewData = [];
if (!$row->archived()) {
$viewData = [
"viewGate" => $viewGate,
"editGate" => $editGate,
"archiveGate" => $archiveGate,
"docuEvalGate" => $docuEvalGate,
"scholasticGate" => $scholasticGate,
"resource" => $resource,
"row" => $row,
];
} else {
$viewData = [
"viewGate" => $viewGate,
"resource" => $resource,
"unarchiveGate" => $unarchiveGate,
"docuEvalGate" => $docuEvalGate,
"scholasticGate" => $scholasticGate,
"row" => $row,
];
}
return view('admin.students.partials.datatable-action-btns', $viewData);
})
->editColumn('stud_createdAt', function ($row) {
return $row->stud_createdAt ? Carbon::createFromFormat('Y-m-d H:i:s', $row->stud_createdAt)->format(config('panel.date_format') . ' ' . config('panel.time_format')) : null;
})
->editColumn('stud_updatedAt', function ($row) {
return $row->stud_updatedAt ? Carbon::createFromFormat('Y-m-d H:i:s', $row->stud_updatedAt)->format(config('panel.date_format') . ' ' . config('panel.time_format')) : null;
})
->editColumn('stud_admissionType', function ($row) {
return $row->stud_admissionType ? (new AdmissionStatusEnum())->getDisplayNames()[$row->stud_admissionType] : '';
})
->editColumn('stud_academicStatus', function ($row) {
$display = (new AcademicStatusEnum())->getDisplayNames()[$row->stud_academicStatus];
if ($row->stud_academicStatus == AcademicStatusEnum::GRADUATED) {
return sprintf("%s <br> on %s", $display, (new Carbon($row->stud_dateExited))->format('m-d-Y'));
} else {
return $display;
}
})
->editColumn('stud_recordType', function ($row) {
return $row->stud_recordType ? (new RecordTypeEnum())->getDisplayNames()[$row->stud_recordType] : '';
})
->filterColumn('full_name', function ($query, $keyword) {
$query->whereRaw("CONCAT(stud_firstName, ' ', stud_middleName, ' ', stud_lastName) like ?", ["%{$keyword}%"])->orWhereRaw("CONCAT(stud_lastName, ', ', stud_firstName, ' ', stud_middleName) like ?", ["%{$keyword}%"]);
})
->rawColumns(['actions', 'remarks', 'stud_academicStatus']);
return $table->make(true);
}
$filterCourses = Course::select([
DB::raw('`cour_id` as `id`'),
DB::raw('`cour_code` as `value`'),
])->get()->toArray();
$filterAcademicStatus = collect(AcademicStatusEnum::getSelectable())->map(function ($academicStatus, $key) {
return [
"id" => $key,
"value" => $academicStatus,
];
})->values()->all();
$filterAdmissionType = collect(AdmissionStatusEnum::getDisplayNames())->map(function ($admissionType, $key) {
return [
"id" => $key,
"value" => $admissionType,
];
})->values()->all();
$filterYearOfAdmission = SchoolYear::select([
DB::raw('`syear_year` as `id`'),
DB::raw('`syear_year` as `value`'),
])->get()->toArray();
return view('admin.students.index', compact('filterCourses', 'filterAcademicStatus', 'filterYearOfAdmission', 'filterAdmissionType'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show(StudentProfile $student, Request $request)
{
$activityLogs = $student->getActivityLogs();
switch ($request->input('tab', 'personal')) {
case 'personal':
(new StudentActionObserver)->viewed($student, 'Personal & Student profile');
return view('admin.students.show_personal', compact('student', 'activityLogs'));
break;
case 'documents':
abort_if(Gate::denies('student_show_documents'), Response::HTTP_FORBIDDEN, '403 Forbidden');
(new StudentActionObserver)->viewed($student, 'Documents');
return view('admin.students.show_documents', compact('student', 'activityLogs'));
break;
case 'scholastic':
if ($student->stud_recordType == "NONSIS") {
abort_if(Gate::denies('student_show_scholastic'), Response::HTTP_FORBIDDEN, '403 Forbidden');
(new StudentActionObserver)->viewed($student, 'Scholastic data');
return view('admin.students.show_scholastic', compact('student', 'activityLogs'));
} else {
abort(Response::HTTP_NOT_FOUND);
}
break;
}
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(StudentProfile $student)
{
abort_if(Gate::denies('student_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden');
$student->delete();
(new StudentActionObserver)->deleted($student);
session()->flash('info', __('global.delete_success', ["attribute" => sprintf("<b>%s</b>", __('cruds.student.title_singular'))]));
return redirect()->route('students.index');
}
/**
* Aechive the specified resource from storage.
*/
public function archive(StudentProfile $student)
{
abort_if(Gate::denies('student_archive'), Response::HTTP_FORBIDDEN, '403 Forbidden');
$student->archive();
(new StudentActionObserver)->archived($student);
session()->flash('info', __('global.archive_success', ["attribute" => sprintf("<b>%s</b>", __('cruds.student.title_singular'))]));
return redirect()->route(previousRoute(), $student->stud_id);
}
/**
* Unarchive the specified resource from storage.
*/
public function unarchive(StudentProfile $student)
{
abort_if(Gate::denies('student_archive_unarchive'), Response::HTTP_FORBIDDEN, '403 Forbidden');
$student->unarchive();
(new StudentActionObserver)->unarchived($student);
session()->flash('info', __('global.unarchive_success', ["attribute" => sprintf("<b>%s</b>", __('cruds.student.title_singular'))]));
return redirect()->route(previousRoute(), $student->stud_id);
}
/**
* Exports
*/
/**
* Export the specified resource.
*/
public function exportDocuments(StudentProfile $student, Request $request)
{
$student = StudentProfile::where('stud_id', $student->stud_id)->with('course', function ($query) {
return $query->withTrashed();
})->first();
$dsi = new DocumentsSubmitted();
$documents['all']["entrance"] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "ENTRANCE", "subm_student" => $student->stud_id])->get();
$documents['all']["records"] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "RECORDS", "subm_student" => $student->stud_id, "docu_isPermanent" => "NO"])->get();
$documents['all']["exit"] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "EXIT", "subm_student" => $student->stud_id])->get();
$documents['default']["records"]['regcert'] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "RECORDS", "subm_student" => $student->stud_id, "docu_id" => "1"])
->orderBy('subm_documentType', 'desc')
->orderBy('subm_documentType_1', 'desc')->get();
$paper_size = ($request->has('size')) ? (($request->input('size') != '') ? $request->input('size') : 'legal') : 'legal';
$pdf = Pdf::loadView('admin.students.pdf.documents', compact('student', 'documents'))->setPaper($paper_size);
$pdf->render();
$canvas = $pdf->getCanvas();
$height = $canvas->get_height();
$width = $canvas->get_width();
if ($student->archived()) {
$canvas->set_opacity(.3, "Multiply");
$canvas->page_text(
$width / 4.7,
$height / 2,
'ARCHIVED',
null,
65,
array(255, 0, 0),
2,
2,
-20
);
$canvas->set_opacity(.4, "Multiply");
$canvas->page_text(
$width / 2.3,
$height / 1.90,
$student->archived_at,
null,
10,
array(255, 0, 0),
0,
2,
-20
);
}
$canvas->set_opacity(.5, "Multiply");
return $pdf->stream();
}
/**
* Export the specified resource.
*/
public function exportScholastic(StudentProfile $student, Request $request)
{
abort_if($student->stud_recordType != 'NONSIS', Response::HTTP_NOT_FOUND);
$tp = $student->leftJoin('s_course', 'cour_stud_id', '=', 'cour_id')
->selectRaw('r_student.*
, md5(stud_id) as stud_id_md5
, cour_name as stud_course_name
, cour_code as stud_course
, DATE_FORMAT(stud_createdAt, "%Y-%m-%d") as `stud_createdAt_m_f`
, DATE_FORMAT(stud_createdAt, "%r") as `stud_createdAt_t_f`
, IFNULL(DATE_FORMAT(stud_updatedAt, "%Y-%m-%d"), "") as `stud_updatedAt_m_f`
, IFNULL(DATE_FORMAT(stud_updatedAt, "%r"), "") as `stud_updatedAt_t_f`
')
->where('stud_id', $student->stud_id)
->get();
$vd = [];
$fp = $tp[0];
$sId = $fp['stud_id'];
$ps = new PreviousSchool();
$fp['stud_sPrimary'] = $ps->where(["extsch_stud_id" => $sId, "extsch_educType" => "PRIMARY"])
->get();
$fp['stud_sSecondary'] = $ps->where(["extsch_stud_id" => $sId, "extsch_educType" => "SECONDARY"])
->get();
$fp['stud_sPrimary'] = (sizeOf($fp['stud_sPrimary']) == 1) ? $fp['stud_sPrimary'][0] : [];
$fp['stud_sSecondary'] = (sizeOf($fp['stud_sSecondary']) == 1) ? $fp['stud_sSecondary'][0] : [];
if ($fp['stud_admissionType'] == "TRANSFEREE" || $fp['stud_admissionType'] == "LADDERIZED") {
$fp['stud_sTertiary'] = $ps->where(["extsch_stud_id" => $sId, "extsch_educType" => "TRANSFER"])
->get();
}
if ($fp['stud_recordType'] == "NONSIS") {
$g = [];
$g['total_semester'] = 0;
$g['total_summer_semester'] = 0;
$sg = new StudentGrades();
$school_year = $sg->leftJoin('s_class', 'class_enrsub_id', '=', 'class_id')
->selectRaw('DISTINCT class_acadYear as acad_year
, CONCAT(class_acadYear, " - ", class_acadYear + 1) as acad_year_long
, CONCAT(class_acadYear, "-\'" ,SUBSTRING(class_acadYear + 1, 3, 2)) as acad_year_short
')
->whereRaw('stud_enrsub_id = "' . $sId . '"')
->orderBy('acad_year', 'desc')
->get();
$i = 0;
foreach ($school_year as $year) {
$semesters = $sg->leftJoin('s_class', 'class_enrsub_id', '=', 'class_id')
->leftJoin('s_term', 'class_term_id', '=', 'term_id')
->selectRaw('DISTINCT term_name, term_order')
->whereRaw('stud_enrsub_id = "' . $sId . '" and class_acadYear = "' . $year->acad_year . '"')
->orderBy('term_order', 'desc')
->get();
$a = 0;
foreach ($semesters as $semester) {
$g['total_semester'] += 1;
if ($semester['term_name'] == "Summer Semester") {
$g['total_summer_semester'] += 1;
}
$grades = $sg->leftJoin('r_student', 'stud_enrsub_id', '=', 'stud_id')
->leftJoin('s_class', 'class_enrsub_id', '=', 'class_id')
->leftJoin('s_instructor', 'class_inst_id', '=', 'inst_id')
->leftJoin('s_subject', 'class_subj_id', '=', 'subj_id')
->leftJoin('s_term', 'class_term_id', '=', 'term_id')
->selectRaw('t_student_enrolled_subjects.*
, md5(enrsub_id) as enrsub_id_md5
, inst_firstName as enrsub_inst_firstName
, inst_middleName as enrsub_inst_middleName
, inst_lastName as enrsub_inst_lastName
, inst_suffix as enrsub_inst_suffixName
, subj_code as enrsub_subj_code
, subj_name as enrsub_subj_name
, subj_units as enrsub_subj_units
, class_section as enrsub_sche_section
')
->whereRaw('stud_enrsub_id = "' . $sId . '" and term_name = "' . $semester->term_name . '"and class_acadYear = "' . $year->acad_year . '"')
->get();
$b = 0;
foreach ($grades as $grade) {
$grades[$b]['enrsub_grade_display'] = $grade['enrsub_finalRating'];
$grades[$b]['enrsub_grade_display_status'] = $grade['enrsub_grade_status'];
$grades[$b]['enrsub_inst_fullName'] = format_name(1, "", $grades[$b]['enrsub_inst_firstName'], $grades[$b]['enrsub_inst_middleName'], $grades[$b]['enrsub_inst_lastName'], $grades[$b]['enrsub_inst_suffixName']);
$b++;
}
$semesters[$a]['subjects'] = $grades;
$a++;
}
$school_year[$i]['semesters'] = $semesters;
$i++;
}
$g["grades"] = $school_year;
$vd = array_merge($vd, [
"stud_grades" => $g['grades'], "stud_total_semester" => $g['total_semester'], "stud_total_summer_semester" => $g['total_summer_semester']
]);
}
$dsi = new DocumentsSubmitted();
$ds["entrance"] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "ENTRANCE", "subm_student" => $sId])->get();
$ds["records"] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "RECORDS", "subm_student" => $sId, "docu_isPermanent" => "NO"])->get();
$ds["exit"] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "EXIT", "subm_student" => $sId])->get();
$dfs["records"]['regcert'] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "RECORDS", "subm_student" => $sId, "docu_id" => "1"])
->orderBy('subm_documentType', 'desc')
->orderBy('subm_documentType_1', 'desc')->get();
$paper_size = ($request->has('size')) ? (($request->input('size') != '') ? $request->input('size') : 'legal') : 'legal';
$pdf = Pdf::loadView('admin.students.pdf.scholastic-data', compact('student', 'vd'))->setPaper($paper_size);
if (sizeof($tp) == 1) {
$vd = [];
$fp = $tp[0];
$sId = $fp['stud_id'];
$ps = new PreviousSchool();
$fp['stud_sPrimary'] = $ps->where(["extsch_stud_id" => $sId, "extsch_educType" => "PRIMARY"])
->get();
$fp['stud_sSecondary'] = $ps->where(["extsch_stud_id" => $sId, "extsch_educType" => "SECONDARY"])
->get();
$fp['stud_sPrimary'] = (sizeOf($fp['stud_sPrimary']) == 1) ? $fp['stud_sPrimary'][0] : [];
$fp['stud_sSecondary'] = (sizeOf($fp['stud_sSecondary']) == 1) ? $fp['stud_sSecondary'][0] : [];
if ($fp['stud_admissionType'] == "TRANSFEREE" || $fp['stud_admissionType'] == "LADDERIZED") {
$fp['stud_sTertiary'] = $ps->where(["extsch_stud_id" => $sId, "extsch_educType" => "TRANSFER"])
->get();
}
if ($fp['stud_recordType'] == "NONSIS") {
$g = [];
$g['total_semester'] = 0;
$g['total_summer_semester'] = 0;
$sg = new StudentGrades();
$school_year = $sg->leftJoin('s_class', 'class_enrsub_id', '=', 'class_id')
->selectRaw('DISTINCT class_acadYear as acad_year
, CONCAT(class_acadYear, " - ", class_acadYear + 1) as acad_year_long
, CONCAT(class_acadYear, "-\'" ,SUBSTRING(class_acadYear + 1, 3, 2)) as acad_year_short
')
->whereRaw('stud_enrsub_id = "' . $sId . '"')
->orderBy('acad_year', 'desc')
->get();
$i = 0;
foreach ($school_year as $year) {
$semesters = $sg->leftJoin('s_class', 'class_enrsub_id', '=', 'class_id')
->leftJoin('s_term', 'class_term_id', '=', 'term_id')
->selectRaw('DISTINCT term_name, term_order')
->whereRaw('stud_enrsub_id = "' . $sId . '" and class_acadYear = "' . $year->acad_year . '"')
->orderBy('term_order', 'desc')
->get();
$a = 0;
foreach ($semesters as $semester) {
$g['total_semester'] += 1;
if ($semester['term_name'] == "Summer Semester") {
$g['total_summer_semester'] += 1;
}
$grades = $sg->leftJoin('r_student', 'stud_enrsub_id', '=', 'stud_id')
->leftJoin('s_class', 'class_enrsub_id', '=', 'class_id')
->leftJoin('s_instructor', 'class_inst_id', '=', 'inst_id')
->leftJoin('s_subject', 'class_subj_id', '=', 'subj_id')
->leftJoin('s_term', 'class_term_id', '=', 'term_id')
->selectRaw('t_student_enrolled_subjects.*
, md5(enrsub_id) as enrsub_id_md5
, inst_firstName as enrsub_inst_firstName
, inst_middleName as enrsub_inst_middleName
, inst_lastName as enrsub_inst_lastName
, inst_suffix as enrsub_inst_suffixName
, subj_code as enrsub_subj_code
, subj_name as enrsub_subj_name
, subj_units as enrsub_subj_units
, class_section as enrsub_sche_section
')
->whereRaw('stud_enrsub_id = "' . $sId . '" and term_name = "' . $semester->term_name . '"and class_acadYear = "' . $year->acad_year . '"')
->get();
$b = 0;
foreach ($grades as $grade) {
$grades[$b]['enrsub_grade_display'] = $grade['enrsub_finalRating'];
$grades[$b]['enrsub_grade_display_status'] = $grade['enrsub_grade_status'];
$grades[$b]['enrsub_inst_fullName'] = format_name(1, "", $grades[$b]['enrsub_inst_firstName'], $grades[$b]['enrsub_inst_middleName'], $grades[$b]['enrsub_inst_lastName'], $grades[$b]['enrsub_inst_suffixName']);
$b++;
}
$semesters[$a]['subjects'] = $grades;
$a++;
}
$school_year[$i]['semesters'] = $semesters;
$i++;
}
$g["grades"] = $school_year;
$vd = array_merge($vd, [
"stud_grades" => $g['grades'], "stud_total_semester" => $g['total_semester'], "stud_total_summer_semester" => $g['total_summer_semester']
]);
}
$dsi = new DocumentsSubmitted();
$ds["entrance"] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "ENTRANCE", "subm_student" => $sId])->get();
$ds["records"] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "RECORDS", "subm_student" => $sId, "docu_isPermanent" => "NO"])->get();
$ds["exit"] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "EXIT", "subm_student" => $sId])->get();
// Get fixed Documents
// -- Records
// --- Registration Cards
$dfs["records"]['regcert'] = $dsi->leftjoin("s_documents", 'subm_document', '=', 'docu_id')
->where(["subm_documentCategory" => "RECORDS", "subm_student" => $sId, "docu_id" => "1"])
->orderBy('subm_documentType', 'desc')
->orderBy('subm_documentType_1', 'desc')->get();
// return $vd['stud_grades'][0];
$pdf = Pdf::loadView('admin.students.pdf.scholastic-data', compact('student', 'vd'));
$pdf->render();
$canvas = $pdf->getCanvas();
$height = $canvas->get_height();
$width = $canvas->get_width();
if ($student->archived()) {
$canvas->set_opacity(.3, "Multiply");
$canvas->page_text(
$width / 4.7,
$height / 2,
'ARCHIVED',
null,
65,
array(255, 0, 0),
2,
2,
-20
);
$canvas->set_opacity(.4, "Multiply");
$canvas->page_text(
$width / 2.3,
$height / 1.90,
$student->archived_at,
null,
10,
array(255, 0, 0),
0,
2,
-20
);
}
$canvas->set_opacity(.5, "Multiply");
$canvas->page_text(35, $height - 30, $student->stud_studentNo . " | Page {PAGE_NUM} of {PAGE_COUNT}", null, 10, array(0, 0, 0));
return $pdf->stream();
} else {
return response(NULL, 404);
};
}
}
|
import * as z from "zod"
import { CompleteArticleCategories, RelatedArticleCategoriesModel } from "./index"
export const ArticleModel = z.object({
id: z.string(),
title: z.string(),
slug: z.string(),
description: z.string(),
image: z.string(),
active: z.boolean(),
body: z.string(),
createdAt: z.date().nullish(),
updatedAt: z.date().nullish(),
categoryId: z.string(),
})
export interface CompleteArticle extends z.infer<typeof ArticleModel> {
category: CompleteArticleCategories
}
/**
* RelatedArticleModel contains all relations on your model in addition to the scalars
*
* NOTE: Lazy required in case of potential circular dependencies within schema
*/
export const RelatedArticleModel: z.ZodSchema<CompleteArticle> = z.lazy(() => ArticleModel.extend({
category: RelatedArticleCategoriesModel,
}))
|
"""Utility files to support QAarchive.py modules"""
from __future__ import annotations
from datetime import timedelta, datetime
import copy
import unicodedata
import re, os
from urllib.parse import urlparse
from typing import List
import Alert, Link
import pathlib
from collections.abc import Iterable
gOptions = None
gDatabase:dict[str] = {} # These will be set later by QSarchive.py
def Contents(container:list|dict) -> list:
try:
return container.values()
except AttributeError:
return container
def ExtendUnique(dest: list, source: Iterable) -> list:
"Append all the items in source to dest, preserving order but eliminating duplicates."
destSet = set(dest)
for item in source:
if item not in destSet:
dest.append(item)
return dest
def ItemCode(item:dict|None = None, event:str = "", session:int|None = None, fileNumber:int|None = None) -> str:
"Return a code for this item. "
if item:
event = item.get("event",None)
session = item.get("sessionNumber",None)
fileNumber = item.get("fileNumber",None)
outputStr = event
if session is not None:
outputStr += f"_S{session:02d}"
if fileNumber is not None:
outputStr += f"_F{fileNumber:02d}"
return outputStr
def ParseItemCode(itemCode:str) -> tuple(str,int|None,int|None):
"Parse an item code into (eventCode,session,fileNumber). If parsing fails, return ("",None,None)."
m = re.match(r"([^_]*)(?:_S([0-9]+))?(?:_F([0-9]+))?",itemCode)
session = None
fileNumber = None
if m:
if m[2]:
session = int(m[2])
if m[3]:
fileNumber = int(m[3])
return m[1],session,fileNumber
else:
return "",None,None
def PosixToWindows(path:str) -> str:
return str(pathlib.PureWindowsPath(pathlib.PurePosixPath(path)))
def PosixJoin(*paths):
"Join directories using / to make nicer html code. Python handles / in pathnames graciously even on Windows."
return str(pathlib.PurePosixPath(*paths))
def DirectoryURL(url:str) -> str:
"Ensure that this url specifies a directory path."
if url.endswith("/"):
return url
else:
return url + "/"
def RemoteURL(url:str) -> bool:
"Does this point to a remote file server?"
return bool(urlparse(url).netloc)
def ReplaceExtension(filename:str, newExt: str) -> str:
"Replace the extension of filename before the file extension"
name,_ = os.path.splitext(filename)
return name + newExt
def AppendToFilename(filename:str, appendStr: str) -> str:
"Append to fileName before the file extension"
name,ext = os.path.splitext(filename)
return name + appendStr + ext
def Mp3Link(item: dict,directoryDepth: int = 2) -> str:
"""Return a link to the mp3 file associated with a given excerpt or session.
item: a dict representing an excerpt or session.
directoryDepth: depth of the html file we are writing relative to the home directory"""
if "fileNumber" in item and item["fileNumber"]: # Is this is a regular (non-session) excerpt?
return Link.URL(item,directoryDepth=directoryDepth)
session = FindSession(gDatabase["sessions"],item["event"],item["sessionNumber"])
return Link.URL(session,directoryDepth=directoryDepth)
def TagLookup(tagRef:str,tagDictCache:dict = {}) -> str|None:
"Search for a tag based on any of its various names. Return the base tag name."
if not tagDictCache: # modify the value of a default argument to create a cache of potential tag references
tagDB = gDatabase["tag"]
tagDictCache.update((tag,tag) for tag in tagDB)
tagDictCache.update((tagDB[tag]["fullTag"],tag) for tag in tagDB)
tagDictCache.update((tagDB[tag]["pali"],tag) for tag in tagDB if tagDB[tag]["pali"])
tagDictCache.update((tagDB[tag]["fullPali"],tag) for tag in tagDB if tagDB[tag]["fullPali"])
return tagDictCache.get(tagRef,None)
def TeacherLookup(teacherRef:str,teacherDictCache:dict = {}) -> str|None:
"Search for a tag based on any of its various names. Return the base tag name."
if not teacherDictCache: # modify the value of a default argument to create a cache of potential teacher references
teacherDB = gDatabase["teacher"]
teacherDictCache.update((t,t) for t in teacherDB)
teacherDictCache.update((teacherDB[t]["fullName"],t) for t in teacherDB)
return teacherDictCache.get(teacherRef,None)
def AboutPageLookup(pageName:str,aboutPageCache:dict = {}) -> str|None:
"Search for an about page based on its name. Return the path to the page relative to prototypeDir."
if not aboutPageCache: # modify the value of a default argument to create a cache of potential tag references
dirs = ["about"]
for dir in dirs:
fileList = os.listdir(PosixJoin(gOptions.prototypeDir,dir))
for file in fileList:
m = re.match(r"[0-9]*_?(.*)\.html",file)
if m:
aboutPageCache[m[1].lower()] = PosixJoin(dir,m[0])
return aboutPageCache.get(pageName.lower().replace(" ","-"),None)
def EllideText(s: str,maxLength = 50) -> str:
"Truncate a string to keep the number of characters under maxLength."
if len(s) <= maxLength:
return s
else:
return s[:maxLength - 3] + "..."
def ItemRepr(item: dict) -> str:
"""Generate a repr-style string for various dict types in gDatabase.
Check the dict keys to guess what it is.
If we can't identify it, return repr(item)."""
if type(item) == dict:
if "tag" in item:
if "level" in item:
kind = "tagDisplay"
else:
kind = "tag"
return(f"{kind}({repr(item['tag'])})")
event = session = fileNumber = None
args = []
if "code" in item and "subtitle" in item:
kind = "event"
event = item["code"]
elif "sessionTitle" in item:
kind = "session"
event = item["event"]
session = item["sessionNumber"]
elif "kind" in item and "sessionNumber" in item:
if "annotations" in item:
kind = "excerpt"
event = item["event"]
session = item["sessionNumber"]
fileNumber = item.get("fileNumber",None)
else:
kind = "annotation"
x = FindOwningExcerpt(item)
if x:
event = x["event"]
session = x["sessionNumber"]
args = [item['kind'],EllideText(item['text'])]
elif "pdfPageOffset" in item:
kind = "reference"
args.append(item["abbreviation"])
else:
return(repr(item))
if event:
name = event
if session is not None:
name += f"_S{session:02d}"
if fileNumber is not None:
name += f"_F{fileNumber:02d}"
args = [name] + args
return f"{kind}({', '.join(repr(i) for i in args)})"
else:
return repr(item)
def StrToTimeDelta(inStr):
"Convert a string with format mm:ss or hh:mm:ss to a timedelta object"
numbers = str.split(inStr,":")
try:
if len(numbers) == 2:
return timedelta(minutes = int(numbers[0]),seconds = int(numbers[1]))
elif len(numbers) == 3:
return timedelta(hours = int(numbers[0]),minutes = int(numbers[1]),seconds = int(numbers[2]))
except ValueError:
pass
raise ValueError("'" + inStr + "' cannot be converted to a time.")
def TimeDeltaToStr(time):
"Convert a timedelta object to the form [HH:]MM:SS"
seconds = (time.days * 24 * 60 * 60) + time.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
if hours:
return f"{hours}:{minutes:02d}:{seconds:02d}"
else:
return f"{minutes}:{seconds:02d}"
def ParseDate(dateStr:str) -> datetime.date:
"Read a date formated as DD/MM/YYYY and return datetime.date."
return datetime.strptime(dateStr,"%d/%m/%Y").date()
def ReformatDate(dateStr:str,fullMonth:bool = False) -> str:
"Take a date formated as DD/MM/YYYY and reformat it as mmm d YYYY."
date = ParseDate(dateStr)
return f'{date.strftime("%B" if fullMonth else "%b.")} {int(date.day)}, {int(date.year)}'
def ModificationDate(file:str) -> datetime:
info = os.stat(file)
return datetime.fromtimestamp(info.st_mtime)
def DependenciesModified(file:str,dependencies:list[str]) -> bool:
"""Returns true if any of the file paths specified in dependencies has a later modification date than file."""
fileDate = ModificationDate(file)
for d in dependencies:
if ModificationDate(d) >= fileDate:
return True
return False
def FindSession(sessions:list, event:str ,sessionNum: int) -> dict:
"Return the session specified by event and sessionNum."
for session in sessions:
if session["event"] == event and session["sessionNumber"] == sessionNum:
return session
raise ValueError(f"Can't locate session {sessionNum} of event {event}")
def SessionIndex(sessions:list, event:str ,sessionNum: int) -> int:
"Return the session specified by event and sessionNum."
for n,session in enumerate(sessions):
if session["event"] == event and session["sessionNumber"] == sessionNum:
return n
raise ValueError(f"Can't locate session {sessionNum} of event {event}")
def FindExcerpt(event: str, session: int|None, fileNumber: int|None) -> dict|None:
"Return the excerpt that matches these parameters. Otherwise return None."
if not gDatabase:
return None
if not event or fileNumber is None:
return None
if session is None:
session = 0
for x in gDatabase["excerpts"]:
if x["event"] == event and x["sessionNumber"] == session and x["fileNumber"] == fileNumber:
return x
return None
def FindOwningExcerpt(annotation: dict) -> dict:
"""Search the global database of excerpts to find which one owns this annotation.
This is a slow function and should be called infrequently."""
if not gDatabase:
return None
for x in gDatabase["excerpts"]:
for a in x["annotations"]:
if annotation is a:
return x
return None
def SubAnnotations(excerpt: dict,annotation: dict) -> list[dict]:
"""Return the annotations that are under this annotation or excerpt."""
if annotation is excerpt:
scanLevel = 1
scanning = True
else:
scanLevel = annotation["indentLevel"] + 1
scanning = False
subs = []
for a in excerpt["annotations"]:
if scanning:
if a["indentLevel"] == scanLevel:
subs.append(a)
elif a["indentLevel"] < scanLevel:
scanning = False
elif a is annotation:
scanning = True
return subs
def ParentAnnotation(excerpt: dict,annotation: dict) -> dict|None:
"""Return this annotation's parent."""
if not annotation or annotation is excerpt:
return None
if annotation["indentLevel"] == 1:
return excerpt
searchForLevel = 0
found = False
for searchAnnotation in reversed(excerpt["annotations"]):
if searchAnnotation["indentLevel"] == searchForLevel:
return searchAnnotation
if searchAnnotation is annotation:
searchForLevel = annotation["indentLevel"] - 1
if not found:
Alert.error("Annotation",annotation,"doesn't have a proper parent.")
return None
def GroupBySession(excerpts: list[dict],sessions: list[dict]|None = None) -> Iterable[tuple[dict,list[dict]]]:
"""Yield excerpts grouped by their session."""
if not sessions:
sessions = gDatabase["sessions"]
sessionIterator = iter(sessions)
curSession = next(sessionIterator)
yieldList = []
for excerpt in excerpts:
while excerpt["event"] != curSession["event"] or excerpt["sessionNumber"] != curSession["sessionNumber"]:
if yieldList:
yield curSession,yieldList
yieldList = []
curSession = next(sessionIterator)
yieldList.append(excerpt)
if yieldList:
yield curSession,yieldList
def GroupByEvent(excerpts: list[dict],events: dict[dict]|None = None) -> Iterable[tuple[dict,list[dict]]]:
"""Yield excerpts grouped by their event. NOT YET TESTED"""
if not events:
events = gDatabase["event"]
yieldList = []
curEvent = ""
for excerpt in excerpts:
while excerpt["event"] != curEvent:
if yieldList:
yield events[curEvent],yieldList
yieldList = []
curEvent = excerpt["event"]
yieldList.append(excerpt)
if yieldList:
yield events[curEvent],yieldList
def PairWithSession(excerpts: list[dict],sessions: list[dict]|None = None) -> Iterable[tuple[dict,dict]]:
"""Yield tuples (session,excerpt) for all excerpts."""
if not sessions:
sessions = gDatabase["sessions"]
for session,excerptList in GroupBySession(excerpts,sessions):
yield from ((session,x) for x in excerptList)
def RemoveDiacritics(string: str) -> str:
"Remove diacritics from string."
return unicodedata.normalize('NFKD', string).encode('ascii', 'ignore').decode('ascii')
def slugify(value, allow_unicode=False):
"""
Taken from https://github.com/django/django/blob/master/django/utils/text.py
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
underscores, or hyphens. Convert to lowercase. Also strip leading and
trailing whitespace, dashes, and underscores.
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize('NFKC', value)
else:
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value.lower())
return re.sub(r'[-\s]+', '-', value).strip('-_')
def RegexMatchAny(strings: Iterable[str],capturingGroup = True,literal = False):
"""Return a regular expression that matches any item in strings.
Optionally make it a capturing group."""
if literal:
strings = [re.escape(s) for s in strings]
if strings:
if capturingGroup:
return r"(" + r"|".join(strings) + r")"
else:
return r"(?:" + r"|".join(strings) + r")"
else:
return r'a\bc' # Looking for a word boundary between text characters always fails: https://stackoverflow.com/questions/1723182/a-regex-that-will-never-be-matched-by-anything
def ReorderKeys(ioDict: dict,firstKeys = [],lastKeys = []) -> None:
"Reorder the keys in ioDict"
spareDict = copy.copy(ioDict) # Make a shallow copy
ioDict.clear()
for key in firstKeys:
ioDict[key] = spareDict.pop(key)
for key in spareDict:
if key not in lastKeys:
ioDict[key] = spareDict[key]
for key in lastKeys:
ioDict[key] = spareDict[key]
def SummarizeDict(d: dict,printer: Alert.AlertClass) -> None:
"Print a summary of dict d, one line per key."
for key,value in d.items():
desc = f"{key}: {value.__class__.__name__}"
try:
desc += f"[{len(value)}]"
except TypeError:
pass
printer(desc)
|
package simulation
import (
"math/rand"
"github.com/cosmos/cosmos-sdk/baseapp"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
sdk "github.com/cosmos/cosmos-sdk/types"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/cosmos/cosmos-sdk/x/simulation"
"luna-delegator/x/delegator/keeper"
"luna-delegator/x/delegator/types"
)
func SimulateMsgCreateDelegation(
ak types.AccountKeeper,
bk types.BankKeeper,
k keeper.Keeper,
) simtypes.Operation {
return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
simAccount, _ := simtypes.RandomAcc(r, accs)
msg := &types.MsgCreateDelegation{
Creator: simAccount.Address.String(),
}
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
Context: ctx,
SimAccount: simAccount,
ModuleName: types.ModuleName,
CoinsSpentInMsg: sdk.NewCoins(),
AccountKeeper: ak,
Bankkeeper: bk,
}
return simulation.GenAndDeliverTxWithRandFees(txCtx)
}
}
func SimulateMsgUpdateDelegation(
ak types.AccountKeeper,
bk types.BankKeeper,
k keeper.Keeper,
) simtypes.Operation {
return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
var (
simAccount = simtypes.Account{}
delegation = types.Delegation{}
msg = &types.MsgUpdateDelegation{}
allDelegation = k.GetAllDelegation(ctx)
found = false
)
for _, obj := range allDelegation {
simAccount, found = FindAccount(accs, obj.Creator)
if found {
delegation = obj
break
}
}
if !found {
return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "delegation creator not found"), nil, nil
}
msg.Creator = simAccount.Address.String()
msg.Id = delegation.Id
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
Context: ctx,
SimAccount: simAccount,
ModuleName: types.ModuleName,
CoinsSpentInMsg: sdk.NewCoins(),
AccountKeeper: ak,
Bankkeeper: bk,
}
return simulation.GenAndDeliverTxWithRandFees(txCtx)
}
}
func SimulateMsgDeleteDelegation(
ak types.AccountKeeper,
bk types.BankKeeper,
k keeper.Keeper,
) simtypes.Operation {
return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
var (
simAccount = simtypes.Account{}
delegation = types.Delegation{}
msg = &types.MsgUpdateDelegation{}
allDelegation = k.GetAllDelegation(ctx)
found = false
)
for _, obj := range allDelegation {
simAccount, found = FindAccount(accs, obj.Creator)
if found {
delegation = obj
break
}
}
if !found {
return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "delegation creator not found"), nil, nil
}
msg.Creator = simAccount.Address.String()
msg.Id = delegation.Id
txCtx := simulation.OperationInput{
R: r,
App: app,
TxGen: simappparams.MakeTestEncodingConfig().TxConfig,
Cdc: nil,
Msg: msg,
MsgType: msg.Type(),
Context: ctx,
SimAccount: simAccount,
ModuleName: types.ModuleName,
CoinsSpentInMsg: sdk.NewCoins(),
AccountKeeper: ak,
Bankkeeper: bk,
}
return simulation.GenAndDeliverTxWithRandFees(txCtx)
}
}
|
package fori;
import java.util.Scanner;
public class For20 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
long s = solution(n); // 1!+2!+..+
System.out.println(s);
}
// a + b
// a,b => -10^100 .. 10^100
// 5! = 1*2*3*4*5
// 5! = 5*4! = 5*24=120
// 4! = 4*3! = 4*6 = 24
// 3! = 3*2! = 3*2=6
// 2! = 2*1! = 2
// 1! = 1
// sum = 1!+2!+3!+4!+...+n!
public static long solution(long n) {
long s = 0;
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
s += factorial;
}
return s;
}
}
|
import { Component } from 'react';
import { connect } from 'react-redux';
import { authOperations } from '../../redux/auth';
import { CSSTransition } from 'react-transition-group';
import Title from '../../components/Title/Title';
import DublicateAlert from '../../components/DublicateAlert';
import styles from './RegisterView.module.css';
class RegisterView extends Component {
state = {
name: '',
email: '',
password: '',
showAlert: false,
message: '',
};
handleChange = ({ target: { name, value } }) => {
this.setState({ [name]: value });
};
handleSubmit = e => {
e.preventDefault();
const { password } = this.state;
const messageError = this.props.errorMessage;
console.log(messageError);
if (password.length < 6) {
this.setState({
showAlert: true,
});
return setTimeout(() => {
this.setState({
showAlert: false,
});
}, 2500);
}
if (messageError === 'Request failed with status code 400') {
this.setState({
message: 'user email is already registered',
showAlert: true,
});
return setTimeout(() => {
console.log(123131);
this.setState({
showAlert: false,
message: '',
});
}, 2500);
}
this.props.onRegister(this.state);
this.setState({
name: '',
email: '',
password: '',
message: '',
showAlert: false,
});
};
render() {
const { name, email, password, message, showAlert } = this.state;
return (
<div>
<DublicateAlert
text={message ? message : 'password must by more then 6 laters!'}
showAlert={showAlert}
/>
<CSSTransition
in={true}
appear={true}
timeout={500}
classNames={styles}
unmountOnExit
>
<Title label="Страница РЕГИСТРАЦИИ" />
</CSSTransition>
<form
onSubmit={this.handleSubmit}
className={styles.form}
autoComplete="off"
>
<label className={styles.label}>
Имя
<input
className={styles.input}
type="text"
name="name"
value={name}
placeholder="Ivan Ivanov"
onChange={this.handleChange}
/>
</label>
<label className={styles.label}>
Почта
<input
className={styles.input}
type="email"
name="email"
value={email}
placeholder="random@mail.com"
onChange={this.handleChange}
/>
</label>
<label className={styles.label}>
Пароль
<input
className={styles.input}
type="password"
name="password"
value={password}
placeholder="password"
onChange={this.handleChange}
/>
</label>
<button className={styles.button} type="submit">
Зарегистрироваться
</button>
</form>
</div>
);
}
}
const mapStateToProps = state => ({
errorMessage: state.auth.error,
});
const mapDispatchToProps = {
onRegister: authOperations.register,
};
export default connect(mapStateToProps, mapDispatchToProps)(RegisterView);
|
//
// PopularMoviesListState.swift
// movies
//
// Created by grace kim on 2022/10/27.
//
import Foundation
import UIKit
import Foundation
import RxSwift
import RxRelay
class PopularMoviesListState {
let disposeBag = DisposeBag()
static var shared = PopularMoviesListState()
var movies = [Movie]() {
didSet {
self.getObserver()
}
}
func getObserver(){
self.MoviesObservable.accept(movies)
}
var MoviesObservable = BehaviorRelay<[Movie]>(value: [])
var moviesObserver: Observable<[Movie]> {
return Observable.of(movies)
}
var moviesObservables: Observable<[Movie]>{
return MoviesObservable.asObservable()
}
var error : Error?
var page : Int = 1
func loadMovies(with endpoint: MovieListEndPoint) {
//initial load movies (without pagination)
RootViewModel.shared.fetchMovies(from: endpoint, pageNum: self.page) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let response):
self.movies = []
self.movies = response.results
case .failure(let error):
//print("error in loading movies")
self.error = error as NSError
}
}
}
func loadSearchMovies(with query: String) {
RootViewModel.shared.searchMovie(from: query) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let response):
self.movies = response.results
case .failure(let error):
self.error = error as NSError
}
}
}
func appendMovies(with endPoint: MovieListEndPoint){
self.page = self.page + 1
RootViewModel.shared.fetchMovies(from: endPoint, pageNum: self.page) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let response):
self.movies += response.results
case .failure(let error):
//print("error in loading movies")
self.error = error as NSError
}
}
}
func initParams(){
self.page = 1
self.movies = []
}
}
|
import subprocess
import undetected_chromedriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from optional import FileWork, UserAgentAndProxy
class Region:
def get_browser_with_proxy(self, proxy):
user_agent = UserAgentAndProxy.get_random_ua()
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = """
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "%s",
port: parseInt(%s)
},
bypassList: ["localhost"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "%s",
password: "%s"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
""" % (
proxy[0],
proxy[1],
proxy[2],
proxy[3],
)
chrome_options = undetected_chromedriver.ChromeOptions()
with open("manifest.json", "w") as file:
file.write(manifest_json)
with open("background.js", "w") as file:
file.write(background_js)
chrome_options.add_argument("--load-extension=D:\\Python\\TEST")
chrome_options.add_argument("--user-agent=%s" % user_agent)
chrome_options.add_argument("--headless=chrome")
driver = undetected_chromedriver.Chrome(options=chrome_options)
return driver
def parse_page(self, url, proxy):
try:
browser = self.get_browser_with_proxy(proxy)
browser.get(url)
WebDriverWait(browser, 60).until(
EC.visibility_of_all_elements_located(
(
By.XPATH,
"//div[@class='d-none d-xl-block col-xl-3 company-item-sidebar']",
)
)
)
src = browser.page_source
soup = BeautifulSoup(src, "lxml")
code = (
soup.find(
"div", class_="company-sidebar border rounded p-3 p-md-4 mb-3"
)
.find_all("div", class_="company-sidebar__item")[0]
.text.strip()
.split("ЄДРПОУ")[-1]
)
company_name = (
soup.find("h1", class_="ui-title col-md-10")
.text.strip()
.replace(",", " ")
)
emails = []
phones = []
sites = []
for item in (
soup.find(
"div", class_="d-none d-xl-block col-xl-3 company-item-sidebar"
)
.find(
"div",
class_="d-none d-lg-block company-sidebar p-3 p-md-4 mb-3 border",
)
.find_all("div", class_="company-sidebar__item")
):
try:
query = item.find("div", class_="company-sidebar__data")
if query.find_all("a") != None:
for subq in item.find(
"div", class_="company-sidebar__data"
).find_all("a"):
element = subq.text
if "@" in element:
emails.append(element)
elif "https://" in element or "http://" in element:
sites.append(element)
else:
phones.append(element.replace("\xa0", " "))
except:
pass
FileWork.add_to_file(
code,
company_name,
" ".join(map(lambda x: f"({x})", emails)),
" ".join(map(lambda x: f"[{x}]", phones)),
" ".join(map(lambda x: f"({x})", sites)),
)
print(f"[INFO] {code} - success parsed!")
except Exception as ex:
print(f"[ERROR] {ex}")
finally:
browser.quit()
subprocess.run(["taskkill", "/f", "/im", "chrome.exe"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def parser_initialization(self):
count_for_proxy = 1
proxy = UserAgentAndProxy.get_random_proxy()
for code in [
"2919103017",
"38853509",
"39165816",
"41675320",
"40672752",
"40396139",
"32181742",
"39714715",
"43383337",
"42830482",
"41215180",
"41266590",
"35466539",
"40401693",
"41585268",
"02904160"
]:
url = "https://www.ua-region.com.ua/" + code
if count_for_proxy % 5 == 0:
proxy = UserAgentAndProxy.get_random_proxy()
print(f"[INFO change proxy to {proxy[0]}]")
self.parse_page(url, proxy)
count_for_proxy += 1
if __name__ == "__main__":
FileWork.create_file()
region = Region()
region.parser_initialization()
|
import { defineField, defineType } from "sanity";
export default defineType({
name: "boxAdd",
title: "Reklama box",
type: "document",
fields: [
defineField({
name: "name",
title: "Nazwa reklamodawcy",
description: "Ta nazwa nie będzie widoczna na stronie internetowej",
type: "string",
}),
defineField({
name: "link",
title: "Przekierowanie (link do reklamodawcy)",
validation: rule => rule.custom((link, context) => {
if (context.document.post && link) {
return "To pole oraz 'Artykuł powiązany z reklamą' (pole poniżej) nie mogą być wypełnione jednocześnie."
}
return true
}),
description:
"Wypełnij tylko, jeżeli po kliknięciu w reklamę ma się otworzyć inna strona. Przykładowa zawartość tego pola to: https://google.com",
type: "string",
}),
defineField({
name: "post",
title: "Artykuł powiązany z reklamą",
validation: rule => rule.custom((post, context) => {
if (context.document.link && post) {
return "To pole oraz 'Przekierowanie (link do reklamodawcy)' (pole powyżej) nie mogą być wypełnione jednocześnie."
}
return true
}),
description:
"Wypełnij tylko, jeżeli po kliknięciu w reklamę ma się otworzyć konkretny artykuł na stronie Głosu Milicza.",
type: "reference",
to: { type: "post" },
}),
defineField({
name: "image",
title: "Reklama",
type: "image",
validation: (Rule) => Rule.required(),
options: {
hotspot: true,
},
fields: [
{
name: "alt",
type: "string",
title: "Tekst alternatywny",
},
],
}),
defineField({
name: "startDate",
title: "Data rozpoczęcia reklamy",
type: "date",
validation: (Rule) => Rule.required(),
}),
defineField({
name: "endDate",
title: "Data zakończenia reklamy",
type: "date",
validation: (Rule) => Rule.required(),
}),
],
preview: {
select: {
name: "name",
startDate: "startDate",
endDate: "endDate",
media: "image",
},
prepare(selection) {
const { name, startDate, endDate, media } = selection;
const today = new Date();
const isActive =
today >= new Date(startDate) && today <= new Date(endDate);
return {
title: `[${isActive ? "Aktywna" : "Nieaktywna"}] ${name}`,
subtitle: `od ${startDate} do ${endDate}`,
media,
};
},
},
});
|
package output
import (
"encoding/json"
"fmt"
"os"
"github.com/ethereum/go-ethereum/accounts"
"github.com/jedib0t/go-pretty/v6/table"
)
// KeystoreOutputWriter is an interface for writing keystore information to different output formats.
type KeystoreOutputWriter interface {
WriteCreateOutput(mnemonic string, seed []byte) error
WriteListOutput(accounts []accounts.Account) error
}
// KeystoreTextOutputWriter writes keystore output in pure text format.
type KeystoreTextOutputWriter struct{}
func (w KeystoreTextOutputWriter) WriteCreateOutput(mnemonic string, seed []byte) error {
return nil
}
func (w KeystoreTextOutputWriter) WriteListOutput(accounts []accounts.Account) error {
if len(accounts) == 0 {
fmt.Println("No accounts found")
return nil
}
fmt.Println("List of Wallets:")
for i, account := range accounts {
fmt.Printf("%d.\t%s", i+1, account.Address.Hex())
}
return nil
}
// KeystoreTableOutputWriter writes keystore output in table format.
type KeystoreTableOutputWriter struct{}
func (w KeystoreTableOutputWriter) WriteCreateOutput(mnemonic string, seed []byte) error {
tw := table.NewWriter()
tw.SetOutputMirror(os.Stdout)
tw.AppendHeader(table.Row{"Mnemonic", "Seed"})
tw.AppendRow([]interface{}{mnemonic, fmt.Sprintf("%x", seed)})
tw.Render()
return nil
}
func (w KeystoreTableOutputWriter) WriteListOutput(accounts []accounts.Account) error {
tw := table.NewWriter()
tw.SetOutputMirror(os.Stdout)
tw.AppendHeader(table.Row{"#", "Address"})
for i, account := range accounts {
tw.AppendRow(table.Row{i + 1, account.Address.Hex()})
}
tw.Render()
return nil
}
// KeyStoreJSONOutputWriter writes keystore output in JSON format.
type KeystoreJSONOutputWriter struct{}
func (w KeystoreJSONOutputWriter) WriteCreateOutput(mnemonic string, seed []byte) error {
seedInfo := map[string]interface{}{
"mnemonic": mnemonic,
"seed": seed,
}
jsonOutput, err := json.Marshal(seedInfo)
if err != nil {
return err
}
fmt.Println(string(jsonOutput))
return nil
}
func (w KeystoreJSONOutputWriter) WriteListOutput(accounts []accounts.Account) error {
accountAddresses := make([]string, len(accounts))
for i, account := range accounts {
accountAddresses[i] = account.Address.Hex()
}
accountInfo := map[string][]string{
"accounts": accountAddresses,
}
jsonOutput, err := json.Marshal(accountInfo)
if err != nil {
return err
}
fmt.Println(string(jsonOutput))
return nil
}
|
import React from "react";
import { Header, Body } from "providers/modals";
import Button from "components/Button";
import Field from "components/Field";
import Input from "components/Input";
import { useModal } from "providers/modals";
import { useTrip } from "providers/trip";
import { randomId } from "lib/helpers";
import { MarkerIcon } from "lib/types";
import MarkerWithIcon from "components/MarkerWithIcon";
import clsx from "clsx";
import toast from "react-hot-toast";
type Props = {
lat: number;
lng: number;
};
export default function AddMarker({ lat, lng }: Props) {
const [icon, setIcon] = React.useState<MarkerIcon>();
const [name, setName] = React.useState("");
const { close } = useModal();
const { appendMarker } = useTrip();
const handleAddMarker = () => {
if (!icon) return toast.error("Please choose an icon");
appendMarker({ lat, lng, name, icon, id: randomId(6) });
close();
};
return (
<>
<Header>Add Custom Marker</Header>
<Body>
<div className="flex gap-2 mb-2">
<div className="flex flex-col gap-5 w-full">
<Field label="Name">
<Input type="text" name="name" value={name} autoFocus onChange={(e: any) => setName(e.target.value)} />
</Field>
<div>
<label>Choose icon</label>
<div className="flex gap-2 mt-2 flex-wrap">
{Object.values(MarkerIcon).map((it) => (
<button
type="button"
key={it}
onClick={() => setIcon(it)}
className={clsx("border-2 p-1", icon === it ? "border-blue-500 rounded-md" : "border-transparent")}
>
<MarkerWithIcon icon={it} className="scale-125" />
</button>
))}
</div>
</div>
<Button type="button" color="primary" className="mt-2" size="md" onClick={handleAddMarker}>
Add Marker
</Button>
</div>
</div>
</Body>
</>
);
}
|
---
layout: post
title: .gitignore
---
First get **git**
sudo aptitude install git-core
Then create your **.gitignore** file to exclude certain files from being versioned.
nano .gitignore
Add what specifics you want to exclude
log/*.log
log*.gz
tmp/**/*
.DS_Store
doc/api
doc/app
Thumbs.db
db/development.sqlite3
db/production.sqlite3
public/cache/*
public/photo/*
index/production/*
The last two are for my html cache directories and sphinx indexing files.
and globally ignore them
git config --global core.excludesfile ~/.gitignore
More here,
* [Elijah Miller](http://jqr.github.com/2009/02/03/global-git-ignore.html)
* and [Toolman Tim](http://toolmantim.com/articles/setting_up_a_new_rails_app_with_git)
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AlunoListComponent } from './components/aluno/aluno-list/aluno-list.component';
import { AlunoSaveComponent } from './components/aluno/aluno-save/aluno-save.component';
import { HomeComponent } from './components/home/home.component';
import { ProfessorListComponent } from './components/professor/professor-list/professor-list.component';
import { ProfessorSaveComponent } from './components/professor/professor-save/professor-save.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'professor-list', component: ProfessorListComponent},
{ path: 'professor-save', component: ProfessorSaveComponent},
{ path: 'aluno-list', component: AlunoListComponent},
{ path: 'aluno-save', component: AlunoSaveComponent},
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
package com.example.gestion_clientes.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.gestion_clientes.model.Cliente;
import com.example.gestion_clientes.service.ClienteService;
@RestController
@RequestMapping("/api/clientes")
public class ClienteController {
@Autowired
private ClienteService clienteService;
@GetMapping
public List<Cliente> getAllClientes() {
return clienteService.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<Cliente> getClienteById(@PathVariable Integer id) {
return clienteService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public Cliente createCliente(@RequestBody Cliente cliente) {
return clienteService.save(cliente);
}
@PutMapping("/{id}")
public ResponseEntity<Cliente> updateCliente(@PathVariable Integer id, @RequestBody Cliente clienteDetails) {
return clienteService.findById(id)
.map(cliente -> {
cliente.setNombre(clienteDetails.getNombre());
cliente.setApellidos(clienteDetails.getApellidos());
cliente.setDireccion(clienteDetails.getDireccion());
cliente.setDetallesCliente(clienteDetails.getDetallesCliente());
return ResponseEntity.ok(clienteService.save(cliente));
})
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteCliente(@PathVariable Integer id) {
return clienteService.findById(id)
.map(cliente -> {
clienteService.deleteById(id);
return ResponseEntity.ok().<Void>build();
})
.orElse(ResponseEntity.notFound().build());
}
}
|
import React,{ useEffect }from "react";
import useReportUserList from "./useUserReport";
import { Chip, Sheet, Table, } from '@mui/joy';
import {
Tbody,
Theader,
HeadList,
TableContainer,
} from "../../admin/student-list/StudentListStyled";
import CustomPagination from "../../../shared/components/pagination/Pagination";
const UserReportList: React.FC = () => {
const {
reportList,
page,
rowsPerPage,
handleChangePage,
handleChangeRowsPerPage,
fetchReportList
} = useReportUserList();
useEffect(() => {
fetchReportList();
}, [fetchReportList]);
return (
<div className="container mx-auto d-flex justify-center align-items-center" style={{ height: "100vh" }}>
<HeadList>
<TableContainer>
<Sheet
sx={{
"--TableCell-height": "40px",
"--TableHeader-height": "calc(1 * var(--TableCell-height))",
"--Table-firstColumnWidth": "80px",
"--Table-lastColumnWidth": "144px",
"--TableRow-stripeBackground": "rgba(0 0 0 / 0.04)",
"--TableRow-hoverBackground": "rgba(0 0 0 / 0.08)",
height: 400,
overflow: "auto",
background: (
theme
) => `linear-gradient(${theme.vars.palette.background.surface} ,
0 100%`,
backgroundSize:
"40px calc(100% - var(--TableCell-height)), 40px calc(100% - var(--TableCell-height)), 14px calc(100% - var(--TableCell-height)), 14px calc(100% - var(--TableCell-height))",
backgroundRepeat: "no-repeat",
backgroundAttachment: "local, local, scroll, scroll",
backgroundPosition:
"var(--Table-firstColumnWidth) var(--TableCell-height), calc(100% - var(--Table-lastColumnWidth)) var(--TableCell-height), var(--Table-firstColumnWidth) var(--TableCell-height), calc(100% - var(--Table-lastColumnWidth)) var(--TableCell-height)",
backgroundColor: "nav.bg",
}}
>
<Table
className="table mb-0"
borderAxis="bothBetween"
stickyHeader
hoverRow
sx={{
"--Table-headerUnderlineThickness": "1px",
"--TableCell-paddingX": "10px",
"--TableCell-paddingY": "7px",
"& tr > *:first-of-type": {
position: "sticky",
zIndex: 1,
left: 0,
boxShadow: "1px 0 var(--TableCell-borderColor)",
// bgcolor: 'background.surface',
},
"& tr > *:last-child": {
position: "sticky",
right: 0,
bgcolor: "var(--TableCell-headBackground)",
},
}}
>
<Theader >
<tr >
<th>No</th>
<th>Name</th>
<th>Report</th>
<th>Status</th>
<th>Date time</th>
</tr>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</Theader>
<Tbody>
{reportList.map((item,index) => (
<tr className="text-center" key={item.id || index}>
<th>{index + 1}</th>
<th>{item.room_number}</th>
<th>{item.report_detail}</th>
<th>
<Chip color={item.report_status.toString() === "Canceled" ? "danger" : item.report_status.toString() === "In progress" ? "warning" : "success"} variant="solid" size="lg">
{item.report_status}
</Chip>
</th>
<th>{formatTimestamp(item.timestamp)}</th>
{/* <th>
<Chip color={item.report_status.toString() === "1" ? "success" : "warning"}variant="solid" size="lg">
{item.report_status.toString() === "1"? "Success" : "Wait"}
</Chip>
</th> */}
</tr>
))}
</Tbody>
</Table>
</Sheet>
<div className="pagination-container">
<CustomPagination
count={100}
page={page}
rowsPerPage={rowsPerPage}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
</div>
</TableContainer>
</HeadList>
</div>
);
};
export default UserReportList;
const formatTimestamp = (timestamp: string | number): string => {
const date = new Date(typeof timestamp === 'string' ? parseInt(timestamp, 10) * 1000 : timestamp * 1000);
return `${date.toLocaleDateString()} : ${date.toLocaleTimeString()}`;
}
|
import type { Metadata } from "next";
import clsx from 'clsx';
//import { Inter } from "next/font/google";
import "./globals.css";
import ThemeProvider from '@/providers/ThemeProvider';
import SettingsProvider from "@/providers/SettingsProvider";
import Header from '@/components/domain/Header';
//const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "To-Dog List",
description: "かわいい犬がタスクを食べてくれるWebアプリ",
openGraph: {
type: 'website',
url: 'https://faveo-systema.net/to-dog-list',
description: 'かわいい犬がタスクを食べてくれるWebアプリ',
siteName: 'To-Dog List',
images: 'https://faveo-systema.net/to-dog-list/thumbnail.png',
}
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en"
suppressHydrationWarning
>
<ThemeProvider attribute='class' enableSystem={true}>
<SettingsProvider>
<body className={clsx(
'h-[100vh] w-[100vw] self-center',
'text-black dark:text-white',
'bg-gradient-to-b from-slate-100 to-slate-200',
'dark:from-slate-800 dark:to-slate-900',
)}>
<Header />
{children}
</body>
</SettingsProvider>
</ThemeProvider>
</html>
);
}
|
import express from 'express';
import {
getAllTours,
addNewTour,
deleteTour,
getTour,
updateTour,
getTourStats,
getMonthlyPlans,
getToursWithin,
getDstances
} from '../controllers/tour.controller.js';
import { aliasTopTours } from '../controllers/tour.controller.js';
import { protectRoute } from '../middlewares/protectRoute.js';
import { restrectRoute } from '../middlewares/restrictRouteByRole.js';
// import reviewRouter from './routes/review.routes.js';
import reviewRouter from '../routes/review.routes.js';
const router = express.Router();
router.route('/tours-within/:distance/center/:latlng/unit/:unit').get(getToursWithin)
router.route('/distances/:latlng/unit/:unit').get(getDstances)
// Nested routing in express
// router.route('/:tourId/review').post(protectRoute, restrectRoute('user'), addNewReview);
// here we are telling to express, go and use reviewRouter if you ever encounter route like /:id/review
// Note: router itself is a middleware. that's why we can use 'use' on it to instruct for usage of reviewRouter
router.use('/:tourId/reviews', reviewRouter); // Similar to mounting the routes
// It will go to reviewRouter (in app.js, as it starts with /tours) then from there it'll move to tourRouter. means it'll come back here. By this we decoupled the 2 routes. to access id of tour, we use mergeParams pattern of express;
// we are protecting our api so that public or any sector can use it;
/*
1) anyone can get all tours. but only admin & lead guide can add new tour;
2) anyone can get info about a specific tour. but deleting and updating a tour only allow to admin & lead guide;
3) if someone wanna access to plans, he have to be authenticated and authorized
*/
router
.route('/')
.get(getAllTours)
.post(protectRoute, restrectRoute('admin', 'lead-guide'), addNewTour);
router
.route('/:id')
.get(getTour)
.patch(protectRoute, restrectRoute('admin', 'lead-guide'), updateTour)
.delete(protectRoute, restrectRoute('admin', 'lead-guide'), deleteTour);
router
.route('/monthly-plan/:year')
.get(protectRoute, restrectRoute('admin', 'lead-guide'), getMonthlyPlans);
router.route('/tour-stats').get(getTourStats);
router.route('/top-5-cheap').get(aliasTopTours, getAllTours);
// /tours-within/400/center/34.0996666470141, -118.17805010835912/mi
export default router;
|
/*
* KCemu -- The emulator for the KC85 homecomputer series and much more.
* Copyright (C) 1997-2010 Torsten Paul
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef __kc_prefs_dirlist_h
#define __kc_prefs_dirlist_h
#include <list>
#include <string>
using namespace std;
class DirectoryListEntry
{
private:
string _dir;
string _filename;
string _path;
public:
DirectoryListEntry(string dir, string filename);
virtual ~DirectoryListEntry(void);
const char *get_dir(void) const;
const char *get_path(void) const;
const char *get_filename(void) const;
};
class DirectoryList : public list<DirectoryListEntry *>
{
string _basedir;
public:
DirectoryList(string basedir);
virtual ~DirectoryList(void);
};
#endif /* __kc_prefs_dirlist_h */
|
import React, { Fragment, useEffect, useState, useCallback } from "react";
import icons from "../../ultils/icons";
import withBaseComponent from "../../hocs/withBaseComponent";
import { updateCart } from "../../store/user/userSlice";
import { Link } from "react-router-dom";
function OrderItem({
element,
handleShowModal,
defaultQuantity = 1,
navigate,
dispatch,
}) {
const { RemoveIcon, AddIcon } = icons;
const [countProduct, setCountProduct] = useState(() => defaultQuantity);
const handleIProduct = useCallback(() => {
setCountProduct((prevCount) => prevCount + 1);
}, []);
const handleDProduct = useCallback(() => {
if (countProduct > 1) {
setCountProduct((prevCount) => prevCount - 1);
}
}, [countProduct]);
useEffect(() => {
dispatch(
updateCart({
productId: element?.product?._id,
quantity: countProduct,
color: element?.color,
})
);
}, [countProduct]);
return (
<div>
<Fragment>
<div className="flex flex-col mb-2 py-6 border-b border-black">
<div className="flex justify-between gap-2 ">
<div className="flex gap-4">
<img
src={element?.thumb}
alt=""
className="w-[200px] h-[200px] object-cover"
/>
<div className="flex flex-col gap-4 font-second">
<div className="flex flex-col gap-2 text-sm">
<Link className="text-base font-semibold font-main">
{element?.product?.title}
</Link>
<span className="font-medium">
Price: ${parseFloat(element?.price).toFixed(2)}
</span>
<span>Color: {element?.color}</span>
<span>Size: {element?.size}</span>
<span className="font-medium">
Subtotal: $
{parseFloat(element?.price * element?.quantity).toFixed(2)}
</span>
</div>
</div>
</div>
<div className="flex items-start gap-2 font-medium text-base relative">
<button
onClick={handleDProduct}
className={`absolute left-[15px] top-[10px] ${
// element?.quantity === 1
countProduct === 1
? "opacity-50 cursor-not-allowed pointer-events-none"
: ""
}`}
>
<RemoveIcon style={{ fontSize: 16 }} />
</button>
<input
type="text"
value={countProduct}
// value={element?.quantity}
readOnly
className="border border-gray-400 text-center w-[120px] py-3 focus:outline-none"
/>
<button
onClick={handleIProduct}
className="absolute right-[15px] top-[10px]"
>
<AddIcon style={{ fontSize: 16 }} />
</button>
</div>
</div>
<div className="flex justify-between items-start font-second text-xs underline">
<div></div>
<div>
{/* <button className="underline custom-text-hover">Edit</button> */}
</div>
<div className="flex gap-3">
{/* <button className="custom-text-hover">Save For Latter</button> */}
<button
className="custom-text-hover"
onClick={() => handleShowModal(element)}
>
Remove
</button>
</div>
</div>
</div>
</Fragment>
</div>
);
}
export default withBaseComponent(OrderItem);
|
//
// TodoItemView.swift
// Learn
//
// Created by Sakshi Chavre on 27/05/24.
//
import SwiftUI
struct TodoItemView: View {
let item: Todo
@StateObject var viewModel = TodoItemViewModel()
var body: some View {
HStack{
VStack(alignment: .leading){
Text(item.title).font(.body).bold()
Text("\(Date(timeIntervalSince1970: item.dueDate).formatted(date: .abbreviated, time: .shortened))").font(.footnote).foregroundColor(.gray)
}
Spacer()
Button {
viewModel.toggleIsDone(item: item)
} label: {
Image(systemName : item.isDone ? "checkmark.circle.fill" : "circle")
}
}
}
}
#Preview {
TodoItemView(item: .init(id: "123", title: "title", dueDate: Date().timeIntervalSince1970, createdDate: Date().timeIntervalSince1970, isDone: false))
}
|
# frozen_string_literal: true
# Serialiser for Visit records. The Visit model represents individual
# visits to pages with tracking enabled on the frontend
class VisitSerializer
include ActiveModel::Serialization
def initialize(visit = {})
@visit = visit
end
def attributes
{
id: nil,
page_id: nil,
page_name: nil,
page_url: nil,
user_id: nil,
visited_at: nil,
ip_address: nil,
latitude: nil,
longitude: nil
}
end
private
def id
@visit[:id]
end
def page_id
@visit[:page_id]
end
def page_name
@visit.page[:name]
end
def page_url
@visit.page[:url]
end
def user_id
@visit[:user_id]
end
def visited_at
@visit[:visited_at]
end
def ip_address
@visit.ip_info[:address]
end
def latitude
@visit.latitude.to_f
end
def longitude
@visit.longitude.to_f
end
end
|
import React from 'react';
import { Field, formValues, reduxForm } from 'redux-form';
class StreamForm extends React.Component {
renderError({error, touched}) {
if(touched && error){
return(
<div className='ui error message'>
<div className='header'>{error}</div>
</div>
);
}
}
renderInput = ({input, label, meta}) => {
const className = `field ${meta.error && meta.touched ? 'error' : ''}`
return (
<div className={className}>
<label>{label}</label>
<input {...input} autoComplete='off'/>
{this.renderError(meta)}
</div>
);
}
onSubmit = (formValues) => {
this.props.onSubmit(formValues);
}
render(){
return(
<form onSubmit={this.props.handleSubmit(this.onSubmit)} className='ui error form'>
<Field name="title" component={this.renderInput} label='Enter Title'/>
<Field name="description" component={this.renderInput} label='Enter Description'/>
<button className='ui button primary'>Submit</button>
</form>
);
}
};
const validate = (formValues) => {
const error = {};
if(!formValues.title)
error.title = 'You must enter a title here';
else if(!formValues.description)
error.description = 'You must enter a description here';
return error;
}
export default reduxForm({
form: 'StreamForm ',
validate: validate
})(StreamForm);
|
package com.fyh.chapter07;
public class Homework13 {
public static void main(String[] args) {
Circle c = new Circle();
c.setRadius(5);
System.out.println(c.findArea());
PassObject po = new PassObject();
po.printAreas(c, 5);
}
}
/*
题目要求:
(1) 定义一个Circle类,包含一个double型的radius属性代表圆的半径,findArea()方法返回圆的面积。
(2) 定义一个类PassObject,在类中定义一个方法printAreas(),该方法的定义如下:
public void printAreas(Circle c, int times) //方法签名/声明
(3) 在printAreas方法中打印输出1到times之间的每个整数半径值,以及对应的面积。例如,times为5,则输出半径1,2,3,4,5,以及对应的圆面积。
(4) 在main方法中调用printAreas()方法,调用完毕后输出当前半径值。程序运行结果如图所示
*/
class Circle {
double radius;
public Circle() {
}
public Circle(double redius) {
this.radius = redius;
}
public double findArea() {
return Math.PI * radius * radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
class PassObject {
public void printAreas(Circle c, int times) {
System.out.println("radius\tarea");
for (int i = 0; i <= times; i++) {
c.setRadius(i);
System.out.println((double) i + "\t" + c.findArea());
}
}
}
|
/**
* MIT LICENSE ***
* -------------------------------------------------------------------------
* This code may be modified and distributed under the MIT license.
* See the LICENSE file for details.
* -------------------------------------------------------------------------
* @summary Collection of layouts
* @author Alvis HT Tang <alvis@hilbert.space>
* @license MIT
* @copyright Copyright (c) 2021 - All Rights Reserved.
* -------------------------------------------------------------------------
*/
import { graphql } from 'gatsby';
import type { PageProps } from 'gatsby';
export const query = graphql`
query Project($id: String!) {
markdownRemark(id: { eq: $id }) {
frontmatter {
title
}
html
}
}
`;
const Project: React.FC<PageProps<Queries.ProjectQuery>> = ({ data }) => {
// since this page is referred from the createPages API, it's safe to assume the mdx node is there
const mdx = data.markdownRemark!;
const title = mdx.frontmatter?.title;
const html = mdx.html || '';
return (
<section className="py-12 px-4">
<div className="mx-auto w-full max-w-2xl font-sans main">
<h1 className="mt-2 mb-6 font-sans text-5xl font-semibold leading-tight text-center font-heading">
{title}
</h1>
<div
className="prose-sm"
dangerouslySetInnerHTML={{ __html: html }}></div>
</div>
</section>
);
};
export default Project;
|
package pl.newbies.auth.application
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.get
import io.ktor.http.HttpMethod
import io.ktor.server.application.Application
import io.ktor.server.application.call
import io.ktor.server.auth.*
import io.ktor.server.response.respond
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import org.jetbrains.exposed.sql.transactions.transaction
import pl.newbies.auth.application.model.GithubUser
import pl.newbies.auth.domain.UnauthorizedException
import pl.newbies.auth.domain.service.AuthService
import pl.newbies.plugins.inject
import pl.newbies.user.domain.service.UserService
import pl.newbies.user.infrastructure.repository.UserDAO
import pl.newbies.user.infrastructure.repository.Users
import pl.newbies.user.infrastructure.repository.toUser
/**
* GitHub DEV implementation, used only for testing
*/
fun Application.devGithubAuthentication(oauthClient: HttpClient) {
val userService by inject<UserService>()
val authService by inject<AuthService>()
val config = environment.config
val userApiUrl = config.property("oauth.devgithub.userUrl").getString()
authentication {
oauth("devgithub") {
urlProvider = { "http://localhost:8080/auth/callback/devgithub" }
providerLookup = {
OAuthServerSettings.OAuth2ServerSettings(
name = "devgithub",
authorizeUrl = "https://github.com/login/oauth/authorize",
accessTokenUrl = "https://github.com/login/oauth/access_token",
requestMethod = HttpMethod.Post,
clientId = config.property("oauth.devgithub.clientId").getString(),
clientSecret = config.property("oauth.devgithub.secret").getString(),
defaultScopes = listOf("user:email", "read:user"),
passParamsInURL = true,
)
}
client = oauthClient
}
}
routing {
authenticate("devgithub") {
get("/api/oauth/login/devgithub") { /* handled automatically */ }
get("/api/oauth/callback/devgithub") {
val token = call.principal<OAuthAccessTokenResponse.OAuth2>()?.accessToken
?: throw UnauthorizedException("Failed to get github auth token")
val githubUser = oauthClient.get(userApiUrl) {
bearerAuth(token)
}.body<GithubUser>()
val user = transaction {
UserDAO.find { Users.devGithubId eq githubUser.id }.singleOrNull()?.toUser()
} ?: userService.createUser(
nickname = githubUser.login,
devgithubId = githubUser.id,
)
val response = authService.generateResponse(user, previousToken = null)
call.respond(response)
}
}
}
}
|
import React, { useState, useEffect } from 'react';
import { InitialState } from './InitialState';
import { database } from '../Firebase/Crud';
export const ProductsContext = React.createContext(InitialState);
export const ProductsProvider = (props) => {
const [hardware, setHardware] = useState(InitialState.hardware);
const [components, setComponents] = useState(InitialState.components);
const [software, setSoftware] = useState(InitialState.software);
const [games, setGames] = useState(InitialState.games);
function getData() {
database.list("item").then((snapshot) => {
const response = snapshot.docs.map((t) => ({ ...t.data(), id: t.id }));
setHardware(response?.filter(d => d.type === "hardware") || []);
setComponents(response?.filter(d => d.type === "component") || []);
setSoftware(response?.filter(d => d.type === "software") || []);
setGames(response?.filter(d => d.type === "game") || []);
});
}
useEffect(() => getData(), []);
const data = {
hardware: hardware,
components: components,
software: software,
games: games
};
return (
<ProductsContext.Provider value={ { ...data } }>
{ props.children }
</ProductsContext.Provider>
);
};
|
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
import { RoleService } from './role.service';
import * as moment from 'moment';
import {environment} from '../../../environments/environment';
import {TypeEtudeVo} from '../model/TypeEtude.model';
@Injectable({
providedIn: 'root'
})
export class TypeEtudeService {
private API = ''
constructor(private http: HttpClient, private roleService: RoleService) {
this.role$ = this.roleService.role$;
this.role$.subscribe(role => {
this.API = environment.apiUrl + role.toLowerCase() + '/typeEtude/';
})
}
private _typeEtudes: Array<TypeEtudeVo> ;
private _selectedTypeEtude: TypeEtudeVo;
private _typeEtudeSelections: Array<TypeEtudeVo>;
private _createTypeEtudeDialog: boolean;
private _editTypeEtudeDialog: boolean;
private _viewTypeEtudeDialog: boolean;
public editTypeEtude$ = new BehaviorSubject<boolean>(false);
private role$: Observable<string>;
private _searchTypeEtude:TypeEtudeVo ;
// methods
public archiver(typeEtude: TypeEtudeVo): Observable<TypeEtudeVo> {
return this.http.put<TypeEtudeVo>(this.API + 'archiver/' ,typeEtude);
}
public desarchiver(typeEtude: TypeEtudeVo): Observable<TypeEtudeVo> {
return this.http.put<TypeEtudeVo>(this.API + 'desarchiver/' ,typeEtude);
}
public findAll(){
return this.http.get<Array<TypeEtudeVo>>(this.API);
}
public save(): Observable<TypeEtudeVo> {
return this.http.post<TypeEtudeVo>(this.API, {...this.selectedTypeEtude,dateCreation: moment(this.selectedTypeEtude.dateCreation).format("YYYY-MM-DD")});
}
delete(typeEtude: TypeEtudeVo) {
return this.http.delete<number>(this.API + 'id/' + typeEtude.id);
}
public edit(): Observable<TypeEtudeVo> {
return this.http.put<TypeEtudeVo>(this.API, this.selectedTypeEtude);
}
public findByCriteria(typeEtude:TypeEtudeVo):Observable<Array<TypeEtudeVo>>{
return this.http.post<Array<TypeEtudeVo>>(this.API +'search', typeEtude);
}
public findByIdWithAssociatedList(typeEtude:TypeEtudeVo):Observable<TypeEtudeVo>{
return this.http.get<TypeEtudeVo>(this.API + 'detail/id/' +typeEtude.id);
}
// getters and setters
get typeEtudes(): Array<TypeEtudeVo> {
if(this._typeEtudes==null){
this._typeEtudes=new Array<TypeEtudeVo>();
}
return this._typeEtudes;
}
set typeEtudes(value: Array<TypeEtudeVo>) {
this._typeEtudes = value;
}
get selectedTypeEtude(): TypeEtudeVo {
if(this._selectedTypeEtude==null){
this._selectedTypeEtude=new TypeEtudeVo();
}
return this._selectedTypeEtude;
}
set selectedTypeEtude(value: TypeEtudeVo) {
this._selectedTypeEtude = value;
}
get typeEtudeSelections(): Array<TypeEtudeVo> {
if(this._typeEtudeSelections==null){
this._typeEtudeSelections=new Array<TypeEtudeVo>();
}
return this._typeEtudeSelections;
}
set typeEtudeSelections(value: Array<TypeEtudeVo>) {
this._typeEtudeSelections = value;
}
get createTypeEtudeDialog(): boolean {
return this._createTypeEtudeDialog;
}
set createTypeEtudeDialog(value: boolean) {
this._createTypeEtudeDialog = value;
}
get editTypeEtudeDialog(): boolean {
return this._editTypeEtudeDialog;
}
set editTypeEtudeDialog(value: boolean) {
this._editTypeEtudeDialog = value;
}
get viewTypeEtudeDialog(): boolean {
return this._viewTypeEtudeDialog;
}
set viewTypeEtudeDialog(value: boolean) {
this._viewTypeEtudeDialog = value;
}
get searchTypeEtude(): TypeEtudeVo {
if(this._searchTypeEtude==null){
this._searchTypeEtude=new TypeEtudeVo();
}
return this._searchTypeEtude;
}
set searchTypeEtude(value: TypeEtudeVo) {
this._searchTypeEtude = value;
}
}
|
import { protectedProcedure, publicProcedure, router } from 'server/trpc'
import { z } from 'zod'
import dayjs from 'dayjs'
export const stylesRouter = router({
my: protectedProcedure.query(async ({ ctx }) => {
return ctx.prisma.styles.findMany({
orderBy: { createdAt: 'desc' },
where: {
userId: ctx.session.user.id,
},
})
}),
recent: publicProcedure.query(async ({ ctx }) => {
return ctx.prisma.styles.findMany({
orderBy: { createdAt: 'desc' },
where: {
OR: [{ public: true }, { userId: ctx.session?.user.id }],
},
take: 50,
})
}),
popular: publicProcedure.query(async ({ ctx }) => {
return ctx.prisma.styles.findMany({
orderBy: { content: 'asc' },
where: {
OR: [{ public: true }, { userId: ctx.session?.user.id }],
},
take: 10,
})
}),
byUser: publicProcedure.input(z.string()).query(async ({ ctx, input }) => {
return ctx.prisma.styles.findMany({
orderBy: { createdAt: 'desc' },
where: {
user: {
name: input,
},
public: true,
},
})
}),
byId: publicProcedure.input(z.string().cuid()).query(async ({ ctx, input }) => {
return ctx.prisma.styles.findUnique({
where: {
id: input,
public: true,
},
})
}),
create: protectedProcedure.mutation(async ({ ctx }) => {
return ctx.prisma.styles.create({
data: {
content: `${ctx.session.user.name}\n\t${dayjs().format('HH:mm:ss DD.MM.YYYY')}`,
userId: ctx.session.user.id,
},
})
}),
edit: protectedProcedure
.input(
z.object({
id: z.string().cuid(),
content: z.string().min(1),
styles: z.object({}).passthrough(),
})
)
.mutation(async ({ ctx, input: { id, ...input } }) => {
return ctx.prisma.styles.update({
where: { id },
data: input,
})
}),
})
|
volatile bool Pulse = false; //Global flag to set on a pulse event
const uint8_t PulsePin = 2; //Pin to measure pulse on
void setup() {
Serial.begin(9600);
Serial.println("Welcome to The Machine...");
attachInterrupt(digitalPinToInterrupt(PulsePin), PulseEvent, FALLING); //Configure interrupt
}
void loop() {
static unsigned long EventTime = millis(); //Used to keep track of time between events
if(Pulse == true) {
unsigned long EventDelta = millis() - EventTime; //Capture event time period immediately
EventTime = millis(); //Reset timing delta
Serial.print("Pulse Delta = ");
Serial.print(EventDelta);
Serial.println(" ms");
Pulse = false; //Clear pulse flag
}
}
void PulseEvent()
{
Pulse = true; //Set pulse flag
}
|
let express = require('express'),
bodyParser = require('body-parser'),
config = require('config');
request = require('request');
app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.listen(8989, () => console.log('Example app listening on port 8989!'));
app.get('/', (req, res) => res.send('Hello World!'));
// Adds support for GET requests to our webhook
app.get('/webhook', (req, res) => {
// Your verify token. Should be a random string.
let VERIFY_TOKEN = "your verify token";
// Parse the query params
let mode = req.query['hub.mode'];
let token = req.query['hub.verify_token'];
let challenge = req.query['hub.challenge'];
// Checks if a token and mode is in the query string of the request
if (mode && token) {
// Checks the mode and token sent is correct
if (mode === 'subscribe' && token === VERIFY_TOKEN) {
// Responds with the challenge token from the request
console.log('WEBHOOK_VERIFIED');
res.status(200).send(challenge);
} else {
// Responds with '403 Forbidden' if verify tokens do not match
res.sendStatus(403);
}
}
});
// Creates the endpoint for our webhook
app.post('/webhook', (req, res) => {
let body = req.body;
console.log(body);
if (body.object === 'page') {
// Iterates over each entry - there may be multiple if batched
body.entry.forEach(function (entry) {
// Gets the message. entry.messaging is an array, but
// will only ever contain one message, so we get index 0
let webhook_event = entry.messaging[0];
console.log(webhook_event);
// Get the sender PSID
let sender_psid = webhook_event.sender.id;
console.log('Sender PSID: ' + sender_psid);
// Check if the event is a message or postback and
// pass the event to the appropriate handler function
if (webhook_event.message) {
handleMessage(sender_psid, webhook_event.message);
} else if (webhook_event.postback) {
handlePostback(sender_psid, webhook_event.postback);
}
});
// Returns a '200 OK' response to all requests
res.status(200).send('EVENT_RECEIVED');
} else {
// Returns a '404 Not Found' if event is not from a page subscription
res.sendStatus(404);
}
});
// Handles messages events
const handleMessage = (sender_psid, received_message) => {
let response;
if (received_message.text) {
response = {'text': received_message.text + ', Tsőőő!'};
callSendAPI(sender_psid, response);
}
}
// Sends response messages via the Send API
const callSendAPI = (sender_psid, response, cb = null) => {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
};
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": config.get('facebook.page.access_token') },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
if (cb) {
cb();
}
} else {
console.error("Unable to send message:" + err);
}
});
}
|
//
// ViewController.swift
// faceDetection
//
// Created by David Isermann on 21.01.22.
//
import UIKit
import Vision
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var imageOrientation = CGImagePropertyOrientation(.up)
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let image = UIImage(named: "group") {
imageView.image = image
imageView.contentMode = .scaleAspectFit
imageOrientation = CGImagePropertyOrientation(image.imageOrientation)
guard let cgImage = image.cgImage else {return}
setupVision(image: cgImage)
}
}
private func setupVision (image: CGImage) {
let faceDetectionRequest = VNDetectFaceRectanglesRequest(completionHandler: self.handelFaceDetectionRequest)
let imageRequestHandler = VNImageRequestHandler(cgImage: image, orientation: imageOrientation, options: [:])
do {
try imageRequestHandler.perform([faceDetectionRequest])
}catch let error as NSError {
print(error)
return
}
}
private func handelFaceDetectionRequest (request: VNRequest?, error: Error?) {
if let requestError = error as NSError? {
print(requestError)
return
}
guard let image = imageView.image else {return}
guard let cgImage = image.cgImage else {return}
let imageRect = self.determineScale(cgImage: cgImage, imageViewFrame: imageView.frame)
self.imageView.layer.sublayers = nil
if let results = request?.results as? [VNFaceObservation] {
for observation in results {
let faceRect = convertUnitToPoint(originalImageRect: imageRect, targetRect: observation.boundingBox)
let emojiRect = CGRect(x: faceRect.origin.x, y: faceRect.origin.y - 5, width: faceRect.size.width + 5, height: faceRect.size.height + 5)
let textLayer = CATextLayer()
textLayer.string = "🦸♂️"
textLayer.fontSize = faceRect.width
textLayer.frame = emojiRect
textLayer.contentsScale = UIScreen.main.scale
self.imageView.layer.addSublayer(textLayer)
}
}
}
}
|
import React from "react";
import { Routes, Route } from "react-router-dom";
import Homepage from "./Homepage";
import SignupForm from "./SignupForm";
import LoginForm from "./LoginForm";
import AccountViewer from "./AccountViewer";
import ProfileViewer from "./ProfileViewer";
import GameList from "./GameList";
import GameDetail from "./GameDetail";
import ReviewForm from "./ReviewForm";
import ReviewList from "./ReviewList";
import ReviewViewer from "./ReviewViewer";
function Router() {
return (
<Routes>
<Route exact path="/" element={<Homepage/>} />
<Route exact path="/signup" element={<SignupForm/>} />
<Route exact path="/login" element={<LoginForm/>} />
<Route exact path="/account" element={<AccountViewer/>} />
<Route exact path="/reviews" element={<ReviewList />} />
<Route exact path="/games/search" element={<GameList/>} />
<Route exact path="/reviews/new" element={<ReviewForm/>} />
<Route exact path="/reviews/edit" element={<ReviewForm isEdit={true} />} />
<Route path="/users/:username" element={<ProfileViewer/>} />
<Route path="/games/:slug" element={<GameDetail/>} />
<Route path="/reviews/:id" element={<ReviewViewer/>} />
{/* <Route path="/reviews/:slug" element={<ReviewList SLUG />} /> */}
</ Routes>
);
}
export default Router;
|
# CRUD using Java 20, Spring Boot, and PostgreSQL
This repository contains a simple CRUD application developed in Java 20, using the Spring Boot framework and PostgreSQL database. The CRUD allows performing basic operations of creating, reading, updating, and deleting products.
## Requirements
Make sure you have the following tools installed in your development environment:
- Java 20
- Spring Boot
- PostgreSQL
## Database Configuration
Before running the application, you need to configure the Postgres database. Follow the steps below:
1. Create a database in PostgreSQL.
2. Open the `application.properties` file located in `src/main/resources`.
3. Modify the properties `spring.datasource.url`, `spring.datasource.username`, and `spring.datasource.password` according to your database settings.
## Running the Application
To run the application, follow the steps below:
1. Clone this repository to your development environment.
2. Navigate to the project's root directory.
3. Run the following command to compile and execute the application:
```shell
./mvnw spring-boot:run
```
1. The application will be available at http://localhost:8080.
## Endpoints
The API has the following endpoints:
- GET /products: Returns all registered products.
- GET /products/{id}: Returns the details of a specific product based on the provided ID.
- POST /products: Registers a new product based on the data provided in the request body.
- PUT /products/{id}: Updates an existing product based on the provided ID and the data provided in the request body.
- DELETE /products/{id}: Deletes a product based on the provided ID.
## 👨🏽💻 Author:
<img src="https://avatars.githubusercontent.com/u/85323953?v=4" width="100px;" alt="foto do desenvolvedor"/>
- [@CelioAmaral](https://github.com/CelioAmaral)
<sup>Systems Analyst</sup>
</br>
<div>
<a href="https://www.linkedin.com/in/celioamaral20" target="_blank"><img align="center" alt="Celio-Link" height="30" width="90" src="https://img.shields.io/badge/-LinkedIn-%230077B5?style=flat&logo=linkedin&logoColor=white" target="_blank"></a>
</div>
|
import { TouchableOpacity, TouchableOpacityProps,Clipboard } from 'react-native';
import { Heading, HStack, Text, VStack } from 'native-base';
export interface PessoaCardProps {
id: string;
nome: string;
rua: string;
numero: string;
complemento: string;
documento: string;
cidade_id: string;
tipo_id: string;
createdAt: string;
updatedAt: string;
}
interface Props extends TouchableOpacityProps {
data: PessoaCardProps;
}
export function PessoaCard({ data, ...rest }: Props) {
const handleCopyData = () => {
const dataToCopy = `${data.id}`;
Clipboard.setString(dataToCopy);
};
return (
<TouchableOpacity {...rest}onLongPress={handleCopyData}>
<HStack
w="full"
h={48}
bgColor="blue.700"
borderBottomWidth={3}
borderBottomColor="blue.500"
justifyContent="space-between"
alignItems="center"
rounded="sm"
mb={3}
p={8}
>
<VStack>
<Heading color="white" fontSize="md" fontFamily="heading">
{data.nome}
</Heading>
<Text color="gray.200" fontSize="xs">
Rua: {data.rua}
</Text>
<Text color="gray.200" fontSize="xs">
Número: {data.numero}
</Text>
<Text color="gray.200" fontSize="xs">
Complemento: {data.complemento}
</Text>
<Text color="gray.200" fontSize="xs">
Documento: {data.documento}
</Text>
<Text color="gray.200" fontSize="xs">
ID da cidade: {data.cidade_id}
</Text>
<Text color="gray.200" fontSize="xs">
ID do tipo sanguíneo: {data.tipo_id}
</Text>
<Text color="gray.200" fontSize="xs">
ID da pessoa no BD: {data.id}
</Text>
</VStack>
</HStack>
</TouchableOpacity>
);
}
|
<?php
namespace davidhirtz\yii2\skeleton\models;
use DateTimeZone;
use davidhirtz\yii2\datetime\Date;
use davidhirtz\yii2\datetime\DateTime;
use davidhirtz\yii2\datetime\DateTimeBehavior;
use davidhirtz\yii2\skeleton\behaviors\TimestampBehavior;
use davidhirtz\yii2\skeleton\behaviors\TrailBehavior;
use davidhirtz\yii2\skeleton\controllers\AccountController;
use davidhirtz\yii2\skeleton\db\ActiveRecord;
use davidhirtz\yii2\skeleton\helpers\FileHelper;
use davidhirtz\yii2\skeleton\helpers\Image;
use davidhirtz\yii2\skeleton\models\interfaces\StatusAttributeInterface;
use davidhirtz\yii2\skeleton\models\queries\UserQuery;
use davidhirtz\yii2\skeleton\models\traits\StatusAttributeTrait;
use davidhirtz\yii2\skeleton\validators\DynamicRangeValidator;
use davidhirtz\yii2\skeleton\validators\UniqueValidator;
use davidhirtz\yii2\skeleton\web\StreamUploadedFile;
use Yii;
use yii\db\ActiveQuery;
use yii\helpers\Url;
use yii\web\UploadedFile;
/**
* @property int $id
* @property int $status
* @property string|null $name
* @property string $email
* @property string|null $password_hash
* @property string|null $password_salt
* @property string|null $first_name
* @property string|null $last_name
* @property Date|null $birthdate
* @property string|null $city
* @property string|null $country
* @property string|null $picture
* @property string $language
* @property string|null $timezone
* @property string|null $auth_key
* @property string|null $verification_token
* @property string|null $password_reset_token
* @property string|null $google_2fa_secret
* @property int $is_owner
* @property int $created_by_user_id
* @property int $login_count
* @property DateTime|null $last_login
* @property DateTime|null $updated_at
* @property DateTime $created_at
*
* @property string $uploadPath {@see static::setUploadPath()}
*
* @property-read User $admin {@see static::getAdmin()}
* @property-read AuthClient[] $authClients {@see static::getAuthClients()}
*
* @mixin TrailBehavior
*/
class User extends ActiveRecord implements StatusAttributeInterface
{
use StatusAttributeTrait;
public const AUTH_USER_CREATE = 'userCreate';
public const AUTH_USER_DELETE = 'userDelete';
public const AUTH_USER_UPDATE = 'userUpdate';
public const AUTH_USER_ASSIGN = 'authUpdate';
public const AUTH_ROLE_ADMIN = 'admin';
/**
* @var bool whether uploads should be automatically rotated based on their EXIF data
*/
public bool $autorotatePicture = true;
/**
* @var int the minimum length for the username
*/
public int $nameMinLength = 3;
/**
* @var int the maximum length for the username
*/
public int $nameMaxLength = 32;
/**
* @var string the pattern for the username
*/
public string $namePattern = '/^\d*[a-z][a-z0-9\.-]*[a-z0-9]$/si';
/**
* @var int the minimum length for the password
*/
public int $passwordMinLength = 5;
/**
* @var bool whether the name is required
*/
public bool $requireName = true;
/**
* @var UploadedFile|StreamUploadedFile|string|null the profile picture upload
*/
public UploadedFile|StreamUploadedFile|string|null $upload = null;
/**
* @var array contains the allowed upload extensions for the profile picture
*/
public array $uploadExtensions = ['gif', 'jpg', 'jpeg', 'png'];
/**
* @var bool whether mimetype should check the upload extension
*/
public bool $uploadCheckExtensionByMimeType = true;
/**
* @var string|false set false to disabled profile pictures
*/
private string|false $_uploadPath = 'uploads/users/';
public function behaviors(): array
{
return array_merge(parent::behaviors(), [
'DateTimeBehavior' => DateTimeBehavior::class,
'TimestampBehavior' => TimestampBehavior::class,
'TrailBehavior' => [
'class' => TrailBehavior::class,
'modelClass' => User::class,
],
]);
}
public function rules(): array
{
return [
[
['name', 'email', 'city', 'country', 'first_name', 'last_name'],
'trim',
],
[
['email'],
'required',
],
[
/**
* @see static::getStatuses()
* @see static::getLanguages()
* @see static::getTimezones()
*/
['status', 'language', 'timezone'],
DynamicRangeValidator::class,
],
[
/**
* @see static::getCountries()
*/
['country'],
DynamicRangeValidator::class,
'skipOnEmpty' => true,
],
[
['name'],
$this->requireName ? 'required' : 'safe',
],
[
['name'],
'string',
'min' => $this->nameMinLength,
'max' => max($this->nameMinLength, $this->nameMaxLength),
'skipOnError' => true,
],
[
['name'],
'match',
'pattern' => $this->namePattern,
'message' => Yii::t('skeleton', 'Username must only contain alphanumeric characters.'),
'skipOnError' => true,
],
[
['name'],
UniqueValidator::class,
'message' => Yii::t('skeleton', 'This username is already used by another user.'),
],
[
['email'],
'string',
'max' => 100,
],
[
['email'],
'email',
'skipOnError' => true,
],
[
['email'],
'unique',
'message' => Yii::t('skeleton', 'This email is already used by another user.'),
'skipOnError' => true,
'when' => fn () => $this->isAttributeChanged('email')
],
[
['city', 'first_name', 'last_name'],
'string',
'max' => 50,
],
[
['upload'],
'file',
'checkExtensionByMimeType' => $this->uploadCheckExtensionByMimeType,
'extensions' => $this->uploadExtensions,
],
];
}
public function validatePassword(string $password): bool
{
return $this->password_hash && Yii::$app->getSecurity()->validatePassword($password . $this->password_salt, $this->password_hash);
}
public function beforeValidate(): bool
{
$this->status ??= static::STATUS_ENABLED;
$this->language ??= Yii::$app->language;
$this->timezone = $this->timezone ?: Yii::$app->getTimeZone();
return parent::beforeValidate();
}
public function afterValidate(): void
{
if (!$this->requireName && !$this->name) {
$this->name = null;
}
parent::afterValidate();
}
public function beforeSave($insert): bool
{
if (parent::beforeSave($insert)) {
if ($insert) {
$this->is_owner ??= !static::find()->exists();
$this->generateAuthKey();
}
if ($this->upload) {
$this->generatePictureFilename();
}
return true;
}
return false;
}
public function afterSave($insert, $changedAttributes): void
{
if (!$insert) {
if (isset($changedAttributes['picture'])) {
$this->deletePicture($changedAttributes['picture']);
}
}
if ($this->upload) {
$this->savePictureUpload();
}
parent::afterSave($insert, $changedAttributes);
// Finally, unset upload, so additional updates won't try to upload again.
$this->upload = null;
}
public function afterDelete(): void
{
if ($this->picture) {
$this->deletePicture($this->picture);
}
parent::afterDelete();
}
public function getAdmin(): UserQuery
{
/** @var UserQuery $query */
$query = $this->hasOne(static::class, ['id' => 'created_by_user_id']);
return $query;
}
public function getAuthClients(): ActiveQuery
{
return $this->hasMany(AuthClient::class, ['user_id' => 'id']);
}
/**
* @return UserQuery<static>
*/
public static function find(): UserQuery
{
return Yii::createObject(UserQuery::class, [static::class]);
}
public static function findByEmail(string $email): UserQuery
{
return static::find()->whereLower([static::tableName() . '.[[email]]' => $email]);
}
public static function findByName(string $name): UserQuery
{
return static::find()->whereLower([static::tableName() . '.[[name]]' => $name]);
}
public function load($data, $formName = null): bool
{
// First load form data, then override upload via instance.
$hasData = parent::load($data, $formName);
$this->upload = $this->getUploadPath() ? UploadedFile::getInstance($this, 'upload') : null;
return $hasData || $this->upload;
}
public function delete(): false|int
{
if ($this->isOwner()) {
$this->addError('id', Yii::t('skeleton', 'This user is the website owner. Please transfer ownership to another user before deleting this user.'));
return false;
}
return parent::delete();
}
public function afterPasswordChange(): void
{
$trail = Trail::create();
$trail->model = User::class;
$trail->model_id = (string)$this->id;
$trail->type = Trail::TYPE_PASSWORD;
$trail->insert();
}
public function generatePictureFilename(): void
{
$extension = $this->upload->extension ?? null;
if (!$extension) {
$extensions = array_intersect($this->uploadExtensions, FileHelper::getExtensionsByMimeType($this->upload->type ?? false));
$extension = $extensions ? current($extensions) : null;
}
$this->picture = FileHelper::generateRandomFilename($extension, 12);
$this->generatePictureFilenameInternal();
}
private function generatePictureFilenameInternal(): void
{
if (is_file($this->getUploadPath() . $this->picture)) {
$this->generatePictureFilename();
}
}
public function savePictureUpload(): bool
{
if (FileHelper::createDirectory($uploadPath = $this->getUploadPath())) {
if ($this->upload->saveAs($uploadPath . $this->picture)) {
if ($this->autorotatePicture) {
Image::autorotate($uploadPath . $this->picture)->save();
}
return true;
}
}
return false;
}
public function deletePicture(?string $picture): bool
{
return $picture && FileHelper::removeFile($this->getUploadPath() . $picture);
}
public function generatePasswordHash(string $password): void
{
$this->password_salt = Yii::$app->getSecurity()->generateRandomString(10);
$this->password_hash = Yii::$app->getSecurity()->generatePasswordHash($password . $this->password_salt);
}
public function generateAuthKey(): void
{
$this->auth_key = Yii::$app->getSecurity()->generateRandomString();
}
public function generateVerificationToken(): void
{
$this->verification_token = Yii::$app->getSecurity()->generateRandomString();
}
public function generatePasswordResetToken(): void
{
$this->password_reset_token = Yii::$app->getSecurity()->generateRandomString();
}
/**
* @noinspection PhpUnused
*/
public function getFullName(): string
{
return trim($this->first_name . ' ' . $this->last_name);
}
/**
* @noinspection PhpUnused
*/
public function getInitials(): string
{
return $this->first_name && $this->last_name ? ($this->first_name[0] . $this->last_name[0]) : substr($this->name, 0, 2);
}
public function getUsername(): ?string
{
return $this->name;
}
/**
* @see AccountController::actionConfirm()
*/
public function getEmailConfirmationUrl(): ?string
{
return $this->verification_token ? Url::to(['account/confirm', 'email' => $this->email, 'code' => $this->verification_token], true) : null;
}
/**
* @see AccountController::actionReset()
*/
public function getPasswordResetUrl(): ?string
{
return $this->password_reset_token ? Url::to(['account/reset', 'email' => $this->email, 'code' => $this->password_reset_token], true) : null;
}
/**
* @noinspection PhpUnused
*/
public function getTimezoneOffset(): string
{
$date = new \DateTime('now');
return 'GMT ' . $date->format('P');
}
public function getUploadPath(): string|false
{
return $this->_uploadPath ? (Yii::getAlias('@webroot') . DIRECTORY_SEPARATOR . $this->_uploadPath) : false;
}
public function setUploadPath(string $uploadPath): void
{
$this->_uploadPath = trim($uploadPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
public function getBaseUrl(): string
{
return '/' . ltrim(str_replace(DIRECTORY_SEPARATOR, '/', $this->_uploadPath), '/');
}
public static function getStatuses(): array
{
return [
static::STATUS_DISABLED => [
'name' => Yii::t('skeleton', 'Disabled'),
'icon' => 'exclamation-triangle',
],
static::STATUS_ENABLED => [
'name' => Yii::t('skeleton', 'Enabled'),
'icon' => 'user',
],
];
}
public function getStatusName(): string
{
return !$this->isOwner() ? (static::getStatuses()[$this->status]['name'] ?? '') : Yii::t('skeleton', 'Site Owner');
}
public function getStatusIcon(): string
{
return !$this->isOwner() ? (static::getStatuses()[$this->status]['icon'] ?? '') : 'star';
}
public function getTrailAttributes(): array
{
return array_diff($this->attributes(), [
'password_hash',
'password_salt',
'auth_key',
'verification_token',
'password_reset_token',
'google_2fa_secret',
'login_count',
'last_login',
'created_by_user_id',
'updated_at',
'created_at',
]);
}
public function getTrailModelName(): string
{
return $this->id ? $this->getUsername() : $this->getTrailModelType();
}
public function getTrailModelType(): string
{
return Yii::t('skeleton', 'User');
}
public function getTrailModelAdminRoute(): array|false
{
return $this->id ? ['/admin/user/update', 'id' => $this->id] : false;
}
public function isOwner(): bool
{
return (bool)$this->is_owner;
}
public function isUnconfirmed(): bool
{
return !$this->isOwner() && !empty($this->verification_token);
}
public static function getCountries(): array
{
return require(Yii::getAlias('@skeleton/messages/') . Yii::$app->language . '/countries.php');
}
public static function getLanguages(): array
{
$i18n = Yii::$app->getI18n();
$languages = [];
foreach (Yii::$app->getI18n()->getLanguages() as $language) {
$languages[$language]['name'] = $i18n->getLabel($language);
}
return $languages;
}
public static function getTimezones(): array
{
return array_combine(DateTimeZone::listIdentifiers(), DateTimeZone::listIdentifiers());
}
public function attributeLabels(): array
{
return [
...parent::attributeLabels(),
'id' => Yii::t('skeleton', 'ID'),
'name' => Yii::t('skeleton', 'Username'),
'email' => Yii::t('skeleton', 'Email'),
'password' => Yii::t('skeleton', 'Password'),
'first_name' => Yii::t('skeleton', 'First name'),
'last_name' => Yii::t('skeleton', 'Last name'),
'birthdate' => Yii::t('skeleton', 'Birthdate'),
'city' => Yii::t('skeleton', 'City'),
'country' => Yii::t('skeleton', 'Country'),
'picture' => Yii::t('skeleton', 'Picture'),
'language' => Yii::t('skeleton', 'Language'),
'timezone' => Yii::t('skeleton', 'Timezone'),
'verification_token' => Yii::t('skeleton', 'Email verification code'),
'login_count' => Yii::t('skeleton', 'Login count'),
'last_login' => Yii::t('skeleton', 'Last login'),
'is_owner' => Yii::t('skeleton', 'Website owner'),
'updated_at' => Yii::t('skeleton', 'Updated'),
'created_at' => Yii::t('skeleton', 'Created'),
'upload' => Yii::t('skeleton', 'Picture'),
];
}
public function formName(): string
{
return 'User';
}
public static function tableName(): string
{
return '{{%user}}';
}
}
|
import type { Result } from "@/types/result";
import { isTrue } from "@/types/result";
import type { ids } from "~/types";
/**
* 获取用户地址列表
* @param token token
* @returns
*/
export function getAddressList(token: string) {
return useHttp.get<Result<AddressInfoVO[]>>("/user/address", {}, { headers: { Authorization: token } });
}
// 地址信息
export interface AddressInfoVO {
id: string
name: string
userId: string
isDefault: number
province: string
city: string
county: string
address: string
postalCode: string
phone: string
createTime: string
updateTime: string
}
/**
* 添加收货地址
* @param dto
* @param token
* @returns
*/
export function addAddressByDTO(dto: AddressDTO, token: string) {
dto.isDefault = +dto.isDefault;
return useHttp.post<Result<string>>("/user/address", { ...dto }, { headers: { Authorization: token } });
}
// 添加收货地址参数
export interface AddressDTO {
name: string
phone: string
isDefault: number | boolean // 是否默认
province: string
city: string
county: string
address: string
postalCode: string
}
/**
* 更新收货地址
* @param addressId 地址id
* @param dto
* @param token
* @returns
*/
export function updateAddressById(addressId: string, dto: AddressDTO, token: string) {
dto.isDefault = +dto.isDefault;
return useHttp.put<Result<string>>(`/user/address/${addressId}`, { ...dto }, { headers: { Authorization: token } });
}
/**
* 设为默认地址
* @param addressId 地址id
* @param isDefault
* @param token
* @returns
*/
export function updateDefaultAddress(addressId: string, isDefault: number, token: string) {
return useHttp.put<Result<string>>(`/user/address/default/${addressId}`, { isDefault: +isDefault }, { headers: { Authorization: token } });
}
/**
* 删除收货地址(单个)
* @param addressId 收货地址id
* @param token
* @returns
*/
export function deleteAddressById(addressId: string, token: string) {
return useHttp.deleted<Result<string>>(`/user/address/one/${addressId}`, {}, { headers: { Authorization: token } });
}
/**
* 删除收货地址(批量)
* @param ids
* @param token
* @returns
*/
export function deleteBatchAddressByIds(ids: ids, token: string) {
return useHttp.deleted<Result<string>>("/user/address/some", {
ids,
}, { headers: { Authorization: token } });
}
|
#pragma once
#include <DirectXMath.h>
class Camera
{
public:
Camera();
void PerspectiveFov(float fovDegrees, float aspectRatio, float nearZ, float farZ);
void OrthographicFov(int screenWidth, int screenHeight, float nearZ, float farZ);
DirectX::XMMATRIX& GetViewMatrix();
DirectX::XMMATRIX& GetBaseViewMatrix();
DirectX::XMMATRIX& GetProjectionMatrix();
const DirectX::XMVECTOR& GetPositionVector() const;
const DirectX::XMFLOAT3& GetPositionFloat3() const;
const DirectX::XMVECTOR& GetRotationVector() const;
const DirectX::XMFLOAT3& GetRotationFloat3() const;
void SetPosition(const DirectX::XMVECTOR& pos);
void SetPosition(DirectX::XMFLOAT3& pos);
void SetPosition(float x, float y, float z);
void AdjustPosition(const DirectX::XMVECTOR& pos);
void AdjustPosition(float x, float y, float z);
void SetRotation(const DirectX::XMVECTOR& rot);
void SetRotation(float x, float y, float z);
void AdjustRotation(const DirectX::XMVECTOR& rot, bool constraint = false);
void AdjustRotation(float x, float y, float z, bool constraint = false);
void SetLookAtPos(DirectX::XMFLOAT3 lookAtPos);
const DirectX::XMVECTOR& GetForwardVector();
const DirectX::XMVECTOR& GetRightVector();
const DirectX::XMVECTOR& GetLeftVector();
const DirectX::XMVECTOR& GetBackwardVector();
DirectX::XMVECTOR camTarget;
DirectX::XMFLOAT4 dir;
DirectX::XMFLOAT3 rot;
float yaw = 0.0f;
float pitch = 0.0f;
bool PossessCharacter = false;
DirectX::XMFLOAT3 pos;
private:
void UpdateViewMatrix();
DirectX::XMVECTOR posVector;
DirectX::XMVECTOR rotVector;
DirectX::XMMATRIX viewMatrix;
DirectX::XMMATRIX projectionMatrix;
const DirectX::XMVECTOR DEFAULT_FORWARD_VECTOR = DirectX::XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
const DirectX::XMVECTOR DEFAULT_UP_VECTOR = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
const DirectX::XMVECTOR DEFAULT_BACKWARD_VECTOR = DirectX::XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);
const DirectX::XMVECTOR DEFAULT_LEFT_VECTOR = DirectX::XMVectorSet(-1.0f, 0.0f, 0.0f, 0.0f);
const DirectX::XMVECTOR DEFAULT_RIGHT_VECTOR = DirectX::XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
public:
DirectX::XMVECTOR vec_forward;
DirectX::XMVECTOR vec_left;
DirectX::XMVECTOR vec_right;
DirectX::XMVECTOR vec_backward;
DirectX::XMVECTOR upDir;
};
|
from jsonschema import ValidationError
from psycopg import IntegrityError
from rest_framework.decorators import (
api_view,
authentication_classes,
permission_classes,
)
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
from ..serializers import CategorySerializer, ExpenseSerializer
from ..models import Expense, Category
@api_view(["GET"])
@authentication_classes([SessionAuthentication])
@permission_classes([IsAuthenticated])
def get_incomes(request):
categories = Category.objects.all()
currency = request.session.get("currency")
serializer = CategorySerializer(
categories, context={"currency": currency}, many=True
)
return Response(serializer.data, status=200)
@api_view(["POST"])
@authentication_classes([SessionAuthentication])
@permission_classes([IsAuthenticated])
def create_expense(request, id):
category_id = request.data.get("category")
title = request.data.get("title")
amount = float(request.data.get("amount")) or 0
date = request.data.get("date")
currency = request.session.get("currency")
category = Category.objects.get(pk=category_id)
try:
expense = Expense.objects.create(
title=title, amount=amount, date=date, category=category
)
except (IntegrityError, ValidationError, AttributeError) as e:
raise e
serializer = ExpenseSerializer(expense, context={"currency": currency}, many = False)
return Response(serializer.data, status=200)
@api_view(["DELETE"])
@authentication_classes([SessionAuthentication])
@permission_classes([IsAuthenticated])
def delete_expense(request, id):
expenseId = request.data
try:
expense = Expense.objects.get(id=expenseId)
expense.delete()
except Expense.DoesNotExist as e:
return Response({"error": "Expense does not exist"}, status=404)
serializer = ExpenseSerializer(expense, many = False)
return Response(serializer.data, status=200)
|
<mat-sidenav-container class="sidenav-container">
<mat-sidenav #drawer class="sidenav" fixedInViewport
[attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
[mode]="(isHandset$ | async) ? 'over' : 'side'"
[opened]="(isHandset$ | async) === false">
<mat-list *ngIf="user">
<mat-list-item>
<mat-icon matListItemIcon>account_circle</mat-icon>
<h4 matListItemTitle>{{ user.name }}</h4>
<p matListItemLine class="demo-2"> {{ user.email }} </p>
</mat-list-item>
<mat-divider></mat-divider>
</mat-list>
<mat-nav-list dense>
<a mat-list-item routerLink="/admin/dashboard">
<mat-icon matListItemIcon>dashboard</mat-icon>
Dashboard
</a>
<a mat-list-item routerLink="/admin/form">
<mat-icon matListItemIcon>dns</mat-icon>
Form
</a>
<a mat-list-item routerLink="/admin/about">
<mat-icon matListItemIcon>dns</mat-icon>
About
</a>
<a mat-list-item routerLink="/admin/gallery">
<mat-icon matListItemIcon>photo_library</mat-icon>
Gallery
</a>
<a mat-list-item routerLink="/admin/pictures">
<mat-icon matListItemIcon>photo_library</mat-icon>
Pictures
</a>
<a mat-list-item (click)="change()">
<mat-icon matListItemIcon>published_with_changes</mat-icon>
change
</a>
<a mat-list-item (click)="logout()">
<mat-icon matListItemIcon>logout</mat-icon>
Logout
</a>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
<mat-toolbar color="primary">
<button
type="button"
aria-label="Toggle sidenav"
mat-icon-button
(click)="drawer.toggle()"
*ngIf="isHandset$ | async">
<mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
</button>
<span>ng Project</span>
</mat-toolbar>
<router-outlet></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
|
raiz quadrada em python
print(9 ** (1/2))
THE BACKSLASH
imprime aspas dentro de uma string
print('Brian\'s mother: He\'s not an angel. He\'s a very naughty boy!')
Brian's mother: He's not an angel. He's very naughty boy!
**LIST FUNCTIONS**
RANGE
para saber que é uma lista se usa list()
number = list(range(10))
APPEND
nums.append(10)
INSERT
words.insert(index, "ex")
INDEX - finds the first occurrence of a list item and returns its index.
letters.index('r')
max(list): Returns the maximum value.
min(list): Returns the minimum value.
list.count(item): Returns a count of how many times an item occurs in a list.
list.remove(item): Removes an item from a list.
list.reverse(): Reverses items in a list.
FORMAT
nums = [4, 5, 6]
msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])
print(msg)
Each argument of the format function is placed in the string at the
corresponding position, which is determined using the curly braces { }.
You can also name the placeholders, instead of the index numbers.
a = "{x}, {y}".format(x=5, y=12)
**STRING FUNCTION**
print(", ".join(["spam", "eggs", "ham"]))
#prints "spam, eggs, ham"
print("Hello ME".replace("ME", "world"))
#prints "Hello world"
print("This is a sentence.".startswith("This"))
# prints "True"
print("This is a sentence.".endswith("sentence."))
# prints "True"
print("This is a sentence.".upper())
# prints "THIS IS A SENTENCE."
print("AN ALL CAPS SENTENCE".lower())
#prints "an all caps sentence"
print("spam, eggs, ham".split(", "))
#prints "['spam', 'eggs', 'ham']"
|
use std::fs;
use std::future::Future;
use std::io::{Read, Write};
use std::ops::Deref;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
use std::sync::Arc;
use std::thread::JoinHandle;
use async_trait::async_trait;
use log::debug;
use hub::config::{ImageConfig, ImageFormat};
use hub::error::*;
use hub::paths::PathManager;
use crate::DiskManager;
pub struct QCow2 {
backing: PathBuf,
image: Arc<ImageConfig>,
paths: Arc<PathManager>,
proc: Option<QemuProc>,
}
struct QemuProc {
qmp: UnixStream,
qemu: JoinHandle<Result<ExitStatus>>,
socket_path: PathBuf,
}
impl QemuProc {
pub fn init(qcow2: &mut QCow2) -> Result<Self> {
let monitor = qcow2
.backing
.parent()
.unwrap_or(qcow2.backing.as_ref())
.join("qemu-monitor.sock");
let file_driver = format!(
"node-name=prot-node,driver=file,filename={}",
qcow2.backing.to_string_lossy()
);
let qcow_driver = format!(
"node-name=fmt-node,driver={},file=prot-node",
match qcow2.image.format {
ImageFormat::Raw => "raw",
#[cfg(feature = "qemu")]
ImageFormat::QCow2 => "qcow2",
}
);
let qemu_monitor = format!(
"socket,path={},id=qemu-monitor",
monitor.to_string_lossy()
);
let fuse_driver = format!(
"type=fuse,id=exp0,node-name=fmt-node,mountpoint={},writable=on",
qcow2.backing.to_string_lossy()
);
if monitor.exists() {
fs::remove_file(&monitor)?;
}
let server = UnixListener::bind(monitor.clone())?;
let (mut sender, receiver) = std::sync::mpsc::channel();
let proc = std::thread::spawn(move || {
let exit = Command::new("qemu-storage-daemon")
.args(["--blockdev", file_driver.as_ref()])
.args(["--blockdev", qcow_driver.as_ref()])
.args(["--chardev", qemu_monitor.as_ref()])
.args(["--monitor", "chardev=qemu-monitor"])
.args(["--export", fuse_driver.as_ref()])
.spawn()?
.wait()?;
if !exit.success() { sender.send(()).unwrap_or(()) }
Ok(exit)
});
let (mut socket, _) = server.accept()?;
let mut vec = vec![0u8; 1024];
match socket.read(&mut vec) {
Ok(read) if read > 0 => Ok(()),
Ok(_) => Err(Error::from(BuildError::QmpQuitWrite0)),
Err(err) => Err(err.into()),
}?;
Self::qmp_send_message(&mut socket, Self::qmp_feature_negotiation())?;
debug!("Feature Negotiation complete");
Ok(Self {
qmp: socket,
qemu: proc,
socket_path: monitor.clone(),
})
}
pub fn kill(mut self) -> Result<ExitStatus> {
Self::qmp_send_message(&mut self.qmp, Self::qmp_quit())?;
let status = self.qemu.join().map_err(|err| Error::from(BuildError::QmpQuitFail(err)))??;
fs::remove_file(self.socket_path)?;
return Ok(status);
}
fn qmp_send_message(socket: &mut UnixStream, value: serde_json::Value) -> Result<()> {
let mut vec = vec![0u8; 1024];
socket.write_all(serde_json::to_string(&value)?.as_bytes())?;
loop {
match socket.read(&mut vec) {
Ok(read) if read > 0 => break,
Ok(_) => Err(Error::from(BuildError::QmpQuitWrite0))?,
Err(ref err) if err.kind() == std::io::ErrorKind::WouldBlock => continue,
Err(err) => Err(Error::from(err))?,
};
}
Ok(())
}
#[inline(always)]
fn qmp_feature_negotiation() -> serde_json::Value {
serde_json::json! {{ "execute": "qmp_capabilities", "arguments": { "enable": [] } }}
}
#[inline(always)]
fn qmp_quit() -> serde_json::Value {
serde_json::json! {{ "execute": "quit" }}
}
}
#[async_trait(? Send)]
impl DiskManager for QCow2 {
fn backing(&self) -> PathBuf {
self.backing.clone()
}
fn image(&self) -> &ImageConfig {
self.image.deref()
}
fn paths(&self) -> &PathManager {
self.paths.deref()
}
fn create_disk(config: Arc<ImageConfig>, path: Arc<PathManager>) -> Result<Self> {
let create = Command::new("qemu-img")
.arg("create")
.arg(path.final_image())
.args([
format!("{}M", config.size).as_ref(),
"-f",
match config.format {
ImageFormat::Raw => "raw",
#[cfg(feature = "qemu")]
ImageFormat::QCow2 => "qcow2",
},
])
.spawn()?
.wait()?;
if create.success() {
Ok(Self {
backing: path.final_image(),
image: config,
paths: Arc::clone(&path),
proc: None,
})
} else {
Err(Error::from(BuildError::FailedToCreateImage))
}
}
fn mount(&mut self) -> Result<()> {
let proc = QemuProc::init(self)?;
self.proc = Some(proc);
debug!("Qemu Storage Daemon running");
Ok(())
}
fn unmount(&mut self) -> Result<()> {
debug!("Killing Storage Daemon");
if let Some(proc) = self.proc.take() {
proc.kill()?;
};
Ok(())
}
}
//
// impl Drop for QCow2 {
// fn drop(&mut self) {
// self.unmount().expect("Failed to gracefully unmount")
// }
// }
|
<!DOCTYPE html>
<html lang="en" xmlns:th=http://www.thymeleaf.org>
<head th:replace="fragments/commons::head"><title>MobiLeLeLe</title></head>
<body>
<div>
<nav th:replace="fragments/commons::nav"></nav>
</div>
<div class="container">
<h2 class="text-center text-white">Update Offer</h2>
<form th:object="${offerDetails}" th:method="post"
th:action="@{/offers/details/delete/{id}(id=*{id})}"
class="main-form mx-auto col-md-8 d-flex flex-column justify-content-center">
<div class="row">
<div class="form-group col-md-6 mb-3">
<label class="text-center text-white font-weight-bold" for="model">Model</label>
<select th:field="*{model}" th:errorclass="*{model}" id="model" class="form-control" th:selected="*{model}">
<optgroup th:each="brand: ${brandsWithModels}" th:object="${brand}" th:label="${brand.name}" >
<!-- <option >-->
<!-- <a th:each="model: ${brand.models}" th:text="${name}" th:value="${name}"></a>-->
<!-- </option>-->
</optgroup>
</select>
<p th:if="${#fields.hasErrors('model')}" th:errors="*{model}" class="errors alert alert-danger">
</p>
</div>
<div class="form-group col-md-6 mb-3">
<label for="price" class="text-white font-weight-bold">Price</label>
<input th:selected="*{price}" th:field="*{price}" th:errorclass="is-invalid" id="price" type="number" class="form-control"
placeholder="Suggested price"/>
<p th:if="${#fields.hasErrors('price')}" th:errors="*{price}" class="errors alert alert-danger invalid-feedback">
</p>
</div>
</div>
<div class="row">
<div class="form-group col-md-6 mb-3">
<label class="text-center text-white font-weight-bold" for="engine">Engine</label>
<select th:selected="*{engine}" th:field="*{engine}" th:errorclass="is-invalid" id="engine" class="form-control">
<option value="">- Select engine type -</option>
<option th:each="engine: ${T(com.example.mobile2.model.entities.Enums.EngineEnum).values()}"
th:text="${engine}" th:value="${engine}" >
</option>
</select>
<p th:if="${#fields.hasErrors('engine')}" th:errors="*{engine}" class="errors alert alert-danger invalid-feedback">
</p>
</div>
<div class="form-group col-md-6 mb-3">
<label class="text-center text-white font-weight-bold" for="transmission">Transmission</label>
<select th:selected="*{transmission}" th:field="*{transmission}" th:errorclass="is-invalid" id="transmission" class="form-control">
<option value="">- Select transmission type -</option>
<option th:each="transmission: ${T(com.example.mobile2.model.entities.Enums.TransmissionEnum).values()}"
th:text="${transmission}" th:value="${transmission}" >
</option>
</select>
<p th:if="${#fields.hasErrors('transmission')}" th:errors="*{transmission}" class="errors alert alert-danger invalid-feedback">
</p>
</div>
</div>
<div class="row">
<div class="form-group col-md-6 mb-3">
<label th:selected="*{year}" for="year" class="text-white font-weight-bold">Year</label>
<input th:field="*{year}" th:errorclass="is-invalid" id="year" type="number" min="1900" max="2099" step="1" class="form-control"
placeholder="Manufacturing year"/>
<p th:if="${#fields.hasErrors('year')}" th:errors="*{year}" class="errors alert alert-danger invalid-feedback">
</p>
</div>
<div class="form-group col-md-6 mb-3">
<label for="mileage" class="text-white font-weight-bold">Mileage</label>
<input th:selected="*{mileage}" th:field="*{mileage}" th:errorclass="is-invalid" id="mileage" type="number"
class="form-control"
placeholder="Mileage in kilometers"/>
<p th:if="${#fields.hasErrors('mileage')}" th:errors="*{mileage}" class="errors alert alert-danger invalid-feedback">
</p>
</div>
</div>
<div class="form-group">
<label class="text-white font-weight-bold" for="description">Description</label>
<textarea th:selected="*{description}" th:field="*{description}" id="description" type="textarea" class="form-control" rows="3"
placeholder="Description"></textarea>
<p>
</p>
</div>
<div class="form-group">
<label class="text-white font-weight-bold" for="imageUrl">Image URL</label>
<input th:selected="*{imageUrl}" th:field="*{imageUrl}" th:errorclass="is-invalid" id="imageUrl" type="url" class="form-control"
placeholder="Put vehicle image URL here">
<p th:if="${#fields.hasErrors('imageUrl')}" th:errors="*{imageUrl}" class="errors alert alert-danger invalid-feedback">
</p>
</div>
<div class="row">
<div class="col col-md-4">
<div class="button-holder d-flex">
<input type="submit" class="btn btn-info btn-lg" value="Update Offer"/>
</div>
</div>
</div>
</form>
</div>
<div>
<footer> </footer>
</div>
</body>
</html>
|
//
// UserDashboardView.swift
// Allwise2
//
// Created by Hugo Peyron on 16/11/2023.
//
import SwiftUI
enum userDataType : String, CaseIterable {
case level
case xp
case bestDayStreak
case questionMastered
}
struct UserDashboardView: View {
@ObservedObject var appViewModel = AppViewModel.shared
@ObservedObject var userManager = UserManager.shared
var body: some View {
ScrollView {
Image("sadOwl")
.resizable()
.scaledToFit()
.frame(maxWidth: .infinity, maxHeight: 200)
.ignoresSafeArea()
HStack {
Text(userManager.name)
.font(.title)
.fontWeight(.black)
.padding()
Spacer()
}
Divider()
VStack {
HStack {
Text("Stats")
.bold()
Spacer()
}
HStack {
userInfoButton(type: .level)
userInfoButton(type: .xp)
}
HStack {
userInfoButton(type: .bestDayStreak)
userInfoButton(type: .questionMastered)
}
}
.padding()
Divider()
VStack {
HStack{
Text("Progress")
.bold()
Spacer()
}
ForEach(appViewModel.lessons, id: \.id) { lesson in
HStack {
Button {
// some code
} label: {
ProgressView(lesson.name, value: appViewModel.progressOfLesson(lessonId: lesson.id))
.progressViewStyle(.linear)
.foregroundStyle(.foreground)
.fontWeight(.bold)
.padding()
.background(.thinMaterial)
.clipShape(RoundedRectangle(cornerRadius: 15))
}
}
}
}
.padding()
}
}
}
struct userInfoButton : View {
@ObservedObject var appViewModel = AppViewModel.shared
@ObservedObject var userManager = UserManager.shared
let type : userDataType
var body: some View {
Button {
// Action
} label: {
HStack{
Image(systemName: icon)
.resizable()
.scaledToFit()
.frame(width: 20)
.foregroundStyle(color)
VStack(alignment: .leading) {
Text(title)
.bold()
Text(subtitle)
.font(.caption2)
}
.foregroundStyle(.foreground)
Spacer()
}
.padding(.horizontal, 10)
.frame(height: 60)
.background(.thinMaterial)
.clipShape(RoundedRectangle(cornerRadius: 15))
}
}
var icon: String {
switch type {
case .level:
return "shield.fill"
case .xp:
return "star.fill"
case .bestDayStreak:
return "flame.fill"
case .questionMastered:
return "checkmark.circle.fill"
}
}
var color: Color {
switch type {
case .level:
return userManager.level.color
case .bestDayStreak:
return .orange
case .questionMastered:
return .green
case .xp:
return .yellow
}
}
var title: String {
switch type {
case .level:
return userManager.level.rawValue
case .xp:
return "\(userManager.xp)"
case .bestDayStreak:
return "\(userManager.bestDayStreakCount)"
case .questionMastered:
return "\(appViewModel.totalNumberOfSolvedQuestions())"
}
}
var subtitle: String {
switch type {
case .level:
return "Current level"
case .xp:
return "XP"
case .bestDayStreak:
return "Best Day Streak"
case .questionMastered:
return "Questions Mastered"
}
}
}
#Preview {
UserDashboardView()
}
|
package com.example.starwarscharacterexplorer.starship.model
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize
@Entity(tableName = "Starship_local")
@Parcelize
data class Starship(
val name: String,
val model: String,
val manufacturer: String,
val cost_in_credits: String,
val length: String,
val max_atmosphering_speed: String,
val crew: String,
val passengers: String,
val cargo_capacity: String,
val consumables: String,
val hyperdrive_rating: String,
val MGLT: String,
val starship_class: String,
// val pilots: List<String>,
// val films: List<String>,
val created: String,
val edited: String,
@PrimaryKey(autoGenerate = false)
val url: String
):Parcelable
|
# さいころの構造体(さいころクラス)
class Dice:
def __init__(self):
# さいころの各面とindexの対応
self.top = 1
self.up = 0
self.down = 5
self.left = 3
self.right = 2
self.back = 4
# さいころ面の入力受付
def input_dice(self):
print("dice:")
self.dice = [int(i) for i in input().split()]
# 転がす方向の入力受付
def input_direction(self):
print("direction:")
self.roll_direction = list(input())
# 転がす関数========
def n_direction(self,dice):
dice[0], dice[1], dice[5], dice[4] = dice[1], dice[5], dice[4], dice[0]
return dice
def s_direction (self,dice):
dice[0], dice[1], dice[4], dice[5] = dice[4], dice[0], dice[5], dice[1]
return dice
def w_direction(self, dice):
dice[3], dice[1], dice[2], dice[4] = dice[1], dice[2], dice[4], dice[3]
return dice
def e_direction(self,dice):
dice[1], dice[2], dice[3], dice[4] = dice[3], dice[1], dice[4], dice[2]
return dice
# 入力方向からさいころを転がす
def direction(self, input_direct):
if input_direct == "N":
self.dice = self.n_direction(self.dice)
elif input_direct == "S":
self.dice = self.s_direction(self.dice)
elif input_direct == "W":
self.dice = self.w_direction(self.dice)
elif input_direct == "E":
self.dice = self.e_direction(self.dice)
# ========
# 各direction関数のテスト関数--------
def _set_test(self, input_flg = False):
self.dice = [1,2,3,4,5,6]
self.roll_direction = ["N", "S", "W", "E"]
def _check_dice(self, dice):
print(f" , {dice[0]}")
print(f"{dice[3]} , {dice[1]} , {dice[2]} , {dice[4]}")
print(f" , {dice[5]}")
def _check_roll(self):
print("初期値")
self._check_dice(self.dice)
for d in self.roll_direction:
self.direction(d)
print(f"{d}--------")
self._check_dice(self.dice)
self.dice = [1,2,3,4,5,6]
#--------
# さいころ面の値を出力
def print_face(self, side):
print(self.dice[side])
# 方向に従いさいころを転がす
def roll(self):
for d in self.roll_direction:
# さいころを転がす
self.direction(d)
self.print_face(self.top)
if __name__ == "__main__":
dd = Dice()
dd.input_dice()
dd.input_direction()
dd.roll()
|
//
// GuideView.swift
// Maskbook
//
// Created by Hugo L on 2022/2/25.
// Copyright © 2022 dimension. All rights reserved.
//
import SwiftUI
struct GuideView: View {
@Environment(\.presentationMode) var presentationMode
@State private var page: Int = 0
let dismiss: (() -> Void)?
var isLastOne: Bool {
guard let pageEnum = GuideItemView.Page.allCases.last else {
return true
}
return pageEnum.rawValue == page
}
var body: some View {
let gradientColors = [
Asset.Colors.Gradient.guide1.asColor(),
Asset.Colors.Gradient.guide2.asColor()
]
return GeometryReader { proxy in
let contentSize = proxy.size
buildPageContent(contentSize: contentSize)
.overlay(buildControls(contentSize: contentSize))
}
.background(
LinearGradient(
colors: gradientColors,
startPoint: .init(x: 0.5, y: 0),
endPoint: .init(x: 0.5, y: 1)
).ignoresSafeArea()
)
}
var skipSection: some View {
HStack {
Spacer()
Button {
dismiss?()
} label: {
Text(L10n.Scene.Guide.skip)
.font(FontStyles.bh5.font)
.foregroundColor(Asset.Colors.Background.lightBlue.asColor())
.opacity(isLastOne ? 0 : 1)
.padding(.horizontal, LayoutConstraints.horizontal)
.padding(.vertical, 8)
.contentShape(Rectangle())
}
}
}
@ViewBuilder
private func buildPageContent(contentSize: CGSize) -> some View {
TabView(selection: $page.animation(.default)) {
ForEach(GuideItemView.Page.allCases) { page in
GuideItemView(page: page, contentSize: contentSize) {
dismiss?()
}
.frame(width: contentSize.width, height: contentSize.height)
}
}
.frame(width: contentSize.width, height: contentSize.height)
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
}
@ViewBuilder
private func buildControls(contentSize: CGSize) -> some View {
VStack {
skipSection
Spacer()
buildPageIndicator(screenSize: contentSize)
}.padding(.bottom, 29)
}
@ViewBuilder
private func buildPageIndicator(screenSize: CGSize) -> some View {
HStack(spacing: 7) {
ForEach(GuideItemView.Page.allCases.indices) { index in
Capsule()
.fill(Asset.Colors.Background.lightBlue.asColor())
.frame(width: page == index ? 20 : 10, height: 6)
}
}
.overlay(
Capsule()
.fill(Asset.Colors.Background.lightBlue.asColor())
.frame(width: 20, height: 6)
.offset(x: getIndicatorOffset(screenSize: screenSize)),
alignment: .leading
)
}
private func getIndicatorOffset(screenSize: CGSize) -> CGFloat {
let maxWidth = 7.0 + 10.0
return maxWidth * CGFloat(page)
}
}
struct GuideView_Previews: PreviewProvider {
static var previews: some View {
Group {
GuideView(dismiss: nil)
GuideView(dismiss: nil)
.previewDevice("iPhone 8")
}
}
}
|
import AOS from 'aos';
import { addDoc, collection, doc } from 'firebase/firestore';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useEffect } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import 'aos/dist/aos.css';
import db from '@/lib/firebase';
import BgImg from '~/images/auth/registerBackground.png';
import Logo from '~/Logo.png';
interface SignupType {
name: string;
phone_number: string;
email: string;
password: string;
password_confirm: string;
}
const Register = () => {
useEffect(() => {
AOS.init();
}, []);
const router = useRouter();
const methods = useForm<SignupType>({ mode: 'onBlur' });
const {
register,
handleSubmit,
formState: { errors },
} = methods;
const onSubmit = async (data: SignupType) => {
try {
const { name, email, phone_number, password } = data;
// await signUp(data.email, data.password);
const userRef = await addDoc(collection(db, `users`), {
name,
phone_number,
});
await addDoc(collection(db, `account`), {
detail: doc(db, `users/${userRef.id}`),
email,
password,
type: 'user',
});
router.push('/auth/login');
} catch (error: any) {
console.log(error.message);
}
};
return (
<div
className='min-h-screen py-40'
style={{
backgroundImage: 'linear-gradient(115deg, #20202B, #E97991)',
}}
>
<div
className='container mx-auto'
data-aos='flip-right'
data-aos-easing='ease-out-cubic'
data-aos-duration='2500'
>
<div className='mx-auto flex w-10/12 flex-col overflow-hidden rounded-xl bg-white shadow-lg lg:w-8/12 lg:flex-row'>
<div
className='flex w-full flex-col items-center justify-center bg-cover bg-center bg-no-repeat p-12 lg:w-1/2'
style={{
backgroundImage: `url(${BgImg.src})`,
}}
>
<h1 className='mb-3 text-3xl text-white'>Welcome</h1>
<div>
<p className='text-white'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean
suspendisse aliquam varius rutrum purus maecenas ac{' '}
<a href='#' className='font-semibold text-pink-400'>
Learn more
</a>
</p>
</div>
</div>
<div className='w-full py-16 px-12 lg:w-1/2'>
<Link href='/'>
<Image src={Logo} alt='Logo' width={128} />
</Link>
<p className='mb-4'>
Create your account. It’s free and only take a minute
</p>
<FormProvider {...methods}>
<form action='#' onSubmit={handleSubmit(onSubmit)}>
<div className='mt-5'>
<input
type='text'
placeholder='Name'
{...register('name')}
className='w-full border border-gray-400 py-1 px-2'
/>
</div>
<div className='mt-5'>
<input
type='text'
placeholder='Phone Number'
{...register('phone_number')}
className='w-full border border-gray-400 py-1 px-2'
/>
</div>
<div className='mt-5'>
<input
type='email'
{...register('email', { required: 'Email is required' })}
placeholder='Email'
className='w-full border border-gray-400 py-1 px-2'
/>
{errors.email && (
<p className='text-red-400'>{errors.email.message}</p>
)}
</div>
<div className='mt-5'>
<input
type='password'
{...register('password', {
required: 'Password is required',
})}
placeholder='Password'
className='w-full border border-gray-400 py-1 px-2'
/>
{errors.password && (
<p className='text-red-400'>{errors.password.message}</p>
)}
</div>
<div className='mt-5'>
<input
type='checkbox'
className='mr-5 border border-gray-400'
/>
<span>
I accept the{' '}
<a href='#' className='font-semibold text-pink-400'>
Terms of Use
</a>{' '}
&{' '}
<a href='#' className='font-semibold text-pink-400'>
Privacy Policy
</a>
</span>
</div>
<div className='mt-5'>
<button
type='submit'
className='w-full rounded-xl bg-pink-400 py-3 text-center font-semibold text-white shadow-lg transition duration-500 hover:scale-110 hover:shadow-2xl'
>
Register Now
</button>
</div>
<p className='mt-2 mb-0 pt-1 text-sm font-semibold'>
Already have an account?
<Link
href='/auth/login'
className='text-red-600 transition duration-200 ease-in-out hover:text-red-700 focus:text-red-700'
>
{' '}
Log in
</Link>
</p>
</form>
</FormProvider>
</div>
</div>
</div>
</div>
);
};
export default Register;
|
"use client";
import { useEffect } from "react";
import html2pdf from "html2pdf.js";
import ProductDetails from "../PDFPages/ProductDetails";
import UseDeleteProduct from "@/Hooks/Product/UseDeleteProduct";
import { MdErrorOutline } from "react-icons/md";
export default function DetailsBox({ closeDetailsBox, detailData }) {
const { deleteProduct, loading, error, setError } = UseDeleteProduct();
useEffect(() => {
const handleExportPDF = async () => {
const element = document.getElementById("pdf-container");
await html2pdf().from(element).save();
};
const exportButton = document.getElementById("export-pdf-button");
if (exportButton) {
exportButton.addEventListener("click", handleExportPDF);
}
return () => {
if (exportButton) {
exportButton.removeEventListener("click", handleExportPDF);
}
};
}, [detailData]);
// for delete
const deleteProductHandle = () => {
const confirmed = window.confirm(
"Are you sure you want to delete this product?"
);
if (confirmed) {
deleteProduct(detailData._id);
}
};
if (error === "success") {
closeDetailsBox();
}
return (
<>
<div className="fixed top-0 left-0 w-screen h-screen overflow-y-auto lg:pb-10 bg-gradient-to-b z-20 to-slate-800 from-slate-700">
<div className="p-2 px-8 bg-black flex items-center justify-center">
<button
onClick={deleteProductHandle}
className="bg-slate-800 p-1 px-4 mx-4 rounded-md text-lime-50"
>
{loading ? "Loading...." : "Delete"}
</button>
<button
id="export-pdf-button"
className="bg-slate-800 p-1 px-4 mx-4 rounded-md text-lime-50"
>
Export as PDF
</button>
<button
onClick={closeDetailsBox}
className="text-slate-800 p-1 px-4 mx-4 rounded-md bg-lime-50"
>
Close
</button>
</div>
{error && (
<h1 className="border flex items-center rounded-lg text-xs bg-red-950 text-black shadow-xl bg-transparent p-2 text-center">
<MdErrorOutline className="mx-2" /> {error}
</h1>
)}
<div id="pdf-container">
<ProductDetails detailData={detailData} />
</div>
</div>
</>
);
}
|
import React, { useState } from "react";
import { useMutation } from "@apollo/client";
import { Container, Heading, Wrapper, Button } from "./topup-wallet.style";
import { Input } from "components/forms/input";
import { FormattedMessage, useIntl } from "react-intl";
import { M_WALLET_TOPUP } from "graphql/mutation/topup-wallet.mutation";
import { useRouter } from "next/router";
import { useAppState } from "contexts/app/app.provider";
function TopupWallet() {
const workFlowPolicy=useAppState("workFlowPolicy")
const storeId = useAppState("activeStoreId");
const [amount, setAmount] = useState(0);
const intl = useIntl();
const router = useRouter();
const [topup] = useMutation(M_WALLET_TOPUP, {
onCompleted: (data) => {
if (data && data.walletTopup && data.walletTopup.stripeCheckoutUrl) {
router.push(data.walletTopup.stripeCheckoutUrl);
}
},
});
function handleSubmit() {
const successUrl =
window.location.protocol + "//" + window.location.host + "/checkout";
topup({
variables: {
input: {
amount: Number(amount),
storeId,
successUrl,
},
},
});
}
return (
<Wrapper>
<Container>
<Heading>
<FormattedMessage id='topupAmount' defaultMessage='Topup Amount' />
</Heading>
<form>
<Input
type="text"
placeholder={intl.formatMessage({
id: "userSignupMobile",
defaultMessage: "Mobile",
})}
value={amount}
onChange={(e) => setAmount(e.target.value)}
required
height="48px"
backgroundColor="#F7F7F7"
mt="10px"
/>
</form>
<Button
variant="primary"
size="big"
style={{ width: "100%", margin: "20px 0" }}
type="submit"
onClick={handleSubmit}
>
<FormattedMessage id='rechargeWallet' defaultMessage='Topup Wallet' />
</Button>
</Container>
</Wrapper>
);
}
export default TopupWallet;
|
import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { GLOBAL_SETTINGS, GlobalSettings } from '../shared/tokens';
import { IUser, IAuth } from '../shared/interfaces';
@Injectable({ providedIn: 'root' })
export class AuthService {
public baseURL: string;
constructor(
@Inject(GLOBAL_SETTINGS)
private readonly settings: GlobalSettings,
private readonly http: HttpClient
) {
this.baseURL = this.settings.api.baseURL;
}
public signIn(data: IAuth): Observable<IUser> {
return this.http.post<IUser>(`${this.baseURL}/auth/login`, data);
}
public register(data: IAuth): Observable<{ message: string }> {
return this.http.post<{ message: string }>(`${this.baseURL}/auth/register`, data);
}
public signOut(data = null): Observable<{ message: string }> {
return this.http.post<{ message: string }>(`${this.baseURL}/auth/logout`, data);
}
}
|
import { Component, EventEmitter, Input, OnInit, Output, TemplateRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { BsModalService } from 'ngx-bootstrap/modal';
import { ToastrService } from 'ngx-toastr';
import { iDocumento } from 'src/app/interfaces/iDocumento';
import { iEtapa } from 'src/app/interfaces/iEtapa';
import { iFuncionario } from 'src/app/interfaces/iFuncionario';
import { iEditarEtapaPost } from 'src/app/interfaces/post/iEditarEtapaPost';
import { InfoTramiteService } from 'src/app/shared/services/info-tramite.service';
@Component({
selector: 'app-editar-info-etapa',
templateUrl: './editar-info-etapa.component.html',
styleUrls: ['./editar-info-etapa.component.css']
})
export class EditarInfoEtapaComponent implements OnInit {
@Input() etapa:iEtapa;
documentos:iDocumento[];
documentosEdit: String[]=[];
funcionario:iFuncionario;
loading:boolean=true;
@Output() refreshEvent: EventEmitter<any> = new EventEmitter();
editarEtapa:iEditarEtapaPost={
nombre: '',
descripcion: '',
posicion: 0,
dias_estimados: 0,
tramite_id: 0,
funcionario_id: 0
};
constructor(
private builder: FormBuilder,
private infoTramiteService: InfoTramiteService,
private bsModalService: BsModalService,
private toast: ToastrService
) { }
editarEtapaForm:FormGroup = new FormGroup({});
ngOnInit(): void {
this.infoTramiteService.getDocumentos(this.etapa.id_etapa).subscribe((data:any)=>{
if(data){
this.documentos=data;
for(let i=0; i<this.documentos.length; i++ ){
this.documentosEdit.push(this.documentos[i].nombre);
}
}else{
console.log("No se pudieron listas documentos")
}
});
this.infoTramiteService.getFuncionarioById(this.etapa.funcionario_id).subscribe((data:any)=>{
if(data){
this.funcionario=data;
this.editarEtapaForm = this.builder.group({
encargado:[this.funcionario.id_funcionario, Validators.required],
tiempoEstimado: [this.etapa.dias_estimados, Validators.required],
descripcionEtapa:[this.etapa.descripcion, [Validators.required, Validators.minLength(10)]],
documentoEtapa:['']
});
this.loading=false;
}else{
console.log("No se pudo cargar funcionario");
}
});
}
onGuardarCambios(){
this.editarEtapa.nombre=this.etapa.nombre;
this.editarEtapa.descripcion=this.editarEtapaForm.value.descripcionEtapa;
this.editarEtapa.posicion= this.etapa.posicion;
this.editarEtapa.dias_estimados= parseInt(this.editarEtapaForm.value.tiempoEstimado) ;
this.editarEtapa.tramite_id= this.etapa.tramite_id;
this.editarEtapa.funcionario_id= parseInt(this.editarEtapaForm.value.encargado) ;
this.infoTramiteService.putEditarEtapa(this.etapa.id_etapa, this.editarEtapa).subscribe((res:any)=>{
this.toast.success('Etapa actualizada correctamente!');
this.bsModalService.hide();
});
}
onEliminarEtapa(){
this.infoTramiteService.deleteEtapa(this.etapa.id_etapa).subscribe((res:any)=>{
console.log(res);
this.toast.warning('Etapa eliminada');
this.bsModalService.hide();
this.refreshEvent.emit()
});
}
onModalConfirmarEliminar(modalTemplate: TemplateRef<any>): void {
this.bsModalService.show(modalTemplate, {
id: 2, // para poder levantar modal sobre modal se debe ir sumando un nivel.
backdrop:false,
class: 'modal-md',
});
}
onAgregarDoc(){
this.documentosEdit.push(this.editarEtapaForm.value.documentoEtapa);
this.editarEtapaForm= this.builder.group({
documentoEtapa:['']
});
}
onEliminarDoc(doc: String){
this.documentosEdit.splice(this.documentosEdit.indexOf(doc), 1) ;
}
}
|
# Lettuce Data Explorer
Welcome to the Lettuce Data Explorer, a Shiny application for exploring lettuce transcriptomic datasets after infection with necrotrophic pathogens (*Botrytis cinerea* and *Sclerotinia sclerotiorum*) and gene regulatory network inferred from them!
This application is hosted on shinyapps.io;
## 🔗 **[Visit the Lettuce Data Explorer on Shinyapps.io](https://hpink97.shinyapps.io/Lettuce-Data/)** 🔗
## Overview
The Lettuce Data Explorer simplifies the exploration of lettuce transcriptomic datasets. It empowers users to swiftly identify lettuce genes using different selection criteria, such as Arabidopsis symbols/IDs, GO terms, protein domains, and more.
### Features:
1. **Data Selection:** Select from multiple datasets, such as:
- **Time-series expression**: Dynamic expression profiles of lettuce genes in response to *Botrytis cinerea* and *Sclerotinia sclerotiorum* infection. For more details see [Pink et al, (2023)](https://doi.org/10.1101/2023.07.19.549542)
- **Gene Regulatory Network (GRN) Analysis**: A direct causal GRN infereing transcriptional regulation in response *Botrytis cinerea* and *Sclerotinia sclerotiorum* infection in lettuce using four transcriptomic datasets. For more details see [Pink et al, (2023).](https://doi.org/10.1101/2023.07.19.549542)
- **Lesion Size Correlation**: How is variation in gene expression across a diverse panel of lettuce accessions associated with their susceptibility to necrotrophic fungal pathogens? . For more details see [Pink et al, (2022).](https://doi.org/10.1007/s00122-022-04129-5)
2. **Gene Selection:** Choose genes based on:
- **Lettuce GeneID**: Input using Lettuce gene ID(s).
- **Orthologues of Arabidopsis Genes**: Specify an Arabidopsis gene ID or symbol.
- **Genes with GO-term**: Enter a GO term to filter genes.
- **Genes with Protein Domain**: Discover genes based on their associated protein domains.
3. **Customization Options**:
- Dataset-specific gene selection criteria.
- Plot customization capabilities.
4. **Results Generation**: After making selections, click 'Generate Results' to view plots and tables.
5. **Save results**: all generated plots, their underlying data, and GRN tables can be downloaded directly from the Shiny app
## Lettuce gene annotations
Gene annotations in the app, such as Arabidopsis orthologues and protein domains, are based on the work of [Reyes-Chin-Wo et al (2017)](https://doi.org/10.1038/ncomms14953). The GO-term annotations derive from the GO-term annotation of the closest Arabidopsis orthologue of each lettuce gene.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.