text
stringlengths 184
4.48M
|
---|
"use client";
import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import Spinner from "@/components/ui/loader";
import { NewPasswordSchema } from "@/schemas/auth";
import {
ArrowLeftIcon,
EyeIcon,
EyeSlashIcon,
} from "@heroicons/react/24/outline";
import FormWrapper from "./form-wrapper";
import { newPassword } from "@/actions/auth";
import { FormError } from "./form-error";
import { Loader } from "lucide-react";
export default function NewPasswordForm() {
const [isPending, startTransition] = useTransition();
const [error, setError] = useState<string | undefined>("");
const [success, setSuccess] = useState<string | undefined>("");
const [showPassword, setShowPassword] = useState(false);
const form = useForm<z.infer<typeof NewPasswordSchema>>({
resolver: zodResolver(NewPasswordSchema),
defaultValues: {
password: "",
confirmPassword: "",
},
});
const onSubmit = (values: z.infer<typeof NewPasswordSchema>) => {
startTransition(() => {
newPassword(values)
.then((data) => {
if (data?.error) {
form.reset();
setError(data.error);
}
})
.catch(() => setError("Oops! Something went wrong!"));
});
};
return (
<FormWrapper
title="You are now Logged in"
description="Please create a new password"
>
<div className="mt-6 space-y-2">
<FormError message={error} />
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormControl>
<div className="relative">
<Input
{...field}
disabled={isPending}
placeholder="Enter Password"
type={showPassword ? "text" : "password"}
/>
<span
onClick={() => setShowPassword(!showPassword)}
className="absolute right-4 top-1/2 transform -translate-y-1/2 cursor-pointer"
>
{showPassword ? (
<EyeIcon className="text-muted-foreground h-5 w-5" />
) : (
<EyeSlashIcon className="text-muted-foreground h-5 w-5" />
)}
</span>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormControl>
<div className="relative">
<Input
{...field}
disabled={isPending}
placeholder="Confirm Password"
type={showPassword ? "text" : "password"}
/>
<span
onClick={() => setShowPassword(!showPassword)}
className="absolute right-4 top-1/2 transform -translate-y-1/2 cursor-pointer"
>
{showPassword ? (
<EyeIcon className="text-muted-foreground h-5 w-5" />
) : (
<EyeSlashIcon className="text-muted-foreground h-5 w-5" />
)}
</span>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div>
<div>
<Button
size="lg"
type="submit"
className="w-full border py-3 px-4 text-base shadow-sm border-black"
disabled={isPending}
>
{isPending && <Loader className="h-5 w-5 animate-spin" />}
<span>Change Password</span>
</Button>
</div>
</div>
</form>
</Form>
</div>
</FormWrapper>
);
}
|
import React, { useState } from "react";
import { Form, Row, Col, Button } from "react-bootstrap";
import { Link, useNavigate } from "react-router-dom";
import { InputField } from "../../Components/InputField";
import { auth } from "../../Config/firebase";
import { createUserWithEmailAndPassword } from "firebase/auth";
import { toast } from "react-toastify";
export const SignUp = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
let navigate = useNavigate();
const SigninUser = (e) => {
e.preventDefault();
if (email && password) {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
toast.success("Account Successfully Created", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
navigate("/");
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
toast.error((errorCode, errorMessage), {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
});
} else if (email && !password) {
toast.error("Enter Password", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
} else if (!email && password) {
toast.error("Enter Email", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
} else {
toast.error("Enter Email & Password", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
}
};
return (
<div className="container">
<section className="d-flex justify-content-center align-item-center py-5">
<Row>
<Col md={9} lg={8} xl={7} className="mx-auto">
<Form
className="border p-4 rounded-3 bg-light"
onSubmit={SigninUser}
>
<h3 className="mb-4 text-dark">Signup Form</h3>
<Row className="g-4">
<Col xs={12}>
<InputField
label="Email"
id="email"
placeholder="Email"
type="email"
onChange={(e) => {
setEmail(e.target.value);
}}
/>
</Col>
<Col xs={12}>
<InputField
label="Password"
id="password"
placeholder="Password"
type="password"
onChange={(e) => {
setPassword(e.target.value);
}}
/>
</Col>
<Col xs={12}>
<Button
variant="primary"
type="submit"
className="w-100 py-2 text-uppercase fw-bold"
>
Create Account
</Button>
</Col>
<Col>
<div className="d-flex gap-3">
<p>Already have an Account</p>
<Link
to="/login"
className="text-uppercase text-decoration-none fw-semibold"
>
Login
</Link>
</div>
</Col>
</Row>
</Form>
</Col>
</Row>
</section>
</div>
);
};
|
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IMinePool {
struct MineBrief {
uint8 nftType;
uint8 gen;
uint32 tokenId;
uint32[] wells;
uint256 power;
uint256 capacity; //油田储能
uint256 output; //架设油井后的产量
uint256 pendingRewards; //待领取Oil的数量
uint256 equivalentOutput; //待领取Oil以USDT计算的产量
uint256 cumulativeOutput; //累计产量
uint256 lastClaimTime;
}
struct PoolOilInfo {
uint8 cid;
uint256 basePct;
uint256 dynamicPct;
uint256 oilPerSec;
uint256 totalCapacity;
}
function mineBrief(uint32 _mineId) external view returns(MineBrief memory);
function totalMineInfo() external view returns(
uint8 k_,
bool addition_,
uint32 claimCD_,
uint32 basePct_,
uint256 oilPerSec_,
PoolOilInfo[3] memory info_
);
function addCapacity(uint32 _mineId, uint256 _capacity) external;
function pendingRewards(uint32 _mineId) external view returns(uint256);
function updatePool() external;
function isWorkingMine(uint32 _mineId) external view returns(bool);
function voteDynamicPct(uint256[3] memory _dynamicPct) external;
}
|
import { createAction, props } from '@ngrx/store';
import { QuestionTemplate } from '../../models';
export const loadQuestionTemplatesRequest = createAction(
'[Question Template] Load Question Templates Request'
);
export const loadQuestionTemplatesSuccess = createAction(
'[Question Template] Load Question Templates Success',
props<{ questionTemplates: QuestionTemplate[]; }>()
);
export const loadQuestionTemplatesFailure = createAction(
'[Question Template] Load Question Templates Failure'
);
export const loadQuestionTemplateByIdRequest = createAction(
'[Question Template] Load Question Template By ID Request',
props<{ templateId: number }>()
);
export const loadQuestionTemplateByIdSuccess = createAction(
'[Question Template] Load Question Template By ID Success',
props<{ questionTemplate: QuestionTemplate }>()
);
export const loadQuestionTemplateByIdFailure = createAction(
'[Question Template] Load Question Template By ID Failure'
);
export const createQuestionTemplateRequest = createAction(
'[Question Template] Create Question Template Request',
props<{ templateData: QuestionTemplate }>()
);
export const updateQuestionTemplateRequest = createAction(
'[Question Template] Update Question Template Request',
props<{ templateId: number; templateData: QuestionTemplate }>()
);
export const searchQuestionTemplatesRequest = createAction(
'[Question Template] Search Question Templates Request',
props<{ searchTerm: string }>()
);
export const createQuestionTemplateSuccess = createAction(
'[Question Template] Create Question Template Success',
props<{ questionTemplate: QuestionTemplate }>()
);
export const createQuestionTemplateFailure = createAction(
'[Question Template] Create Question Template Failure'
);
export const updateQuestionTemplateSuccess = createAction(
'[Question Template] Update Question Template Success'
);
export const updateQuestionTemplateFailure = createAction(
'[Question Template] Update Question Template Failure'
);
export const searchQuestionTemplatesSuccess = createAction(
'[Question Template] Search Question Templates Success',
props<{ searchResults: QuestionTemplate[] }>()
);
export const searchQuestionTemplatesFailure = createAction(
'[Question Template] Search Question Templates Failure'
);
export const deleteQuestionTemplateRequest = createAction(
'[Question Template] Delete Question Template Request',
props<{ templateId: number }>()
);
export const deleteQuestionTemplateSuccess = createAction(
'[Question Template] Delete Question Template Success'
);
export const deleteQuestionTemplateFailure = createAction(
'[Question Template] Delete Question Template Failure'
);
|
import styled from "styled-components";
import PersonAddIcon from "@mui/icons-material/PersonAdd";
import { useRecoilValue } from "recoil";
import { studentLoginState } from "../../atom/atoms";
import { useForm } from "react-hook-form";
import { useEffect, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { profileChange } from "../../api/api";
import { toast } from "react-toastify";
const Wrapper = styled.div`
width: 80%;
padding-right: 5vw;
height: 82vh;
display: flex;
flex-direction: column;
padding-left: 2vw;
`;
const Title = styled.div`
height: 5vh;
width: 100%;
border-bottom: 2px solid #ecf0f1;
display: flex;
align-items: center;
padding-bottom: 1vw;
h2 {
font-size: 1.3vw;
font-weight: 600;
color: #ecf0f1;
}
`;
const ProfileForm = styled.form`
width: 100%;
height: auto;
margin-top: 2vw;
background-color: rgba(99, 110, 114, 0.5);
border-radius: 20px;
display: flex;
`;
const ProfileImageBox = styled.div`
width: 30%;
height: 100%;
border-right: 1px solid rgba(255, 255, 255, 0.3);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
span {
margin-top: 2vw;
font-size: 1.3vw;
color: #ecf0f1;
}
`;
const ProfileImageLabel = styled.label`
width: 13vw;
height: 13vw;
border: 1px solid #bdc3c7;
border-radius: 100%;
display: flex;
align-items: center;
justify-content: center;
&:hover {
cursor: pointer;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 100%;
}
svg {
width: 6vw;
height: 6vw;
color: white;
}
input[type="file"] {
display: none;
}
`;
const ProfileContent = styled.div`
width: 70%;
height: 100%;
/* border: 1px solid red; */
padding: 2vw;
padding-left: 3vw;
`;
const ProfileContentSubBox = styled.div`
width: 100%;
height: auto;
display: flex;
flex-direction: column;
margin-bottom: 2vw;
label {
&#email {
input[type="text"] {
background-color: rgba(127, 140, 141, 0.3);
/* border: none; */
&::placeholder {
color: #bdc3c7;
}
}
}
display: flex;
flex-direction: column;
input[type="text"] {
background-color: transparent;
width: 40%;
border: 1px solid ${(props) => props.theme.textColor};
padding: 0.7vw;
color: ${(props) => props.theme.textColor};
font-size: 1.1vw;
border-radius: 10px;
transition: all 0.2s ease-in-out;
}
input[type="text"]:focus {
outline: none;
border-color: #7f8c8d;
}
span {
color: ${(props) => props.theme.textColor};
font-weight: 600;
margin-bottom: 1vw;
}
}
/* border: 1px solid red; */
`;
const ProfileSubmitBox = styled.div`
width: 100%;
height: 6vh;
display: flex;
/* justify-content: flex-end; */
label[for="profile_save"] {
span {
font-size: 1.3vw;
padding: 1vw 5vw;
color: ${(props) => props.theme.textColor};
border-radius: 10px;
background-color: #e74c3c;
transition: all 0.2s ease-in-out;
&:hover {
cursor: pointer;
filter: brightness(1.2);
}
}
height: 100%;
display: flex;
align-items: center;
input[type="submit"] {
display: none;
}
}
`;
interface DProps {
nickname: string;
name: string;
profileImage: FileList;
}
export default function ProfileSub() {
const loginState = useRecoilValue(studentLoginState);
const { mutate, isLoading } = useMutation({
mutationFn: profileChange,
onSuccess: () => {
toast.success("변경 성공!");
// todo Query 초기화
return;
},
onError: () => {
toast.error("프로필사진을 변경하는데 문제가 발생했습니다.");
},
});
const [preview, setPreview] = useState("");
const {
register,
watch,
formState,
setError,
clearErrors,
handleSubmit,
setValue,
} = useForm<DProps>();
// console.log("watch ?");
// console.log(watch());
// console.log("formState ?");
// console.log(formState.errors);
useEffect(() => {
if (watch("profileImage")[0]) {
const profilePreview = URL.createObjectURL(watch("profileImage")[0]);
setPreview(profilePreview);
}
return () => URL.revokeObjectURL(preview);
}, [watch("profileImage")]);
useEffect(() => {
// 초기 프로필 값 세팅
if (loginState.username) {
setValue("name", loginState.username);
}
if (loginState.nickname) {
setValue("nickname", loginState.nickname);
}
if (loginState.profileImg) {
setPreview(loginState.profileImg);
}
}, [loginState]);
// 1. 사용자가 전부 변경하는 경우
// 2. 사용자가 하나만 변경하는 경우 (모든 경우에 해당)
// 3. 사영자가 닉네임 이름을 변경하고 프로필사진을 변경하지 않은 경우
// 4. 사용자가 사진만 변경하는 경우 -> 기존에 있는 사진을 지운다 (backend)
const onValid = (data: DProps) => {
const formData = new FormData();
formData.append("nickname", data.nickname);
formData.append("name", data.name);
formData.append("email", loginState.email);
if (data.profileImage[0]) {
formData.append("profileImage", data.profileImage[0]);
}
mutate(formData);
};
return (
<Wrapper>
<Title>
<h2>프로필 수정</h2>
</Title>
<ProfileForm onSubmit={handleSubmit(onValid)}>
<ProfileImageBox>
<ProfileImageLabel htmlFor="profile_image">
<input
{...register("profileImage", {
required: false,
// validate: (value) => {
// console.log("validation 내부에서 vlaue ?");
// console.log(value);
// if (value && value[0] && value[0].type) {
// return value[0].type.startsWith("image/")
// ? undefined
// : "이미지 파일만 올려주세요";
// }
// return "Please select an image.";
// },
})}
id="profile_image"
type="file"
accept=".png,.jpg,.jpeg"
/>
{preview ? (
<img src={preview} alt="student profile image" />
) : (
<PersonAddIcon />
)}
</ProfileImageLabel>
<span>프로필 이미지 등록하기</span>
</ProfileImageBox>
<ProfileContent>
<ProfileContentSubBox>
<label htmlFor="user_name">
<span>닉네임</span>
<input
{...register("nickname", {
required: "닉네임을 입력해주세요",
minLength: {
value: 2,
message: "최소 2글자 이상입니다",
},
})}
id="user_name"
type="text"
/>
</label>
</ProfileContentSubBox>
<ProfileContentSubBox>
<label htmlFor="name">
<span>이름</span>
<input
{...register("name", {
required: "이름을 입력해주세요",
minLength: {
value: 2,
message: "최소 2글자 이상입니다",
},
})}
id="name"
type="text"
/>
</label>
</ProfileContentSubBox>
<ProfileContentSubBox>
<label htmlFor="email" id="email">
<span>가입이메일</span>
<input
id="email"
type="text"
readOnly
placeholder={loginState.email}
/>
</label>
</ProfileContentSubBox>
<ProfileSubmitBox>
<label htmlFor="profile_save">
<span>프로필 저장</span>
<input id="profile_save" type="submit" />
</label>
</ProfileSubmitBox>
</ProfileContent>
</ProfileForm>
</Wrapper>
);
}
|
package PratikAtm;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String userName, password;
Scanner input = new Scanner(System.in);
int right = 3;
int balance = 1500;
// int select; -- do while ;
byte choise = 0;
int price;
while (right > 0) {
System.out.print("Kullanıcı Adınız: ");
userName = input.nextLine();
System.out.print("Parolanız: ");
password = input.nextLine();
if (userName.equals("Mert") && password.equals("Mert123")) {
System.out.println("Merhaba, Kodluyoruz Bankasına Hoşgeldiniz!");
System.out.println("Lütfen yapmak istediğiniz işlemi belirtin:\n" +
"1-Para yatırma\n" +
"2-Para Çekme\n" +
"3-Bakiye Sorgula\n" +
"4-Çıkış Yap");
choise = input.nextByte();
switch (choise){
case 1:
System.out.println("Para miktarı: ");
price = input.nextInt();
balance += price;
break;
case 2:
System.out.println("Para miktarı: ");
price = input.nextInt();
if(price > balance){
System.out.println("Bakiye yetersiz.");
} else {
balance -= price;
}
break;
case 3:
System.out.println("Bakiyeniz: " + balance);
break;
default:
throw new IllegalStateException("Hatalı seçim: " + choise);
}
/* do-while örnek
do {
System.out.println("1-Para yatırma\n" +
"2-Para Çekme\n" +
"3-Bakiye Sorgula\n" +
"4-Çıkış Yap");
System.out.print("Lütfen yapmak istediğiniz işlemi seçiniz : ");
select = input.nextInt();
if (select == 1) {
System.out.print("Para miktarı : ");
int price = input.nextInt();
balance += price;
} else if (select == 2) {
System.out.print("Para miktarı : ");
int price = input.nextInt();
if (price > balance) {
System.out.println("Bakiye yetersiz.");
} else {
balance -= price;
}
} else if (select == 3) {
System.out.println("Bakiyeniz : " + balance);
}
} while (select != 4);
System.out.println("Tekrar görüşmek üzere.");
break;
*/
} else {
right--;
System.out.println("Hatalı kullanıcı adı veya şifre. Tekrar deneyiniz.");
if (right == 0) {
System.out.println("Hesabınız bloke olmuştur lütfen banka ile iletişime geçiniz.");
} else {
System.out.println("Kalan Hakkınız : " + right);
}
}
}
}
}
|
# Prerequisite
This guide will start at the point where your original orange backlight is removed from your Flipper. You can use [This Guide](https://telegra.ph/Izmenenie-cveta-podsvetki-Flipper-Zero-11-14) (Needs translation if you don't speak Russian), [This Guide](https://telegra.ph/Flipper-Zero-RGB-backlight-guide-12-26) or [This Video Guide](https://www.youtube.com/watch?v=pft1CI5ikA4) to get to that point.
If you're just installing the RGB Backlight, skip all steps necessary for Internal RGB and only solder a wire to the Data-In pad on the RGB Backlight.
# For this installation you will need
- Flipper Zero
- PH #0 Screwdriver
- ~1mm Flathead Screwdriver
- Soldering Iron
- Solder and Flux
- Some thin wire (I like using [UL10064 36ga insulated wire](https://www.aliexpress.us/item/3256805268543019.html) from AliExpress)
- Double-sided adhesive under 4mm thick (I used some random 3mm stuff that I had laying around)
- RGB Backlight with a Data-Out Pad
- Internal RGB Flex PCB

# The Install
Cut two lengths of your wire, one about double the length of the other. Keep them longer than needed; you can always trim them later. Solder the longer length of wire to the Data-Out Pad on your backlight and the shorter one to the Data-In Pad on the backlight.

Place the Backlight into the LCD like so; make sure to reinstall the reflector on the back of the LCD; otherwise, you'll have a very bad time.

Now, reinstall the LCD Assembly. Make sure you route the data wires under the LCD Flex Connector and to the left.

Solder the backlight to the Flipper's Main PCB, use lots of flux during this process.

Since the "ground" pad for the backlight on the Main PCB isn't really a ground point, solder a wire from the left pad to the GND3 test point.

Take the shorter data wire (Data-In) and solder it to the VIBRO test pad. Be careful as that pad is very close to a GPIO header and some capacitors.

This would be a good time to connect the battery and test that the RGB Backlight works. If everything is good, you can reinstall the Black plastic that holds the buttons and LCD in place.
Route the remaining data wire like shown, pulling it underneath the Data-In wire.

Now, you can start reassembling the Flipper and snap the Main PCB Assembly to the rest of the Flipper's internals. The Data-Out wire should be on top of the USB-C port, as shown below.

It is time to start bending the Internal RGB PCB and applying the adhesive. Apply a thin strip of double-sided tape to the back of LED 1 and make bends along the dotted lines shown below.

After making all the necessary bends, compare your Internal RGB PCB to the one below.

If everything looks good, remove the backing on the double-sided tape and place the Internal RGB PCB on the flipper, as shown below. Make sure you line up all of the holes on the Internal RGB PCB with the test pads on the NFC/RFID PCB.


If everything lines up, liberally apply flux and solder the 5V, GND, and two anchors to the Flippers NFC/RFID PCB. Next, bring the remaining data wire over the Vibro motor and solder it to the Internal RGB PCB. Finally, you can reinstall the iButton PCB.

Now its time to test that everything is working correctly before putting it back in the shell. Reconnect the battery and plug your sd card in, then flash [OFW (With Internal RGB Support)](https://github.com/Z3BRO/Flipper-Zero-OFW-RGB) to your Flipper. Go through the RGB Settings page in the setting app and make sure everything is working. If it is, then you can disconnect the battery and sd card, then continue with the guide.
Be careful when inserting the Flipper into the top shell. It's very easy to rip the LEDs off their pads. The single LED between the two GPIO headers should go completely into the top shell, while the strip of 6 LEDs will have some sticking out.


Now its time to put the bottom shell on; in my experience, it is easiest to start with the side with 6 LEDs, and then clip the other side in. When putting the bottom shell on it WILL rip the LEDs off their pads if you are not careful. Take your small Flathead screwdriver and use it to push LEDs 1, 2, and 6 underneath the bottom shell. Take your time with this process, if you do it wrong you're screwed.

Once all the LEDs are under the bottom shell, you can clip the bottom shell into place, and that's it! Go and test all the LEDs BEFORE screwing in the bottom shell.
YAYAYAYAYAYAYAY. You are now the proud owner of a blindly bright RGB Flipper Zero, be sure to make fun of all your hacker friends who don't have an RGB Fliper because I'm poor and need people to buy my mod.
|
import 'package:ecommerce/models/activity_model.dart';
import 'package:ecommerce/themes/colors.dart';
import 'package:ecommerce/widgets/activity_widget.dart';
import 'package:flutter/material.dart';
class NotificationActivityScreen extends StatelessWidget {
NotificationActivityScreen({Key? key}) : super(key: key);
List<ActivityModel> listOfActivity = [
ActivityModel(
title: 'Transaction Nike Air Zoom Product',
description: 'Culpa cillum consectetur labore nulla nulla magna irure. Id veniam culpa officia aute dolor amet deserunt ex proident commodo',
date: 'April 30, 2014 1:01 PM',
),
ActivityModel(
title: 'Transaction Nike Air Zoom Pegasus 36 Miami',
description: 'Culpa cillum consectetur labore nulla nulla magna irure. Id veniam culpa officia aute dolor',
date: 'April 30, 2014 1:01 PM',
),
ActivityModel(
title: 'Transaction Nike Air Max',
description: 'Culpa cillum consectetur labore nulla nulla magna irure. Id veniam culpa officia aute dolor amet deserunt ex proident commodo',
date: 'April 30, 2014 1:01 PM',
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size(0, 78),
child: Padding(
padding: const EdgeInsets.only(top: 15, left: 8, right: 8),
child: AppBar(
title: const Text('Activity'),
titleSpacing: 0,
titleTextStyle: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w700,
color: AppColors.primaryDarkColor,
letterSpacing: 0.5,
height: 1.5,
fontFamily: 'poppins',
),
elevation: 0,
backgroundColor: Colors.white,
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: Icon(
Icons.arrow_back_ios,
color: AppColors.grey,
),
),
),
),
),
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
body: SafeArea(
child: Center(
child: Column(
children: [
/// divider
Container(
child: Divider(
thickness: 1,
color: AppColors.lightGrey,
),
),
/// offers
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: listOfActivity.length,
itemBuilder: (context,index){
return ActivityWidget(activityModel: listOfActivity[index]);
},
),
],
),
),
),
);
}
}
|
package com.colegioapi.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
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.colegioapi.dto.Profesores;
import com.colegioapi.service.ProfesoresServiceImpl;
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")
public class ProfesoresController {
//Call Our Service
@Autowired
ProfesoresServiceImpl profesoresServiceImpl;
//Method GET type list
@GetMapping("/profesores")
public List<Profesores> listarProfesores(){
return profesoresServiceImpl.listarProfesores();
}
//Method POST
@PostMapping("/profesores")
public Profesores guardarProfesores(@RequestBody Profesores profesores) {
return profesoresServiceImpl.guardarProfesores(profesores);
}
//Method GET for ID
@GetMapping("/profesores/{id}")
//does the id to id conversion @PathVariable:
public Profesores profesoresXID(@PathVariable(name = "id") Long id) {
Profesores profesores_xid = new Profesores();
//the whole object saves it in the variable:
profesores_xid = profesoresServiceImpl.profesoresXID(id);
//see in console
System.out.println("Profesor Seleccionado: " + profesores_xid);
return profesores_xid;
}
//Method PUT
@PutMapping("/profesores/{id}")
public Profesores actualizarProfesores(@PathVariable(name = "id") Long id, @RequestBody Profesores profesores) {
Profesores profesores_seleccionado = new Profesores();
Profesores profesores_actualizado = new Profesores();
profesores_seleccionado = profesoresServiceImpl.profesoresXID(id);
profesores_seleccionado.setNombre(profesores.getNombre());
profesores_actualizado = profesoresServiceImpl.actualizarProfesores(profesores_seleccionado);
//see in console
System.out.println("Profesor Actualizado es: " + profesores_actualizado);
return profesores_actualizado;
}
//Method DELETE
@DeleteMapping("/profesores/{id}")
public void eliminarProfesores(@PathVariable(name = "id") Long id) {
profesoresServiceImpl.eliminarProfesores(id);
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class PenyesuaianTableUsers extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string("username", 10)->unique();
$table->enum("roles",["ADMIN","MASTER"]);
$table->string("foto")->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColomn("username");
$table->dropColomn("roles");
$table->dropColomn("foto");
});
}
}
|
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import '../../controller/profile_controller.dart';
import '../../model/profile_model.dart';
class ProfileView extends StatefulWidget {
@override
State<ProfileView> createState() => _ProfileViewState();
}
class _ProfileViewState extends State<ProfileView> {
final ProfileController _profileController = Get.put(ProfileController());
final TextEditingController _nameController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final ImagePicker _picker = ImagePicker();
File? _image;
@override
void initState() {
super.initState();
_profileController.fetchUserProfile(); // Fetch user profile data
}
void _uploadImage() async {
final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
if (pickedFile != null) {
setState(() {
_image = File(pickedFile.path);
});
// Implement code to upload image to Firebase Storage
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Profile'),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Obx(() {
if (_profileController.userProfile.value == null) {
// If userProfile is null, show a loading indicator
return const Center(child: CircularProgressIndicator());
} else {
UserProfile userProfile = _profileController.userProfile.value!;
_nameController.text = userProfile.displayName;
_emailController.text = userProfile.email;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Stack(
children: [
CircleAvatar(
radius: 70,
backgroundImage: _image != null
? FileImage(_image!)
: userProfile.photoURL.isNotEmpty
? NetworkImage(userProfile.photoURL)
: null,
child: IconButton(
icon: const Icon(Icons.camera_alt),
onPressed: _uploadImage,
),
),
],
),
),
const SizedBox(height: 20),
TextField(
controller: _nameController,
decoration: const InputDecoration(labelText: 'Name'),
),
const SizedBox(height: 10),
TextField(
controller: _emailController,
decoration: const InputDecoration(labelText: 'Email'),
),
const SizedBox(height: 20),
Center(
child: ElevatedButton(
onPressed: () {
// Implement functionality to update profile
_profileController.updateProfile(
name: _nameController.text,
email: _emailController.text,
);
},
child: const Text('Save'),
),
),
],
);
}
}),
],
),
),
);
}
}
|
import { useEffect, useState } from "react"
import { useAppSelector } from "../../app/hooks"
import { ICurrent } from "../../Interfaces/Weather/current"
const Current = ({ cityName }: { cityName?: string }) => {
const tempCurrent = useAppSelector((e) => e.weather.current)
const [current, setCurrent] = useState<ICurrent>()
const [dateTime, setDateTime] = useState<Date>()
useEffect(() => {
setCurrent({ ...tempCurrent })
}, [tempCurrent])
useEffect(() => {
if (current?.dt !== undefined)
setDateTime(new Date(current.dt * 1000))
}, [current])
return (
<div className='md:px-5 px-2 flex'>
<div className='w-full text-start flex'>
<div className='text-6xl align-top mr-1'>{current?.temp.toFixed()}</div>
<div className='mt-1 text-start align-top '>C°</div>
<div className=' text-xs md:m-2 mt-2 text-start text-slate-400'>
<div>FeelsLike:
<span className='mx-1'>{current?.feels_like}C°</span>
</div>
<div>Humidity:
<span className='mx-1'>{current?.humidity}%</span>
</div>
<div>Wind:
<span className='mx-1'>{current?.wind_speed}km/h</span>
</div>
</div>
</div>
<div className='w-full align-top text-end'>
<div className='md:text-3xl text-2xl'>{cityName}</div>
<div>
<span className='mx-2'>{dateTime?.toDateString().slice(0, 3)}</span>
<span>{dateTime?.toLocaleTimeString('tr', { timeStyle: 'short' })}</span>
</div>
{current?.weather.length && <div className='text-sm text-slate-400'>{current?.weather[0].description}</div>}
</div>
</div>
)
}
export default Current
|
--NPCManager is required for setting basic NPC properties
local npcManager = require("npcManager")
local npcutils = require("npcs/npcutils")
--Create the library table
local sampleNPC = {}
--NPC_ID is dynamic based on the name of the library file
local npcID = NPC_ID
--Defines NPC config for our NPC. You can remove superfluous definitions.
local sampleNPCSettings = {
id = npcID,
--Sprite size
gfxheight = 32,
gfxwidth = 32,
gfxoffsety = 4,
--Hitbox size. Bottom-center-bound to sprite size.
width = 24,
height = 24,
--Frameloop-related
frames = 1,
framestyle = 0,
framespeed = 8, --# frames between frame change
--Movement speed. Only affects speedX by default.
speed = 1,
--Collision-related
npcblock = false,
npcblocktop = false, --Misnomer, affects whether thrown NPCs bounce off the NPC.
playerblock = false,
playerblocktop = false, --Also handles other NPCs walking atop this NPC.
nohurt=true,
nogravity = false,
noblockcollision = false,
nofireball = false,
noiceball = false,
noyoshi= false,
nowaterphysics = true,
--Various interactions
jumphurt = false, --If true, spiny-like
spinjumpsafe = true, --If true, prevents player hurt when spinjumping
harmlessgrab = false, --Held NPC hurts other NPCs if false
harmlessthrown = false, --Thrown NPC hurts other NPCs if false
grabside=false,
grabtop=false,
staticdirection = true,
}
--Applies NPC settings
npcManager.setNpcSettings(sampleNPCSettings)
--Register the vulnerable harm types for this NPC. The first table defines the harm types the NPC should be affected by, while the second maps an effect to each, if desired.
npcManager.registerHarmTypes(npcID,
{
HARM_TYPE_JUMP,
--HARM_TYPE_FROMBELOW,
HARM_TYPE_NPC,
--HARM_TYPE_PROJECTILE_USED,
HARM_TYPE_LAVA,
--HARM_TYPE_HELD,
HARM_TYPE_TAIL,
HARM_TYPE_SPINJUMP,
--HARM_TYPE_OFFSCREEN,
HARM_TYPE_SWORD
},
{
[HARM_TYPE_JUMP]=10,
--[HARM_TYPE_FROMBELOW]=10,
[HARM_TYPE_NPC]=10,
--[HARM_TYPE_PROJECTILE_USED]=10,
[HARM_TYPE_LAVA]={id=13, xoffset=0.5, xoffsetBack = 0, yoffset=1, yoffsetBack = 1.5},
--[HARM_TYPE_HELD]=10,
[HARM_TYPE_TAIL]=10,
[HARM_TYPE_SPINJUMP]=10,
--[HARM_TYPE_OFFSCREEN]=10,
[HARM_TYPE_SWORD]=10,
}
);
--[[************************
Rotation code by MrDoubleA
**************************]]
local function drawSprite(args) -- handy function to draw sprites
args = args or {}
args.sourceWidth = args.sourceWidth or args.width
args.sourceHeight = args.sourceHeight or args.height
if sprite == nil then
sprite = Sprite.box{texture = args.texture}
else
sprite.texture = args.texture
end
sprite.x,sprite.y = args.x,args.y
sprite.width,sprite.height = args.width,args.height
sprite.pivot = args.pivot or Sprite.align.TOPLEFT
sprite.rotation = args.rotation or 0
if args.texture ~= nil then
sprite.texpivot = args.texpivot or sprite.pivot or Sprite.align.TOPLEFT
sprite.texscale = args.texscale or vector(args.texture.width*(args.width/args.sourceWidth),args.texture.height*(args.height/args.sourceHeight))
sprite.texposition = args.texposition or vector(-args.sourceX*(args.width/args.sourceWidth)+((sprite.texpivot[1]*sprite.width)*((sprite.texture.width/args.sourceWidth)-1)),-args.sourceY*(args.height/args.sourceHeight)+((sprite.texpivot[2]*sprite.height)*((sprite.texture.height/args.sourceHeight)-1)))
end
sprite:draw{priority = args.priority,color = args.color,sceneCoords = args.sceneCoords or args.scene}
end
--Register events
function sampleNPC.onInitAPI()
npcManager.registerEvent(npcID, sampleNPC, "onTickEndNPC")
npcManager.registerEvent(npcID, sampleNPC, "onDrawNPC")
end
function sampleNPC.onTickEndNPC(v)
local config = NPC.config[v.id]
local data = v.data
local settings = v.data._settings
v.animationFrame = 0
if v:mem(0x12A, FIELD_WORD) <= 0 then
data.rotation = nil
return
end
if settings.spread == nil then settings.spread = 3 end
if v.despawnTimer <= 0 then
--Reset our properties, if necessary
data.initialized = false
data.timer = 0
return
end
if not data.initialized then
--Initialize necessary data.
data.initialized = true
data.timer = data.timer or 0
end
if not data.rotation then
data.rotation = 0
end
data.timer = data.timer + 1
if data.timer == 3 then
Effect.spawn(npcID, v.x + math.random(-6, 6), v.y + math.random(-6, 6))
data.timer = 0
end
data.rotation = ((data.rotation or 0) + math.deg((v.speedX*config.speed)/((v.width+v.height)/4)))
if v.collidesBlockBottom then
for _,npc in ipairs (NPC.getIntersecting(v.x - 8, v.y - 8, v.x + v.width + 8, v.y + v.height + 8)) do
if npc.id == npcID + 1 then
break
else
for i = 0,settings.spread - 1 do
local g = i * 32
local n = NPC.spawn(npcID + 1,(v.x + g - 4) - (settings.spread * 16 - 16), v.y - 8, player.section, false)
if settings.spread == 1 then
n.ai1 = 3
else
if i == 0 then
n.ai1 = 0
elseif i == settings.spread - 1 then
n.ai1 = 2
else
n.ai1 = 1
end
end
end
end
end
Effect.spawn(npcID + 1, v.x - 36, v.y + 26)
v:kill(HARM_TYPE_OFFSCREEN)
SFX.play(72)
end
if v:mem(0x120, FIELD_BOOL) then
v:mem(0x120, FIELD_BOOL, false)
end
end
function sampleNPC.onDrawNPC(v)
local config = NPC.config[v.id]
local data = v.data
if v:mem(0x12A,FIELD_WORD) <= 0 or not data.rotation or data.rotation == 0 then return end
local priority = -45
if config.priority then
priority = -15
end
drawSprite{
texture = Graphics.sprites.npc[v.id].img,
x = v.x+(v.width/2)+config.gfxoffsetx,y = v.y+v.height-(config.gfxheight/2)+config.gfxoffsety,
width = config.gfxwidth,height = config.gfxheight,
sourceX = 0,sourceY = v.animationFrame*config.gfxheight,
sourceWidth = config.gfxwidth,sourceHeight = config.gfxheight,
priority = priority,rotation = data.rotation,
pivot = Sprite.align.CENTRE,sceneCoords = true,
}
npcutils.hideNPC(v)
end
return sampleNPC
|
/*
package com.trace.sdkapp;
import io.grpc.ManagedChannel;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hyperledger.fabric.client.CallOption;
import org.hyperledger.fabric.client.Contract;
import org.hyperledger.fabric.client.Gateway;
import org.hyperledger.fabric.client.Network;
import org.hyperledger.fabric.client.identity.Identities;
import org.hyperledger.fabric.client.identity.Signers;
import org.hyperledger.fabric.client.identity.X509Identity;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
@Configuration
@AllArgsConstructor
@Slf4j
public class HyperLedgerFabricGatewayConfig {
final HyperLedgerFabricProperties hyperLedgerFabricProperties;
@Bean
public Gateway gateway() throws Exception {
BufferedReader certificateReader = Files
.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getCertificatePath()), StandardCharsets.UTF_8);
X509Certificate certificate = Identities.readX509Certificate(certificateReader);
BufferedReader privateKeyReader = Files
.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getPrivateKeyPath()), StandardCharsets.UTF_8);
PrivateKey privateKey = Identities.readPrivateKey(privateKeyReader);
Gateway gateway = Gateway.newInstance()
.identity(new X509Identity(hyperLedgerFabricProperties.getMspId(), certificate))
.signer(Signers.newPrivateKeySigner(privateKey))
.connection(newGrpcConnection())
.evaluateOptions(CallOption.deadlineAfter(5, TimeUnit.SECONDS))
.endorseOptions(CallOption.deadlineAfter(15, TimeUnit.SECONDS))
.submitOptions(CallOption.deadlineAfter(5, TimeUnit.SECONDS))
.commitStatusOptions(CallOption.deadlineAfter(1, TimeUnit.MINUTES))
.connect();
return gateway;
}
private ManagedChannel newGrpcConnection() throws IOException, CertificateException {
Reader tlsCertReader = Files.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getTlsCertPath()));
X509Certificate tlsCert = Identities.readX509Certificate(tlsCertReader);
return NettyChannelBuilder.forTarget("peer0.org1.example.com:7051")
.sslContext(GrpcSslContexts.forClient().trustManager(tlsCert).build())
.overrideAuthority("peer0.org1.example.com:")
.build();
}
@Bean
public Network network(Gateway gateway) {
return gateway.getNetwork(hyperLedgerFabricProperties.getChannel());
}
@Bean
public Contract recordContract(Network network) {
return network.getContract("trace", "trace");
}
}
*/
|
/**
* @author:syf20020816@outlook.com
* @since:20230915
* @version:0.1.3
* @type:interface
* @description:
* # SURProgress
* SURProgress is commonly used to display download progress or event processing progress
* And you can fully control it through the progress property
* ## properties
* - in property <Themes> theme : Surrealism theme
* - in property <string> content : what you wanna show to others
* - in-out property <float> progress : progress
* - private property <length> unit : unit of progress length
* ## functions
* - pure public function get-progress() : get timely progress
* - public function full() : make progress 100%
* - public function clear() : : make progress 0%
* - public function add(num:float) : increase progress
* ## callbacks
*/
import { SURText } from "../text/index.slint";
import { SURCard } from "../card/index.slint";
import { ROOT_STYLES,Themes } from "../../themes/index.slint";
export component Progress inherits Rectangle {
width: 100%;
height: layout.height;
in property <Themes> theme :Light;
in property <string> content : @tr("now: {}% used 100%" , progress);
in-out property <float> progress : 16;
private property <length> unit : self.width / 100;
public function add(num:float) {
if(progress<=100 - num){
root.progress+=num;
}else{
progress = 100;
}
}
pure public function get-progress() {
root.progress
}
public function clear() {
root.progress = 0;
}
public function full() {
root.progress = 100;
}
states [
light when theme == Themes.Light: {
inner.background : ROOT-STYLES.sur-theme-colors.light.deepest;
}
primary when theme == Themes.Primary: {
inner.background : ROOT-STYLES.sur-theme-colors.primary.deepest;
}
success when theme == Themes.Success: {
inner.background : ROOT-STYLES.sur-theme-colors.success.deepest;
}
info when theme == Themes.Info: {
inner.background : ROOT-STYLES.sur-theme-colors.info.deepest;
}
warning when theme == Themes.Warning: {
inner.background : ROOT-STYLES.sur-theme-colors.warning.deepest;
}
error when theme == Themes.Error: {
inner.background : ROOT-STYLES.sur-theme-colors.error.deepest;
}
dark when theme == Themes.Dark: {
inner.background : ROOT-STYLES.sur-theme-colors.dark.deepest;
}
]
layout:=VerticalLayout {
height: bar.height + txt-view.height;
padding-left: 4px;
padding-right: 4px;
bar:=Rectangle {
height: outer.height;
outer:=SURCard {
theme: Light;
height: 8px;
width: 100%;
border-radius: self.height / 2;
clip: true;
inner:=SURCard {
x: 0;
theme: root.theme;
height: 8px;
width: root.progress * root.unit;
border-radius: self.height / 2;
padding: 0;
padding-left: 0;
padding-right: 0;
padding-top: 0;
padding-bottom: 0;
drop-shadow-blur: 0;
drop-shadow-offset-y: 0;
drop-shadow-offset-x: 0;
}
}
}
txt-view:=Rectangle{
height: txt.height * 1.5;
txt:=SURText {
theme: root.theme;
width: parent.width;
content:root.content;
font-size: ROOT-STYLES.sur-font.font-size - 4px;
horizontal-alignment: left;
}
}
}
}
|
import streamlit as st
import plotly.graph_objects as go
import altair as alt
from visualisation import Visualization
from Pred import LinearForecast
from Pred import ExponentialSmoothingForecast
from scipy.stats import pearsonr, spearmanr
import pandas as pd
st.set_page_config(
page_title="Cryptocurrency Reddit Insights.",
layout="wide",
page_icon="🤑",
initial_sidebar_state="expanded")
st.markdown(
"""
<style>
footer {display: none}
[data-testid="stHeader"] {display: none}
</style>
""", unsafe_allow_html = True
)
with open('style.css') as f:
st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html = True)
title_col, emp_col, btc_col, eth_col, sol_col, dodge_col, xrp_col = st.columns([1,0.2,1,1,1,1,1])
with title_col:
st.markdown('<p class="dashboard_title">Crypto<br>Dashboard</p>', unsafe_allow_html = True)
with btc_col:
with st.container():
btc_price = '7.32 T'
st.markdown(f'<p class="btc_text">BTC / USDT<br></p><p class="price_details">{btc_price}</p>', unsafe_allow_html = True)
with eth_col:
with st.container():
eth_price = '3.41 T'
st.markdown(f'<p class="eth_text">ETH / USDT<br></p><p class="price_details">{eth_price}</p>', unsafe_allow_html = True)
with dodge_col:
with st.container():
dodge_price = '0.36 T'
st.markdown(f'<p class="xmr_text"> Ð / USDT<br></p><p class="price_details">{dodge_price}</p>', unsafe_allow_html = True)
with sol_col:
with st.container():
sol_price = '0.63 T'
st.markdown(f'<p class="sol_text">SOL / USDT<br></p><p class="price_details">{sol_price}</p>', unsafe_allow_html = True)
with xrp_col:
with st.container():
xrp_price = '0.38 T'
st.markdown(f'<p class="xrp_text">XRP / USDT<br></p><p class="price_details">{xrp_price}</p>', unsafe_allow_html = True)
# Read CSV files for each cryptocurrency
bitcoin_df = pd.read_csv('data/Bitcoin.csv')
ethereum_df = pd.read_csv('data/Ethereum.csv')
solana_df = pd.read_csv('data/Solana.csv')
dogecoin_df = pd.read_csv('data/Dodgecoin.csv')
dataframes = {
'Bitcoin': bitcoin_df,
'Ethereum': ethereum_df,
'Solana': solana_df,
'Dogecoin': dogecoin_df
}
visualizer = Visualization(dataframes)
models = ['Exponential Smoothing', 'Linear Regression', 'Prophet']
merged_df = pd.read_csv('data/btc_reddit.csv')
def correlation_gauge(merged_df):
pearson_corr, _ = pearsonr(merged_df['return'], merged_df['score'])
# Calculate Spearman correlation coefficient and p-value
spearman_corr, _ = spearmanr(merged_df['return'], merged_df['score'])
# Create gauge plot
fig = go.Figure()
fig.add_trace(go.Indicator(
mode="gauge+number",
value=pearson_corr,
domain={'x': [0, 1], 'y': [0.6, 1]},
title={'text': "Pearson Correlation"},
gauge={'axis': {'range': [-1, 1],'tickcolor': "darkblue"},'bgcolor': 'royalblue','bar': {'color': "darkblue"},}
))
fig.add_trace(go.Indicator(
mode="gauge+number",
value=spearman_corr,
domain={'x': [0, 1], 'y': [0, 0.4]},
title={'text': "Spearman Correlation"},
gauge={'axis': {'range': [-1, 1],'tickcolor': "darkblue"},'bgcolor': 'royalblue','bar': {'color': "darkblue"},}
))
# Update layout
fig.update_layout(template='plotly_dark')
# Show plot
st.plotly_chart(fig, use_container_width=True)
params_col, chart_col, data_col = st.columns([0.5,1.2,0.6])
with params_col:
with st.form(key = 'params_form'):
st.markdown(f'<p class="params_text">Dashboard Parameters', unsafe_allow_html = True)
selected_coin = st.selectbox('Coins', dataframes.keys(), key = 'Models_selectbox')
update_chart = st.form_submit_button('Update chart')
st.markdown('')
Model = st.selectbox('Models', models, key = 'Coins_selectbox')
Predict = st.form_submit_button('Forecast')
st.markdown('')
if update_chart:
with chart_col:
with st.container():
visualizer.candlestick(dataframes[selected_coin])
st.divider()
visualizer.box_plot(dataframes[selected_coin])
with data_col:
visualizer.gauge_chart(dataframes[selected_coin])
st.divider()
visualizer.gauge_chart_2(dataframes[selected_coin])
st.divider()
if Predict:
train_size = int(len(merged_df) * 0.8)
train_data, test_data = merged_df[:train_size], merged_df[train_size:]
model = ExponentialSmoothingForecast(train_data, test_data)
exponential_model = model.fit()
forecast = model.forecast(exponential_model)
mse, mae, r2 = model.evaluate(forecast)
with chart_col:
with st.container():
model.plot_forecast(exponential_model, forecast)
model.plot_metrics_gauge(forecast)
with data_col:
correlation_gauge(merged_df)
footer="""<style>
a:link , a:visited{
font-family: 'Space Grotesk';
color: white;
background-color: transparent;
text-decoration: underline;
}
a:hover, a:active {
color: #030e3b;
background-color: transparent;
text-decoration: underline;
}
.footer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
background-color: transparent;
color: #f7931a;
text-align: center;
box-shadow: -6px 8px 20px 1px #ccc6c652;
}
</style>
<div class="footer">
<p>Developed by <a style='display: block; text-align: center;'href="https:https://www.linkedin.com/in/yassine-ben-zekri-72aa6b199/" target="_blank">Med Yassine Ben Zekri</a></p>
</div>
"""
st.markdown(footer,unsafe_allow_html=True)
|
/************************************************************************************
*
* Name : mrLED
* File : LED.h
* Author : Mark Reds <marco@markreds.it>
* Date : September 8, 2020
* Version : 1.0.2
* Notes : This library allows an Arduino board to control LEDs.
*
* Copyright (C) 2020 Marco Rossi (aka Mark Reds). All right reserved.
*
* This file is part of mrLED.
*
* mrLED 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 3 of the License, or
* (at your option) any later version.
*
* mrLED 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 mrLED. If not, see <http://www.gnu.org/licenses/>.
*
************************************************************************************/
#ifndef _LED_h_
#define _LED_h_
#if defined(ARDUINO) && ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#include "pins_arduino.h"
#endif
enum ledstate_t {
kSwitchOff,
kSwitchOn,
kBlinkOn,
kBlinkOff,
kBlinkPause,
kBreathIn,
kBreathOut
};
class LED {
private:
uint8_t m_pin;
uint8_t m_lo;
uint8_t m_hi;
uint8_t m_count;
uint32_t m_start;
uint32_t m_interval;
ledstate_t m_state;
public:
LED(uint8_t pin);
LED(uint8_t pin, uint8_t lo, uint8_t hi);
virtual ~LED();
inline void begin() { pinMode(m_pin, OUTPUT); }
void on();
void off();
void toggle();
void blink(uint32_t interval);
void blink(uint32_t interval, uint32_t duration);
void flash(uint8_t count, uint32_t pause, uint32_t timeOn = 180UL, uint32_t timeOff = 120UL);
void reset();
void breath(uint32_t interval);
inline ledstate_t state() { return m_state; }
};
#endif
|
import {Room, RoomInfo, RoomState, RoomVisibility} from "../struct/room";
import {Constants, Util, Validation} from "../helpers";
import pool from "./pool";
import {User, UserState} from "../struct/user";
import {Message, MessageLike} from "../struct/message";
import db from "./db";
class RoomDBHandler {
static async create(userId: number, name: string | undefined, visibility: string, votingMethod: string): Promise<Room> {
if (!Validation.uint(userId)) throw new Error("Invalid User");
let user = await db.users.get(userId);
if (!Room.VisibilityOptions.includes(visibility)) throw new Error("Invalid Visibility Setting");
if (!Room.VotingMethods.includes(votingMethod)) throw new Error("Invalid Voting Method");
let isPublic = visibility === RoomVisibility.PUBLIC;
let timestamp = Util.unixTimestamp();
let token = isPublic ? undefined : Util.makeHash(Constants.TokenLength);
let props = [];
if (name) props.push(name);
props.push(timestamp, visibility, votingMethod);
if (!isPublic) props.push(token);
let res = await pool.query(`
INSERT INTO rooms (${name ? "name, " : ""}lastActive, visibility, votingMethod${isPublic ? "" : ", token"})
VALUES (${name ? "?, " : ""}?, ?, ?${isPublic ? "" : ", ?"})
`, props);
let roomId = res.insertId;
return this.addUser(userId, roomId, UserState.SELECTING_QUESTION).then(() => {
user.active = true;
user.state = UserState.SELECTING_QUESTION;
user.score = 0;
let room = new Room({
id: roomId,
name: name,
lastActive: timestamp,
visibility: visibility,
votingMethod: votingMethod,
token: token,
state: RoomState.PICKING_QUESTION,
users: {
[user.id]: user
}
} as Room);
return db.messages.create(user, room, "Created the room", true).then((message) => {
room.messages = {[message.id]: message};
return room;
}).catch((error) => {
console.warn(`Failed to create initial message for room #${room.id}:`, error.message);
room.messages = {};
return room;
})
}).catch(async (error) => {
console.warn(`Failed to add user #${userId} to newly created room #${roomId}:`, error.message);
await pool.query(`DELETE FROM rooms WHERE id = ? LIMIT 1`, [roomId]);
throw error;
});
}
static async markActive(room: Room): Promise<void> {
let timestamp = Util.unixTimestamp();
await pool.query(`
UPDATE rooms SET lastActive = ? WHERE id = ?
`, [timestamp, room.id]);
}
static async get(id: number | string, withUsers = false, withExtras = false): Promise<Room> {
let res = await pool.query(`SELECT * FROM rooms WHERE id = ?`, [Util.parseId(id)]);
if (res.length < 1) throw new Error("Invalid Room ID");
let room = new Room(res[0]);
if (withUsers) {
let users = await pool.query(`
SELECT * FROM roomUsers
INNER JOIN users ON roomUsers.userId = users.id
WHERE roomUsers.roomId = ?
`, [room.id]);
room.users = {};
for (let i = 0; i < users.length; i++) {
let user = new User(users[i]);
room.users[user.id] = user;
}
}
if (withExtras) {
let messages = await pool.query(`
SELECT
msg.id, msg.createdAt, msg.userId,
msg.body, msg.type,
GROUP_CONCAT(
DISTINCT CONCAT(likes.userId, ':', likes.since)
SEPARATOR ','
) AS likes
FROM messages msg
LEFT JOIN messageLikes likes ON msg.id = likes.messageId
WHERE msg.roomId = ?
GROUP BY msg.id
ORDER BY msg.id DESC
LIMIT 50
`, [room.id]);
room.messages = {};
for (let msg = 0; msg < messages.length; msg++) {
let row = messages[msg];
let likes: Record<number, MessageLike> = {};
if (row.likes) {
let likesData = row.likes.split(",");
for (let like = 0; like < likesData.length; like++) {
let likeData = likesData[like].split(":");
likes[likeData[0]] = new MessageLike({
userId: likeData[0],
since: likeData[1]
});
}
}
room.messages[row.id] = new Message({
id: row.id,
createdAt: row.createdAt,
userId: row.userId,
body: row.body,
type: row.type,
likes: likes
});
if (msg === messages.length - 1) room.messages[row.id].isChained = false;
}
let kickVotes = await pool.query(`
SELECT userId, votedUserId
FROM kickVotes WHERE roomId = ?
`, [room.id]);
for (let k = 0; k < kickVotes.length; k++) {
let vote = kickVotes[k];
if (room.kickVotes.hasOwnProperty(vote.votedUserId)) room.kickVotes[vote.votedUserId].push(vote.userId);
else room.kickVotes[vote.votedUserId] = [vote.userId];
}
if (room.state !== RoomState.PICKING_QUESTION) {
let question = await db.questions.getSelected(room);
if (question) {
room.questions = [question];
if (room.state !== RoomState.COLLECTING_ANSWERS) {
let answers = await db.answers.getAll(room, question, true);
let guessResults: Record<number, boolean> = {};
room.answerUserIds = [];
answers.forEach((answer) => {
if (answer.userId) {
room.answerUserIds.push(answer.userId);
if (answer.displayPosition !== undefined && answer.guesses.length > 0) {
// TODO: democratic voting
guessResults[answer.displayPosition] = answer.guesses[0].guessedUserId === answer.userId;
}
}
answer.strip();
});
room.answers = answers;
let roomFavorites = await db.answers.getFavorites(room, question, true);
let favorites: number[] = [];
roomFavorites.forEach((favorite) => favorites.push(favorite.displayPosition));
room.favoriteAnswers = favorites;
if (room.state === RoomState.VIEWING_RESULTS) {
room.guessResults = guessResults;
}
}
}
}
}
return room;
}
static async getList(): Promise<RoomInfo[]> {
let timestamp = Util.unixTimestamp();
let res = await pool.query(`
SELECT * FROM rooms
WHERE visibility = ? AND ? - lastActive < 900
ORDER BY lastActive DESC
LIMIT 15
`, [RoomVisibility.PUBLIC, timestamp]);
let rooms: RoomInfo[] = [];
for (let i = 0; i < res.length; i++) {
let row = res[i];
let users = await pool.query(`
SELECT active FROM roomUsers WHERE roomId = ?
`, [row.id]);
let activeUsers = 0;
users.forEach((user: any) => {
if (user.active) activeUsers++;
});
let lastMessage = await pool.query(`
SELECT createdAt, body FROM messages WHERE roomId = ? ORDER BY id DESC LIMIT 1
`, [row.id]);
let lastActive = row.lastActive;
if (lastMessage.length > 0) {
let lastMessageAt = lastMessage[0].createdAt;
if (lastMessageAt > lastActive) lastActive = lastMessageAt;
}
rooms.push(new RoomInfo({
id: row.id,
name: row.name,
lastActive: lastActive,
visibility: RoomVisibility.PUBLIC,
votingMethod: row.votingMethod,
players: users.length,
activePlayers: activeUsers
}));
}
rooms.sort((a, b) => {
return b.lastActive - a.lastActive;
});
return rooms;
}
static async setState(room: Room, state: RoomState): Promise<boolean> {
let res = await pool.query(`
UPDATE rooms
SET state = ?, lastActive = ?
WHERE id = ?
`, [state, Util.unixTimestamp(), room.id]);
return res.affectedRows > 0;
}
static async getUser(id: number | string, roomId: number | string, withToken = false): Promise<User> {
id = Util.parseId(id);
roomId = Util.parseId(roomId);
let res = await pool.query(`
SELECT * FROM roomUsers
INNER JOIN users ON roomUsers.userId = users.id
WHERE roomUsers.userId = ? AND roomUsers.roomId = ?
`, [id, roomId]);
if (res.length < 1) throw new Error("Invalid Room or User");
return new User(res[0], withToken);
}
static async setUserActive(userId: number | string, roomId: number | string, active: boolean, state = UserState.IDLE): Promise<boolean> {
userId = Util.parseId(userId);
roomId = Util.parseId(roomId);
let res = await pool.query(`
UPDATE roomUsers
SET active = ?, state = ?
WHERE userId = ? AND roomId = ?
`, [active, state, userId, roomId]);
return res.affectedRows > 0;
}
static async resetRound(room: Room): Promise<void> {
// TODO: randomly select question in democratic mode
await this.setState(room, RoomState.PICKING_QUESTION);
await db.questions.clearFromRoom(room);
await pool.query(`
UPDATE roomUsers
SET state = ?
WHERE roomId = ?
`, [UserState.IDLE, room.id]);
}
static async startCollectingAnswers(room: Room): Promise<void> {
await this.setState(room, RoomState.COLLECTING_ANSWERS);
await pool.query(`
UPDATE roomUsers
SET state = ?
WHERE roomId = ?
`, [UserState.ANSWERING_QUESTION, room.id]);
}
static async setUserState(userId: number | string, roomId: number | string, state: UserState, scoreIncrease = 0): Promise<boolean> {
userId = Util.parseId(userId);
roomId = Util.parseId(roomId);
let res = await pool.query(`
UPDATE roomUsers
SET state = ?, score = score + ?
WHERE userId = ? AND roomId = ?
`, [state, scoreIncrease, userId, roomId]);
return res.affectedRows > 0;
}
static async getActiveIdsFor(userId: number | string): Promise<number[]> {
userId = Util.parseId(userId);
let rooms = await pool.query(`
SELECT roomId from roomUsers where userId = ? AND active = true
`, [userId]);
let roomIds: number[] = [];
for (let room = 0; room < rooms.length; room++) {
roomIds.push(rooms[room].roomId);
}
return roomIds;
}
static async addUser(userId: number, roomId: number, state = UserState.IDLE) {
return pool.query(`
INSERT INTO roomUsers (userId, roomId, state) VALUES (?, ?, ?)
`, [userId, roomId, state]);
}
static async getKickVotes(room: Room, user: User): Promise<number[]> {
let res = await pool.query(`
SELECT userId FROM kickVotes
WHERE roomId = ? AND votedUserId = ?
`, [room.id, user.id]);
let votes = [];
for (let r = 0; r < res.length; r++) {
votes.push(res[r].userId);
}
return votes;
}
static async placeKickVote(room: Room, user: User, votedUser: User): Promise<number[]> {
let votes = await db.rooms.getKickVotes(room, votedUser);
if (votes.includes(user.id)) throw new Error("Can't vote on the same player twice");
await pool.query(`
INSERT INTO kickVotes (roomId, userId, votedUserId) VALUES (?, ?, ?)
`, [room.id, user.id, votedUser.id]);
await pool.query(`
UPDATE roomUsers SET kickVotesPlaced = kickVotesPlaced + 1
WHERE userId = ? AND roomId = ?
`, [user.id, room.id]);
votes.push(user.id);
return votes;
}
static async kickUser(room: Room, user: User) {
await pool.query(`
UPDATE roomUsers SET timesKicked = timesKicked + 1
WHERE userId = ? AND roomId = ?
`, [user.id, room.id]);
}
static async clearKickVotes(room: Room, user: User) {
await pool.query(`
DELETE FROM kickVotes WHERE roomId = ? AND votedUserId = ?
`, [room.id, user.id]);
}
}
export {RoomDBHandler};
|
package controllers
import (
"context"
"errors"
"fmt"
"github.com/mylxsw/aidea-server/pkg/ai/chat"
"github.com/mylxsw/aidea-server/pkg/misc"
"github.com/mylxsw/aidea-server/pkg/rate"
repo2 "github.com/mylxsw/aidea-server/pkg/repo"
"github.com/mylxsw/aidea-server/pkg/repo/model"
service2 "github.com/mylxsw/aidea-server/pkg/service"
"github.com/mylxsw/aidea-server/pkg/youdao"
"io"
"net/http"
"strings"
"time"
"github.com/Timothylock/go-signin-with-apple/apple"
"github.com/go-redis/redis_rate/v10"
"github.com/hashicorp/go-uuid"
"github.com/hibiken/asynq"
"github.com/mylxsw/aidea-server/config"
"github.com/mylxsw/aidea-server/internal/coins"
"github.com/mylxsw/aidea-server/internal/queue"
"github.com/mylxsw/aidea-server/server/auth"
"github.com/mylxsw/aidea-server/server/controllers/common"
"github.com/mylxsw/asteria/log"
"github.com/mylxsw/glacier/infra"
"github.com/mylxsw/glacier/web"
"github.com/mylxsw/go-utils/array"
"github.com/redis/go-redis/v9"
passwordvalidator "github.com/wagslane/go-password-validator"
)
// UserController 用户控制器
type UserController struct {
translater youdao.Translater `autowire:"@"`
rds *redis.Client `autowire:"@"`
limiter *rate.RateLimiter `autowire:"@"`
queue *queue.Queue `autowire:"@"`
userRepo *repo2.UserRepo `autowire:"@"`
conf *config.Config `autowire:"@"`
userSrv *service2.UserService `autowire:"@"`
secSrv *service2.SecurityService `autowire:"@"`
}
// NewUserController 创建用户控制器
func NewUserController(resolver infra.Resolver) web.Controller {
ctl := UserController{}
resolver.MustAutoWire(&ctl)
return &ctl
}
func (ctl *UserController) Register(router web.Router) {
router.Group("/users", func(router web.Router) {
// 获取当前用户信息
router.Get("/current", ctl.CurrentUser)
router.Post("/current/avatar", ctl.UpdateAvatar)
router.Post("/current/realname", ctl.UpdateRealname)
// 获取当前用户配额详情
router.Get("/quota", ctl.UserQuota)
// 获取当前用户配额情况统计
router.Get("/quota/usage-stat", ctl.UserQuotaUsageStatistics)
router.Get("/quota/usage-stat/{date}", ctl.UserQuotaUsageDetails)
// 用户免费聊天次数统计
router.Get("/stat/free-chat-counts", ctl.UserFreeChatCounts)
router.Get("/stat/free-chat-counts/{model}", ctl.UserFreeChatCountsForModel)
// 自定义首页模型
router.Post("/custom/home-models", ctl.CustomHomeModels)
// 重置密码
router.Post("/reset-password/sms-code", ctl.SendResetPasswordSMSCode)
router.Post("/reset-password", ctl.ResetPassword)
// 账号销毁
router.Delete("/destroy", ctl.Destroy)
router.Post("/destroy/sms-code", ctl.SendResetPasswordSMSCode)
})
}
// UpdateAvatar 更新用户头像
func (ctl *UserController) UpdateAvatar(ctx context.Context, webCtx web.Context, user *auth.User) web.Response {
avatarURL := webCtx.Input("avatar_url")
if !strings.HasPrefix(avatarURL, ctl.conf.StorageDomain) {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "非法的头像地址"), http.StatusBadRequest)
}
if err := ctl.userRepo.UpdateAvatarURL(ctx, user.ID, avatarURL); err != nil {
log.WithFields(log.Fields{
"user_id": user.ID,
}).Errorf("failed to update user avatar: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
u, err := ctl.userSrv.GetUserByID(ctx, user.ID, true)
if err != nil {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
return webCtx.JSON(web.M{
"user": auth.CreateAuthUserFromModel(u),
})
}
// UpdateRealname 更新用户真实姓名
func (ctl *UserController) UpdateRealname(ctx context.Context, webCtx web.Context, user *auth.User) web.Response {
realname := webCtx.Input("realname")
if realname == "" || len(realname) > 50 {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "昵称无效,请重新设置"), http.StatusBadRequest)
}
checkRes := ctl.secSrv.NicknameDetect(realname)
if checkRes.IsReallyUnSafe() {
log.WithFields(log.Fields{
"user_id": user.ID,
"details": checkRes.ReasonDetail(),
"content": realname,
}).Warningf("用户 %d 违规,违规内容:%s", user.ID, checkRes.Reason)
return webCtx.JSONError("内容违规,已被系统拦截,如有疑问邮件联系:support@aicode.cc", http.StatusNotAcceptable)
}
if err := ctl.userRepo.UpdateRealname(ctx, user.ID, realname); err != nil {
log.WithFields(log.Fields{
"user_id": user.ID,
}).Errorf("failed to update user realname: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
u, err := ctl.userSrv.GetUserByID(ctx, user.ID, true)
if err != nil {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
return webCtx.JSON(web.M{
"user": auth.CreateAuthUserFromModel(u),
})
}
// Destroy 销毁账号
func (ctl *UserController) Destroy(ctx context.Context, webCtx web.Context, user *auth.User) web.Response {
verifyCodeId := strings.TrimSpace(webCtx.Input("verify_code_id"))
if verifyCodeId == "" {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "验证码 ID 不能为空"), http.StatusBadRequest)
}
verifyCode := strings.TrimSpace(webCtx.Input("verify_code"))
if verifyCode == "" {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "验证码不能为空"), http.StatusBadRequest)
}
// 流控:每个用户每 60 分钟只能重置密码 5 次
err := ctl.limiter.Allow(ctx, fmt.Sprintf("auth:reset-password:%s:limit", user.Phone), rate.MaxRequestsInPeriod(5, 60*time.Minute))
if err != nil {
if err == rate.ErrRateLimitExceeded {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "操作频率过高,请稍后再试"), http.StatusTooManyRequests)
}
log.WithFields(log.Fields{
"username": user.Phone,
}).Errorf("failed to check verify code rate limit: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
// 检查验证码是否正确
realVerifyCode, err := ctl.rds.Get(ctx, fmt.Sprintf("auth:verify-code:%s:%s", verifyCodeId, user.Phone)).Result()
if err != nil {
if err != redis.Nil {
log.WithFields(log.Fields{
"username": user.Phone,
"id": verifyCodeId,
"code": verifyCode,
}).Errorf("failed to get verify code: %s", err)
}
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "验证码已过期,请重新获取"), http.StatusBadRequest)
}
if realVerifyCode != verifyCode {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "验证码错误"), http.StatusBadRequest)
}
_ = ctl.rds.Del(ctx, fmt.Sprintf("auth:verify-code:%s:%s", verifyCodeId, user.Phone)).Err()
if err := ctl.userRepo.UpdateStatus(ctx, user.ID, repo2.UserStatusDeleted); err != nil {
log.With(user).Errorf("failed to update user status: %s", err)
return webCtx.JSONError("内部错误,请稍后再试", http.StatusInternalServerError)
}
// 撤销 Apple 账号绑定
if user.AppleUID != "" {
func() {
defer func() {
if err := recover(); err != nil {
log.Errorf("revoke apple account token panic: %v", err)
}
}()
client := apple.New()
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
secret, err := apple.GenerateClientSecret(
ctl.conf.AppleSignIn.Secret,
ctl.conf.AppleSignIn.TeamID,
"cc.aicode.flutter.askaide.askaide",
ctl.conf.AppleSignIn.KeyID,
)
if err != nil {
log.Errorf("generate client secret for revoke apple account failed: %v", err)
} else {
req := apple.RevokeAccessTokenRequest{
ClientID: "cc.aicode.flutter.askaide.askaide",
ClientSecret: secret,
AccessToken: user.AppleUID,
}
var resp apple.RevokeResponse
if err := client.RevokeAccessToken(ctx, req, &resp); err != nil && err != io.EOF {
log.Errorf("revoke apple access token failed: %v", err)
}
}
}()
}
return webCtx.JSON(web.M{})
}
// SendResetPasswordSMSCode 发送重置密码的短信验证码
func (ctl *UserController) SendResetPasswordSMSCode(ctx context.Context, webCtx web.Context, user *auth.User) web.Response {
username := user.Phone
if username == "" {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "请退出后重新登录,绑定手机号后再进行操作"), http.StatusBadRequest)
}
// 流控:每个用户每分钟只能发送一次短信
smsCodeRateLimitPerMinute := fmt.Sprintf("auth:sms-code:limit:%s:min", username)
optCountPerMin, err := ctl.limiter.OperationCount(ctx, smsCodeRateLimitPerMinute)
if err != nil {
log.WithFields(log.Fields{
"username": username,
}).Errorf("failed to check sms code rate limit: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
if optCountPerMin > 0 {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "发送短信验证码过于频繁,请稍后再试"), http.StatusTooManyRequests)
}
// 流控:每个用户每天只能发送 5 次短信
smsCodeRateLimitPerDay := fmt.Sprintf("auth:sms-code:limit:%s:day", username)
optCountPerDay, err := ctl.limiter.OperationCount(ctx, smsCodeRateLimitPerDay)
if err != nil {
log.WithFields(log.Fields{
"username": username,
}).Errorf("failed to check sms code rate limit: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
if optCountPerDay >= 5 {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "当前账号今日发送验证码次数已达上限,请 24 小时后再试"), http.StatusTooManyRequests)
}
// 业务检查
if _, err := ctl.userRepo.GetUserByPhone(ctx, username); err != nil {
if err == repo2.ErrNotFound {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "用户不存在"), http.StatusBadRequest)
}
log.WithFields(log.Fields{
"username": username,
}).Errorf("failed to get user: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
// 生成验证码
id, _ := uuid.GenerateUUID()
code := verifyCodeGenerator()
smsPayload := &queue.SMSVerifyCodePayload{
Receiver: username,
Code: code,
CreatedAt: time.Now(),
}
taskId, err := ctl.queue.Enqueue(smsPayload, queue.NewSMSVerifyCodeTask, asynq.Queue("mail"))
if err != nil {
log.WithFields(log.Fields{
"username": username,
"id": id,
"code": code,
}).Errorf("failed to enqueue mail task: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
if err := ctl.rds.SetNX(ctx, fmt.Sprintf("auth:verify-code:%s:%s", id, username), code, 15*time.Minute).Err(); err != nil {
log.WithFields(log.Fields{
"username": username,
"id": id,
"code": code,
"task_id": taskId,
}).Errorf("failed to set email code: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
// 设置流控
if err := ctl.limiter.OperationIncr(ctx, smsCodeRateLimitPerMinute, 50*time.Second); err != nil {
log.WithFields(log.Fields{
"username": username,
"id": id,
"code": code,
"task_id": taskId,
}).Errorf("failed to set email code rate limit: %s", err)
}
if err := ctl.limiter.OperationIncr(ctx, smsCodeRateLimitPerDay, 24*time.Hour); err != nil {
log.WithFields(log.Fields{
"username": username,
"id": id,
"code": code,
"task_id": taskId,
}).Errorf("failed to set email code rate limit: %s", err)
}
return webCtx.JSON(web.M{
"id": id,
})
}
// ResetPassword 重置密码
func (ctl *UserController) ResetPassword(ctx context.Context, webCtx web.Context, user *auth.User, userRepo *repo2.UserRepo, limiter *redis_rate.Limiter) web.Response {
password := strings.TrimSpace(webCtx.Input("password"))
if len(password) < 8 || len(password) > 20 {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "密码长度必须在 8-20 位之间"), http.StatusBadRequest)
}
if err := passwordvalidator.Validate(password, minEntropyBits); err != nil {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "密码强度不够,建议使用字母、数字、特殊符号组合"), http.StatusBadRequest)
}
verifyCodeId := strings.TrimSpace(webCtx.Input("verify_code_id"))
if verifyCodeId == "" {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "验证码 ID 不能为空"), http.StatusBadRequest)
}
verifyCode := strings.TrimSpace(webCtx.Input("verify_code"))
if verifyCode == "" {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "验证码不能为空"), http.StatusBadRequest)
}
// 流控:每个用户每 60 分钟只能重置密码 5 次
err := ctl.limiter.Allow(ctx, fmt.Sprintf("auth:reset-password:%s:limit", user.Phone), rate.MaxRequestsInPeriod(5, 60*time.Minute))
if err != nil {
if errors.Is(err, rate.ErrRateLimitExceeded) {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "操作频率过高,请稍后再试"), http.StatusTooManyRequests)
}
log.WithFields(log.Fields{
"username": user.Phone,
}).Errorf("failed to check verify code rate limit: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
// 检查验证码是否正确
realVerifyCode, err := ctl.rds.Get(ctx, fmt.Sprintf("auth:verify-code:%s:%s", verifyCodeId, user.Phone)).Result()
if err != nil {
if err != redis.Nil {
log.WithFields(log.Fields{
"username": user.Phone,
"id": verifyCodeId,
"code": verifyCode,
}).Errorf("failed to get verify code: %s", err)
}
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "验证码已过期,请重新获取"), http.StatusBadRequest)
}
if realVerifyCode != verifyCode {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "验证码错误"), http.StatusBadRequest)
}
_ = ctl.rds.Del(ctx, fmt.Sprintf("auth:verify-code:%s:%s", verifyCodeId, user.Phone)).Err()
if err := userRepo.UpdatePassword(ctx, user.ID, password); err != nil {
log.WithFields(log.Fields{
"username": user.Phone,
}).Errorf("failed to update password: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
return webCtx.JSON(web.M{})
}
// CurrentUser 获取当前用户信息
func (ctl *UserController) CurrentUser(ctx context.Context, webCtx web.Context, user *auth.User, quotaRepo *repo2.QuotaRepo) web.Response {
quota, err := ctl.userSrv.UserQuota(ctx, user.ID)
if err != nil {
log.Errorf("get user quota failed: %s", err)
}
u, err := ctl.userSrv.GetUserByID(ctx, user.ID, true)
if err != nil {
if errors.Is(err, repo2.ErrNotFound) {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "用户不存在"), http.StatusNotFound)
}
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "内部错误,请稍后再试"), http.StatusInternalServerError)
}
if u.Status == repo2.UserStatusDeleted {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, "用户不存在"), http.StatusNotFound)
}
user = auth.CreateAuthUserFromModel(u)
if user.Phone != "" {
user.Phone = misc.MaskPhoneNumber(user.Phone)
}
return webCtx.JSON(web.M{
"user": user,
"quota": quota,
"control": web.M{
"is_set_pwd": user.IsSetPassword,
"enable_invite": user.InviteCode != "",
"invite_message": fmt.Sprintf("【AIdea】玩转 GPT,实在太有趣啦!\n\n用我的专属邀请码 %s 注册,不仅免费用,还有额外奖励!\n\n快去下载 aidea.aicode.cc ,我在未来世界等你!", user.InviteCode),
"user_card_bg": "https://ssl.aicode.cc/ai-server/assets/quota-card-bg.webp-thumb1000",
"invite_card_bg": "https://ssl.aicode.cc/ai-server/assets/invite-card-bg.webp-thumb1000",
"invite_card_color": "FF000000",
"invite_card_slogan": fmt.Sprintf("你与好友均可获得 %d 个智慧果\n好友充值享佣金\n成功邀请多人奖励可累积", coins.InvitedGiftCoins),
"with_lab": user.InternalUser(),
},
})
}
// UserQuota 获取当前用户配额详情
func (ctl *UserController) UserQuota(ctx context.Context, webCtx web.Context, user *auth.User, quotaRepo *repo2.QuotaRepo) web.Response {
quotas, err := quotaRepo.GetUserQuotaDetails(ctx, user.ID)
if err != nil {
log.Errorf("get user quota failed: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, common.ErrInternalError), http.StatusInternalServerError)
}
var rest int64
for _, quota := range quotas {
if quota.Expired || quota.Rest <= 0 {
continue
}
rest += quota.Rest
}
return webCtx.JSON(web.M{
"details": quotas,
"total": rest,
})
}
type QuotaUsageStatistics struct {
Date string `json:"date"`
Used int64 `json:"used"`
}
// UserQuotaUsageStatistics 获取当前用户配额使用情况统计
func (ctl *UserController) UserQuotaUsageStatistics(ctx context.Context, webCtx web.Context, user *auth.User, quotaRepo *repo2.QuotaRepo) web.Response {
usages, err := quotaRepo.GetQuotaStatisticsRecently(ctx, user.ID, 30)
if err != nil {
log.WithFields(log.Fields{"user_id": user.ID}).Debugf("get quota statistics failed: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, common.ErrInternalError), http.StatusInternalServerError)
}
usagesMap := array.ToMap(usages, func(item model.QuotaStatistics, _ int) string {
return item.CalDate.Format("2006-01-02")
})
// 生成当前日期以及前 30 天的日期列表
results := make([]QuotaUsageStatistics, 0)
results = append(results, QuotaUsageStatistics{
Date: time.Now().Format("2006-01-02"),
Used: -1,
})
for i := 0; i < 30; i++ {
// 最多统计到用户注册日期
if time.Now().AddDate(0, 0, -i).Before(user.CreatedAt) {
break
}
curDate := time.Now().AddDate(0, 0, -i-1).Format("2006-01-02")
if usage, ok := usagesMap[curDate]; ok {
results = append(results, QuotaUsageStatistics{
Date: curDate,
Used: usage.Used,
})
} else {
results = append(results, QuotaUsageStatistics{
Date: curDate,
Used: 0,
})
}
}
return webCtx.JSON(web.M{
"usages": results,
})
}
type QuotaUsageDetail struct {
Used int64 `json:"used"`
Type string `json:"type"`
CreatedAt string `json:"created_at"`
}
// UserQuotaUsageDetails 获取当前用户配额使用情况详情
func (ctl *UserController) UserQuotaUsageDetails(ctx context.Context, webCtx web.Context, user *auth.User, quotaRepo *repo2.QuotaRepo) web.Response {
startAt, err := time.Parse("2006-01-02", webCtx.PathVar("date"))
if err != nil {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, common.ErrInvalidRequest), http.StatusBadRequest)
}
endAt := startAt.AddDate(0, 0, 1)
usages, err := quotaRepo.GetQuotaDetails(ctx, user.ID, startAt, endAt)
if err != nil {
log.WithFields(log.Fields{"user_id": user.ID}).Debugf("get quota statistics failed: %s", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, common.ErrInternalError), http.StatusInternalServerError)
}
return webCtx.JSON(web.M{
"data": array.Map(usages, func(item repo2.QuotaUsage, _ int) QuotaUsageDetail {
var typ string
switch item.QuotaMeta.Tag {
case "chat":
typ = "聊天"
case "text2voice":
typ = "语音合成"
case "upload":
typ = "文件上传"
case "openai-voice":
typ = "语音转文本"
default:
typ = "创作岛"
}
return QuotaUsageDetail{
Used: item.Used,
Type: typ,
CreatedAt: item.CreatedAt.In(time.Local).Format("15:04"),
}
}),
})
}
// UserFreeChatCounts 用户免费聊天次数统计
func (ctl *UserController) UserFreeChatCounts(ctx context.Context, webCtx web.Context, user *auth.User, client *auth.ClientInfo) web.Response {
freeModels := ctl.userSrv.FreeChatStatistics(ctx, user.ID)
if client.IsCNLocalMode(ctl.conf) && !user.ExtraPermissionUser() {
freeModels = array.Filter(freeModels, func(m service2.FreeChatState, _ int) bool {
return !m.NonCN
})
}
return webCtx.JSON(web.M{
"data": freeModels,
})
}
// UserFreeChatCountsForModel 用户模型免费聊天次数统计
func (ctl *UserController) UserFreeChatCountsForModel(ctx context.Context, webCtx web.Context, user *auth.User) web.Response {
modelID := webCtx.PathVar("model")
segs := strings.Split(modelID, ":")
modelID = segs[len(segs)-1]
res, err := ctl.userSrv.FreeChatStatisticsForModel(ctx, user.ID, modelID)
if err != nil {
if errors.Is(err, service2.ErrorModelNotFree) {
return webCtx.JSON(service2.FreeChatState{
ModelWithName: coins.ModelWithName{
Model: modelID,
},
LeftCount: 0,
MaxCount: 0,
})
}
log.WithFields(log.Fields{"model": modelID}).Errorf("get free chat statistics for model failed: %v", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, common.ErrInternalError), http.StatusInternalServerError)
}
return webCtx.JSON(res)
}
// CustomHomeModels 自定义首页模型
func (ctl *UserController) CustomHomeModels(ctx context.Context, webCtx web.Context, user *auth.User) web.Response {
models := array.Filter(strings.Split(webCtx.Input("models"), ","), func(item string, index int) bool {
return item != ""
})
if len(models) == 0 {
return webCtx.JSON(web.M{})
}
if len(models) != 2 {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, common.ErrInvalidRequest), http.StatusBadRequest)
}
supportModels := array.ToMap(chat.Models(ctl.conf, true), func(item chat.Model, _ int) string { return item.RealID() })
for _, model := range models {
if _, ok := supportModels[model]; !ok {
return webCtx.JSONError(common.Text(webCtx, ctl.translater, common.ErrInvalidRequest), http.StatusBadRequest)
}
}
cus, err := ctl.userRepo.CustomConfig(ctx, user.ID)
if err != nil {
log.WithFields(log.Fields{"user_id": user.ID}).Errorf("get user custom config failed: %v", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, common.ErrInternalError), http.StatusInternalServerError)
}
cus.HomeModels = models
if err := ctl.userRepo.UpdateCustomConfig(ctx, user.ID, *cus); err != nil {
log.WithFields(log.Fields{"user_id": user.ID}).Errorf("update user custom config failed: %v", err)
return webCtx.JSONError(common.Text(webCtx, ctl.translater, common.ErrInternalError), http.StatusInternalServerError)
}
return webCtx.JSON(web.M{})
}
|
package Testes;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
import Sistema.*;
public class EscritorXML {
static XMLOutputter xout = new XMLOutputter();
public static void criarXML() {
Element listas = new Element("listas");
Document myDoc = new Document(listas);
Element clinica = new Element("clinica");
Element nomeClinica = new Element("nome");
nomeClinica.setText("L'hopital");
clinica.addContent(nomeClinica);
listas.addContent(clinica);
listas.addContent(criaPessoas());
listas.addContent(criaExames());
listas.addContent(criaConsultas());
try {
FileWriter arquivo = new FileWriter(new File(
"src/Testes/teste2.xml"));
xout.output(myDoc, arquivo);
} catch (IOException e) {
e.printStackTrace();
}
}
private static Element criaConsultas() {
Element consultas = new Element("consultas");
Sistema.getListas();
for (Consulta c : Listas.getConsultas()) {
Element consulta = new Element("consulta");
Element data = new Element("data").setText(String.valueOf(c
.getData()));
Element idMedico = new Element("idMedico").setText(String.valueOf(c
.getMedico().getId()));
Element idCliente = new Element("idCliente").setText(String
.valueOf(c.getCliente().getId()));
Element tipo = new Element("tipo").setText(String.valueOf(c
.getTipo()));
consulta.addContent(data);
consulta.addContent(idMedico);
consulta.addContent(idCliente);
consulta.addContent(tipo);
consultas.addContent(consulta);
}
return consultas;
}
private static Element criaExames() {
Element exames = new Element("exames");
Sistema.getListas();
for (Exame e : Listas.getExames()) {
Element exame = new Element("exame");
Element nome = new Element("nome").setText(e.getNome());
Element tipo = new Element("tipo").setText(String.valueOf(e
.getTipo()));
Element data = new Element("data").setText(String.valueOf(e
.getData()));
Element idCliente = new Element("idCliente").setText(String
.valueOf(e.getCliente().getId()));
exame.addContent(nome);
exame.addContent(tipo);
exame.addContent(data);
exame.addContent(idCliente);
exames.addContent(exame);
}
return exames;
}
private static Element criaPessoas() {
Element pessoas = new Element("pessoas");
Element clientes = new Element("clientes");
Element medicos = new Element("medicos");
Element funcionarios = new Element("funcionarios");
Element tecnicos = new Element("tecnicos");
for (Pessoa p : Sistema.getListas().getPessoas()) {
if (p instanceof Cliente) {
Element cliente = new Element("cliente");
Element nome = new Element("nome").setText(p.getNome());
Element identidade = new Element("identidade").setText(p
.getIdentidade());
Element cpf = new Element("cpf").setText(p.getCpf());
Element endereco = new Element("endereco").setText(p
.getEndereco());
Element telefone = new Element("telefone").setText(p
.getTelefone());
Element nascimento = new Element("nascimento").setText(p
.getNascimento());
Element senha = new Element("senha").setText(((Cliente) p)
.getSenha());
cliente.addContent(nome);
cliente.addContent(identidade);
cliente.addContent(cpf);
cliente.addContent(endereco);
cliente.addContent(telefone);
cliente.addContent(nascimento);
cliente.addContent(senha);
clientes.addContent(cliente);
}
if (p instanceof Medico) {
Element medico = new Element("medico");
Element nome = new Element("nome").setText(p.getNome());
Element identidade = new Element("identidade").setText(p
.getIdentidade());
Element cpf = new Element("cpf").setText(p.getCpf());
Element endereco = new Element("endereco").setText(p
.getEndereco());
Element telefone = new Element("telefone").setText(p
.getTelefone());
Element nascimento = new Element("nascimento").setText(p
.getNascimento());
Element especialidade = new Element("especialidade")
.setText(((Medico) p).getEspecialidade());
Element datas = new Element("datas");
/*
for (String horario : ((Medico) p).getAgendaMedico()
.getHorariosOcupados()) {
Element data = new Element("data").setText(horario);
datas.addContent(data);
}*/
medico.addContent(nome);
medico.addContent(identidade);
medico.addContent(cpf);
medico.addContent(endereco);
medico.addContent(telefone);
medico.addContent(nascimento);
medico.addContent(especialidade);
medico.addContent(datas);
medicos.addContent(medico);
}
if (p instanceof Funcionario) {
Element funcionario = new Element("funcionario");
Element nome = new Element("nome").setText(p.getNome());
Element identidade = new Element("identidade").setText(p
.getIdentidade());
Element cpf = new Element("cpf").setText(p.getCpf());
Element endereco = new Element("endereco").setText(p
.getEndereco());
Element telefone = new Element("telefone").setText(p
.getTelefone());
Element nascimento = new Element("nascimento").setText(p
.getNascimento());
Element cargo = new Element("cargo").setText(((Funcionario) p)
.getCargo());
funcionario.addContent(nome);
funcionario.addContent(identidade);
funcionario.addContent(cpf);
funcionario.addContent(endereco);
funcionario.addContent(telefone);
funcionario.addContent(nascimento);
funcionario.addContent(cargo);
funcionarios.addContent(funcionario);
}
if (p instanceof Tecnico) {
Element tecnico = new Element("tecnico");
Element nome = new Element("nome").setText(p.getNome());
Element identidade = new Element("identidade").setText(p
.getIdentidade());
Element cpf = new Element("cpf").setText(p.getCpf());
Element endereco = new Element("endereco").setText(p
.getEndereco());
Element telefone = new Element("telefone").setText(p
.getTelefone());
Element nascimento = new Element("nascimento").setText(p
.getNascimento());
Element especialidade = new Element("especialidade")
.setText(((Tecnico) p).getEspecialidade());
tecnico.addContent(nome);
tecnico.addContent(identidade);
tecnico.addContent(cpf);
tecnico.addContent(endereco);
tecnico.addContent(telefone);
tecnico.addContent(nascimento);
tecnico.addContent(especialidade);
tecnicos.addContent(tecnico);
}
}
pessoas.addContent(clientes);
pessoas.addContent(medicos);
pessoas.addContent(funcionarios);
pessoas.addContent(tecnicos);
return pessoas;
}
}
|
//
// InfoViewController.swift
// Navigation
//
// Created by ROMAN VRONSKY on 19.07.2022.
//
import UIKit
class InfoViewController: UIViewController {
private var namesResidents = [String]()
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .plain)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = 44
tableView.estimatedRowHeight = 50
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)
tableView.register(InfoTableVIewCell.self, forCellReuseIdentifier: "InfoCell")
return tableView
}()
private lazy var infoTextLabel: UILabel = {
let infoLabel = UILabel()
infoLabel.lineBreakMode = .byWordWrapping
infoLabel.numberOfLines = 0
infoLabel.textAlignment = .center
infoLabel.translatesAutoresizingMaskIntoConstraints = false
return infoLabel
}()
private lazy var infoPlanetLabel: UILabel = {
let infoLabel = UILabel()
infoLabel.textAlignment = .center
infoLabel.translatesAutoresizingMaskIntoConstraints = false
return infoLabel
}()
private lazy var myButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.layer.cornerRadius = 10
button.layer.borderWidth = 2.0
button.layer.borderColor = UIColor.white.cgColor
button.backgroundColor = .link
button.setTitle("text".localized, for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(showText), for: .touchUpInside)
return button
}()
private lazy var planetButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.layer.cornerRadius = 10
button.layer.borderWidth = 2.0
button.layer.borderColor = UIColor.white.cgColor
button.backgroundColor = .link
button.setTitle("orbitalPeriod".localized, for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(self.showPlanetOrbital), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
InfoNetworkManager.loadResidents {[weak self] name in
let group = DispatchGroup()
group.enter()
DispatchQueue.global().async {
self?.namesResidents.append(name ?? "")
group.leave()
}
group.notify(queue: .main) {
self?.tableView.reloadData()
print(self?.namesResidents ?? " ")
}
}
}
private func setupView() {
self.view.backgroundColor = .white
self.view.addSubview(self.myButton)
self.view.addSubview(self.infoTextLabel)
self.view.addSubview(self.planetButton)
self.view.addSubview(self.infoPlanetLabel)
self.view.addSubview(self.tableView)
NSLayoutConstraint.activate([
self.planetButton.topAnchor.constraint(equalTo: self.myButton.bottomAnchor, constant: 16),
self.planetButton.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -16),
self.planetButton.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 16),
self.planetButton.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -16),
self.planetButton.heightAnchor.constraint(equalToConstant: 50),
self.myButton.topAnchor.constraint(equalTo: self.infoPlanetLabel.bottomAnchor, constant: 16),
self.myButton.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 16),
self.myButton.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -16),
self.myButton.heightAnchor.constraint(equalToConstant: 50),
self.infoPlanetLabel.topAnchor.constraint(equalTo: self.infoTextLabel.bottomAnchor),
self.infoPlanetLabel.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 16),
self.infoPlanetLabel.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -16),
self.infoPlanetLabel.heightAnchor.constraint(equalToConstant: 50),
self.infoTextLabel.bottomAnchor.constraint(equalTo: self.infoPlanetLabel.topAnchor, constant: -16),
self.infoTextLabel.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 16),
self.infoTextLabel.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -16),
self.infoTextLabel.heightAnchor.constraint(equalToConstant: 100),
self.tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
self.tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 16),
self.tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -16),
self.tableView.bottomAnchor.constraint(equalTo: self.infoTextLabel.topAnchor),
])
}
@objc func showText() {
self.tableView.reloadData()
InfoNetworkManager.loadText { [weak self] textArray in
DispatchQueue.main.async {
self?.infoTextLabel.text = textArray?.randomElement()
}
}
}
@objc func showPlanetOrbital() {
InfoNetworkManager.loadOrbitalPeriod { [weak self] orbital_period in
DispatchQueue.main.async {
self?.infoPlanetLabel.text = "\("orbitalPeriod".localized) - \(orbital_period ?? "0")"
}
}
}
}
extension InfoViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
namesResidents.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell", for: indexPath) as! InfoTableVIewCell
cell.setupInfo(text: namesResidents[indexPath.row])
return cell
}
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeResolver } from './home/home.resolver';
import { HomeComponent } from './home/home.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { SpinnerComponent } from './spinner/spinner.component';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home/:id', component: HomeComponent, resolve: { orgs: HomeResolver } },
{ path: 'home', component: HomeComponent, resolve: { orgs: HomeResolver } },
{ path: 'stockpile', component: HomeComponent, resolve: { orgs: HomeResolver } },
{ path: 'redirect', component: SpinnerComponent},
{ path: '404', component: PageNotFoundComponent},
{
path: '**', pathMatch: 'full',
component: PageNotFoundComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
sap.ui.define([
"sap/ui/base/Object",
"sap/m/MessageBox"
], function (UI5Object, MessageBox) {
"use strict";
return UI5Object.extend("ean.edu.solicitud.controller.ErrorHandler", {
// /**
// * Handles application errors by automatically attaching to the model events and displaying errors when needed.
// * @class
// * @param {sap.ui.core.UIComponent} oComponent reference to the app's component
// * @public
// * @alias ean.edu.solicitud.controller.ErrorHandler
// */
// constructor : function (oComponent) {
// this._oResourceBundle = oComponent.getModel("i18n").getResourceBundle();
// this._oComponent = oComponent;
// this._oModel = oComponent.getModel();
// this._bMessageOpen = false;
// this._sErrorText = this._oResourceBundle.getText("errorText");
// this._oModel.attachMetadataFailed(function (oEvent) {
// var oParams = oEvent.getParameters();
// this._showMetadataError(oParams.response);
// }, this);
// this._oModel.attachRequestFailed(function (oEvent) {
// var oParams = oEvent.getParameters();
// // An entity that was not found in the service is also throwing a 404 error in oData.
// // We already cover this case with a notFound target so we skip it here.
// // A request that cannot be sent to the server is a technical error that we have to handle though
// if (oParams.response.statusCode !== "404" || (oParams.response.statusCode === 404 && oParams.response.responseText.indexOf("Cannot POST") === 0)) {
// this._showServiceError(oParams.response);
// }
// }, this);
// },
// /**
// * Shows a {@link sap.m.MessageBox} when the metadata call has failed.
// * The user can try to refresh the metadata.
// * @param {string} sDetails a technical error to be displayed on request
// * @private
// */
// _showMetadataError : function (sDetails) {
// MessageBox.error(
// this._sErrorText,
// {
// id : "metadataErrorMessageBox",
// details: sDetails,
// styleClass: this._oComponent.getContentDensityClass(),
// actions: [MessageBox.Action.RETRY, MessageBox.Action.CLOSE],
// onClose: function (sAction) {
// if (sAction === MessageBox.Action.RETRY) {
// this._oModel.refreshMetadata();
// }
// }.bind(this)
// }
// );
// },
// /**
// * Shows a {@link sap.m.MessageBox} when a service call has failed.
// * Only the first error message will be display.
// * @param {string} sDetails a technical error to be displayed on request
// * @private
// */
// _showServiceError : function (sDetails) {
// if (this._bMessageOpen) {
// return;
// }
// this._bMessageOpen = true;
// MessageBox.error(
// this._sErrorText,
// {
// id : "serviceErrorMessageBox",
// details: sDetails,
// styleClass: this._oComponent.getContentDensityClass(),
// actions: [MessageBox.Action.CLOSE],
// onClose: function () {
// this._bMessageOpen = false;
// }.bind(this)
// }
// );
// }
});
}
);
|
import axios from 'axios';
import Restaurant from '../../interfaces/restaurantInterface';
import {
loadRestaurants,
loadFavorites,
addToFavorites,
updateRestaurant,
updateRestaurantFavs,
deleteFromFavorites
} from './actionCreators';
import actionTypes from './actionTypes';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
describe('Given a actionCreator file', () => {
const response = {
data: [
{ id: 13, name: "Testing"}
]};
const restaurant: Restaurant = {
id: 1,
name: "Restaurant for test",
image_url: "https://image.freepik.com/free-photo/delicious-vietnamese-food-including-pho-ga-noodles-spring-rolls-white-table_181624-34062.jpg",
reviews: [3,2,3,2,2,4,5,5,5,5,5],
food_type: "Cocktails & Surprises",
address: [
"C/ Gran Vía, 12",
"28013, Madrid"
],
visited: true,
open_hours: [{open_time:"",
close_time:""}]
};
const dispatch = jest.fn();
describe('When loadRestaurants is called', () => {
test('Then should dispatch type and payload', async () => {
mockedAxios.get.mockResolvedValue(Promise.resolve(response));
await loadRestaurants()(dispatch);
expect(dispatch).toHaveBeenCalledWith({
type: actionTypes.LOAD_ALL_RESTAURANTS,
restaurants: response.data,
});
});
});
describe('When loadFavorites is called', () => {
test('Then should dispatch type and payload', async () => {
mockedAxios.get.mockResolvedValue(Promise.resolve(response));
await loadFavorites()(dispatch);
expect(dispatch).toHaveBeenCalledWith({
type: actionTypes.LOAD_ALL_FAVORITES,
favorites: response.data,
});
});
});
describe('When addToFavorites is called', () => {
test('Then should dispatch type and payload', async () => {
mockedAxios.post.mockResolvedValue(Promise.resolve(response));
await addToFavorites(restaurant)(dispatch);
expect(dispatch).toHaveBeenCalledWith({
type: actionTypes.ADD_TO_FAVORITES,
newFavorite: response.data,
});
});
});
describe('When deleteFromFavorites is called', () => {
test('Then should dispatch type and payload', async () => {
mockedAxios.post.mockResolvedValue(Promise.resolve(response));
await deleteFromFavorites(restaurant.id)(dispatch);
expect(dispatch).toHaveBeenCalledWith({
type: actionTypes.DELETE_FROM_FAVORITES,
id: restaurant.id,
});
});
});
describe('When updateRestaurant is called', () => {
test('Then should dispatch type and payload', async () => {
mockedAxios.put.mockResolvedValue(Promise.resolve(response));
await updateRestaurant(restaurant)(dispatch);
expect(dispatch).toHaveBeenCalledWith({
type: actionTypes.UPDATE_RESTAURANT,
updatedRestaurant: response.data,
});
});
});
describe('When updateRestaurantFavs is called', () => {
test('Then should dispatch type and payload', async () => {
mockedAxios.put.mockResolvedValue(Promise.resolve(response));
await updateRestaurantFavs(restaurant)(dispatch);
expect(dispatch).toHaveBeenCalledWith({
type: actionTypes.UPDATE_RESTAURANT_FAV,
updatedRestaurant: response.data,
});
});
});
});
|
pkgs <- c("terra", "tidyverse", "wavethresh", "sf")
sapply(pkgs, require, character.only=TRUE, quietly=TRUE)
# --- wavelet decomposition -----------------
w.filter.number = 1; w.family = "DaubExPhase"
# -------------------------------------------
f <- list.files("~/../../Volumes/az_drive/temp/CorralsTrail/", pattern = "_chm_", full.names = TRUE)#list.files("~/Downloads/tmp", pattern = "_chm_", full.names = TRUE)
roi <- rast("~/Desktop/UAV_demography/FieldData/2022_campaign_field_data/cells_data/CorrlasTrail_5m_raster.tif")
chm <- rast(f[2]) |> crop(ext(roi) + 10)
chm <- classify(chm, rcl = matrix(c(-Inf, 0, 0,
3, Inf, 0), nc = 3, byrow = TRUE))
# === Decompose the matrix into tiles stored in a list
cmat <- as.matrix(chm, wide = TRUE)
n <- 256
xtiles <- floor(ncol(chm)/n)
ytiles <- floor(nrow(chm)/n)
xN <- n * xtiles/2
yN <- n * ytiles/2
xmp <- floor(ncol(chm)/2)
ymp <- floor(nrow(chm)/2)
idl <- xmp - xN; idr <- xmp + (xN-1) # left and right boundaries
idb <- ymp + (yN); idt <- ymp - (yN-1) # top and bottom boundaries
e <- cmat[idt:idb, idl:idr]
e_rast <- chm[idt:idb, idl:idr, drop = FALSE]
# raster index starts in NW corner
# list - level 1 - rows
# |___ - level 2 - columns
# ie columns are stored within rows
lout <- list()
xidx <- 1;
for(i in 1:xtiles) {
ltmp <- list()
yidx <- 1;
for(j in 1:ytiles) {
tmp <- e[yidx:c(j*n), xidx:c(i*n)]
yidx <- yidx + n
ltmp[[j]] <- tmp
# out <- paste0("~/Downloads/tmp_rast/tile_", i, ".csv")
# write.table(tmp, out, row.names = FALSE, col.names = FALSE, sep=',')
}
lout[[i]] <- ltmp
xidx <- xidx + n
}
# === Bring the tiles back together into a larger image
out <- NULL;
for(i in 1:xtiles){
tmp <- NULL;
for(j in 1:ytiles){
tmp = rbind(tmp, lout[[i]][[j]])
}
out <- cbind(out, tmp)
}
plot(rast(e))
plot(rast(out))
# ==== end reassembling
# === apply wavelet transformation and store the output
total <- 1
# list storing wavelet coefs
ldiff <- list()
# list storing full transform output
lro <- list()
for(i in 1:length(lout)){ # rows
lcol <- list()
ldiffc <- list()
for(j in 1:length(lout[[i]])){ # columns
dat <- lout[[i]][[j]]
wn <- imwd(dat, filter.number = w.filter.number,
family = w.family,
type = "wavelet", bc = "symmetric")
lcol[[j]] <- wn
D <- list()
for(k in (wn$nlevels-1):0) { # decomposition levels
HH <- wn[[paste0("w", k,"L1")]] # horizontal
hh <- matrix(HH, nc = sqrt(length(HH)))
# hh <- matrix(approx(HH, n = n^2)$y, nc = n) # nc = sqrt(length(HH)))
VV <- wn[[paste0("w", k,"L2")]] # vertical
vv <- matrix(VV, nc = sqrt(length(VV)))
# vv <- matrix(approx(VV, n = n^2)$y, nc = n) #nc = sqrt(length(VV)))
DD <- wn[[paste0("w", k,"L3")]] # diagonal
dd <- matrix(DD, nc = sqrt(length(DD)))
# dd <- matrix(approx(DD, n = n^2)$y, nc = n) #nc = sqrt(length(DD)))
SS <- wn[[paste0("w", k,"L4")]] # averages
ss <- matrix(SS, nc = sqrt(length(SS)))
# ss <- matrix(approx(SS, n = n^2)$y, nc = n) #nc = sqrt(length(SS)))
if(total){
D[[k+1]] <- hh^2 + vv^2 + dd^2 # + abs(ss)
} else {
D[[k+1]] <- hh + vv + dd #+ ss
}
}
ldiffc[[j]] <- D
}
lro[[i]] <- lcol # imwd.objects
ldiff[[i]] <- ldiffc # difference coefs interpolate for nlevel-1:1
}
# === reassemble wavelet coefs back into #nlevels CHM images
rlist <- list()
par(mfrow = c(2,3))
# plot(rast(e), legend = FALSE, col=topo.colors(64))
for(k in 1:(log2(n)-1 - 1)){
level <- k
out <- NULL;
for(i in 1:xtiles){
tmp <- NULL;
for(j in 1:ytiles){
tmp = rbind(tmp, ldiff[[i]][[j]][[level]]) # lout[[i]][[j]])#
}
out <- cbind(out, tmp)
}
plot(rast(out), col=topo.colors(64), legend = FALSE)
rlist[[k]] <- rast(out)
}
# === end assembling difference coefs tiles
# === relationship between cover and structural heterogeneity
em <- rast(e) |> classify(rcl = matrix(c(-Inf, .25, 0,
.25, Inf, 1), nc = 3, byrow = TRUE)) |>
as.matrix(wide = TRUE)
r <- rast(ncols=4, nrows=4, xmin = n, xmax = n*5, ymin = n, ymax = n*5)
values(r) <- 1:ncell(r)
plot(rast(em))
plot(r, add = TRUE)
rpts <- as.points(r) |> st_as_sf() |>
mutate(x = st_coordinates(geometry)[,1],
y = st_coordinates(geometry)[,2]) |>
rename(id = lyr.1) |>
st_buffer(50) |>
dplyr::select(-geometry)
plot(rast(em))
plot(rpts$geometry, add = TRUE)
plot(rlist[[4]])
points(rpts$x/vec[4], rpts$y/vec[4], pch = 19)
# --- calculate response - cover in 1m^2, and predictors at 7 scales
em |> rast() |>
terra::extract(y = rpts, touches = TRUE) |>
group_by(ID) |>
summarize(mean = mean(lyr.1)) |>
ungroup() -> dfy
rdf <- rpts |>
as.data.frame() |>
dplyr::select(-geometry)
vec <- rev(2^(2:8))
xout <- list()
for(k in 1:(log2(n)-1)) {
rdf |>
mutate(x = x/vec[k], y = y/vec[k]) |>
st_as_sf(coords = c("x", "y")) |>
st_buffer(50/vec[k])-> tmp_in # within 1m^2 only
rdf |>
mutate(x = x/vec[k], y = y/vec[k]) |>
st_as_sf(coords = c("x", "y")) |>
st_buffer(n/vec[k])-> tmp_out # within 1m^2 + neighborhood
rlist[[k]] |>
terra::extract(y = tmp_out, touches = TRUE) |>
group_by(ID) |>
summarize(sum = sum(lyr.1)) |>
ungroup() |> dplyr::select(-ID) |>
mutate(var = sum - rlist[[k]] |>
terra::extract(y = tmp_in, touches = TRUE) |>
group_by(ID) |>
summarize(sum = sum(lyr.1)) |>
ungroup() |> dplyr::select(-ID) |> pull(sum)) -> dfx_tmp
xout[[k]] <- dfx_tmp[,"var"]
}
dfx <- do.call(cbind, xout)
names(dfx) <- paste0("scale_", 2:8)
# --- combine outputs
df <- bind_cols(dfy, dfx)
cs <- cor(dfy$mean, dfx)
data.frame(corr = t(cs)) |>
mutate(scale = 2:8) |>
pivot_longer(corr) |>
ggplot() +
geom_line(aes(x = scale, y = value), lwd = 2) +
labs(x = "Scale", y = "Correlation") +
theme_bw()
# === Field data
# --- project transformed rasters
for(i in 1:length(rlist)){
tmp <- rlist[[i]]
ext(tmp) <- ext(e_rast)
rlist[[i]] <- tmp
}
# ---
cells <- st_read("~/Desktop/UAV_demography/FieldData/SurveyPts_shapes_2022/CorralsTrail/CorralsTrail_pts_wgs84.shp") |>
st_transform(32611)
fd <- read.csv("~/Desktop/UAV_demography/FieldData/2022_campaign_field_data/plant_data/CorralsTrail_2022_plants.csv") |>
filter(!is.na(ID))
ppts <- read.csv("~/Desktop/UAV_demography/FieldData/2022_campaign_field_data/gps/CorralsTrail/CorralsTrail_20220516_20_plants.csv")
fd |>
filter(ID != 0) |>
left_join(ppts, by = c("ID" = "label")) |>
st_as_sf(coords = c("long", "lat"), crs = 4326) |>
st_transform(32611) -> plant_df
# ---
burnt <- st_read("~/Desktop/UAV_demography/FieldData/2022_campaign_field_data/burn_lines/CorralsTrail_burn_line_wgs84.geojson") |>
st_transform(32611) |> filter(burnt == 1)
plant_df |>
as.data.frame() |>
dplyr::select(CID, Class, Species, Ht_gt_25) |>
group_by(CID) |>
summarize(pHt25 = sum(Ht_gt_25)/n(), N = n(),
Shrubs = sum(Class == "Shrub"), Grasses = sum(Class == "Grass"),
ARTR = sum(Species == "ARTR"), PUTR = sum(Species == "PUTR")) -> df
# = scale-dependent heterogeneity
sout <- matrix(NA, nc = length(rlist), nr = nrow(cells))
names()
for(i in 1:ncol(sout)){
tmp <- rlist[[i]] |>
terra::extract(y = st_buffer(cells, 5), touches = TRUE, ID = FALSE) |>
group_by(ID) |>
summarize(sum = sum(lyr.1)) |>
ungroup() |> pull(sum)
sout[,i] <- tmp
}
cells |>
mutate(burnt = lengths(st_intersects(geometry, burnt, sparse = TRUE))) |>
bind_cols(sout) |>
as.data.frame() |>
dplyr::select(-geometry) |>
right_join(df, by = c("cid" = "CID")) -> out
plot(rast(cor(out |> dplyr::select(-cid))))
out |>
mutate(burnt = as.factor(burnt)) |>
pivot_longer(cols = starts_with("...")) |>
mutate(scale = gsub("...", "Scale_", name)) |>
dplyr::select(-name) |> rename(heterogen = value) |>
mutate(juv = N*pHt25) |>
ggplot(aes(y = juv, x = log(heterogen), colour = burnt)) +
geom_point(size = 3) +
facet_wrap(~scale) +
theme_bw()
f1 <- glm(ARTR ~ 1 + (log(...4)|burnt), family = poisson, data = out)
summary(f1)
as.data.frame(VarCorr(f1))
|
<!--/*-->
<html>
<head>
<link rel="stylesheet" type="text/css" href="narrative.css"/>
</head>
<body>
<!--*/-->
<div>
<div class="hapiHeaderText">
<th:block th:text="Vaccination"/>
</div>
<table class="hapiPropertyTable">
<th:block th:if="${resource.hasPatient}">
<thead><tr><td colspan="2">Patient</td></tr></thead>
<tr th:if="${resource.patient.hasIdentifier}">
<td>Identifier</td>
<td>
<th:block th:if="${resource.patient.hasIdentifier}" th:text="${resource.patient.identifier.value} + ' (' + ${resource.patient.identifier.system} + ')'"/>
</td>
</tr>
<tr th:if="${resource.patient.hasReference}">
<td>Reference</td>
<td>
<th:block th:if="${resource.patient.hasReference}" th:text="${resource.patient.reference}"/>
</td>
</tr>
</th:block>
<thead><tr><td colspan="2">Information</td></tr></thead>
<tbody>
<tr th:if="${resource.hasIdentifier}" th:each="identifier : ${resource.identifier}">
<td>Identifier</td>
<td>
<th:block th:if="${identifier.hasValue}" th:text="${identifier.value}" />
<!--<th:block th:if="${identifier.hasSystem}" th:text="'(' + ${identifier.system} + ')'" />-->
</td>
</tr>
<tr th:if="${resource.hasVaccineCode}" >
<td>Vaccine code</td>
<td>
<th:block th:if="${resource.vaccineCode.hasCoding}">
<th:block th:if="${resource.vaccineCode.codingFirstRep.hasDisplay}" th:text="${resource.vaccineCode.codingFirstRep.display}"/>
<th:block th:if="${not resource.vaccineCode.codingFirstRep.hasDisplay} and ${resource.vaccineCode.hasText}" th:text="${resource.vaccineCode.text}"/>
<th:block th:if="${not resource.vaccineCode.codingFirstRep.hasDisplay} and ${not resource.vaccineCode.hasText} and ${resource.vaccineCode.codingFirstRep.hasCode}" th:text="${resource.vaccineCode.codingFirstRep.code}"/>
</th:block>
</td>
</tr>
<tr th:if="${resource.hasStatus}">
<td>Status</td>
<td>
<th:block th:text="${resource.status}" />
</td>
</tr>
<tr th:if="${resource.hasStatusReason}">
<td>Status reason</td>
<td>
<th:block th:if="${resource.statusReason.hasCoding}">
<th:block th:if="${resource.statusReason.codingFirstRep.hasDisplay}" th:text="${resource.statusReason.codingFirstRep.display}"/>
<th:block th:if="${not resource.statusReason.codingFirstRep.hasDisplay} and ${resource.statusReason.hasText}" th:text="${resource.statusReason.text}"/>
<th:block th:if="${not resource.statusReason.codingFirstRep.hasDisplay} and ${not resource.statusReason.hasText} and ${resource.statusReason.codingFirstRep.hasCode}" th:text="${resource.statusReason.codingFirstRep.code}"/>
</th:block>
</td>
</tr>
<tr th:if="${resource.hasEncounter}">
<td>Encounter</td>
<td>
<th:block th:if="${resource.encounter.hasReference}" th:text="${resource.encounter.reference}"/>
</td>
</tr>
<tr th:if="${resource.hasOccurrenceDateTimeType} or ${resource.hasOccurrenceStringType}">
<td>Occurence</td>
<td>
<th:block th:if="${resource.hasOccurrenceDateTimeType}" th:text="${#dates.format(resource.occurrenceDateTimeType.value,'dd MMMM yyyy HH:mm:ss')}"/>
<th:block th:if="${resource.hasOccurrenceStringType}">
<th:block th:if="${#strings.contains(resource.occurrenceStringType, '\n')}"><pre><th:block th:include="@{inlinetext} :: inlinetext (${resource.occurrenceStringType})"/></pre></th:block>
<th:block th:unless="${#strings.contains(resource.occurrenceStringType, '\n')}"><th:block th:include="@{inlinetext} :: inlinetext (${resource.occurrenceStringType})"/></th:block>
</th:block>
</td>
</tr>
<tr th:if="${resource.hasRecorded}">
<td>Recorded</td>
<td>
<th:block th:text="${#dates.format(resource.recorded,'dd MMMM yyyy HH:mm:ss')}" />
</td>
</tr>
<tr th:if="${resource.hasManufacturer}">
<td>Manufacturer</td>
<td>
<th:block th:if="${resource.manufacturer.hasReference}" th:text="${resource.manufacturer.reference}"/>
</td>
</tr>
<tr th:if="${resource.hasSite}">
<td>Site</td>
<td>
<th:block th:if="${resource.site.hasId}" th:text="${resource.site.id}" />
<th:block th:if="${resource.site.hasCoding}">
<th:block th:if="${resource.site.codingFirstRep.hasDisplay}" th:text="${resource.site.codingFirstRep.display}" />
<th:block th:if="${resource.site.codingFirstRep.hasCode}" th:text="${resource.site.codingFirstRep.code}" />
<th:block th:if="${resource.site.codingFirstRep.hasSystem}" th:text="${resource.site.codingFirstRep.system}" />
</th:block>
<th:block th:if="${resource.site.hasText}" th:text="${resource.site.text}" />
</td>
</tr>
<tr th:if="${resource.hasRoute}">
<!-- TODO check display conditional code/display -->
<td>Route</td>
<td>
<th:block th:if="${resource.route.hasCoding}">
<th:block th:if="${resource.route.codingFirstRep.hasDisplay}" th:text="${resource.route.codingFirstRep.display}" />
<th:block th:if="${resource.route.codingFirstRep.hasCode}" th:text="${resource.route.codingFirstRep.code}" />
<th:block th:if="${resource.route.codingFirstRep.hasSystem}" th:text="${resource.route.codingFirstRep.system}" />
</th:block>
</td>
</tr>
<tr th:if="${resource.hasDoseQuantity}">
<td>Dose quantity</td>
<td>
<th:block th:text="${resource.doseQuantity.value}" />
</td>
</tr>
<tr th:if="${resource.hasPerformer}" th:each="performer : ${resource.performer}">
<td>Performer</td>
<td>
<th:block th:if="${performer.actor.hasDisplay}" th:text="${performer.actor.display}"/>
<th:block th:if="(not ${performer.actor.hasDisplay}) and ${performer.actor.hasIdentifier}" >
<th:block th:if="(${performer.actor.identifier.hasValue})" th:text="${performer.actor.identifier.value}" />
<th:block th:if="(${performer.actor.identifier.hasSystem})" th:text="' (' + ${performer.actor.identifier.system} + ')'" />
</th:block>
<th:block th:if="${performer.actor.hasReference}" th:text="${performer.actor.reference}"/>
</td>
</tr>
<tr th:if="${resource.hasReasonReference}" th:each="reasonReference : ${resource.reasonReference}">
<td>Reason reference</td>
<td>
<th:block th:if="${reasonReference.hasReference}" th:text="${reasonReference.reference}"/>
</td>
</tr>
<tr th:if="${resource.hasReaction}" th:each="reaction : ${resource.reaction}">
<td>Reaction</td>
<td>
<th:block th:if="${reaction.hasDate}" th:text="${#dates.format(reaction.date,'dd MMMM yyyy HH:mm:ss')}"/>
<th:block th:if="${reaction.hasDetail}" th:text="${reaction.detail.reference}"/>
</td>
</tr>
<tr th:if="${resource.hasNote}" th:each="note : ${resource.note}">
<td>Note</td>
<td th:narrative="${note}"></td>
</tr>
<!-- extensions -->
<th:block th:if="${resource.hasExtension('https://www.ehealth.fgov.be/standards/fhir/core/StructureDefinition/be-ext-recorder')}">
<th:block th:each="ext : ${resource.getExtensionsByUrl('https://www.ehealth.fgov.be/standards/fhir/core/StructureDefinition/be-ext-recorder')}">
<tr>
<td>Recorder</td>
<td th:narrative="${ext.value}"/>
</tr>
</th:block>
</th:block>
<th:block th:if="${resource.hasExtension('https://www.ehealth.fgov.be/standards/fhir/vaccination/StructureDefinition/be-ext-vaccination-originalorder')}">
<th:block th:each="ext : ${resource.getExtensionsByUrl('https://www.ehealth.fgov.be/standards/fhir/vaccination/StructureDefinition/be-ext-vaccination-originalorder')}">
<tr>
<td>Original order</td>
<td th:narrative="${ext.value}"/>
</tr>
</th:block>
</th:block>
<th:block th:if="${resource.hasExtension('https://www.ehealth.fgov.be/standards/fhir/vaccination/StructureDefinition/be-ext-simple-note')}">
<th:block th:each="ext : ${resource.getExtensionsByUrl('https://www.ehealth.fgov.be/standards/fhir/vaccination/StructureDefinition/be-ext-simple-note')}">
<tr>
<td>Note</td>
<td th:narrative="${ext.value}"/>
</tr>
</th:block>
</th:block>
<th:block th:if="${resource.hasExtension('https://www.ehealth.fgov.be/standards/fhir/vaccination/StructureDefinition/be-ext-vaccination-confirmationStatus')}">
<th:block th:each="ext : ${resource.getExtensionsByUrl('https://www.ehealth.fgov.be/standards/fhir/vaccination/StructureDefinition/be-ext-vaccination-confirmationStatus')}">
<tr>
<td>Confirmation status</td>
<td th:narrative="${ext.value}"/>
</tr>
</th:block>
</th:block>
<th:block th:if="${resource.hasExtension('https://www.ehealth.fgov.be/standards/fhir/vaccination/StructureDefinition/be-ext-administeredProduct')}">
<th:block th:each="ext : ${resource.getExtensionsByUrl('https://www.ehealth.fgov.be/standards/fhir/vaccination/StructureDefinition/be-ext-administeredProduct')}">
<th:block th:if="${ext.hasExtension('lotNumber')}">
<th:block th:each="ext2 : ${ext.getExtensionsByUrl('lotNumber')}">
<tr>
<td>Administrated product lot number</td>
<td th:narrative="${ext2.value}"/>
</tr>
</th:block>
</th:block>
<th:block th:if="${ext.hasExtension('reference')}">
<th:block th:each="ext2 : ${ext.getExtensionsByUrl('reference')}">
<tr>
<td>Administrated product reference</td>
<td th:narrative="${ext2.value}"/>
</tr>
</th:block>
</th:block>
<th:block th:if="${ext.hasExtension('expirationDate')}">
<th:block th:each="ext2 : ${ext.getExtensionsByUrl('expirationDate')}">
<tr>
<td>Administrated product expiration date</td>
<td>
<th:block th:narrative="${ext2.value}"/>
</td>
</tr>
</th:block>
</th:block>
<th:block th:if="${ext.hasExtension('coded')}">
<th:block th:each="ext2 : ${ext.getExtensionsByUrl('coded')}">
<th:block th:include="@{inlinecode} :: inlinecoderows (code=${ext2.value}, title='Administrated product code')"/>
</th:block>
</th:block>
</th:block>
</th:block>
</tbody>
<th:block th:if="${resource.hasContained}" th:each="contained : ${resource.contained}">
<th:block th:if="${#strings.trim(contained.resourceType)} == 'Medication'" th:include="@{medication} :: medication (medication=${contained}, title='Medication', id='Medication')"/>
<th:block th:if="${#strings.trim(contained.resourceType)} == 'Encounter'" th:include="@{encounter} :: encounter (encounter=${contained}, title='Encounter', id='Encounter')"/>
<th:block th:if="${#strings.trim(contained.resourceType)} == 'Location'" th:include="@{location} :: location (location=${contained}, title='Location', id='Location')"/>
<th:block th:if="${#strings.trim(contained.resourceType)} == 'Organization'" th:include="@{organization} :: organization (organization=${contained}, title='Organization', id='Organization')"/>
</th:block>
</table>
</div>
<!--/*-->
</body>
</html>
<!--*/-->
|
import { expect } from '@storybook/jest';
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { screen, userEvent, within } from '@storybook/testing-library';
import { List } from 'immutable';
import React from 'react';
import { convertJs } from '@graasp/sdk';
import { FlagRecord } from '@graasp/sdk/frontend';
import { TABLE_CATEGORIES } from '../utils/storybook';
import ItemFlagDialog from './ItemFlagDialog';
export default {
title: 'Actions/Flag/ItemFlagDialog',
component: ItemFlagDialog,
argTypes: {
onClose: {
action: 'onClose',
},
onFlag: {
action: 'onFlag',
},
setOpen: {
table: {
category: TABLE_CATEGORIES.EVENTS,
},
},
},
} as ComponentMeta<typeof ItemFlagDialog>;
const flags: List<FlagRecord> = convertJs([
{ id: 'flag-1', name: 'flag-1' },
{ id: 'flag-2', name: 'flag-2' },
{ id: 'flag-3', name: 'flag-3' },
]);
const Template: ComponentStory<typeof ItemFlagDialog> = (args) => (
<ItemFlagDialog {...args} flags={flags} open />
);
export const Primary = Template.bind({});
Primary.args = {};
Primary.play = async () => {
const modal = within(screen.getByRole('dialog'));
flags.forEach(({ name }) => {
expect(modal.getByText(name)).toBeInTheDocument();
});
await userEvent.click(modal.getByText('Cancel'));
expect(modal.getByText('Flag')).toBeDisabled();
// choose a flag and validate
const flagName = flags.first()?.name;
if (flagName) {
await userEvent.click(modal.getByText(flagName));
}
await userEvent.click(modal.getByText('Flag'));
};
|
<template>
<div class="search-panel">
<el-row class="m-header-searchbar">
<el-col :span="3" class="left">
<img src="https://s0.meituan.net/bs/fe-web-meituan/e5eeaef/img/logo.png" alt="">
</el-col>
<el-col :span="15" class="center">
<div class="wrapper">
<el-input v-model="search" placeholder="搜索商家或地点" @focus="focus" @blur="blur" @input="input"></el-input>
<button class="el-button el-button--primary"><i class="el-icon-search"></i></button>
<dl class="hotPlace" v-if="isHotPlace">
<dt>热门搜索</dt>
<dd v-for="(item, idx) in hotPlace" :key="idx">{{item}}</dd>
</dl>
<dl class="searchList" v-if="isSearchList">
<dd v-for="(item, idx) in searchList" :key="idx">{{item}}</dd>
</dl>
</div>
<p class="suggset">
<a href="#">故宫博物院</a>
<a href="#">故宫博物院</a>
<a href="#">故宫博物院</a>
<a href="#">故宫博物院</a>
<a href="#">故宫博物院</a>
<a href="#">故宫博物院</a>
</p>
<ul class="nav">
<li>
<nuxt-link to="/" class="takeout">美团外卖</nuxt-link>
<nuxt-link to="/" class="movie">猫眼电影</nuxt-link>
<nuxt-link to="/" class="hotel">美团酒店</nuxt-link>
<nuxt-link to="/" class="apartment">民宿/公寓</nuxt-link>
<nuxt-link to="/" class="business">商家入驻</nuxt-link>
</li>
</ul>
</el-col>
<el-col :span="6" class="right">
<ul class="security">
<li>
<i class="refund"></i>
<p class="txt">随机退</p>
</li>
<li>
<i class="single"></i>
<p class="txt">不满意免单</p>
</li>
<li>
<i class="overdue"></i>
<p class="txt">过期退</p>
</li>
</ul>
</el-col>
</el-row>
</div>
</template>
<script>
export default {
data() {
return {
search: '',
isFocus: false,
hotPlace: ['故宫', '天安门', '颐和园'],
searchList: ['火锅', '火锅', '火锅', '火锅']
}
},
computed: {
isHotPlace() {
return this.isFocus && !this.search
},
isSearchList() {
return this.isFocus && this.search
}
},
methods: {
focus() {
this.isFocus = true
},
blur() {
setTimeout(() => {
this.isFocus = false
}, 200)
},
input() {
console.log('input')
}
}
}
</script>
<style scoped>
</style>
|
/*
* Copyright (c) 2019 sep.gg <seputaes@sep.gg>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gg.sep.battlenet.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import okhttp3.HttpUrl;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import gg.sep.battlenet.APITest;
import gg.sep.battlenet.BattleNet;
import gg.sep.battlenet.auth.api.OAuthAPI;
import gg.sep.battlenet.auth.model.OAuthToken;
import gg.sep.battlenet.model.BattleNetEntity;
import gg.sep.result.Ok;
import gg.sep.result.Result;
/**
* Unit test for {@link gg.sep.battlenet.auth.api.OAuthAPI}.
*/
public class OAuthAPITest extends APITest {
private OAuthAPI basicAPI(final BattleNetEntity entity, final HttpUrl baseUrl) {
return basicAPI(baseUrl, setupBattleNet(entity));
}
private OAuthAPI basicAPI(final HttpUrl baseUrl, final BattleNet battleNet) {
final OAuthAPI.OAuthAPIBuilder builder = OAuthAPI.builder()
.clientId("")
.clientSecret("")
.battleNet(battleNet);
if (baseUrl != null) {
builder.baseUrl(baseUrl);
}
return builder.build();
}
@Test void builder_WhenBaseUrlNotSet_UsesDefaultBaseUrl() {
final OAuthToken simpleToken = OAuthToken.builder()
.build();
final OAuthAPI oAuthAPI = basicAPI(simpleToken, null);
assertEquals(HttpUrl.get("https://us.battle.net"), oAuthAPI.getBaseUrl());
}
@Test void builder_BaseUrlSet_UsesSetBaseUrl() {
final OAuthToken simpleToken = OAuthToken.builder()
.build();
final HttpUrl expected = HttpUrl.get("https://sep.gg");
final OAuthAPI oAuthAPI = basicAPI(simpleToken, expected);
assertEquals(expected, oAuthAPI.getBaseUrl());
}
@Test void getToken_SuccessPath_ReturnsValidToken() {
final OAuthToken expectedToken = OAuthToken.builder()
.accessToken("foo")
.expiresIn(123L)
.tokenType("access_token")
.build();
final BattleNet battleNet = setupBattleNet(expectedToken);
final OAuthAPI oAuthAPI = basicAPI(expectedToken, battleNet.getRetrofit().baseUrl());
final Result<OAuthToken, String> token = oAuthAPI.getToken();
assertEquals(Ok.of(expectedToken), token);
}
@Test void getToken_UnparsableResponse_ReturnsErr() {
final BattleNetEntity mockEntity = Mockito.mock(BattleNetEntity.class);
Mockito.when(mockEntity.toJson()).thenReturn("[123]"); // unparsable for the type
final BattleNet battleNet = setupBattleNet(mockEntity);
final OAuthAPI oAuthAPI = basicAPI(mockEntity, battleNet.getRetrofit().baseUrl());
final Result<OAuthToken, String> token = oAuthAPI.getToken();
assertTrue(token.isErr());
}
@Test void getToken_IOError_ReturnsErr() {
final OAuthToken simpleToken = OAuthToken.builder()
.build();
// invalid URL that won't be able to resolve DNS
final OAuthAPI oAuthAPI = basicAPI(simpleToken, HttpUrl.get("https://willnotrespond.tld"));
final Result<OAuthToken, String> token = oAuthAPI.getToken();
assertTrue(token.isErr());
}
@Test void battleNet_UsesPostProcessor_SetsBattleNetOnEntity() {
final OAuthToken expectedToken = OAuthToken.builder()
.accessToken("foo")
.expiresIn(123L)
.tokenType("access_token")
.build();
final BattleNet battleNet = setupBattleNet(expectedToken);
final OAuthAPI oAuthAPI = basicAPI(battleNet.getRetrofit().baseUrl(), battleNet);
final Result<OAuthToken, String> token = oAuthAPI.getToken();
assertTrue(token.isOk());
assertSame(battleNet, token.unwrap().getBattleNet());
}
}
|
# примеры API-запросов
#@baseUrl = http://localhost:8000/api/v1
# создание продукта
POST {{baseUrl}}/products/
Content-Type: application/json
{
"title": "Помидор_6",
"description": "Лучшие помидоры на рынке_2"
}
###
# получение продуктов
GET {{baseUrl}}/products/
Content-Type: application/json
###
# обновление продукта
PATCH {{baseUrl}}/products/2/
Content-Type: application/json
{
"description": "Самые сочные и ароматные помидорки"
}
###
# удаление продукта
DELETE {{baseUrl}}/products/2/
Content-Type: application/json
###
# поиск продуктов по названию и описанию
GET {{baseUrl}}/products/?search=Лучшие
Content-Type: application/json
###
# поиск продуктов по id
GET {{baseUrl}}/products/?id=1
Content-Type: application/json
###
# создание склада
POST {{baseUrl}}/stocks/
Content-Type: application/json
{
"address": "раз три",
"positions": [
{
"product": 1,
"quantity": 11,
"price": 11
},
{
"product": 3,
"quantity": 22,
"price": 22
}
]
}
###
# обновляем записи на складе
PATCH {{baseUrl}}/stocks/35/
Content-Type: application/json
{
"positions": [
{
"product": 1,
"quantity": 666,
"price": 777
},
{
"product": 3,
"quantity": 888,
"price": 999
},
{
"product": 5,
"quantity": 1010,
"price": 1010
}
]
}
###
# удаление склада
DELETE {{baseUrl}}/stocks/34/
Content-Type: application/json
###
# поиск складов, где есть определенный продукт
GET {{baseUrl}}/stocks/?products=1
Content-Type: application/json
|
## これはなに
- [うひょさんに聞く!React 19アップデートの勘所](https://findy.connpass.com/event/318090/)に参加したので、まとめ
- スライド資料とか追加されたら追記するかも
- 13時にしゃぶしゃぶ予約しちゃったので、Q&Aは聴けないかも
## React19 RC
- React19のRCが公開されたので、それをメインに解説
- 具体的なAPIを細かく見ていくというよりは、React19時代に重要になりそうな概念などの話がメイン
## Reactの歴史
- React16
- Hooksの時代
- React17
- No New Features
- React18
- Suspenseの時代
- React19
- Actionsの時代
## Actionsって?
- ReactのActionsは、Next.jsのActionsと必ずしも同一ではない
- 非同期トランジションを使う関数のことを、慣例的にActionsと呼称する?
- トランジションという概念自体は、React18ですでに導入されていた(useTransition)
- 非同期の部分がReact19の新しい概念
## トランジションの性質
- 描画に時間がかかる処理のための機能
- 別のステート更新で割り込んだり、必要に応じてレンダリングをキャンセルしたり出来る
- サスペンドを起こしたレンダリングの最中に、サスペンド前のUIを残し続けたりといったことが可能になる
## React19の非同期トランジション
- startTransition関数に非同期関数を渡せる
- この非同期関数がActionsと呼ばれている
- 非同期トランジションの実行中は、isPendingがtrueになる、完了したらfalseになる
- 非同期トランジションの挙動は、普通のトランジション + Suspenseと同じ?
- 参照系はSuspense、更新系は非同期トランジションを使うべき
- Suspenseは更新系の処理には向いていなかったが、非同期トランジションでそこが補完された
- 公式ドキュメントにも、非同期トランジションは更新系の処理のための機能であることが書かれている
## useOptimistic
- 楽観的更新のためのAPI
- 楽観的更新とは、更新リクエストを送った後、レスポンスが返ってくる前に更新後のUIを反映させること
- 楽観的更新はステート管理が煩雑になりがち
- 元データの楽観的更新版のステートを宣言できる
- 非同期トランジションの中でaddOptimisticを呼び出すことで、楽観的更新として反映できる
- スレートが更新されとトランジションが終了した時点で楽観的更新状態ではなくなり、値として整合性が取れた状態になる
- 具体的な構文などは公式ドキュメントを参照
## useActionState
- ステートの初期値と、ステートを更新するためのアクションを生成するためのAPI
- useReducerと近い部分がある
- useActionStateから返ってきた関数を呼び出せばアクションが実行される
- useActionStateから得られたアクション関数を使うと、自動的に非同期トランジションになる
- useTransitionとuseStateをくっつけたような便利なHooks
- useReducerの非同期版ともいえる
- useActionStateがあるため、非同期トランジションのためにuseTransitionを直接使う機会はあまりないかも
- 連打した時に、アクションが複数並列実行されないように制御してくれる
- useReducerの非同期版と考えると、並列実行できないのは自然といえる
## formとアクション
- formのaction属性にアクションを渡せるようになり、フォームが送信されると渡したアクションが実行される
- 従来のonSubmitの代わりに使える
- アクションということはisPendingの概念があり、それはuseFormStatusで取得できる
- ReactDOMからexportされている初めてのHooks
- useActionStateと組み合わせることが推奨されている
## Server Actionsとの関係
- クライアントから見れば、Sercer Actionsはアクションの一つといえる
- 同じ非同期処理なので
## アクション系以外の新機能ダイジェスト
### メタデータ
- titleなどをレンダリングスロとheadに反映してくれるように
- スタイルシートもレンダリング可能
- Suspense対応
- スタイルシートが読み込まれるまで、サスペンドしてコンポーネントの表示を待ってくれる
- CSSがあたっていない状態のUIを見せないように出来る
- スクリプトもasync属性をつけることでサスペンド対応になる
- 謎のサードパーティスクリプトを読み込む必要があるときに便利
### Contextを直接コンポーネントとして渡せるように
- Providerの記述がいらなくなった
## React19のは破壊的変更
- 結構緩やかな印象
- 非推奨化済みの古い機能が色々削除されるので、5年以上メンテされていないコードベースは注意
- 引数のないuseRefが不可になったり、TypeScript型定義の破壊的変更のほうが破壊力が高い
## まとめ
- Reacr19で新しく登場したAPIたちは、アクションという新概念でまとめられている
- 今回省略したuseは別
- Suspenseやトランジションという既存概念を土台にアクションを理解することが、Reacr19を使いこなす近道になる
## 感想
- Reactの新概念は、自分なりに調べて素晴らしい説明ができた、と思ったら、公式ドキュメントに同じことが最初から書いてあった、ということがよくあるらしく、やっぱり公式ドキュメントは偉大
- Reactの公式ドキュメントはクオリティが高い
- 妥協しないで公式ドキュメントを読んで、深く正確に理解するのが最短ルート
- ドキュメントの更新が追いついていない場合もあるので、そういうときは個人的に調べたり実験したりする必要もある
- なんとこのイベントの後にReact19の新機能の詳細をまとめたZenn本を公開してくれるらしい、最高
- 色々と大きな変更が入って追従が大変、という印象を持っていたが、既存概念をしっかり理解していればそれを土台として理解することは簡単っぽい?
- 概念としては理解できていても実際のコードで応用できるかは別なので、やはり手を動かして理解することが重要
- formとか値の更新、非同期処理なんかは実際のフロントエンド開発でも頻出かつ重要な要素だと思うので、このタイミングで一回しっかりと土台から理解したいと感じた
|
import { createSignal } from "solid-js";
import { Avatar } from "~/components";
import { useCommentsContext } from "~/context";
import DATA from "~/data/data.json";
import { generateRandomId } from "~/helpers";
import { TComment } from "~/types";
type TNewCommentProps = {
isReply?: boolean;
id?: string;
className?: string;
};
export function NewComment({ isReply, id, className }: TNewCommentProps) {
const { comments, setComments, me } = useCommentsContext();
console.log(DATA.users[Math.floor(Math.random() * DATA.users.length)]);
const [textArea, setTextArea] = createSignal("");
const handleSaveNewComment = () => {
const comment: TComment = {
id: generateRandomId(),
likes: 0,
/* author: DATA.users[Math.floor(Math.random() * DATA.users.length)], */
author: me(),
date: new Date(),
content: textArea(),
child: [],
isBeingReplied: false,
};
setTextArea("");
setComments([...comments(), comment]);
};
const handleSaveReplyComment = () => {
const comment: TComment = {
id: generateRandomId(),
likes: 0,
author: me(),
date: new Date(),
content: textArea(),
child: [],
isBeingReplied: false,
};
setTextArea("");
const newComments = comments().map((c) => {
if (c.id === id) {
c.child.push(comment);
c.isBeingReplied = false;
}
return c;
});
setComments(newComments);
};
const handleSaveComment = () => {
if (textArea().trim() === "") return;
if (isReply) {
handleSaveReplyComment();
} else {
handleSaveNewComment();
}
};
return (
<div class={`rounded-md bg-white p-8 flex gap-8 w-full ${className}`}>
<Avatar user={me()} />
<textarea
onChange={(e) => {
setTextArea(e.target.value);
}}
cols="10"
rows="2"
placeholder="Write a comment..."
class="w-full p-2 rounded-md border-2 min-h-[100px] max-h-[175px] border-gray-300"
value={textArea()}
/>
<button
onClick={handleSaveComment}
class="font-semibold text-sm bg-blue-800 text-white px-6 py-2 rounded-md h-[48px] hover:bg-opacity-80 transition-all duration-200 ease-in-out active:scale-95"
>
REPLY
</button>
</div>
);
}
|
//SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.20;
import "./interfaces/IRiver.1.sol";
import "./interfaces/IELFeeRecipient.1.sol";
import "./libraries/LibUint256.sol";
import "./Initializable.sol";
import "./state/shared/RiverAddress.sol";
/// @title Execution Layer Fee Recipient (v1)
/// @author Kiln
/// @notice This contract receives all the execution layer fees from the proposed blocks + bribes
contract ELFeeRecipientV1 is Initializable, IELFeeRecipientV1 {
/// @inheritdoc IELFeeRecipientV1
function initELFeeRecipientV1(address _riverAddress) external init(0) {
RiverAddress.set(_riverAddress);
emit SetRiver(_riverAddress);
}
/// @inheritdoc IELFeeRecipientV1
function pullELFees(uint256 _maxAmount) external {
address river = RiverAddress.get();
if (msg.sender != river) {
revert LibErrors.Unauthorized(msg.sender);
}
uint256 amount = LibUint256.min(_maxAmount, address(this).balance);
if (amount > 0) {
IRiverV1(payable(river)).sendELFees{value: amount}();
}
}
/// @inheritdoc IELFeeRecipientV1
receive() external payable {
this;
}
/// @inheritdoc IELFeeRecipientV1
fallback() external payable {
revert InvalidCall();
}
}
|
import { Engine } from "../engines/engine";
import { Primitive } from "../engines/engine.draw";
import { BufferStore, DataType, IndexFormat, PrimitiveType } from "../engines/engine.enum";
import { iGeometryIndex, IndexBuffer } from "./index-buffer";
import { iGeometryAttribute, VertexArrayBuffer } from "./vertex-array-buffer";
/**
* 几何体信息
* eg:
* ```js
* const geoInfo = {
indices: {
value: []
},
attributes: [
{
name: "aPosition"
value: model.positions,
itemSize: 3,
},
},
];
* ```
*/
export interface iGeometryData {
attributes: iGeometryAttribute[];
indices?: iGeometryIndex;
drawType?: PrimitiveType;
instanceCount?: number;
}
export class Geometry {
private _engine: Engine;
public instancing: boolean;
public vertexArrayBuffer: VertexArrayBuffer;
public indexBuffer: IndexBuffer;
public drawType: PrimitiveType;
public instanceCount: number;
constructor(engine: Engine, geometryData: iGeometryData) {
this._engine = engine;
this.drawType = geometryData.drawType !== undefined ? geometryData.drawType : PrimitiveType.PRIMITIVE_TRIANGLES;
this.instancing = geometryData.instanceCount !== undefined ? geometryData.instanceCount > 0 : false;
this.instanceCount = geometryData.instanceCount !== undefined ? geometryData.instanceCount : 0;
this.vertexArrayBuffer = new VertexArrayBuffer(engine, geometryData.attributes, this.instanceCount);
if (geometryData?.indices) {
this.indexBuffer = new IndexBuffer(engine, geometryData?.indices);
}
}
public setBuffers(program: WebGLProgram): void {
this.vertexArrayBuffer.unlock(program);
if (this.indexBuffer) {
this.indexBuffer.unlock();
}
}
getDrawInfo(): Primitive {
let count = 0;
if (this.indexBuffer) {
count = this.indexBuffer.indexCount;
} else {
count = this.vertexArrayBuffer.vertexCount;
}
return {
type: this.drawType,
indexed: this.indexBuffer?.storage,
count: count,
instanceCount: this.instanceCount,
};
}
updateAttribure(name: string) {
return this.vertexArrayBuffer.updateAttribure(name);
}
getAttribute(name: string): iGeometryAttribute {
return this.vertexArrayBuffer.getAttribute(name);
}
}
|
# Introduction
V-pipe is a bio-informatics pipeline built on top of the Snakemake workflow management system.
Bioconda is optimized for use on Unix and MacOS systems but does not have a Windows Channel. For that reason, WSL (Windows Subsystem for Linux) installation is advised.
This Markdown shares resources that makes installation easier and solutions for problems you may encounter when using WSL.
For this project setup , VSCode IDE was used.
## Installation Resources
1. How to [Setup WSL](https://learn.microsoft.com/en-gb/windows/wsl/install) on your windows device
2. Install and configure [Anaconda](https://medium.com/@sawepeter6/conda-command-not-found-ac28bea24291)
3. [V-pipe](https://github.com/cbg-ethz/V-pipe/blob/master/docs/tutorial_0_install.md) setup tutorial
> Handy tips - From step 2, aim to work in the 'home' directory of WSL to avoid errors as will be seen.
## Probable Errors & Their Solutions
### 1. Symbolic Links aka Symlinks
A symbolic link is a special type of file that acts like a shortcut to another file or directory.
A symbolic link directly or indirectly points back to itself, creating an infinite loop. The system gets stuck trying to follow the chain of links forever.
#### Error
```
CreateCondaEnvironmentException:
Could not create conda environment from
OSError: [Errno 40] Too many levels of symbolic links: '/mnt/c/Users/..'
```
#### Solution
Check your V-pipe working directory and move it from `mnt/c/Users/... ` (Windows) to `/home/projects...` (Linux) to resolve the *__"too many levels of symbolic links"__* error because of the inherent differences in how Windows and Linux handle file systems and symbolic links.
### 2. The Assertion Error
#### Error
```
AssertionError in file /home/user/v-pipe/vp-analysis/V-pipe/workflow/rules/common.smk, line 505:
ERROR: Line '1' does not contain at least two entries!
File "/home/user/v-pipe/vp-analysis/V-pipe/workflow/Snakefile", line 12, in <module>
File "/home/user/v-pipe/vp-analysis/V-pipe/workflow/rules/common.smk", line 505, in <module>
```
#### Solution
The pipeline expects at **minimum two tab seperated values in the samples.tsv**
(For VSCode IDE) - Check your Tab settings. For Python, it is important that the tab size is set to 4. Here is a useful [resource](https://araldhafeeri.medium.com/specify-indentation-tab-size-per-filetype-in-vs-code-91d95d51248a) to ensure that.
### 3. Locked directories
#### Error
If maybe after running `./vpipe -p --cores 2 ` and for some reason, the set up doesnt complete after a few processes or encounter an error that halts the pipeline execution.
#### Solution
Snakemake by default prevents production of the same output file, to continue working,
Run `./vpipe -p --cores 2 --unlock` first then `./vpipe -p --cores 2 ` again to resolve the issue.
### 4. Conda environment
#### Error
`Conda environment not activated`
#### Solution
Ensure you have rightfully activated the Conda Environment as detailed [here.](https://medium.com/@sawepeter6/conda-command-not-found-ac28bea24291)
|
package com.example.rdo_server.utilities;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* @author Xabier Ferrer Ardanaz
* @author Razican (Iban Eguia)
*/
public class Database extends SQLiteOpenHelper {
private static Database instance;
/**
* @param context - The context of the application
*/
private Database(final Context context)
{
super(context, "RDO-Server-DB", null, 1);
}
@Override
public void onCreate(final SQLiteDatabase db)
{
db.execSQL("PRAGMA foreign_keys=ON;");
create_tables(db);
insert_data(db);
}
private void create_tables(final SQLiteDatabase db)
{
db.execSQL("CREATE TABLE CONFIG ("
+ "\"key\" TEXT PRIMARY KEY NOT NULL, \"value\" TEXT);");
db.execSQL("CREATE TABLE USER ("
+ "\"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "\"name\" TEXT UNIQUE NOT NULL, \"password\" TEXT NOT NULL);");
db.execSQL("CREATE TABLE SENSOR ("
+ "\"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "\"description\" TEXT,"
+ "\"enabled\" INTEGER CHECK (enabled BETWEEN 0 AND 1));");
db
.execSQL("CREATE TABLE MEASUREMENT ("
+ "\"date\" INTEGER NOT NULL,"
+ "\"sensor_id\" INTEGER NOT NULL REFERENCES SENSOR(id) ON DELETE CASCADE,"
+ "\"latitude\" REAL NOT NULL, \"longitude\" REAL NOT NULL,"
+ "\"value\" REAL NOT NULL, PRIMARY KEY (date, sensor_id));");
}
private void insert_data(SQLiteDatabase db)
{
db
.execSQL("INSERT INTO CONFIG VALUES (\"patient_id\", \"Paciente 1\");");
db.execSQL("INSERT INTO USER (\"name\", \"password\") VALUES "
+ "(\"Razican\", \"8cb2237d0679ca88db6464eac60da96345513964\")," + // 12345
"(\"Jordan\", \"d5f12e53a182c062b6bf30c1445153faff12269a\");"); // 4321
db
.execSQL("INSERT INTO SENSOR (\"description\", \"enabled\") VALUES "
+ "(\"Pulsometro\", 1), (\"Termometro\", 1),(\"Medidor de respiracion\", 1),(\"Medidor de glucosa\", 1);");
}
@Override
public SQLiteDatabase getWritableDatabase()
{
final SQLiteDatabase db = super.getWritableDatabase();
db.execSQL("PRAGMA foreign_keys=ON;");
return db;
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion,
final int newVersion)
{
// TODO upgrade
}
/**
* Initializes the database
*
* @param context - The context of the application
*/
public static void init(Context context)
{
instance = new Database(context);
}
/**
* @return The database of the application
*/
public static Database getInstance()
{
return instance;
}
}
|
# Copyright (C) 2017 Greenbone Networks GmbH
# Some text descriptions might be excerpted from (a) referenced
# source(s), and are Copyright (C) by the respective right holder(s).
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA.
if(description)
{
script_oid("1.3.6.1.4.1.25623.1.0.843399");
script_cve_id("CVE-2017-1000405", "CVE-2017-12193", "CVE-2017-15299", "CVE-2017-15306", "CVE-2017-15951", "CVE-2017-16535", "CVE-2017-16643", "CVE-2017-16939");
script_tag(name:"creation_date", value:"2017-12-09 06:39:06 +0000 (Sat, 09 Dec 2017)");
script_version("2023-01-23T10:11:56+0000");
script_tag(name:"last_modification", value:"2023-01-23 10:11:56 +0000 (Mon, 23 Jan 2023)");
script_tag(name:"cvss_base", value:"7.2");
script_tag(name:"cvss_base_vector", value:"AV:L/AC:L/Au:N/C:C/I:C/A:C");
script_tag(name:"severity_vector", value:"CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H");
script_tag(name:"severity_origin", value:"NVD");
script_tag(name:"severity_date", value:"2023-01-19 15:46:00 +0000 (Thu, 19 Jan 2023)");
script_name("Ubuntu: Security Advisory (USN-3507-1)");
script_category(ACT_GATHER_INFO);
script_copyright("Copyright (C) 2017 Greenbone Networks GmbH");
script_family("Ubuntu Local Security Checks");
script_dependencies("gather-package-list.nasl");
script_mandatory_keys("ssh/login/ubuntu_linux", "ssh/login/packages", re:"ssh/login/release=UBUNTU17\.10");
script_xref(name:"Advisory-ID", value:"USN-3507-1");
script_xref(name:"URL", value:"https://ubuntu.com/security/notices/USN-3507-1");
script_tag(name:"summary", value:"The remote host is missing an update for the 'linux, linux-raspi2' package(s) announced via the USN-3507-1 advisory.");
script_tag(name:"vuldetect", value:"Checks if a vulnerable package version is present on the target host.");
script_tag(name:"insight", value:"Mohamed Ghannam discovered that a use-after-free vulnerability existed in
the Netlink subsystem (XFRM) in the Linux kernel. A local attacker could
use this to cause a denial of service (system crash) or possibly execute
arbitrary code. (CVE-2017-16939)
It was discovered that the Linux kernel did not properly handle copy-on-
write of transparent huge pages. A local attacker could use this to cause a
denial of service (application crashes) or possibly gain administrative
privileges. (CVE-2017-1000405)
Fan Wu, Haoran Qiu, and Shixiong Zhao discovered that the associative array
implementation in the Linux kernel sometimes did not properly handle adding
a new entry. A local attacker could use this to cause a denial of service
(system crash). (CVE-2017-12193)
Eric Biggers discovered that the key management subsystem in the Linux
kernel did not properly restrict adding a key that already exists but is
uninstantiated. A local attacker could use this to cause a denial of
service (system crash) or possibly execute arbitrary code. (CVE-2017-15299)
It was discovered that a null pointer dereference error existed in the
PowerPC KVM implementation in the Linux kernel. A local attacker could use
this to cause a denial of service (system crash). (CVE-2017-15306)
Eric Biggers discovered a race condition in the key management subsystem of
the Linux kernel around keys in a negative state. A local attacker could
use this to cause a denial of service (system crash) or possibly execute
arbitrary code. (CVE-2017-15951)
Andrey Konovalov discovered that the USB subsystem in the Linux kernel did
not properly validate USB BOS metadata. A physically proximate attacker
could use this to cause a denial of service (system crash).
(CVE-2017-16535)
Andrey Konovalov discovered an out-of-bounds read in the GTCO digitizer USB
driver for the Linux kernel. A physically proximate attacker could use this
to cause a denial of service (system crash) or possibly execute arbitrary
code. (CVE-2017-16643)");
script_tag(name:"affected", value:"'linux, linux-raspi2' package(s) on Ubuntu 17.10.");
script_tag(name:"solution", value:"Please install the updated package(s).");
script_tag(name:"solution_type", value:"VendorFix");
script_tag(name:"qod_type", value:"package");
exit(0);
}
include("revisions-lib.inc");
include("pkg-lib-deb.inc");
release = dpkg_get_ssh_release();
if(!release)
exit(0);
res = "";
report = "";
if(release == "UBUNTU17.10") {
if(!isnull(res = isdpkgvuln(pkg:"linux-image-4.13.0-1008-raspi2", ver:"4.13.0-1008.8", rls:"UBUNTU17.10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"linux-image-4.13.0-19-generic-lpae", ver:"4.13.0-19.22", rls:"UBUNTU17.10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"linux-image-4.13.0-19-generic", ver:"4.13.0-19.22", rls:"UBUNTU17.10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"linux-image-4.13.0-19-lowlatency", ver:"4.13.0-19.22", rls:"UBUNTU17.10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"linux-image-generic-lpae", ver:"4.13.0.19.20", rls:"UBUNTU17.10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"linux-image-generic", ver:"4.13.0.19.20", rls:"UBUNTU17.10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"linux-image-lowlatency", ver:"4.13.0.19.20", rls:"UBUNTU17.10"))) {
report += res;
}
if(!isnull(res = isdpkgvuln(pkg:"linux-image-raspi2", ver:"4.13.0.1008.6", rls:"UBUNTU17.10"))) {
report += res;
}
if(report != "") {
security_message(data:report);
} else if(__pkg_match) {
exit(99);
}
exit(0);
}
exit(0);
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from PIL import Image
from torch.utils import data
from torchvision import transforms, utils
from torch.utils.data import Dataset, DataLoader
import cv2
def ratioFunction(num1, num2):
num1 = int(num1) # Now we are good
num2 = int(num2) # Good, good
if num1 > num2:
ratio12 = num2/num1
else:
ratio12 = num1/num2
# print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
return ratio12
# transformer
transform = transforms.Compose([
transforms.RandomHorizontalFlip(p=0.9),
transforms.RandomAffine(degrees=0, translate=(0.005, 0.0025)),
])
transform_toTensor = transforms.Compose([
transforms.ToTensor()
])
def image2label(img, cm2lbl):
data = np.array(img, dtype='int32')
idx = (data[:, :, 0] * 256 + data[:, :, 1]) * 256 + data[:, :, 2]
# print(np.unique(idx))
# print(cm2lbl[idx])
result = np.array(cm2lbl[idx], dtype='int64')
return result[:,:,None]
class IS_Dataset_test(Dataset):
CLASSES = ['background', 'girder', 'net', 'lanyard', 'guardrail']
def __init__(self, data_list, label_list, classes, cm2lbl, transform=None, transform_toTensor=None, resize_size=None):
self.data_list = data_list
self.label_list = label_list
self.transform = transform
self.transform_toTensor = transform_toTensor
self.cm2lbl = cm2lbl
self.resize_size = resize_size
# convert str names to class values on masks
self.class_values = [self.CLASSES.index(cls.lower()) for cls in classes]
print('Read ' + str(len(self.data_list)) + ' images')
def __getitem__(self, index):
# read data
image = cv2.imread(self.data_list[index])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# image = cv2.resize(image, self.resize_size, interpolation=cv2.INTER_AREA)
mask = cv2.imread(self.label_list[index])
# mask = cv2.resize(mask, self.resize_size, interpolation=cv2.INTER_NEAREST)
if self.resize_size:
image = cv2.resize(image, self.resize_size, interpolation=cv2.INTER_AREA)
mask = cv2.resize(mask, self.resize_size, interpolation=cv2.INTER_NEAREST)
if image.shape[0] > 1400 or image.shape[1] > 1400 :
ratio = ratioFunction(image.shape[0], image.shape[1])
new_size = (960, int(960*ratio))
image = cv2.resize(image, new_size, interpolation=cv2.INTER_AREA)
mask = cv2.resize(mask, new_size, interpolation=cv2.INTER_NEAREST)
if image.shape[0]%16 !=0 or image.shape[1]%16 !=0 :
new_size = (960, 720)
image = cv2.resize(image, new_size, interpolation=cv2.INTER_AREA)
mask = cv2.resize(mask, new_size, interpolation=cv2.INTER_NEAREST)
print(image.shape)
# apply data augmentations
if self.transform:
# ndarray to PIL image
image = Image.fromarray(image)
mask = Image.fromarray(mask)
# apply the transforms
image = self.transform(image)
mask = self.transform(mask)
#把RGB改成0,1,...,class_num : (w, w, 1)
mask = image2label(mask, self.cm2lbl)
mask = mask.squeeze()
# print(np.unique(mask))
# print(mask.shape)
# 把每個不同目標分成0,1 : (w, w, class_num)
masks = [(mask == v) for v in self.class_values]
mask = np.stack(masks, axis=-1).astype('float')
if self.transform_toTensor:
image = self.transform_toTensor(image)
mask = self.transform_toTensor(mask)
return image, mask
def __len__(self):
return len(self.data_list)
|
import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path:'pocetna',
loadChildren: ()=> import('./pocetna/pocetna.module').then(m=>m.PocetnaPageModule)
},
{
path: '',
redirectTo: 'pocetna',
pathMatch: 'full'
},
{
path: 'pacijent',
loadChildren: () => import('./pacijent/pacijent.module').then( m => m.PacijentPageModule)
},
{
path: 'druga',
loadChildren: () => import('./druga/druga.module').then( m => m.DrugaPageModule)
},
{
path: 'treca',
loadChildren: () => import('./treca/treca.module').then( m => m.TrecaPageModule)
},
{
path: 'cetvrta',
loadChildren: () => import('./cetvrta/cetvrta.module').then( m => m.CetvrtaPageModule)
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import { Component, Inject, OnDestroy, OnInit, Optional } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Editor, toHTML, Toolbar } from 'ngx-editor';
import { ToastrService } from 'ngx-toastr';
import { EmailManagerService } from 'src/_services/rest/emailManager.service';
@Component({
selector: 'app-new-email',
templateUrl: './new-email.component.html',
styleUrls: ['./new-email.component.scss'],
})
export class NewEmailComponent implements OnInit, OnDestroy {
editor: Editor;
toolbar: Toolbar = [
['bold', 'italic'],
['underline', 'strike'],
['code', 'blockquote'],
['ordered_list', 'bullet_list'],
[{ heading: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] }],
['link', 'image'],
['text_color', 'background_color'],
['align_left', 'align_center', 'align_right', 'align_justify'],
];
form: FormGroup;
notifications: [] = [];
EmailManagerID: string = null;
constructor(
private formBuilder: FormBuilder,
@Optional() private dialogRef: MatDialogRef<NewEmailComponent>,
private emailManagerService: EmailManagerService,
@Inject(MAT_DIALOG_DATA) private data,
private toaster: ToastrService) {
this.EmailManagerID = this.data.id;
this.form = this.formBuilder.group({
name: [null, [Validators.required, Validators.maxLength(32)]],
subject: [null, [Validators.required, Validators.maxLength(150)]],
sendTo: [null, [Validators.maxLength(500)]],
description: ['', [Validators.maxLength(500)]],
previewFirst: [false],
sendtorep: [false],
sendtolinkedcontacts: [false],
active: [true],
templateHTML: [null, Validators.required]
});
}
ngOnInit(): void {
this.editor = new Editor();
if (this.EmailManagerID) {
const sub = this.emailManagerService
.getSingleEmailNotification(this.EmailManagerID)
.subscribe({
next: (res) => {
this.form.patchValue({
name: res['data'].name ? res['data'].name : '',
subject: res['data'].subject ? res['data'].subject : '',
sendTo: res['data'].sendTo ? res['data'].sendTo : '',
description: res['data'].description ? res['data'].description : '',
previewFirst: res['data'].previewFirst ? res['data'].previewFirst : false,
sendtorep: res['data'].sendToRep ? res['data'].sendToRep : false,
sendtolinkedcontacts: res['data'].sendToLinkedContacts ? res['data'].sendToLinkedContacts : false,
active: res['data'].active ? res['data'].active : false,
templateHTML: res['data'].templateHTML ? res['data'].templateHTML : '',
});
sub.unsubscribe();
},
error: (res) => {
sub.unsubscribe();
},
});
}
}
close() {
this.dialogRef.close();
}
onSubmit() {
if (this.form.valid) {
const html = (typeof this.form.value.templateHTML == "object") ? toHTML(this.form.value.templateHTML) : this.form.value.templateHTML;
const data = Object.assign({}, this.form.value);
data.templateHTML = html;
if (this.EmailManagerID) {
data.id = this.EmailManagerID;
}
const sub = this.emailManagerService
.createOrUpdateNotification(data)
.subscribe({
next: (res) => {
this.toaster.success(
`Email Manager ${this.EmailManagerID ? 'Updated' : 'Created'
} Successfully`,
'Success'
);
this.dialogRef.close();
sub.unsubscribe();
},
error: (res) => {
sub.unsubscribe();
},
});
}
else {
this.form.markAllAsTouched();
}
}
ngOnDestroy(): void {
this.editor.destroy();
}
}
|
/**
* @file LinkedListHolderTest.h
* @brief Header file for class LinkedListHolderTest
* @date 06/08/2015
* @author Giuseppe Ferrò
*
* @copyright Copyright 2015 F4E | European Joint Undertaking for ITER and
* the Development of Fusion Energy ('Fusion for Energy').
* Licensed under the EUPL, Version 1.1 or - as soon they will be approved
* by the European Commission - subsequent versions of the EUPL (the "Licence")
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
*
* @warning Unless required by applicable law or agreed to in writing,
* software distributed under the Licence is distributed on an "AS IS"
* basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the Licence permissions and limitations under the Licence.
* @details This header file contains the declaration of the class LinkedListHolderTest
* with all of its public, protected and private members. It may also include
* definitions for inline methods which need to be visible to the compiler.
*/
#ifndef LINKEDLISTHOLDERTEST_H_
#define LINKEDLISTHOLDERTEST_H_
/*---------------------------------------------------------------------------*/
/* Standard header includes */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Project header includes */
/*---------------------------------------------------------------------------*/
#include "LinkedListHolder.h"
#include "MutexSem.h"
/*---------------------------------------------------------------------------*/
/* Class declaration */
/*---------------------------------------------------------------------------*/
using namespace MARTe;
/**
* @brief Tests all the LinkedListHolder functions.
*/
class LinkedListHolderTest {
public:
/**
* @brief Tests the LinkedListHolder constructor.
* @return true if at the beginning the size of the list is zero, false otherwise.
*/
bool TestConstructor();
/**
* @brief Tests the LinkedListHolder destructor.
* @return true if the first element of the list is null and the size is zero after the destructor call.
*/
bool TestDestructor();
/**
* @brief Tests the LinkedListHolder::Reset function.
* @param[in] nElements is the desired number of elements in the list.
* @return true if the first element of the list is null and the size is zero after the function call.
*/
bool TestReset(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::CleanUp function.
* @param[in] nElements is the desired number of elements in the list.
* @return true if all the elements of the list are deleted after the function call.
*/
bool TestCleanup(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::List function.
* @param[in] nElements is the desired number of elements in the list.
* @return true if the function returns the first element in the list and NULL if the list is empty.
*/
bool TestList(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::ListSize function.
* @details Creates a list and checks that the size of the list is correct.
* @param[in] nElements is the desired number of elements in the list.
* @return true if successful, false otherwise.
*/
bool TestListSize(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::FastListInsertSingle function.
* @details Creates a list inserting elements one by one and checks their order in the list (they should be added on the queue).
* @param[in] nElements is the desired number of elements in the list.
* @return true if successful, false otherwise.
*/
bool TestFastListInsertSingle(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::ListInsert function.
* @details Creates two lists and merges them checking if the insert adds the second list at the beginning.
* @param[in] nElements is the desired number of elements in the two lists.
* @return true if successful, false otherwise.
*/
bool TestListInsert(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::ListInsert with a SortFilter as input.
* @details Creates two lists of integers and merges them specifying a descending order. Then checks that the elements are ordered correctly.
* @param[in] nElements is the desired number of elements in the two lists.
* @return true if successful, false otherwise.
*/
bool TestListInsertSortedSorter(uint32 nElements);
/**
* @brief Tests the insert function passing a null SortFilter as input.
* @details Checks if the insert function, inserts the second list at the beginning of the first (normal insert behaviour).
* @param[in] nElements is the desired number of elements in the two lists.
* @return true if successful, false otherwise.
*/
bool TestListInsertNullSorter(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::ListInsert passing the element position.
* @details Creates two lists and inserts the second on the first after the specified position. Then checks if the result list is as expected.
* @param[in] index is the position of the first list where the second list must be inserted.
* @param[in] size is the number of elements of the two lists.
* @return true if successful, false otherwise.
*/
bool TestListInsertIndex(uint32 index,
uint32 size);
/**
* @brief Tests the LinkedListHolder::ListAdd function.
* @details Creates two lists and adds the second to the first. Then checks that after the function only the first element of the second list
* is added on the queue of the first.
* @param[in] nElements is the desired number of elements in the two lists.
* @return true if successful, false otherwise.
*/
bool TestListAdd(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::ListAddL function.
* @details Creates two lists and adds the second to the first. Then checks that all the second list is added on the queue of the first.
* @param[in] nElements is the desired number of elements of the two lists.
* @return true if successful, false otherwise.
*/
bool TestListAddL(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::ListSearch.
* @details Creates a list and checks if the function returns true searching all elements in the list and if it returns false for elements not in the list.
* @return true if successful, false otherwise.
*/
bool TestListSearch();
/**
* @brief Tests the LinkedListHolder::ListSearch function with a SearchFilter in input.
* @details Creates a list of integers and checks if the function returns true for elements in the list and false for elements not in the list
* using a SearchFilter object.
* @return true if successful, false otherwise.
*/
bool TestListSearchFilter();
/**
* @brief Tests the LinkedListHolder::ListExtract function.
* @details Creates a list and extracts all elements in it checking that the size decreases. Checks also that
* the function returns true for elements in the list and false otherwise.
* @return true if successful, false otherwise.
*/
bool TestListExtract();
/**
* @brief Tests the extract function with a SearchFilter in input.
* @details Creates a list of integers and extracts all elements using a SearchFilter object and checking that the size decreases.
* Checks also that the function returns the correct elements extracted.
* @return true if successful, false otherwise.
*/
bool TestListExtractSearchFilter();
/**
* @brief Tests the extract function with the element position in input.
* @details Creates a list and removes all the elements by index checking that the size decreases. Checks also that the function returns
* the correct elements extracted.
* @return true if successful, false otherwise.
*/
bool TestListExtractIndex();
/**
* @brief Tests the LinkedListHolder::Delete function.
* @details Creates a list and deletes all elements checking that the size decreases. Checks also if
* the function returns true if the element is in the list and false otherwise.
* @return true if successful, false otherwise.
*/
bool TestListDelete();
/**
* @brief Tests the delete function passing a SearchFilter object in input.
* @details Creates a list of integer and checks if the delete function removes from the list all the elements in the list which
* satisfies the specified search criteria. Checks also if the function returns true if at least one element is removed, false if the requested
* element is not in the list.
* @return true if successful, false otherwise.
*/
bool TestListDeleteSearchFilter();
/**
* @see TestListDeleteSearchFilter.
*/
bool TestListSafeDelete();
/**
* @brief Tests the LinkedListHolder::ListBSort function with a SortFilter object in input.
* @details Creates a list of integers and sorts them in a descending order. Then checks if the elements are sorted correctly in the list.
* @param[in] nElements is the desired number of elements in the list.
* @return true if successful, false otherwise.
*/
bool TestListBSortSorter(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::Peek function.
* @details Creates a list and browses it checking that the elements are in the correct positions. Then checks if the function
* returns NULL in case of index greater than the list size.
* @param[in] nElements is the desired number of elements in the list.
* @return true if successful, false otherwise.
*/
bool TestListPeek(uint32 nElements);
/**
* @brief Tests the LinkedListHolder::Iterate with an Iterator object in input.
* @details Creates a list of integers and increments each element using an iterator object. Then checks if all elements were incremented
* as expected.
* @return true if successful, false otherwise.
*/
bool TestListIterateIterator();
};
/*---------------------------------------------------------------------------*/
/* Inline method definitions */
/*---------------------------------------------------------------------------*/
#endif /* LINKEDLISTHOLDERTEST_H_ */
|
import { mixins } from 'vue-class-component';
import { Component, Vue, Inject } from 'vue-property-decorator';
import Vue2Filters from 'vue2-filters';
import { IAnswerToOffer } from '@/shared/model/answer-to-offer.model';
import AlertMixin from '@/shared/alert/alert.mixin';
import AnswerToOfferService from './answer-to-offer.service';
@Component({
mixins: [Vue2Filters.mixin],
})
export default class AnswerToOffer extends mixins(AlertMixin) {
@Inject('answerToOfferService') private answerToOfferService: () => AnswerToOfferService;
private removeId: number = null;
public answerToOffers: IAnswerToOffer[] = [];
public isFetching = false;
public mounted(): void {
this.retrieveAllAnswerToOffers();
}
public clear(): void {
this.retrieveAllAnswerToOffers();
}
public retrieveAllAnswerToOffers(): void {
this.isFetching = true;
this.answerToOfferService()
.retrieve()
.then(
res => {
this.answerToOffers = res.data;
this.isFetching = false;
},
err => {
this.isFetching = false;
}
);
}
public prepareRemove(instance: IAnswerToOffer): void {
this.removeId = instance.id;
if (<any>this.$refs.removeEntity) {
(<any>this.$refs.removeEntity).show();
}
}
public removeAnswerToOffer(): void {
this.answerToOfferService()
.delete(this.removeId)
.then(() => {
const message = this.$t('riportalApp.answerToOffer.deleted', { param: this.removeId });
this.alertService().showAlert(message, 'danger');
this.getAlertFromStore();
this.removeId = null;
this.retrieveAllAnswerToOffers();
this.closeDialog();
});
}
public closeDialog(): void {
(<any>this.$refs.removeEntity).hide();
}
}
|
# HOW PROMISES WORK
Assume, you have only promise types P, and P's can fulfill, reject and then as anticipated. Assume that fulfill(value) and reject(reason) behaves as expected, not permitting other transitions. How then, does then work? Believe it or not, like this:
```cofeescript
class P
...
then: (onFulfill, onReject) =>
new P (p2) => @state.thenP(onFulfill, onReject, p2)
```
We have three cases, when @state is pending, fulfilled, and rejected. Pending is easy, we simply remember to schedule callbacks later, for when they are fulfilled by pushing them on a stack:
```coffeescript
class PendingState
...
thenP: (onFulfill, onReject) =>
new P (p2)=> @pendings.push [onFulfill, onReject, p2]
```
For the fulfilled case, we need to run the callback, so we think ahead and consider how we intend to `resolve` the callbacks. This is accomplished by making the p2 "behave like" the value given to us, or something like
```coffeescript
class FulfilledState
...
then: (onFulfill, __) =>
new P (p2) => @enqueue =>
p2.then
```
|
<?php
namespace App\Http\Controllers\API\v1;
use App\Http\Controllers\Controller;
use App\Http\Requests\v1\StoreGoodRequest;
use App\Http\Requests\v1\UpdateGoodRequest;
use App\Http\Resources\v1\GoodResource;
use App\Jobs\GeneratePDFJob;
use App\Jobs\MergePDFsJob;
use App\Models\Good;
use App\Models\Warehouse;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class GoodController extends Controller
{
/**
* Display a listing of the resource.
*
* @param Request $request
* @return JsonResponse|AnonymousResourceCollection
*/
public function index(Request $request): JsonResponse|AnonymousResourceCollection
{
$goods = Good::query();
$orderColumn = $request->input('order_column', 'goods.id');
$orderDirection = $request->input('order_direction', 'asc');
if ($request->filled('include')) {
//Check Errors on includes
$errors = $this->checkRequestRelationshipErrors($request, Good::$relationships);
if (!empty($errors['errors'])) {
return response()->json($errors, 422);
}
$this->setRequestRelationships($request, $goods, Good::$relationships);
}
//Sort data
//Sort data
if ($orderColumn != 'warehouse_id') {
// dd('es diferente a wh');
$goods->orderBy($orderColumn, $orderDirection);
} else {
$goods->select('goods.*')
->join('warehouses', 'warehouses.id', '=', 'goods.warehouse_id')
->orderBy('warehouses.description', $orderDirection);
}
$goods->when($request->filled('search_global'), function ($query) use ($request) {
$query->where(function ($query) use ($request) {
$query->where('id', 'LIKE', '%' . $request->input('search_global') . '%')
->orWhere('code', 'LIKE', '%' . $request->input('search_global') . '%')
->orWhere('description', 'LIKE', '%' . $request->input('search_global'));
});
})
->when($request->filled('search_is_active'), function ($query) use ($request) {
$query->where('goods.is_active', $request->input('search_is_active'));
})
->when($request->filled('search_warehouse'), function ($query) use ($request) {
$query->where('goods.warehouse_id', $request->input('search_warehouse'));
})
->when($request->filled('search_id'), function ($query) use ($request) {
$query->where('goods.id', 'LIKE', '%' . $request->input('search_id') . '%');
})
->when($request->filled('search_code'), function ($query) use ($request) {
$query->where('goods.code', 'LIKE', '%' . $request->input('search_code') . '%');
})
->when($request->filled('search_description'), function ($query) use ($request) {
$query->where('goods.description', 'LIKE', '%' . $request->input('search_description') . '%');
});
return GoodResource::collection($goods->paginate(10));
}
public function list(Request $request): JsonResponse|AnonymousResourceCollection
{
$goods = Good::query();
$orderColumn = $request->input('order_column', 'goods.id');
$orderDirection = $request->input('order_direction', 'asc');
if ($request->filled('include')) {
//Check Errors on includes
$errors = $this->checkRequestRelationshipErrors($request, Good::$relationships);
if (!empty($errors['errors'])) {
return response()->json($errors, 422);
}
$this->setRequestRelationships($request, $goods, Good::$relationships);
}
//Sort data
//Sort data
if ($orderColumn != 'warehouse_id') {
// dd('es diferente a wh');
$goods->orderBy($orderColumn, $orderDirection);
} else {
$goods->select('goods.*')
->join('warehouses', 'warehouses.id', '=', 'goods.warehouse_id')
->orderBy('warehouses.description', $orderDirection);
}
$goods->when($request->filled('search_global'), function ($query) use ($request) {
$query->where(function ($query) use ($request) {
$query->where('id', 'LIKE', '%' . $request->input('search_global') . '%')
->orWhere('code', 'LIKE', '%' . $request->input('search_global') . '%')
->orWhere('description', 'LIKE', '%' . $request->input('search_global'));
});
})
->when($request->filled('search_is_active'), function ($query) use ($request) {
$query->where('goods.is_active', $request->input('search_is_active'));
})
->when($request->filled('search_warehouse'), function ($query) use ($request) {
$query->where('goods.warehouse_id', $request->input('search_warehouse'));
})
->when($request->filled('search_id'), function ($query) use ($request) {
$query->where('goods.id', 'LIKE', '%' . $request->input('search_id') . '%');
})
->when($request->filled('search_code'), function ($query) use ($request) {
$query->where('goods.code', 'LIKE', '%' . $request->input('search_code') . '%');
})
->when($request->filled('search_description'), function ($query) use ($request) {
$query->where('goods.description', 'LIKE', '%' . $request->input('search_description') . '%');
});
return GoodResource::collection($goods->get());
}
/**
* Store a newly created resource in storage.
*
* @param StoreGoodRequest $request
* @return JsonResponse
*/
public function store(StoreGoodRequest $request): JsonResponse
{
try {
DB::beginTransaction();
$good = Good::create($request->validated());
DB::commit();
return response()->json([
'data' => [
'title' => 'Good created successfully',
'product' => GoodResource::make($good)
]
], 201);
} catch (Exception $e) {
DB::rollBack();
return response()->json([
'errors' => [
'title' => 'Good creation failed',
'details' => $e->getMessage()
]
], 422);
}
}
/**
* Display the specified resource.
*
* @param Request $request
* @param Good $good
* @return GoodResource
*/
public function show(Request $request, Good $good): GoodResource
{
$this->setRequestRelationships($request, $good, Good::$relationships);
return GoodResource::make($good);
}
/**
* Update the specified resource in storage.
*
* @param UpdateGoodRequest $request
* @param Good $good
* @return JsonResponse
*/
public function update(UpdateGoodRequest $request, Good $good): JsonResponse
{
try {
DB::beginTransaction();
$good->update($request->validated());
DB::commit();
return response()->json([
'data' => [
'title' => 'Good updated successfully',
'product' => GoodResource::make($good)
]
], 201);
} catch (Exception $e) {
DB::rollBack();
return response()->json([
'errors' => [
'title' => 'Good update failed',
'details' => $e->getMessage()
]
], 422);
}
}
/**
* Remove the specified resource from storage.
*
* @param Good $good
* @return JsonResponse
*/
public function destroy(Good $good)
{
try {
DB::beginTransaction();
// $good->warehouse()->Delete();
// $good->goodsCatalog()->delete();
$good->delete();
DB::commit();
return response()->json([
'data' => [
'title' => 'Good deleted successfully'
]
], 201);
} catch (Exception $e) {
DB::rollBack();
return response()->json([
'errors' => [
'title' => 'Good delete failed',
'details' => $e->getMessage()
]
], 422);
}
}
/**
* @param Request $request
* @return JsonResponse
* @throws \Throwable
*/
public function generateReport(Request $request): JsonResponse
{
$searchWarehouseId = $request->input('search_warehouse_id');
// Construye la consulta de almacenes
$warehousesQuery = Warehouse::with(['users']);
// Si se proporciona search_warehouse_id, filtra por ese almacén
if ($searchWarehouseId) {
$warehousesQuery->where('id', $searchWarehouseId);
}
// Obtén los almacenes según la consulta
$warehouses = $warehousesQuery->get();
// generate a time value
$time = time();
$jobs = [];
$warehouses->each(function ($warehouse) use ($time, &$jobs) {
// Aquí puedes ajustar la cantidad de bienes por página
$goodsPerPage = 23; // Por ejemplo, paginación de 23 bienes por página
// obtener los bienes paginados, no los almacenes
$goods = Good::where('warehouse_id', $warehouse->id)->paginate($goodsPerPage);
$currentPage = $goods->currentPage(); // Obtén la página actual de bienes
//ciclo para generar informes PDF de bienes
while ($currentPage <= $goods->lastPage()) {
$data = [
'warehouse' => $warehouse,
'goods' => $goods,
'time' => $time
];
$jobs [] = new GeneratePDFJob($data);
// get the next page of goods
$goods = Good::where('warehouse_id', $warehouse->id)->paginate($goodsPerPage, ['*'], 'page', $currentPage + 1);
$currentPage = $goods->currentPage(); // Obtén la página actual de bienes
}
});
$batch = Bus::batch($jobs)->name('Reporte ' . $time);
$batch->add(new MergePDFsJob(['time' => $time]));
$batch = $batch->dispatch();
return response()->json([
'data' => [
'message' => 'Trabajos de informe generados correctamente',
'batch' => $batch
]
]);
}
public function downloadPDFReport(Request $request): BinaryFileResponse|JsonResponse
{
$time = $request->input('report_id');
// Verifica si el archivo PDF combinado existe
$mergedFilePath = storage_path("app/public/reports/{$time}/report_{$time}.pdf");
if (!File::exists($mergedFilePath)) {
return response()->json(['error' => 'El archivo no existe.'], 404);
}
// Define el encabezado de la respuesta para la descarga del archivo
$headers = [
'Content-Type' => 'application/pdf',
];
// Descarga el archivo PDF utilizando una BinaryFileResponse
return response()->download($mergedFilePath, "report.pdf", $headers);
}
}
|
import { useState } from "react";
function AddNewNote({onAddNote}) {
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const handelSubmit = (e) => {
e.preventDefault();
if (!title || !description) return null;
const newNote = {
title,
description,
id: Date.now(),
completed: false,
createdAt: new Date().toISOString(),
};
onAddNote(newNote);
setTitle("");
setDescription("");
};
return (
<div className="add-new-note">
<h2>Add New Note</h2>
<form
className="note-form"
onSubmit={handelSubmit}
>
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
type="text"
className="text-field"
placeholder="Note Title" />
<input
value={description}
onChange={(e) => setDescription(e.target.value)}
type="text"
className="text-field"
placeholder="Note Description" />
<button
type="submit"
className="btn btn--primary"
>
Add New Note
</button>
</form>
</div>
);
}
export default AddNewNote
|
:- use_module('../prolog/clp_term').
:- begin_tests(clp_term).
% Tests for term_indomain/2
test('term_indomain_+_+_fails', [ throws(error(uninstantiation_error(1), _)) ]) :-
term_indomain(1, all_terms).
test('term_indomain_+_-_fails', [ throws(error(uninstantiation_error(1), _)) ]) :-
term_indomain(1, _).
test('term_indomain_-_+_succeeds') :-
term_indomain(Term, all_terms),
get_attr(Term, clp_term, all_terms).
test('term_indomain_-_+_put_twice_unifies', [ fail ]) :-
term_indomain(Term, terms_from(const(1))),
term_indomain(Term, terms_to(const(2))),
\+ get_attr(Term, clp_term, [const(1), const(2)]).
test('term_indomain_-_-_succeeds') :-
put_attr(Term, clp_term, all_terms),
term_indomain(Term, Dom),
Dom == all_terms.
test('term_indomain_-_-_put_get') :-
term_indomain(Term, all_terms),
term_indomain(Term, Dom),
Dom == all_terms.
% Tests for is_term/1
test('is_term_-_get') :-
is_term(Term),
get_attr(Term, clp_term, all_terms).
test('is_term_-_already_constrained') :-
term_indomain(Term, terms_from(const(42))),
is_term(Term),
get_attr(Term, clp_term, terms_from(const(42))).
% Tests for is_empty_term/1
test('is_empty_term_-_get') :-
is_empty_term(Term),
get_attr(Term, clp_term, empty).
test('is_empty_term_-_already_constrained') :-
term_indomain(Term, terms_from(const(42))),
is_empty_term(Term),
get_attr(Term, clp_term, empty).
% Tests for is_singleton_term/1
test('is_singleton_term_-_+_c_get') :-
is_singleton_term(Term, 42),
get_attr(Term, clp_term, singleton(const(42))).
test('is_singleton_term_-_+_v_get') :-
is_singleton_term(Term, X),
get_attr(Term, clp_term, singleton(variable(X))).
test('is_singleton_term_-_+_already_constrained_c_c') :-
term_at_least(Term, 42),
is_singleton_term(Term, 43),
get_attr(Term, clp_term, singleton(const(43))).
test('is_singleton_term_-_+_already_constrained_c_c_empty') :-
term_at_least(Term, 43),
is_singleton_term(Term, 42),
is_empty_term(Term).
test('is_singleton_term_-_+_already_constrained_c_v') :-
term_at_least(Term, 42),
is_singleton_term(Term, X),
get_attr(Term, clp_term, singleton(variable(X))),
get_attr(X, clp_term, terms_from(const(42))).
test('is_singleton_term_-_+_already_constrained_v_c') :-
term_at_least(Term, X),
is_singleton_term(Term, 42),
get_attr(Term, clp_term, singleton(const(42))),
get_attr(X, clp_term, terms_to(const(42))).
test('is_singleton_term_-_+_already_constrained_v_v') :-
term_at_least(Term, X),
is_singleton_term(Term, Y),
get_attr(Term, clp_term, singleton(variable(Y))),
get_attr(X, clp_term, terms_to(variable(Y))),
get_attr(Y, clp_term, terms_from(variable(X))).
% Tests for term_at_least/2
test('term_at_least_-_+') :-
term_at_least(Term, x),
get_attr(Term, clp_term, terms_from(const(x))).
test('term_at_least_-_-') :-
term_at_least(Term, X),
get_attr(Term, clp_term, terms_from(variable(X))).
test('term_at_least_-_+_already_constrained', [ fail ]) :-
term_at_least(Term, x),
term_at_least(Term, y),
\+ get_attr(Term, clp_term, terms_from(const(y))).
% Tests for term_at_most/2
test('term_at_most_-_+') :-
term_at_most(Term, y),
get_attr(Term, clp_term, terms_to(const(y))).
test('term_at_most_-_-') :-
term_at_most(Term, Y),
get_attr(Term, clp_term, terms_to(variable(Y))).
test('term_at_most_-_+_already_constrained', [ fail ]) :-
term_at_most(Term, y),
term_at_most(Term, x),
\+ get_attr(Term, clp_term, terms_to(const(x))).
% Tests for term_normalized/2
test('term_normalized_c_c') :-
clp_term:term_normalized(const(a), const(a)).
test('term_normalized_c_-') :-
clp_term:term_normalized(const(a), Term),
Term == const(a).
test('term_normalized_v_c') :-
X = a,
clp_term:term_normalized(variable(X), const(a)).
test('term_normalized_v_-') :-
X = a,
clp_term:term_normalized(variable(X), Term),
Term == const(a).
test('term_normalized_v_v') :-
clp_term:term_normalized(variable(X), variable(X)).
test('term_normalized_v_v_-') :-
clp_term:term_normalized(variable(X), Term),
Term == variable(X).
test('term_normalized_uninst_const_-_+', [ throws(error(instantiation_error(X), _)) ]) :-
clp_term:term_normalized(X, const(a)).
test('term_normalized_uninst_var_-_+', [ throws(error(instantiation_error(X), _)) ]) :-
clp_term:term_normalized(X, variable(_)).
test('term_normalized_uninst_-_-', [ throws(error(instantiation_error(X), _)) ]) :-
clp_term:term_normalized(X, _).
test('term_normalized_naked_const_+_+', [ fail ]) :-
clp_term:term_normalized(a, a).
test('term_normalized_unknown_functor_1st_+_+', [ fail ]) :-
clp_term:term_normalized(foo(_), variable(_)).
test('term_normalized_unknown_functor_2nd_+_+', [ fail ]) :-
clp_term:term_normalized(variable(_), foo(_)).
test('term_normalized_unknown_functor_1st_+_-', [ fail ]) :-
clp_term:term_normalized(foo(_), Y),
Y = variable(_).
test('term_normalized_unknown_functor_2nd_+_-', [ fail ]) :-
clp_term:term_normalized(variable(_), Y),
Y = foo(_).
test('term_normalized_naked_const_+_-', [ fail ]) :-
clp_term:term_normalized(a, _).
% Tests for dom_normalized/2
test('dom_normalized_empty_empty_+_+') :-
clp_term:dom_normalized(empty, empty).
test('dom_normalized_empty_empty_+_-') :-
clp_term:dom_normalized(empty, Dom),
Dom == empty.
test('dom_normalized_all_terms_+_+') :-
clp_term:dom_normalized(all_terms, all_terms).
test('dom_normalized_all_terms_+_-') :-
clp_term:dom_normalized(all_terms, Dom),
Dom == all_terms.
test('dom_normalized_terms_from_+_+_c') :-
Term0 = const(a),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_from(Term0), terms_from(Term)).
test('dom_normalized_terms_from_+_+_v') :-
Term0 = variable(_),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_from(Term0), terms_from(Term)).
test('dom_normalized_terms_from_+_+_v_to_c') :-
X = a,
Term0 = variable(X),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_from(Term0), terms_from(Term)).
test('dom_normalized_terms_from_+_-_c') :-
Term0 = const(a),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_from(Term0), Dom),
Dom == terms_from(Term).
test('dom_normalized_terms_from_+_-_v') :-
Term0 = variable(_),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_from(Term0), Dom),
Dom == terms_from(Term).
test('dom_normalized_terms_from_+_-_v_to_c') :-
X = a,
Term0 = variable(X),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_from(Term0), Dom),
Dom == terms_from(Term).
test('dom_normalized_terms_to_+_+_c') :-
Term0 = const(a),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_to(Term0), terms_to(Term)).
test('dom_normalized_terms_to_+_+_v') :-
Term0 = variable(_),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_to(Term0), terms_to(Term)).
test('dom_normalized_terms_to_+_+_v_to_c') :-
X = a,
Term0 = variable(X),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_to(Term0), terms_to(Term)).
test('dom_normalized_terms_to_+_-_c') :-
Term0 = const(a),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_to(Term0), Dom),
Dom == terms_to(Term).
test('dom_normalized_terms_to_+_-_v') :-
Term0 = variable(_),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_to(Term0), Dom),
Dom == terms_to(Term).
test('dom_normalized_terms_to_+_-_v_to_c') :-
X = a,
Term0 = variable(X),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(terms_to(Term0), Dom),
Dom == terms_to(Term).
test('dom_normalized_singleton_+_+_c') :-
Term0 = const(a),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(singleton(Term0), singleton(Term)).
test('dom_normalized_singleton_+_+_v') :-
Term0 = variable(_),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(singleton(Term0), singleton(Term)).
test('dom_normalized_singleton_+_+_v_to_c') :-
X = a,
Term0 = variable(X),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(singleton(Term0), singleton(Term)).
test('dom_normalized_singleton_+_-_c') :-
Term0 = const(a),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(singleton(Term0), Dom),
Dom == singleton(Term).
test('dom_normalized_singleton_+_-_v') :-
Term0 = variable(_),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(singleton(Term0), Dom),
Dom == singleton(Term).
test('dom_normalized_singleton_+_-_v_to_c') :-
X = a,
Term0 = variable(X),
clp_term:term_normalized(Term0, Term),
clp_term:dom_normalized(singleton(Term0), Dom),
Dom == singleton(Term).
test('dom_normalized_interval_+_+_c_c') :-
TermX0 = const(a),
TermY0 = const(b),
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], [TermX, TermY]).
test('dom_normalized_interval_+_+_c_v') :-
TermX0 = const(a),
TermY0 = variable(_),
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], [TermX, TermY]).
test('dom_normalized_interval_+_+_v_c') :-
TermX0 = variable(_),
TermY0 = const(b),
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], [TermX, TermY]).
test('dom_normalized_interval_+_+_v_v') :-
TermX0 = variable(_),
TermY0 = variable(_),
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], [TermX, TermY]).
test('dom_normalized_interval_+_+_v_v2c') :-
TermX0 = variable(_),
TermY0 = variable(Y),
Y = b,
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], [TermX, TermY]).
test('dom_normalized_interval_+_+_v2c_v') :-
TermX0 = variable(X),
TermY0 = variable(_),
X = a,
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], [TermX, TermY]).
test('dom_normalized_interval_+_+_v2c_v2c') :-
TermX0 = variable(X),
TermY0 = variable(Y),
X = a,
Y = b,
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], [TermX, TermY]).
test('dom_normalized_interval_+_-_c_c') :-
TermX0 = const(a),
TermY0 = const(b),
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], Dom),
Dom == [TermX, TermY].
test('dom_normalized_interval_+_-_c_v') :-
TermX0 = const(a),
TermY0 = variable(_),
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], Dom),
Dom == [TermX, TermY].
test('dom_normalized_interval_+_-_v_c') :-
TermX0 = variable(_),
TermY0 = const(b),
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], Dom),
Dom == [TermX, TermY].
test('dom_normalized_interval_+_-_v_v') :-
TermX0 = variable(_),
TermY0 = variable(_),
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], Dom),
Dom == [TermX, TermY].
test('dom_normalized_interval_+_-_v_v2c') :-
TermX0 = variable(_),
TermY0 = variable(Y),
Y = b,
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], Dom),
Dom == [TermX, TermY].
test('dom_normalized_interval_+_-_v2c_v') :-
TermX0 = variable(X),
TermY0 = variable(_),
X = a,
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], Dom),
Dom == [TermX, TermY].
test('dom_normalized_interval_+_-_v2c_v2c') :-
TermX0 = variable(X),
TermY0 = variable(Y),
X = a,
Y = b,
clp_term:term_normalized(TermX0, TermX),
clp_term:term_normalized(TermY0, TermY),
clp_term:dom_normalized([TermX0, TermY0], Dom),
Dom == [TermX, TermY].
test('dom_normalized_interval_+_+_c_c_sing') :-
clp_term:dom_normalized([const(a), const(a)], singleton(const(a))).
test('dom_normalized_interval_+_+_c_v2c_sing') :-
Y = a,
clp_term:dom_normalized([const(a), variable(Y)], singleton(const(a))).
test('dom_normalized_interval_+_+_v2c_c_sing') :-
X = a,
clp_term:dom_normalized([variable(X), const(a)], singleton(const(a))).
test('dom_normalized_interval_+_+_v2c_v2c_sing') :-
X = a, Y = a,
clp_term:dom_normalized([variable(X), variable(Y)], singleton(const(a))).
test('dom_normalized_interval_+_+_v_v_eq_sing') :-
X = Y,
clp_term:dom_normalized([variable(X), variable(Y)], singleton(variable(X))).
test('dom_normalized_interval_+_-_c_c_sing') :-
clp_term:dom_normalized([const(a), const(a)], Dom),
Dom = singleton(const(a)).
test('dom_normalized_interval_+_-_c_v2c_sing') :-
Y = a,
clp_term:dom_normalized([const(a), variable(Y)], Dom),
Dom = singleton(const(a)).
test('dom_normalized_interval_+_-_v2c_c_sing') :-
X = a,
clp_term:dom_normalized([variable(X), const(a)], Dom),
Dom = singleton(const(a)).
test('dom_normalized_interval_+_-_v2c_v2c_sing') :-
X = a, Y = a,
clp_term:dom_normalized([variable(X), variable(Y)], Dom),
Dom = singleton(const(a)).
test('dom_normalized_interval_+_-_v_v_eq_sing') :-
X = Y,
clp_term:dom_normalized([variable(X), variable(Y)], Dom),
Dom = singleton(variable(X)).
test('dom_normalized_+_+_unknown_functor_1st', [ fail ]) :-
X = a,
clp_term:dom_normalized(foo(variable(X)), terms_from(const(a))).
test('dom_normalized_+_+_unknown_functor_2nd', [ fail ]) :-
X = a,
clp_term:dom_normalized(terms_from(variable(X)), foo(const(a))).
test('dom_normalized_+_+_functors_dont_match', [ fail ]) :-
X = a,
clp_term:dom_normalized(terms_from(variable(X)), terms_to(const(a))).
test('dom_normalized_+_+_uninstantiated_endpoint', [ throws(error(instantiation_error(X), _)) ]) :-
clp_term:dom_normalized(terms_from(X), terms_from(const(a))).
test('dom_normalized_-_+_uninstantiated_1st', [ fail ]) :-
clp_term:dom_normalized(_, all_terms).
test('dom_normalized_+_-_unknown_functor_1st', [ fail ]) :-
X = a,
clp_term:dom_normalized(foo(variable(X)), _).
test('dom_normalized_+_-_unknown_functor_2nd', [ fail ]) :-
X = a,
clp_term:dom_normalized(terms_from(variable(X)), Y),
Y = foo(const(a)).
test('dom_normalized_+_-_functors_dont_match', [ fail ]) :-
X = a,
clp_term:dom_normalized(terms_from(variable(X)), Y),
Y = terms_to(const(a)).
test('dom_normalized_+_-_uninstantiated_endpoint', [ throws(error(instantiation_error(X), _)) ]) :-
clp_term:dom_normalized(terms_from(X), Y),
Y = terms_from(const(a)).
% Tests for terms_intersection_from_from/3
test('terms_from_from_intersection_c_c_>=') :-
setof(I, clp_term:terms_intersection_from_from(terms_from(const(y)), terms_from(const(x)), I), [terms_from(const(y))]).
test('terms_from_from_intersection_c_c_<') :-
setof(I, clp_term:terms_intersection_from_from(terms_from(const(x)), terms_from(const(y)), I), [terms_from(const(y))]).
test('terms_from_from_intersection_c_v') :-
setof(Y-I, clp_term:terms_intersection_from_from(terms_from(const(x)), terms_from(variable(Y)), I), Ans),
Ans = [Y-terms_from(variable(Y)), Y-terms_from(const(x))].
test('terms_from_from_intersection_v_c') :-
setof(X-I, clp_term:terms_intersection_from_from(terms_from(variable(X)), terms_from(const(y)), I), Ans),
Ans = [X-terms_from(const(y)), X-terms_from(variable(X))].
test('terms_from_from_intersection_v_v') :-
setof(X-Y-I, clp_term:terms_intersection_from_from(terms_from(variable(X)), terms_from(variable(Y)), I), Ans),
Ans = [X-Y-terms_from(variable(X)), X-Y-terms_from(variable(Y))].
% Tests for terms_intersection_to_to/3
test('terms_to_to_intersection_c_c_>=') :-
setof(I, clp_term:terms_intersection_to_to(terms_to(const(y)), terms_to(const(x)), I), [terms_to(const(x))]).
test('terms_to_to_intersection_c_c_<') :-
setof(I, clp_term:terms_intersection_to_to(terms_to(const(x)), terms_to(const(y)), I), [terms_to(const(x))]).
test('terms_to_to_intersection_c_v') :-
setof(Y-I, clp_term:terms_intersection_to_to(terms_to(const(x)), terms_to(variable(Y)), I), Ans),
Ans = [Y-terms_to(variable(Y)), Y-terms_to(const(x))].
test('terms_to_to_intersection_v_c') :-
setof(X-I, clp_term:terms_intersection_to_to(terms_to(variable(X)), terms_to(const(y)), I), Ans),
Ans = [X-terms_to(const(y)), X-terms_to(variable(X))].
test('terms_to_to_intersection_v_v') :-
setof(X-Y-I, clp_term:terms_intersection_to_to(terms_to(variable(X)), terms_to(variable(Y)), I), Ans),
Ans = [X-Y-terms_to(variable(X)), X-Y-terms_to(variable(Y))].
% Tests for terms_intersection_from_to/3
test('terms_from_to_intersection_c_c_=') :-
setof(I, clp_term:terms_intersection_from_to(terms_from(const(x)), terms_to(const(x)), I), [singleton(const(x))]).
test('terms_from_to_intersection_c_c_<') :-
setof(I, clp_term:terms_intersection_from_to(terms_from(const(x)), terms_to(const(y)), I), [[const(x), const(y)]]).
test('terms_from_to_intersection_c_c_>') :-
setof(I, clp_term:terms_intersection_from_to(terms_from(const(y)), terms_to(const(x)), I), [empty]).
test('terms_from_to_intersection_c_v') :-
setof(Y-I, clp_term:terms_intersection_from_to(terms_from(const(x)), terms_to(variable(Y)), I), Ans),
Ans = [Y-empty, Y-[const(x), variable(Y)], Y-singleton(const(x))].
test('terms_from_to_intersection_c_v_unified') :-
setof(Y, clp_term:terms_intersection_from_to(terms_from(const(x)), terms_to(variable(Y)), singleton(const(x))), [Y1]),
Y1 == x.
test('terms_from_to_intersection_v_c') :-
setof(X-I, clp_term:terms_intersection_from_to(terms_from(variable(X)), terms_to(const(y)), I), Ans),
Ans = [X-empty, X-[variable(X), const(y)], X-singleton(const(y))].
test('terms_from_to_intersection_v_c_unified') :-
setof(X, clp_term:terms_intersection_from_to(terms_from(variable(X)), terms_to(const(y)), singleton(const(y))), [X1]),
X1 == y.
test('terms_from_to_intersection_v_v') :-
setof(X-Y-I, clp_term:terms_intersection_from_to(terms_from(variable(X)), terms_to(variable(Y)), I), Ans),
Ans = [X-Y-empty, X-Y-[variable(X), variable(Y)], X-Y-singleton(variable(X))].
test('terms_from_to_intersection_v_v_unified') :-
setof(X-Y, clp_term:terms_intersection_from_to(terms_from(variable(X)), terms_to(variable(Y)), singleton(variable(X))), [X1-Y1]),
X1 == Y1.
test('terms_from_to_intersection_v_v_not_interval_if_identical', [ fail ]) :-
X = Y,
clp_term:terms_intersection_from_to(terms_from(variable(X)), terms_to(variable(Y)), [variable(X), variable(Y)]).
% Tests for terms_intersection_to_from/3
test('terms_to_from_intersection_agrees_with_from_to') :-
setof(X-Y-ToFrom, clp_term:terms_intersection_to_from(terms_to(variable(X)), terms_from(variable(Y)), ToFrom), ToFroms),
setof(X-Y-FromTo, clp_term:terms_intersection_from_to(terms_from(variable(Y)), terms_to(variable(X)), FromTo), ToFroms).
% Tests for terms_intersection_from_int/3
% | x R y | x R z | Out |
% | ? | ? | [y, z]; [x, z]; [z]; [] |
% | ? | < | [y, z]; [x, z] |
% | ? | = | [z] |
% | ? | > | [] |
% | < | ? | [y,z] |
% | < | < | [y,z] |
% | = | < | [y,z] |
% | > | ? | [x,z]; [z]; [] |
% | > | < | [x,z] |
% | > | = | [z] |
% | > | > | [] |
test('terms_from_int_intersection_?_?') :-
setof(Y-Z-I, clp_term:terms_intersection_from_int(terms_from(const(a)), [variable(Y), variable(Z)], I), Ans),
Ans = [Y-Z-empty, Y-Z-singleton(const(a)), Y-Z-[const(a), variable(Z)], Y-Z-[variable(Y), variable(Z)]].
test('terms_from_int_intersection_?_?_unified') :-
setof(Z, clp_term:terms_intersection_from_int(terms_from(const(a)), [variable(_), variable(Z)], singleton(const(a))), [Z1]),
Z1 == a.
test('terms_from_int_intersection_?_<') :-
setof(Y-I, clp_term:terms_intersection_from_int(terms_from(const(a)), [variable(Y), const(c)], I), Ans),
Ans = [Y-[const(a), const(c)], Y-[variable(Y), const(c)]].
test('terms_from_int_intersection_?_=') :-
clp_term:terms_intersection_from_int(terms_from(const(a)), [variable(_), const(a)], singleton(const(a))).
test('terms_from_int_intersection_?_>') :-
clp_term:terms_intersection_from_int(terms_from(const(b)), [variable(_), const(a)], empty).
test('terms_from_int_intersection_<_?') :-
clp_term:terms_intersection_from_int(terms_from(const(a)), [const(b), variable(Z)], [const(b), variable(Z)]).
test('terms_from_int_intersection_<_<') :-
clp_term:terms_intersection_from_int(terms_from(const(a)), [const(b), const(c)], [const(b), const(c)]).
test('terms_from_int_intersection_=_<') :-
clp_term:terms_intersection_from_int(terms_from(const(a)), [const(a), const(b)], [const(a), const(b)]).
test('terms_from_int_intersection_>_?') :-
setof(Z-I, clp_term:terms_intersection_from_int(terms_from(const(b)), [const(a), variable(Z)], I), Ans),
Ans = [Z-empty, Z-[const(b), variable(Z)], Z-singleton(const(b))].
test('terms_from_int_intersection_>_?_unified') :-
setof(Z, clp_term:terms_intersection_from_int(terms_from(const(b)), [const(a), variable(Z)], singleton(const(b))), [Z1]),
Z1 == b.
test('terms_from_int_intersection_>_<') :-
clp_term:terms_intersection_from_int(terms_from(const(b)), [const(a), const(c)], [const(b), const(c)]).
test('terms_from_int_intersection_>_=') :-
clp_term:terms_intersection_from_int(terms_from(const(b)), [const(a), const(b)], singleton(const(b))).
test('terms_from_int_intersection_>_>') :-
clp_term:terms_intersection_from_int(terms_from(const(c)), [const(a), const(b)], empty).
% Tests for terms_intersection_int_from/3
test('terms_int_from_intersection_agrees_with_from_int', [ fail ]) :-
member(X, [const(1), variable(_)]),
member(Y, [const(3), variable(_)]),
member(Z, [const(2), variable(_)]),
setof(X-Y-Z-IntFrom, clp_term:terms_intersection_int_from([X, Y], terms_from(Z), IntFrom), IntFroms),
\+ setof(X-Y-Z-FromInt, clp_term:terms_intersection_from_int(terms_from(Z), [X, Y], FromInt), IntFroms).
% Tests for terms_intersection_to_int/3
% | x R y | x R z | Out |
% | ? | ? | [y,z]; [y,x]; [y]; [] |
% | ? | < | [y,x]; [y]; [] |
% | ? | = | [y,z] |
% | ? | > | [y,z] |
% | < | ? | [] |
% | < | < | [] |
% | = | < | [y] |
% | = | ? | [y] |
% | > | ? | [y,x]; [y,z] |
% | > | < | [y,x] |
% | > | = | [y,z] |
% | > | > | [y,z] |
test('terms_to_int_intersection_?_?') :-
setof(Y-Z-I, clp_term:terms_intersection_to_int(terms_to(const(a)), [variable(Y), variable(Z)], I), Ans),
Ans = [Y-Z-empty, Y-Z-[variable(Y), const(a)], Y-Z-[variable(Y), variable(Z)], Y-Z-singleton(const(a))].
test('terms_to_int_intersection_?_?_unified') :-
setof(Y, clp_term:terms_intersection_to_int(terms_to(const(a)), [variable(Y), variable(_)], singleton(const(a))), [Y1]),
Y1 == a.
test('terms_to_int_intersection_?_<') :-
setof(Y-I, clp_term:terms_intersection_to_int(terms_to(const(a)), [variable(Y), const(c)], I), Ans),
Ans = [Y-empty, Y-[variable(Y), const(a)], Y-singleton(const(a))].
test('terms_to_int_intersection_?_<_unified') :-
setof(Y, clp_term:terms_intersection_to_int(terms_to(const(a)), [variable(Y), const(c)], singleton(const(a))), [Y1]),
Y1 == a.
test('terms_to_int_intersection_?_=') :-
clp_term:terms_intersection_to_int(terms_to(const(a)), [variable(Y), const(a)], [variable(Y), const(a)]).
test('terms_to_int_intersection_?_>') :-
clp_term:terms_intersection_to_int(terms_to(const(b)), [variable(Y), const(a)], [variable(Y), const(a)]).
test('terms_to_int_intersection_<_?') :-
clp_term:terms_intersection_to_int(terms_to(const(a)), [const(b), variable(_)], empty).
test('terms_to_int_intersection_<_<') :-
clp_term:terms_intersection_to_int(terms_to(const(a)), [const(b), const(c)], empty).
test('terms_to_int_intersection_=_<') :-
clp_term:terms_intersection_to_int(terms_to(const(a)), [const(a), const(b)], singleton(const(a))).
test('terms_to_int_intersection_=_?') :-
clp_term:terms_intersection_to_int(terms_to(const(a)), [const(a), variable(_)], singleton(const(a))).
test('terms_to_int_intersection_>_?') :-
setof(Z-I, clp_term:terms_intersection_to_int(terms_to(const(b)), [const(a), variable(Z)], I), Ans),
Ans = [Z-[const(a), variable(Z)], Z-[const(a), const(b)]].
test('terms_to_int_intersection_>_<') :-
clp_term:terms_intersection_to_int(terms_to(const(b)), [const(a), const(c)], [const(a), const(b)]).
test('terms_to_int_intersection_>_=') :-
clp_term:terms_intersection_to_int(terms_to(const(b)), [const(a), const(b)], [const(a), const(b)]).
test('terms_to_int_intersection_>_>') :-
clp_term:terms_intersection_to_int(terms_to(const(c)), [const(a), const(b)], [const(a), const(b)]).
% Tests for terms_intersection_int_to/3
test('terms_int_to_intersection_agrees_with_to_int', [ fail ]) :-
member(X, [const(1), variable(_)]),
member(Y, [const(3), variable(_)]),
member(Z, [const(2), variable(_)]),
setof(X-Y-Z-IntTo, clp_term:terms_intersection_int_to([X, Y], terms_to(Z), IntTo), IntTos),
\+ setof(X-Y-Z-ToInt, clp_term:terms_intersection_to_int(terms_to(Z), [X, Y], ToInt), IntTos).
% Tests for terms_intersection_int_int/3
% | xRz | xRw | yRz | yRw | Out | Analysis
% | | | < | | empty | [xy][zw]
% | | > | | | empty | [zw][xy]
% | | | = | | [y] | [x[y]w]
% | | = | | | [x] | [z[x]y]
test('terms_int_int_intersection_y<z') :-
clp_term:terms_intersection_int_int([variable(_), const(b)], [const(c), variable(_)], empty).
test('terms_int_int_intersection_x>w') :-
clp_term:terms_intersection_int_int([const(b), variable(_)], [variable(_), const(a)], empty).
test('terms_int_int_intersection_y=z') :-
clp_term:terms_intersection_int_int([variable(_), const(b)], [const(b), variable(_)], singleton(const(b))).
test('terms_int_int_intersection_x=w') :-
clp_term:terms_intersection_int_int([const(a), variable(_)], [variable(_), const(a)], singleton(const(a))).
% | xRz | xRw | yRz | yRw | Out | Analysis
% | < | < | > | < | [z,y] | [x[zy]w]
% | < | < | > | = | [z,y] | [x[zy]y]
% | < | < | > | > | [z,w] | [x[zw]y]
test('terms_int_int_intersection_<_<_>_<') :-
clp_term:terms_intersection_int_int([const(a), const(c)], [const(b), const(d)], [const(b), const(c)]).
test('terms_int_int_intersection_<_<_>_=') :-
clp_term:terms_intersection_int_int([const(a), const(c)], [const(b), const(c)], [const(b), const(c)]).
test('terms_int_int_intersection_<_<_>_>') :-
clp_term:terms_intersection_int_int([const(a), const(d)], [const(b), const(c)], [const(b), const(c)]).
% | xRz | xRw | yRz | yRw | Out | Analysis
% | < | < | ? | ? | [z,w]; [z,y]; [z]; empty | [x[zw]y] or [x[zy]w] or [xy][zw]
test('terms_int_int_intersection_<_<_?_?') :-
setof(Y-I, clp_term:terms_intersection_int_int([const(a), variable(Y)], [const(b), const(c)], I), Ans),
Ans = [Y-empty, Y-[const(b), variable(Y)], Y-[const(b), const(c)], Y-singleton(const(b))].
test('terms_int_int_intersection_<_<_?_?_unified') :-
setof(Y, clp_term:terms_intersection_int_int([const(a), variable(Y)], [const(b), const(c)], singleton(const(b))), [Y1]),
Y1 == b.
% | xRz | xRw | yRz | yRw | Out | Analysis
% | < | ? | > | ? | [z,w]; [z,y] | [x[zw]y] or [x[zy]w]
test('terms_int_int_intersection_<_?_>_?') :-
setof(W-I, clp_term:terms_intersection_int_int([const(a), const(c)], [const(b), variable(W)], I), Ans),
Ans = [W-[const(b), const(c)], W-[const(b), variable(W)]].
% | xRz | xRw | yRz | yRw | Out | Analysis
% | < | ? | ? | ? | [z,w]; [z,y]; [y]; empty | [x[zw]y] or [x[zy]w] or [xy][zw]
test('terms_int_int_intersection_<_?_?_?') :-
setof(Y-W-I, clp_term:terms_intersection_int_int([const(a), variable(Y)], [const(c), variable(W)], I), Ans),
Ans = [Y-W-empty, Y-W-[const(c), variable(Y)], Y-W-[const(c), variable(W)], Y-W-singleton(const(c))].
test('terms_int_int_intersection_<_?_?_?_unified') :-
setof(Y, clp_term:terms_intersection_int_int([const(a), variable(Y)], [const(c), variable(_)], singleton(const(c))), [Y1]),
Y1 == c.
% | xRz | xRw | yRz | yRw | Out | Analysis
% | = | < | > | < | [z,y] | [[zy]w]
% | = | < | > | = | [z,y] | [[zy]y]
% | = | < | > | > | [z,w] | [[zw]y]
test('terms_int_int_intersection_=_<_>_<') :-
clp_term:terms_intersection_int_int([const(a), const(b)], [const(a), const(d)], [const(a), const(b)]).
test('terms_int_int_intersection_=_<_>_=') :-
clp_term:terms_intersection_int_int([const(a), const(d)], [const(a), const(d)], [const(a), const(d)]).
test('terms_int_int_intersection_=_<_>_>') :-
clp_term:terms_intersection_int_int([const(a), const(d)], [const(a), const(c)], [const(a), const(c)]).
% | xRz | xRw | yRz | yRw | Out | Analysis
% | = | < | ? | ? | [z,w]; [z,y] | [[zw]y] or [[zy]w]
test('terms_int_int_intersection_=_<_?_?') :-
setof(Y-I, clp_term:terms_intersection_int_int([const(a), variable(Y)], [const(a), const(d)], I), Ans),
Ans = [Y-[const(a), variable(Y)], Y-[const(a), const(d)]].
% | xRz | xRw | yRz | yRw | Out | Analysis
% | = | ? | > | ? | [z,w]; [z,y] | [[zw]y] or [[zy]w]
test('terms_int_int_intersection_=_?_>_?') :-
setof(W-I, clp_term:terms_intersection_int_int([const(a), const(b)], [const(a), variable(W)], I), Ans),
Ans = [W-[const(a), const(b)], W-[const(a), variable(W)]].
% | xRz | xRw | yRz | yRw | Out | Analysis
% | = | ? | ? | ? | [z,w]; [z,y] | [[zw]y] or [[zy]w]
test('terms_int_int_intersection_=_?_?_?') :-
setof(Y-W-I, clp_term:terms_intersection_int_int([const(a), variable(Y)], [const(a), variable(W)], I), Ans),
Ans = [Y-W-[const(a), variable(Y)], Y-W-[const(a), variable(W)]].
% | xRz | xRw | yRz | yRw | Out | Analysis
% | > | < | > | < | [x,y] | [z[xy]w]
% | > | < | > | = | [x,y] | [z[xy]y]
% | > | < | > | > | [x,w] | [z[xw]y]
test('terms_int_int_intersection_>_<_>_<') :-
clp_term:terms_intersection_int_int([const(b), const(c)], [const(a), const(d)], [const(b), const(c)]).
test('terms_int_int_intersection_>_<_>_=') :-
clp_term:terms_intersection_int_int([const(b), const(c)], [const(a), const(c)], [const(b), const(c)]).
test('terms_int_int_intersection_>_<_>_>') :-
clp_term:terms_intersection_int_int([const(b), const(d)], [const(a), const(c)], [const(b), const(c)]).
% | xRz | xRw | yRz | yRw | Out | Analysis
% | > | < | ? | ? | [x,w]; [x,y] | [z[xw]y] or [z[xy]w]
test('terms_int_int_intersection_>_<_?_?') :-
setof(Y-I, clp_term:terms_intersection_int_int([const(c), variable(Y)], [const(a), const(d)], I), Ans),
Ans = [Y-[const(c), variable(Y)], Y-[const(c), const(d)]].
% | xRz | xRw | yRz | yRw | Out | Analysis
% | > | ? | > | ? | [x,w]; [x,y]; [x]; empty | [z[xw]y] or [z[xy]w] or [zw][xy]
test('terms_int_int_intersection_>_?_>_?') :-
setof(W-I, clp_term:terms_intersection_int_int([const(b), const(c)], [const(a), variable(W)], I), Ans),
Ans = [W-empty, W-[const(b), const(c)], W-[const(b), variable(W)], W-singleton(const(b))].
test('terms_int_int_intersection_>_?_>_?_unified') :-
setof(W, clp_term:terms_intersection_int_int([const(b), const(c)], [const(a), variable(W)], singleton(const(b))), [W1]),
W1 == b.
% | xRz | xRw | yRz | yRw | Out | Analysis
% | > | ? | ? | ? | [x,w]; [x,y]; [x]; empty | [z[xw]y] or [z[xy]w] or [zw][xy]
test('terms_int_int_intersection_>_?_?_?') :-
setof(Y-W-I, clp_term:terms_intersection_int_int([const(c), variable(Y)], [const(a), variable(W)], I), Ans),
Ans = [Y-W-empty, Y-W-singleton(const(c)), Y-W-[const(c), variable(Y)], Y-W-[const(c), variable(W)]].
test('terms_int_int_intersection_>_?_?_?_unified') :-
setof(W, clp_term:terms_intersection_int_int([const(c), variable(_)], [const(a), variable(W)], singleton(const(c))), [W1]),
W1 == c.
% | xRz | xRw | yRz | yRw | Out | Analysis
% | ? | < | ? | < | [z,y]; [x,y]; [y]; empty | [z[xy]w] or [x[zy]w] or [xy][zw]
% | ? | < | ? | = | [z,y]; [x,y] | [z[xy]] or [x[zy]]
% | ? | < | ? | > | [z,w]; [x,w] | [z[xw]y] or [x[zw]y]
% | ? | < | ? | ? | [z,w]; [x,w]; [z,y]; |
% | [x,y]; [y]; empty |
test('terms_int_int_intersection_?_<_?_<') :-
setof(Z-I, clp_term:terms_intersection_int_int([const(a), const(b)], [variable(Z), const(d)], I), Ans),
Ans = [Z-empty, Z-[const(a), const(b)], Z-[variable(Z), const(b)], Z-singleton(const(b))].
test('terms_int_int_intersection_?_<_?_<_unified') :-
setof(Z, clp_term:terms_intersection_int_int([const(a), const(b)], [variable(Z), const(d)], singleton(const(b))), [Z1]),
Z1 == b.
test('terms_int_int_intersection_?_<_?_=') :-
setof(Z-I, clp_term:terms_intersection_int_int([const(a), const(b)], [variable(Z), const(b)], I), Ans),
Ans = [Z-[const(a), const(b)], Z-[variable(Z), const(b)]].
test('terms_int_int_intersection_?_<_?_>') :-
setof(Z-I, clp_term:terms_intersection_int_int([const(a), const(c)], [variable(Z), const(b)], I), Ans),
Ans = [Z-[const(a), const(b)], Z-[variable(Z), const(b)]].
test('terms_int_int_intersection_?_<_?_?') :-
setof(Y-Z-I, clp_term:terms_intersection_int_int([const(a), variable(Y)], [variable(Z), const(b)], I), Ans),
Ans = [Y-Z-empty, Y-Z-singleton(variable(Y)), Y-Z-[const(a), variable(Y)], Y-Z-[variable(Z), variable(Y)],
Y-Z-[const(a), const(b)], Y-Z-[variable(Z), const(b)]].
test('terms_int_int_intersection_?_<_?_?_v') :-
setof(Y-Z, clp_term:terms_intersection_int_int([const(a), variable(Y)], [variable(Z), const(b)], singleton(variable(Y))), [Y1-Z1]),
Y1 == Z1.
% | xRz | xRw | yRz | yRw | Out | Analysis
% | ? | ? | > | < | [z,y]; [x,y] | [x[zy]w] or [z[xy]w]
% | ? | ? | > | = | [z,y]; [x,y] | [x[zy]] or [z[xy]]
% | ? | ? | > | > | [z,w]; [x,w]; [x]; empty | [x[zw]y] or [z[xw]y] or [zw][xy]
% | ? | ? | > | ? | [z,w]; [x,w]; [z,y]; |
% | [x,y]; [x]; empty |
test('terms_int_int_intersection_?_?_>_<') :-
setof(X-I, clp_term:terms_intersection_int_int([variable(X), const(c)], [const(b), const(d)], I), Ans),
Ans = [X-[variable(X), const(c)], X-[const(b), const(c)]].
test('terms_int_int_intersection_?_?_>_=') :-
setof(X-I, clp_term:terms_intersection_int_int([variable(X), const(c)], [const(b), const(c)], I), Ans),
Ans = [X-[variable(X), const(c)], X-[const(b), const(c)]].
test('terms_int_int_intersection_?_?_>_>') :-
setof(X-I, clp_term:terms_intersection_int_int([variable(X), const(d)], [const(b), const(c)], I), Ans),
Ans = [X-empty, X-[variable(X), const(c)], X-[const(b), const(c)], X-singleton(const(c))].
test('terms_int_int_intersection_?_?_>_>_X==c') :-
setof(X, clp_term:terms_intersection_int_int([variable(X), const(d)], [const(b), const(c)], singleton(const(c))), [X1]),
X1 == c.
test('terms_int_int_intersection_?_?_>_?') :-
setof(X-W-I, clp_term:terms_intersection_int_int([variable(X), const(c)], [const(b), variable(W)], I), Ans),
Ans = [X-W-empty, X-W-singleton(variable(X)), X-W-[variable(X), const(c)], X-W-[const(b), const(c)],
X-W-[variable(X), variable(W)], X-W-[const(b), variable(W)]].
test('terms_int_int_intersection_?_?_>_?_v') :-
setof(X-W, clp_term:terms_intersection_int_int([variable(X), const(c)], [const(b), variable(W)], singleton(variable(X))), [X1-W1]),
X1 == W1.
% | xRz | xRw | yRz | yRw | Out | Analysis
% | ? | ? | ? | < | [x,y]; [z,y]; [y]; empty | [z[xy]w] or [x[zy]w] or [xy][zw]
% | ? | ? | ? | = | [x,y]; [z,y] | [x[zy]] or [z[xy]]
% | ? | ? | ? | > | [z,w]; [x,w]; [x]; empty | [x[zw]y] or [z[xw]y] or [zw][xy]
% | ? | ? | ? | ? | [z,w]; [x,w]; [z,y]; |
% | [x,y]; [x]; [y]; empty |
test('terms_int_int_intersection_?_?_?_<') :-
setof(X-Z-I, clp_term:terms_intersection_int_int([variable(X), const(b)], [variable(Z), const(d)], I), Ans),
Ans = [X-Z-empty, X-Z-singleton(const(b)), X-Z-[variable(X), const(b)], X-Z-[variable(Z), const(b)]].
test('terms_int_int_intersection_?_?_?_<_Z==b') :-
setof(Z, clp_term:terms_intersection_int_int([variable(_), const(b)], [variable(Z), const(d)], singleton(const(b))), [Z1]),
Z1 == b.
test('terms_int_int_intersection_?_?_?_=') :-
setof(X-Z-I, clp_term:terms_intersection_int_int([variable(X), const(b)], [variable(Z), const(b)], I), Ans),
Ans = [X-Z-[variable(X), const(b)], X-Z-[variable(Z), const(b)]].
test('terms_int_int_intersection_?_?_?_>') :-
setof(X-Z-I, clp_term:terms_intersection_int_int([variable(X), const(d)], [variable(Z), const(b)], I), Ans),
Ans = [X-Z-empty, X-Z-[variable(Z), const(b)], X-Z-[variable(X), const(b)], X-Z-singleton(const(b))].
test('terms_int_int_intersection_?_?_?_>_X==b') :-
setof(X, clp_term:terms_intersection_int_int([variable(X), const(d)], [variable(_), const(b)], singleton(const(b))), [X1]),
X1 == b.
test('terms_int_int_intersection_?_?_?_?') :-
setof(X-Y-Z-W-I, clp_term:terms_intersection_int_int([variable(X), variable(Y)], [variable(Z), variable(W)], I), Ans),
Ans = [X-Y-Z-W-empty, X-Y-Z-W-singleton(variable(Y)), X-Y-Z-W-singleton(variable(X)),
X-Y-Z-W-[variable(X), variable(Y)], X-Y-Z-W-[variable(Z), variable(Y)],
X-Y-Z-W-[variable(X), variable(W)], X-Y-Z-W-[variable(Z), variable(W)]].
test('terms_int_int_intersection_?_?_?_?_x==w', [ fail ]) :-
clp_term:terms_intersection_int_int([variable(X), variable(_)], [variable(_), variable(W)], singleton(variable(X))),
\+ X == W.
test('terms_int_int_intersection_?_?_?_?_y==z', [ fail ]) :-
clp_term:terms_intersection_int_int([variable(_), variable(Y)], [variable(Z), variable(_)], singleton(variable(Y))),
\+ Y == Z.
test('terms_int_int_intersection_y==z_shortcuts_to_singleton') :-
Y = Z,
setof(Y-Z-I, clp_term:terms_intersection_int_int([variable(_), variable(Y)], [variable(Z), variable(_)], I), Ans),
Ans = [Y-Z-singleton(variable(Y))].
test('terms_int_int_intersection_x==w_shortcuts_to_singleton') :-
X = W,
setof(X-W-I, clp_term:terms_intersection_int_int([variable(X), variable(_)], [variable(_), variable(W)], I), Ans),
Ans = [X-W-singleton(variable(X))].
% Tests for terms_dom_intersection/3
test('terms_dom_intersection_allterms_allterms') :-
terms_dom_intersection(all_terms, all_terms, all_terms).
test('terms_dom_intersection_allterms_singleton') :-
terms_dom_intersection(all_terms, singleton(variable(X)), singleton(variable(X))).
test('terms_dom_intersection_allterms_termsfrom') :-
terms_dom_intersection(all_terms, terms_from(variable(X)), terms_from(variable(X))).
test('terms_dom_intersection_allterms_termsto') :-
terms_dom_intersection(all_terms, terms_to(variable(X)), terms_to(variable(X))).
test('terms_dom_intersection_allterms_int') :-
terms_dom_intersection(all_terms, [variable(X),variable(Y)], [variable(X),variable(Y)]).
test('terms_dom_intersection_termsfrom_allterms') :-
terms_dom_intersection(terms_from(variable(X)), all_terms, terms_from(variable(X))).
test('terms_dom_intersection_termsfrom_singleton_c_c') :-
terms_dom_intersection(terms_from(const(1)), singleton(const(2)), singleton(const(2))).
test('terms_dom_intersection_termsfrom_singleton_c_c_empty') :-
setof(I, terms_dom_intersection(terms_from(const(2)), singleton(const(1)), I), Ans),
Ans = [empty].
test('terms_dom_intersection_termsfrom_singleton_c_v') :-
setof(Y-I, terms_dom_intersection(terms_from(const(1)), singleton(variable(Y)), I), Actuals),
Expecteds = [Y-empty, Y-singleton(variable(Y))],
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_termsfrom_singleton_c_v_unifies') :-
terms_dom_intersection(terms_from(const(1)), singleton(variable(Y)), singleton(variable(Y))),
get_attr(Y, clp_term, terms_from(const(1))).
test('terms_dom_intersection_termsfrom_singleton_v_c') :-
setof(I, terms_dom_intersection(terms_from(variable(_)), singleton(const(2)), I), Ans),
Ans = [empty, singleton(const(2))].
test('terms_dom_intersection_termsfrom_singleton_v_c_unifies') :-
terms_dom_intersection(terms_from(variable(X)), singleton(const(2)), singleton(const(2))),
get_attr(X, clp_term, terms_to(const(2))).
test('terms_dom_intersection_termsfrom_singleton_v_v') :-
setof(Y-I, terms_dom_intersection(terms_from(variable(_)), singleton(variable(Y)), I), Actuals),
Expecteds = [Y-empty, Y-singleton(variable(Y))],
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_termsfrom_singleton_v_v_attributes_x') :-
terms_dom_intersection(terms_from(variable(X)), singleton(variable(Y)), singleton(variable(Y))),
get_attr(X, clp_term, terms_to(variable(Y))),
get_attr(Y, clp_term, terms_from(variable(X))).
test('terms_dom_intersection_termsfrom_termsfrom') :-
setof(X-Y-FromFrom1, terms_dom_intersection(terms_from(variable(X)), terms_from(variable(Y)), FromFrom1), FromFrom1s),
setof(X-Y-FromFrom2, clp_term:terms_intersection_from_from(terms_from(variable(X)), terms_from(variable(Y)), FromFrom2), FromFrom1s).
test('terms_dom_intersection_termsfrom_termsto') :-
setof(X-Y-FromTo1, terms_dom_intersection(terms_from(variable(X)), terms_to(variable(Y)), FromTo1), FromTo1s),
setof(X-Y-FromTo2, clp_term:terms_intersection_from_to(terms_from(variable(X)), terms_to(variable(Y)), FromTo2), FromTo1s).
test('terms_dom_intersection_termsfrom_int') :-
setof(X-Y-Z-FromInt1, terms_dom_intersection(terms_from(variable(X)), [variable(Y),variable(Z)], FromInt1), FromInt1s),
setof(X-Y-Z-FromInt2, clp_term:terms_intersection_from_int(terms_from(variable(X)), [variable(Y),variable(Z)], FromInt2), FromInt1s).
test('terms_dom_intersection_termsto_allterms') :-
terms_dom_intersection(terms_to(variable(X)), all_terms, terms_to(variable(X))).
test('terms_dom_intersection_termsto_singleton_c_c') :-
terms_dom_intersection(terms_to(const(2)), singleton(const(1)), singleton(const(1))).
test('terms_dom_intersection_termsto_singleton_c_c_empty') :-
setof(I, terms_dom_intersection(terms_to(const(1)), singleton(const(2)), I), Ans),
Ans = [empty].
test('terms_dom_intersection_termsto_singleton_c_v') :-
setof(X-I, terms_dom_intersection(terms_to(const(1)), singleton(variable(X)), I), Actuals),
Expecteds = [X-empty, X-singleton(variable(X))],
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_termsto_singleton_c_v_unifies') :-
terms_dom_intersection(terms_to(const(1)), singleton(variable(Y)), singleton(variable(Y))),
get_attr(Y, clp_term, terms_to(const(1))).
test('terms_dom_intersection_termsto_singleton_v_c') :-
setof(I, terms_dom_intersection(terms_to(variable(_)), singleton(const(1)), I), Ans),
Ans = [empty, singleton(const(1))].
test('terms_dom_intersection_termsto_singleton_v_c_unifies') :-
terms_dom_intersection(terms_to(variable(X)), singleton(const(1)), singleton(const(1))),
get_attr(X, clp_term, terms_from(const(1))).
test('terms_dom_intersection_termsto_singleton_v_v') :-
setof(I, terms_dom_intersection(terms_to(variable(_)), singleton(variable(Y)), I), Ans),
Ans = [empty, singleton(variable(Y))].
test('terms_dom_intersection_termsto_singleton_v_v_attributes_x') :-
terms_dom_intersection(terms_to(variable(X)), singleton(variable(Y)), singleton(variable(Y))),
get_attr(X, clp_term, terms_from(variable(Y))),
get_attr(Y, clp_term, terms_to(variable(X))).
test('terms_dom_intersection_termsto_termsfrom') :-
setof(X-Y-ToFrom1, terms_dom_intersection(terms_to(variable(X)), terms_from(variable(Y)), ToFrom1), ToFrom1s),
setof(X-Y-ToFrom2, clp_term:terms_intersection_to_from(terms_to(variable(X)), terms_from(variable(Y)), ToFrom2), ToFrom1s).
test('terms_dom_intersection_termsto_termsto') :-
setof(X-Y-ToTo1, terms_dom_intersection(terms_to(variable(X)), terms_to(variable(Y)), ToTo1), ToTo1s),
setof(X-Y-ToTo2, clp_term:terms_intersection_to_to(terms_to(variable(X)), terms_to(variable(Y)), ToTo2), ToTo1s).
test('terms_dom_intersection_termsto_int') :-
setof(X-Y-Z-ToInt1, terms_dom_intersection(terms_to(variable(X)), [variable(Y),variable(Z)], ToInt1), ToInt1s),
setof(X-Y-Z-ToInt2, clp_term:terms_intersection_to_int(terms_to(variable(X)), [variable(Y),variable(Z)], ToInt2), ToInt1s).
test('terms_dom_intersection_int_allterms') :-
terms_dom_intersection([variable(X),variable(Y)], all_terms, [variable(X),variable(Y)]).
test('terms_dom_intersection_int_singleton_[c,c]_c') :-
terms_dom_intersection([const(1), const(3)], singleton(const(2)), singleton(const(2))).
test('terms_dom_intersection_int_singleton_[c,c]_c_empty') :-
setof(I, terms_dom_intersection([const(1), const(3)], singleton(const(4)), I), Ans),
Ans = [empty].
test('terms_dom_intersection_int_singleton_[c,c]_v') :-
setof(Y-I, terms_dom_intersection([const(1), const(3)], singleton(variable(Y)), I), Actuals),
Expecteds = [Y-empty, Y-singleton(variable(Y))],
subset(Expecteds, Actuals), subset(Actuals, Expecteds).
test('terms_dom_intersection_int_singleton_[c,c]_v_attributes_x') :-
terms_dom_intersection([const(1), const(3)], singleton(variable(Y)), singleton(variable(Y))),
get_attr(Y, clp_term, [const(1), const(3)]).
test('terms_dom_intersection_int_singleton_[c,v]_c') :-
setof(I, terms_dom_intersection([const(1), variable(_)], singleton(const(3)), I), Ans),
Ans = [empty, singleton(const(3))].
test('terms_dom_intersection_int_singleton_[c,v]_c_attributes_x') :-
terms_dom_intersection([const(1), variable(Z)], singleton(const(3)), singleton(const(3))),
get_attr(Z, clp_term, terms_from(const(3))).
test('terms_dom_intersection_int_singleton_[c,v]_v') :-
setof(Y-I, terms_dom_intersection([const(1), variable(_)], singleton(variable(Y)), I), Actuals),
Expecteds = [Y-empty, Y-singleton(variable(Y))],
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_int_singleton_[c,v]_v_attributes_x') :-
terms_dom_intersection([const(1), variable(Z)], singleton(variable(Y)), singleton(variable(Y))),
get_attr(Y, clp_term, [const(1), variable(Z)]),
get_attr(Z, clp_term, terms_from(variable(Y))).
test('terms_dom_intersection_int_singleton_[v,c]_c') :-
setof(I, terms_dom_intersection([variable(_), const(3)], singleton(const(1)), I), Ans),
Ans = [empty, singleton(const(1))].
test('terms_dom_intersection_int_singleton_[v,c]_c_attributes_x') :-
terms_dom_intersection([variable(X), const(3)], singleton(const(1)), singleton(const(1))),
get_attr(X, clp_term, terms_to(const(1))).
test('terms_dom_intersection_int_singleton_[v,c]_v') :-
setof(Y-I, terms_dom_intersection([variable(_), const(3)], singleton(variable(Y)), I), Actuals),
Expecteds = [Y-empty, Y-singleton(variable(Y))],
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_int_singleton_[v,c]_v_attributes_x') :-
terms_dom_intersection([variable(X), const(3)], singleton(variable(Y)), singleton(variable(Y))),
get_attr(Y, clp_term, [variable(X), const(3)]),
get_attr(X, clp_term, terms_to(variable(Y))).
test('terms_dom_intersection_int_singleton_[v,v]_c') :-
setof(I, terms_dom_intersection([variable(_), variable(_)], singleton(const(2)), I), Ans),
Ans = [empty, singleton(const(2))].
test('terms_dom_intersection_int_singleton_[v,v]_c_attributes_x') :-
terms_dom_intersection([variable(X), variable(Z)], singleton(const(2)), singleton(const(2))),
get_attr(X, clp_term, terms_to(const(2))),
get_attr(Z, clp_term, terms_from(const(2))).
test('terms_dom_intersection_int_singleton_[v,v]_v') :-
setof(Y-I, terms_dom_intersection([variable(_), variable(_)], singleton(variable(Y)), I), Actuals),
Expecteds = [Y-empty, Y-singleton(variable(Y))],
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_int_singleton_[v,v]_v_attributes_x') :-
terms_dom_intersection([variable(X), variable(Z)], singleton(variable(Y)), singleton(variable(Y))),
get_attr(Y, clp_term, [variable(X), variable(Z)]).
test('terms_dom_intersection_int_termsfrom') :-
setof(X-Y-Z-IntFrom1, terms_dom_intersection([variable(X),variable(Y)], terms_from(variable(Z)), IntFrom1), IntFrom1s),
setof(X-Y-Z-IntFrom2, clp_term:terms_intersection_from_int(terms_from(variable(Z)), [variable(X),variable(Y)], IntFrom2), IntFrom1s).
test('terms_dom_intersection_int_termsto') :-
setof(X-Y-Z-IntTo1, terms_dom_intersection([variable(X),variable(Y)], terms_to(variable(Z)), IntTo1), IntTo1s),
setof(X-Y-Z-IntTo2, clp_term:terms_intersection_to_int(terms_to(variable(Z)), [variable(X),variable(Y)], IntTo2), IntTo1s).
test('terms_dom_intersection_int_int') :-
setof(X-Y-Z-W-IntInt1, terms_dom_intersection([variable(X),variable(Y)], [variable(Z),variable(W)], IntInt1), IntInt1s),
setof(X-Y-Z-W-IntInt2, clp_term:terms_intersection_int_int([variable(X),variable(Y)], [variable(Z),variable(W)], IntInt2), IntInt1s).
test('terms_dom_intersection_singleton_allterms') :-
terms_dom_intersection(singleton(variable(X)), all_terms, singleton(variable(X))).
test('terms_dom_intersection_singleton_singleton_c_c') :-
terms_dom_intersection(singleton(const(1)), singleton(const(1)), singleton(const(1))).
test('terms_dom_intersection_singleton_singleton_c_c_empty') :-
setof(I, terms_dom_intersection(singleton(const(1)), singleton(const(2)), I), Ans),
Ans = [empty].
test('terms_dom_intersection_singleton_singleton_c_v') :-
setof(Y-I, terms_dom_intersection(singleton(const(1)), singleton(variable(Y)), I), Ans),
Ans = [Y-empty, Y-singleton(const(1))].
test('terms_dom_intersection_singleton_singleton_c_v_unifies') :-
setof(Y, terms_dom_intersection(singleton(const(1)), singleton(variable(Y)), singleton(const(1))), [Y1]),
Y1 == 1.
test('terms_dom_intersection_singleton_singleton_v_c') :-
setof(X-I, terms_dom_intersection(singleton(variable(X)), singleton(const(1)), I), Ans),
Ans = [X-empty, X-singleton(const(1))].
test('terms_dom_intersection_singleton_singleton_v_c_unifies') :-
setof(X, terms_dom_intersection(singleton(variable(X)), singleton(const(1)), singleton(const(1))), [X1]),
X1 == 1.
test('terms_dom_intersection_singleton_singleton_v_v') :-
setof(X-I, terms_dom_intersection(singleton(variable(X)), singleton(variable(_)), I), Ans),
Ans = [X-singleton(variable(X)), X-empty].
test('terms_dom_intersection_singleton_singleton_v_v_unifies') :-
setof(X-Y, terms_dom_intersection(singleton(variable(X)), singleton(variable(Y)), singleton(variable(X))), [X1-Y1]),
X1 == Y1.
test('terms_dom_intersection_singleton_termsfrom_c_c') :-
terms_dom_intersection(singleton(const(2)), terms_from(const(1)), Intersection),
terms_dom_intersection(terms_from(const(1)), singleton(const(2)), Intersection).
test('terms_dom_intersection_singleton_termsfrom_c_v') :-
setof(Y-SFrom1, terms_dom_intersection(singleton(const(2)), terms_from(variable(Y)), SFrom1), SFrom1s),
setof(Y-SFrom2, terms_dom_intersection(terms_from(variable(Y)), singleton(const(2)), SFrom2), SFrom1s).
test('terms_dom_intersection_singleton_termsfrom_v_c') :-
setof(X-SFrom1, terms_dom_intersection(singleton(variable(X)), terms_from(const(1)), SFrom1), SFrom1s),
setof(X-SFrom2, terms_dom_intersection(terms_from(const(1)), singleton(variable(X)), SFrom2), SFrom1s).
test('terms_dom_intersection_singleton_termsfrom_v_v', [ fail ]) :-
setof(X-Y-SFrom1, terms_dom_intersection(singleton(variable(X)), terms_from(variable(Y)), SFrom1), Actuals),
setof(X-Y-SFrom2, terms_dom_intersection(terms_from(variable(Y)), singleton(variable(X)), SFrom2), Expecteds),
\+ (subset(Actuals, Expecteds), subset(Expecteds, Actuals)).
test('terms_dom_intersection_singleton_termsto_c_c') :-
terms_dom_intersection(singleton(const(1)), terms_to(const(2)), Intersection),
terms_dom_intersection(terms_to(const(2)), singleton(const(1)), Intersection).
test('terms_dom_intersection_singleton_termsto_c_v') :-
setof(Y-STo1, terms_dom_intersection(singleton(const(1)), terms_to(variable(Y)), STo1), STo1s),
setof(Y-STo2, terms_dom_intersection(terms_to(variable(Y)), singleton(const(1)), STo2), STo1s).
test('terms_dom_intersection_singleton_termsto_v_c') :-
setof(X-STo1, terms_dom_intersection(singleton(variable(X)), terms_to(const(2)), STo1), STo1s),
setof(X-STo2, terms_dom_intersection(terms_to(const(2)), singleton(variable(X)), STo2), STo1s).
test('terms_dom_intersection_singleton_termsto_v_v') :-
setof(X-Y-STo1, terms_dom_intersection(singleton(variable(X)), terms_to(variable(Y)), STo1), Actuals),
setof(X-Y-STo2, terms_dom_intersection(terms_to(variable(Y)), singleton(variable(X)), STo2), Expecteds),
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_singleton_int_c_[c,c]') :-
terms_dom_intersection(singleton(const(2)), [const(1), const(3)], Intersection),
terms_dom_intersection([const(1), const(3)], singleton(const(2)), Intersection).
test('terms_dom_intersection_singleton_int_c_[c,v]') :-
setof(Z-SInt1, terms_dom_intersection(singleton(const(2)), [const(1), variable(Z)], SInt1), SInt1s),
setof(Z-SInt2, terms_dom_intersection([const(1), variable(Z)], singleton(const(2)), SInt2), SInt1s).
test('terms_dom_intersection_singleton_int_c_[v,c]') :-
setof(Y-SInt1, terms_dom_intersection(singleton(const(2)), [variable(Y), const(3)], SInt1), SInt1s),
setof(Y-SInt2, terms_dom_intersection([variable(Y), const(3)], singleton(const(2)), SInt2), SInt1s).
test('terms_dom_intersection_singleton_int_c_[v,v]') :-
setof(Y-Z-SInt1, terms_dom_intersection(singleton(const(2)), [variable(Y), variable(Z)], SInt1), SInt1s),
setof(Y-Z-SInt2, terms_dom_intersection([variable(Y), variable(Z)], singleton(const(2)), SInt2), SInt1s).
test('terms_dom_intersection_singleton_int_v_[c,c]') :-
setof(X-SInt1, terms_dom_intersection(singleton(variable(X)), [const(1), const(3)], SInt1), SInt1s),
setof(X-SInt2, terms_dom_intersection([const(1), const(3)], singleton(variable(X)), SInt2), SInt1s).
test('terms_dom_intersection_singleton_int_v_[c,v]') :-
setof(X-Z-SInt1, terms_dom_intersection(singleton(variable(X)), [const(1), variable(Z)], SInt1), Actuals),
setof(X-Z-SInt2, terms_dom_intersection([const(1), variable(Z)], singleton(variable(X)), SInt2), Expecteds),
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_singleton_int_v_[v,c]') :-
setof(X-Y-SInt1, terms_dom_intersection(singleton(variable(X)), [variable(Y), const(3)], SInt1), Actuals),
setof(X-Y-SInt2, terms_dom_intersection([variable(Y), const(3)], singleton(variable(X)), SInt2), Expecteds),
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_singleton_int_v_[v,v]') :-
setof(X-Y-Z-SInt1, terms_dom_intersection(singleton(variable(X)), [variable(Y), variable(Z)], SInt1), Actuals),
setof(X-Y-Z-SInt2, terms_dom_intersection([variable(Y), variable(Z)], singleton(variable(X)), SInt2), Expecteds),
subset(Actuals, Expecteds), subset(Expecteds, Actuals).
test('terms_dom_intersection_normalizes_allterms_singleton') :-
X = 42,
terms_dom_intersection(all_terms, singleton(variable(X)), singleton(const(42))).
test('terms_dom_intersection_normalizes_allterms_termsfrom') :-
X = 42,
terms_dom_intersection(all_terms, terms_from(variable(X)), terms_from(const(X))).
test('terms_dom_intersection_normalizes_allterms_termsto') :-
X = 42,
terms_dom_intersection(all_terms, terms_to(variable(X)), terms_to(const(X))).
test('terms_dom_intersection_normalizes_allterms_int') :-
X = 42, Y = 43,
terms_dom_intersection(all_terms, [variable(X), variable(Y)], [const(X), const(Y)]).
test('terms_dom_intersection_normalizes_termsfrom_allterms') :-
X = 42,
terms_dom_intersection(terms_from(variable(X)), all_terms, terms_from(const(X))).
test('terms_dom_intersection_normalizes_termsfrom_singleton') :-
X = 42, Y = 43,
terms_dom_intersection(terms_from(variable(X)), singleton(variable(Y)), singleton(const(Y))).
test('terms_dom_intersection_normalizes_termsfrom_termsfrom') :-
X = 42, Y = 43,
setof(I, terms_dom_intersection(terms_from(variable(X)), terms_from(variable(Y)), I), [terms_from(const(Y))]).
test('terms_dom_intersection_normalizes_termsfrom_termsto') :-
X = 42, Y = 43,
setof(I, terms_dom_intersection(terms_from(variable(X)), terms_to(variable(Y)), I), [[const(X), const(Y)]]).
test('terms_dom_intersection_normalizes_termsfrom_int') :-
X = 42, Y = 43, Z = 44,
terms_dom_intersection(terms_from(variable(X)), [variable(Y), variable(Z)], [const(Y), const(Z)]).
test('terms_dom_intersection_normalizes_termsto_allterms') :-
X = 42,
terms_dom_intersection(terms_to(variable(X)), all_terms, terms_to(const(X))).
test('terms_dom_intersection_normalizes_termsto_singleton') :-
X = 43, Y = 42,
terms_dom_intersection(terms_to(variable(X)), singleton(variable(Y)), singleton(const(Y))).
test('terms_dom_intersection_normalizes_termsto_termsfrom') :-
X = 43, Y = 42,
setof(I, terms_dom_intersection(terms_to(variable(X)), terms_from(variable(Y)), I), [[const(Y), const(X)]]).
test('terms_dom_intersection_normalizes_termsto_termsto') :-
X = 42, Y = 43,
setof(I, terms_dom_intersection(terms_to(variable(X)), terms_to(variable(Y)), I), [terms_to(const(X))]).
test('terms_dom_intersection_normalizes_termsto_int') :-
X = 44, Y = 42, Z = 43,
terms_dom_intersection(terms_to(variable(X)), [variable(Y), variable(Z)], [const(Y), const(Z)]).
test('terms_dom_intersection_normalizes_int_allterms') :-
X = 42, Y = 43,
terms_dom_intersection([variable(X), variable(Y)], all_terms, [const(X), const(Y)]).
test('terms_dom_intersection_normalizes_int_singleton') :-
X = 41, Y = 43, Z = 42,
terms_dom_intersection([variable(X), variable(Y)], singleton(variable(Z)), singleton(const(Z))).
test('terms_dom_intersection_normalizes_int_termsfrom') :-
X = 42, Y = 43, Z = 41,
setof(I, terms_dom_intersection([variable(X), variable(Y)], terms_from(variable(Z)), I), [[const(X), const(Y)]]).
test('terms_dom_intersection_normalizes_int_termsto') :-
X = 42, Y = 43, Z = 44,
setof(I, terms_dom_intersection([variable(X), variable(Y)], terms_to(variable(Z)), I), [[const(X), const(Y)]]).
test('terms_dom_intersection_normalizes_int_int') :-
X = 42, Y = 44, Z = 43, W = 45,
terms_dom_intersection([variable(X), variable(Y)], [variable(Z), variable(W)], [const(Z), const(Y)]).
test('terms_dom_intersection_normalizes_singleton_allterms') :-
X = 42,
terms_dom_intersection(singleton(variable(X)), all_terms, singleton(const(X))).
test('terms_dom_intersection_normalizes_singleton_singleton') :-
X = 42, Y = 42,
terms_dom_intersection(singleton(variable(X)), singleton(variable(Y)), singleton(const(X))).
test('terms_dom_intersection_normalizes_singleton_termsfrom') :-
X = 42, Y = 41,
terms_dom_intersection(singleton(variable(X)), terms_from(variable(Y)), singleton(const(X))).
test('terms_dom_intersection_normalizes_singleton_termsto') :-
X = 42, Y = 43,
terms_dom_intersection(singleton(variable(X)), terms_to(variable(Y)), singleton(const(X))).
test('terms_dom_intersection_normalizes_singleton_int') :-
X = 42, Y = 41, Z = 43,
terms_dom_intersection(singleton(variable(X)), [variable(Y), variable(Z)], singleton(const(X))).
test('terms_dom_intersection_uninst_1st', [ fail ]) :-
terms_dom_intersection(_, terms_from(variable(_)), terms_from(variable(_))).
test('terms_dom_intersection_uninst_2nd', [ fail ]) :-
terms_dom_intersection(terms_from(variable(_)), _, terms_from(variable(_))).
test('terms_dom_intersection_1st_uninst_endpoint', [ throws(error(instantiation_error(X), _)) ]) :-
terms_dom_intersection(terms_from(X), terms_from(variable(_)), terms_from(variable(_))).
test('terms_dom_intersection_2nd_uninst_endpoint', [ throws(error(instantiation_error(Y), _)) ]) :-
terms_dom_intersection(terms_from(variable(_)), terms_from(Y), terms_from(variable(_))).
test('terms_dom_intersection_first_empty') :-
terms_dom_intersection(empty, terms_from(variable(_)), empty).
test('terms_dom_intersection_second_empty') :-
terms_dom_intersection(terms_from(variable(_)), empty, empty).
% Tests for the unification hook
test('unify_empty_intersection_fails_to_unify', [ fail ]) :-
term_at_least(X, 2),
term_at_most(Y, 1),
X = Y.
test('unify_singleton_intersection_sets_exact_value_and_removes_attributes_c', [ fail ]) :-
term_at_least(X, 2),
term_at_most(Y, 2),
X = Y,
(X \== 2 ; Y \== 2 ; get_attr(X, clp_term, _) ; get_attr(Y, clp_term, _)).
test('unify_singleton_intersection2_sets_exact_value_and_removes_attributes_c', [ fail ]) :-
term_indomain(X, [const(1), const(2)]),
term_indomain(Y, [const(2), const(3)]),
X = Y,
(X \== 2 ; Y \== 2 ; get_attr(X, clp_term, _) ; get_attr(Y, clp_term, _)).
test('unify_singleton_intersection_sets_exact_value_and_removes_attributes_v', [ fail ]) :-
term_at_least(X, Z),
term_at_most(Y, Z),
X = Y,
(X \== Z ; Y \== Z ; get_attr(X, clp_term, _) ; get_attr(Y, clp_term, _)).
test('unify_singleton_intersection2_sets_exact_value_and_removes_attributes_v', [ fail ]) :-
term_indomain(X, [const(1), variable(Z)]),
term_indomain(Y, [variable(Z), const(3)]),
X = Y,
(X \== Z ; Y \== Z ; get_attr(X, clp_term, _) ; get_attr(Y, clp_term, _)).
test('unify_allterms_allterms', [ fail ]) :-
is_term(X),
is_term(Y),
X = Y,
\+ (get_attr(X, clp_term, all_terms), get_attr(Y, clp_term, all_terms)).
test('unify_allterms_termsfrom_c', [ fail ]) :-
is_term(X),
term_at_least(Y, 1),
X = Y,
\+ get_attr(X, clp_term, terms_from(const(1))).
test('unify_allterms_termsfrom_v', [ fail ]) :-
is_term(X),
term_at_least(Y, Z),
X = Y,
\+ get_attr(X, clp_term, terms_from(variable(Z))).
test('unify_allterms_termsto_c', [ fail ]) :-
is_term(X),
term_at_most(Y, 1),
X = Y,
\+ get_attr(X, clp_term, terms_to(const(1))).
test('unify_allterms_termsto_v', [ fail ]) :-
is_term(X),
term_at_most(Y, Z),
X = Y,
\+ get_attr(X, clp_term, terms_to(variable(Z))).
test('unify_allterms_int_c_c', [ fail ]) :-
is_term(X),
term_at_least(Y, 1), term_at_most(Y, 2),
X = Y,
\+ get_attr(X, clp_term, [const(1), const(2)]).
test('unify_allterms_int_c_v', [ fail ]) :-
is_term(X),
term_at_least(Y, 1), term_at_most(Y, U), dif(1, U),
X = Y,
\+ get_attr(X, clp_term, [const(1), variable(U)]).
test('unify_allterms_int_v_c', [ fail ]) :-
is_term(X),
term_at_least(Y, L), term_at_most(Y, 2), dif(L, 2),
X = Y,
\+ get_attr(X, clp_term, [variable(L), const(2)]).
test('unify_allterms_int_v_v', [ fail ]) :-
is_term(X),
term_at_least(Y, L), term_at_most(Y, U), dif(L, U),
X = Y,
\+ get_attr(X, clp_term, [variable(L), variable(U)]).
test('unify_termsfrom_allterms', [ fail ]) :-
term_at_least(X, 1),
is_term(Y),
X = Y,
\+ get_attr(Y, clp_term, terms_from(const(1))).
test('unify_termsfrom_termsfrom_c_c', [ fail ]) :-
term_at_least(X, 1),
term_at_least(Y, 2),
X = Y,
\+ get_attr(Y, clp_term, terms_from(const(2))).
test('unify_termsfrom_termsfrom_c_v', [ fail ]) :-
term_at_least(X, 1),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_from(Dom1, Dom2, Expected)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_termsfrom_termsfrom_v_c', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_from_from(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_termsfrom_termsfrom_v_v', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_from_from(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_termsfrom_termsto_c_c', [ fail ]) :-
term_at_least(X, 1),
term_at_most(Y, 2),
X = Y,
\+ get_attr(Y, clp_term, [const(1), const(2)]).
test('unify_termsfrom_termsto_c_v', [ fail ]) :-
term_at_least(X, 1),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_to(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
Expecteds = [_-_-Es], Actuals = [_-_-As],
\+ Es = As.
test('unify_termsfrom_termsto_c_v_singleton', [ fail ]) :-
term_at_least(X, 1),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_from_to(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsfrom_termsto_v_c', [ fail ]) :-
term_at_least(X, _),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_to(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsfrom_termsto_v_c_singleton', [ fail ]) :-
term_at_least(X, _),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_from_to(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsfrom_termsto_v_v', [ fail ]) :-
term_at_least(X, _),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_to(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsfrom_termsto_v_v_singleton', [ fail ]) :-
term_at_least(X, _),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_from_to(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsfrom_int_c_[c,c]', [ fail ]) :-
term_at_least(X, 2),
term_at_least(Y, 1), term_at_most(Y, 3),
X = Y,
\+ get_attr(X, clp_term, [const(2), const(3)]).
test('unify_termsfrom_int_c_[c,v]', [ fail ]) :-
term_at_least(X, 2),
term_at_least(Y, 1), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_int(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
Expecteds = [_-_-Es], Actuals = [_-_-As],
\+ Es = As.
test('unify_termsfrom_int_c_[c,v]_singleton', [ fail ]) :-
term_at_least(X, 2),
term_at_least(Y, 1), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_from_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsfrom_int_c_[v,c]', [ fail ]) :-
term_at_least(X, 2),
term_at_least(Y, _), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_from_int(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsfrom_int_c_[v,v]', [ fail ]) :-
term_at_least(X, 2),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_int(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
Expecteds = [_-_-Es1, _-_-Es2], Actuals = [_-_-As1, _-_-As2],
(Es1 \= As1 ; Es2 \= As2).
test('unify_termsfrom_int_c_[v,v]_singleton', [ fail ]) :-
term_at_least(X, 2),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_from_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsfrom_int_v_[c,c]', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, 1), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_int(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsfrom_int_v_[c,c]_singleton', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, 1), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_from_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsfrom_int_v_[c,v]', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, 1), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_int(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsfrom_int_v_[c,v]_singleton', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, 1), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_from_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsfrom_int_v_[v,c]', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, _), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsfrom_int_v_[v,c]_singleton', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, _), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_from_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsfrom_int_v_[v,v]', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_from_int(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsfrom_int_v_[v,v]_singleton', [ fail ]) :-
term_at_least(X, _),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_from_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsto_allterms', [ fail ]) :-
term_at_most(X, 1),
is_term(Y),
X = Y,
\+ get_attr(Y, clp_term, terms_to(const(1))).
test('unify_termsto_termsfrom_c_c', [ fail ]) :-
term_at_most(X, 2),
term_at_least(Y, 1),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_int(Dom1, Dom2, Expected)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_termsfrom_c_v', [ fail ]) :-
term_at_most(X, 2),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_from(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_termsfrom_c_v_singleton', [ fail ]) :-
term_at_most(X, 2),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_to_from(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsto_termsfrom_v_c', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, 1),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_from(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
Expecteds = [_-_-Es], Actuals = [_-_-As],
\+ Es = As.
test('unify_termsto_termsfrom_v_c_singleton', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, 1),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_to_from(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsto_termsfrom_v_v', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_from(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_termsfrom_v_v_singleton', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_to_from(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsto_termsto_c_c', [ fail ]) :-
term_at_most(X, 1),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_to(Dom1, Dom2, Expected)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_termsto_c_v', [ fail ]) :-
term_at_most(X, 1),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_to_to(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_termsto_termsto_v_c', [ fail ]) :-
term_at_most(X, _),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_to_to(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_termsto_termsto_v_v', [ fail ]) :-
term_at_most(X, _),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_to_to(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_int_c_[c,c]', [ fail ]) :-
term_at_most(X, 2),
term_at_least(Y, 1), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_to_int(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_int_c_[c,v]', [ fail ]) :-
term_at_most(X, 2),
term_at_least(Y, 1), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_to_int(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_int_c_[v,c]', [ fail ]) :-
term_at_most(X, 2),
term_at_least(Y, _), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2), Dom2 = [_,_],
setof(X-Y-Expected, (clp_term:terms_intersection_to_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_int_c_[v,c]_singleton', [ fail ]) :-
term_at_most(X, 2),
term_at_least(Y, _), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2), Dom2 = [_,_],
clp_term:terms_intersection_to_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsto_int_c_[v,v]', [ fail ]) :-
term_at_most(X, 2),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_int(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_int_c_[v,v]_singleton', [ fail ]) :-
term_at_most(X, 2),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2), Dom2 = [_,_],
clp_term:terms_intersection_to_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsto_int_v_[c,c]', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, 1), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_int_v_[c,c]_singleton', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, 1), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_to_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsto_int_v_[c,v]', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, 1), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_int_v_[c,v]_singleton', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, 1), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_to_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsto_int_v_[v,c]', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, _), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_int(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_int_v_[v,c]_singleton', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, _), term_at_most(Y, 3),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_to_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_termsto_int_v_[v,v]', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_to_int(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_termsto_int_v_[v,v]_singleton', [ fail ]) :-
term_at_most(X, _),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_to_int(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_allterms_[c,c]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
is_term(Y),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (terms_dom_intersection(Dom1, Dom2, Expected)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_allterms_[c,v]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
is_term(Y),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (terms_dom_intersection(Dom1, Dom2, Expected)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_allterms_[v,c]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
is_term(Y),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (terms_dom_intersection(Dom1, Dom2, Expected)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_allterms_[v,v]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
is_term(Y),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (terms_dom_intersection(Dom1, Dom2, Expected)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsfrom_[c,c]_c', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_least(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (terms_dom_intersection(Dom1, Dom2, Expected)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsfrom_[c,c]_v', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_from(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsfrom_[c,c]_v_singleton', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_from(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsfrom_[c,v]_c', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_least(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_from(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
Expecteds = [_-_-Es], Actuals = [_-_-As],
\+ Es = As.
test('unify_int_termsfrom_[c,v]_c_singleton', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_least(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_from(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsfrom_[c,v]_v', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_from(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsfrom_[c,v]_v_singleton', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_from(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsfrom_[v,c]_c', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_least(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_int_from(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsfrom_[v,c]_v', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_from(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsfrom_[v,c]_v_singleton', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_from(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsfrom_[v,v]_c', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_least(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_from(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsfrom_[v,v]_c_singleton', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_least(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_from(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsfrom_[v,v]_v', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_from(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsfrom_[v,v]_v_singleton', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_least(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_from(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsto_[c,c]_c', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_to(Dom1, Dom2, Expected)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsto_[c,c]_v', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_to(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsto_[c,c]_v_singleton', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_to(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsto_[c,v]_c', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_int_to(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsto_[c,v]_v', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_to(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsto_[c,v]_v_singleton', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_to(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsto_[v,c]_c', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_to(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsto_[v,c]_c_singleton', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_to(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsto_[v,c]_v', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_to(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsto_[v,c]_v_singleton', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_to(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsto_[v,v]_c', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_to(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsto_[v,v]_c_singleton', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_most(Y, 2),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_to(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_termsto_[v,v]_v', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_to(Dom1, Dom2, Expected),
\+ Expected == empty, \+ Expected = singleton(_)), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ Expecteds = Actuals.
test('unify_int_termsto_[v,v]_v_singleton', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_most(Y, _),
get_attr(X, clp_term, Dom1),
get_attr(Y, clp_term, Dom2),
clp_term:terms_intersection_int_to(Dom1, Dom2, singleton(S)),
X = Y, \+ get_attr(Y, clp_term, _), arg(1, S, V),
\+ Y == V.
test('unify_int_int_[c,c]_[c,c]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_least(Y, 2), term_at_most(Y, 4),
X = Y,
\+ get_attr(X, clp_term, [const(2), const(3)]).
test('unify_int_int_[c,c]_[c,v]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_least(Y, 2), term_at_most(Y, _),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[c,c]_[v,c]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_least(Y, _), term_at_most(Y, 4),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[c,c]_[v,v]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, 3),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[c,v]_[c,c]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_least(Y, 2), term_at_most(Y, 4),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[c,v]_[c,v]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_least(Y, 2), term_at_most(Y, _),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[c,v]_[v,c]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_least(Y, _), term_at_most(Y, 4),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[c,v]_[v,v]', [ fail ]) :-
term_at_least(X, 1), term_at_most(X, _),
term_at_least(Y, _), term_at_most(Y, 4),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[v,c]_[c,c]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_least(Y, 2), term_at_most(Y, 4),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[v,c]_[c,v]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_least(Y, 2), term_at_most(Y, _),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[v,c]_[v,c]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_least(Y, _), term_at_most(Y, 4),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[v,c]_[v,v]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 3),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[v,v]_[c,c]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_least(Y, 2), term_at_most(Y, 4),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[v,v]_[c,v]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_least(Y, 2), term_at_most(Y, _),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[v,v]_[v,c]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_least(Y, _), term_at_most(Y, 4),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_int_int_[v,v]_[v,v]', [ fail ]) :-
term_at_least(X, _), term_at_most(X, _),
term_at_least(Y, _), term_at_most(Y, _),
get_attr(X, clp_term, Dom1), get_attr(Y, clp_term, Dom2),
setof(X-Y-Expected, (clp_term:terms_intersection_int_int(Dom1, Dom2, Expected), \+ Expected == empty), Expecteds),
setof(X-Y-Actual, (X = Y, get_attr(Y, clp_term, Actual)), Actuals),
\+ (subset(Expecteds, Actuals), subset(Actuals, Expecteds)).
test('unify_attr_free_sets_domain', [ fail ]) :-
term_at_least(X, 2), term_at_most(X, 4),
setof(X-Y-Dom, (X = Y, get_attr(Y, clp_term, Dom)), Actuals),
\+ Actuals = [X-Y-[const(2), const(4)]].
test('unify_free_attr_sets_domain', [ fail ]) :-
term_at_least(X, 2), term_at_most(X, 4),
setof(X-Y-Dom, (Y = X, get_attr(Y, clp_term, Dom)), Actuals),
\+ Actuals = [X-Y-[const(2), const(4)]].
test('unify_allterms_unifies_with_any') :-
is_term(X),
X = a.
test('unify_termsfrom_const_unifies_indomain') :-
term_at_least(X, 2),
X = 3.
test('unify_termsfrom_const_unifies_outdomain', [ fail ]) :-
term_at_least(X, 2),
X = 1.
test('unify_termsfrom_var_unifies_indomain') :-
term_at_least(X, Z),
X = 3,
get_attr(Z, clp_term, Dom),
Dom == terms_to(const(3)).
test('unify_termsto_const_unifies_indomain') :-
term_at_most(Y, 2),
Y = 1.
test('unify_termsto_const_unifies_outdomain', [ fail ]) :-
term_at_most(Y, 2),
Y = 3.
test('unify_termsto_var_unifies_indomain') :-
term_at_most(Y, Z),
Y = 3,
get_attr(Z, clp_term, Dom),
Dom == terms_from(const(3)).
test('unify_int_[c,c]_unifies_indomain') :-
term_at_least(X, 2), term_at_most(X, 4),
X = 3.
test('unify_int_[c,c]_unifies_outdomain', [ fail ]) :-
term_at_least(X, 2), term_at_most(X, 4),
X = 1.
test('unify_int_[c,v]_unifies_indomain', [ fail ]) :-
term_at_least(X, 2), term_at_most(X, Z),
X = 3,
\+ term_at_least(Z, 3).
test('unify_int_[c,v]_unifies_outdomain', [ fail ]) :-
term_at_least(X, 2), term_at_most(X, _),
X = 1.
test('unify_int_[v,c]_unifies_indomain', [ fail ]) :-
term_at_least(X, Z), term_at_most(X, 4),
X = 3,
\+ term_at_most(Z, 3).
test('unify_int_[v,c]_unifies_outdomain', [ fail ]) :-
term_at_least(X, _), term_at_most(X, 4),
X = 5.
test('unify_int_[v,v]_unifies_indomain', [ fail ]) :-
term_at_least(X, Z1), term_at_most(X, Z2),
X = 3,
\+ term_at_most(Z1, 3), term_at_least(Z2, 3).
test('unify_normalizes_input_domain') :-
term_at_least(X, Y), % term_indomain(X, terms_from(variable(Y)))
Y = a, % Y not attributed, term_indomain(X, terms_from(variable(a)))
X = b. % Lack of normalization will blow up this unification for X
% Tests for attribute_termorder_goals/3
test('attribute_termorder_goals_from_c') :-
clp_term:attribute_termorder_goals(Term, terms_from(const(1)), ResidualGoals),
ResidualGoals == [term_at_least(Term, 1)].
test('attribute_termorder_goals_from_v') :-
clp_term:attribute_termorder_goals(Term, terms_from(variable(X)), ResidualGoals),
ResidualGoals == [term_at_least(Term, X)].
test('attribute_termorder_goals_to_c') :-
clp_term:attribute_termorder_goals(Term, terms_to(const(2)), ResidualGoals),
ResidualGoals == [term_at_most(Term, 2)].
test('attribute_termorder_goals_to_v') :-
clp_term:attribute_termorder_goals(Term, terms_to(variable(Y)), ResidualGoals),
ResidualGoals == [term_at_most(Term, Y)].
test('attribute_termorder_goals_int_c_c') :-
clp_term:attribute_termorder_goals(Term, [const(1), const(2)], ResidualGoals),
ResidualGoals == [term_at_least(Term, 1), term_at_most(Term, 2)].
test('attribute_termorder_goals_int_c_v') :-
clp_term:attribute_termorder_goals(Term, [const(1), variable(Y)], ResidualGoals),
ResidualGoals == [term_at_least(Term, 1), term_at_most(Term, Y)].
test('attribute_termorder_goals_int_v_c') :-
clp_term:attribute_termorder_goals(Term, [variable(X), const(2)], ResidualGoals),
ResidualGoals == [term_at_least(Term, X), term_at_most(Term, 2)].
test('attribute_termorder_goals_int_v_v') :-
clp_term:attribute_termorder_goals(Term, [variable(X), variable(Y)], ResidualGoals),
ResidualGoals == [term_at_least(Term, X), term_at_most(Term, Y)].
test('attribute_termorder_goals_singleton_c') :-
clp_term:attribute_termorder_goals(Term, singleton(const(X)), ResidualGoals),
ResidualGoals == [is_singleton_term(Term, X)].
test('attribute_termorder_goals_singleton_v') :-
clp_term:attribute_termorder_goals(Term, singleton(variable(X)), ResidualGoals),
ResidualGoals == [is_singleton_term(Term, X)].
test('attribute_termorder_goals_empty') :-
clp_term:attribute_termorder_goals(Term, empty, ResidualGoals),
ResidualGoals == [is_empty_term(Term)].
test('attribute_termorder_goals_allterms') :-
clp_term:attribute_termorder_goals(Term, all_terms, ResidualGoals),
ResidualGoals == [is_term(Term)].
:- end_tests(clp_term).
|
import React, {useEffect, useRef} from "react";
interface DialogProps {
isOpen: boolean;
onOk?: () => void;
onClose?: () => void;
onCancel?: () => void;
title?: string;
children: React.ReactNode;
ok: string | boolean;
cancel: string | boolean;
fullScreen?: boolean;
}
export default function Dialog({
isOpen,
onOk,
onClose,
onCancel,
title,
children,
ok = true,
cancel = true,
fullScreen = false,
}: DialogProps): JSX.Element {
const ref = useRef<HTMLDialogElement>(null);
useEffect(() => {
if (isOpen) {
if (!ref.current?.open) ref.current?.showModal();
document.body.classList.add("modal-open");
} else {
ref.current?.close();
document.body.classList.remove("modal-open");
}
}, [isOpen]);
const okAndClose = () => {
onOk && onOk();
onClose && onClose();
};
const cancelAndClose = () => {
onCancel && onCancel();
onClose && onClose();
}
const preventAutoClose = (e: React.MouseEvent) => e.stopPropagation();
return (
<dialog className={`backdrop:backdrop-blur border-orange-500 border-2 rounded-md p-0 overflow-hidden ${fullScreen ? "w-[95vw] h-[95vh]" :""}`}
id="dialog"
ref={ref}
onCancel={onClose}
onClick={onClose}>
<div className="flex flex-col h-full max-h-full" onClick={preventAutoClose}>
<div className="bg-orange-500 text-white font-bold m-0 p-4 sticky top-0 z-10">{title}</div>
<div className="p-4 flex-grow h-full max-h-full">{children}</div>
<div className="flex flex-row justify-end m-0 p-2 bg-orange-300 bottom-0 sticky z-10">
{
cancel ? (
<button className="bg-white border-orange-500 border-2 rounded-sm p-2 m-1"
onClick={cancelAndClose}>
{typeof cancel === "string" ? cancel : "Cancel"}
</button>
) : (
<></>
)
}
{
ok ? (
<button className="bg-orange-500 text-white border-white border-2 rounded-sm p-2 m-1"
onClick={okAndClose}>
{typeof ok === "string" ? ok : "OK"}
</button>
) : (
<></>
)
}
</div>
</div>
</dialog>
)
}
|
Introduction to Azure Active Directory
--------------------------------------
Microsoft previewed Active Directory in 1999, released it first with Windows 2000 Server edition, and revised it to extend functionality and improve administration in Windows Server 2003. Active Directory support was also added to Windows 95, Windows 98 and Windows NT 4.0 via patch, with some features being unsupported.
Domain Services
---------------
Active Directory Domain Services (AD DS) is the foundation of every Windows domain network. It stores information about members of the domain, including devices and users, verifies their credentials and defines their access rights.
What is Azure Active Directory
------------------------------
Azure Active Directory (Azure AD) is a cloud-based identity and access management service. This service helps your employees access external resources, such as Microsoft 365, the Azure portal, and thousands of other SaaS applications. Azure Active Directory also helps them access internal resources like apps on your corporate intranet network, along with any cloud apps developed for your own organization. For more information about creating a tenant for your organization.
Who uses Azure AD?
-------------------
Azure AD is intended for:
------------------------
IT admins: As an IT admin, use Azure AD to control access to your apps and your app resources, based on your business requirements. For example, you can use Azure AD to require multi-factor authentication when accessing important organizational resources. You can also use Azure AD to automate user provisioning between your existing Windows Server AD and your cloud apps, including Microsoft 365. Finally, Azure AD gives you powerful tools to automatically help protect user identities and credentials and to meet your access governance requirements.
|
import { toFileUrl } from "std/path/mod.ts";
import { Api, VERSION as telegramVersion } from "$grm";
import { bigInt } from "$grm-deps";
import {
bold,
CommandHandler,
fmt,
longText,
Module,
type Stringable,
updateMessage,
version,
} from "$xor";
import { whois } from "./helpers.ts";
const LOAD_TIME = Date.now();
const EVAL_HEADER =
`import { Api, type NewMessageEvent, type TelegramClient } from "$grm";
import { Methods } from "$xor";
interface EvalParams {
client: TelegramClient;
event: NewMessageEvent;
}
export async function eval_({ client, event }: EvalParams): Promise<any> {
const c = client;
const e = event;
const message = event.message;
const m = message;
const methods = new Methods(client);
const reply = await message.getReplyMessage();
const r = reply;
`;
const EVAL_FOOTER = "}\n";
const util: Module = {
name: "util",
handlers: [
new CommandHandler("ping", async ({ client, event }) => {
const before = Date.now();
await client.invoke(new Api.Ping({ pingId: bigInt(0) }));
const diff = Date.now() - before;
await updateMessage(event, `${diff}ms`);
}),
new CommandHandler(
"shell",
async ({ event, args, input }) => {
if (args.length < 1) {
return;
}
args = args.slice(1);
let { text } = event.message;
text = text.slice(text.split(/\s/)[0].length);
const cmd = text.trim().split(/\s/);
const proc = Deno.run({
cmd,
stdout: "piped",
stderr: "piped",
stdin: input.length == 0 ? undefined : "piped",
});
text = `[${proc.pid}]${text}`;
await event.message.edit({ text });
const encoder = new TextEncoder();
const decoder = new TextDecoder();
if (input.length != 0) {
proc.stdin?.write(encoder.encode(input));
proc.stdin?.close();
}
const stdout = decoder.decode(await proc.output());
const stderr = decoder.decode(await proc.stderrOutput());
if (stdout.length > 0) {
await event.message.reply(
longText(stdout, "stdout.txt"),
);
}
if (stderr.length > 0) {
await event.message.reply(
longText(stderr, "stderr.txt"),
);
}
const { code } = await proc.status();
text += "\n" + `Exited with code ${code}.`;
await event.message.edit({ text });
},
{
aliases: ["sh", "cmd", "exec"],
},
),
new CommandHandler("uptime", async ({ event }) => {
let seconds = Math.floor(
(Date.now() - LOAD_TIME) / 1000,
);
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds - hours * 3600) / 60);
seconds = seconds - hours * 3600 - minutes * 60;
// TODO: use deno std for the time format?
await updateMessage(
event,
(hours > 0 ? `${hours > 9 ? hours : "0" + hours}:` : "") +
`${minutes > 9 ? minutes : "0" + minutes}:` +
`${seconds > 9 ? seconds : "0" + seconds}`,
);
}),
new CommandHandler(
"version",
async ({ event }) => {
await updateMessage(
event,
`Grm ${telegramVersion}
Xor ${version}
Deno ${Deno.version.deno}
TypeScript ${Deno.version.typescript}
V8 ${Deno.version.v8}`,
);
},
{ aliases: ["v"] },
),
new CommandHandler("whois", async ({ client, event, args }) => {
const info = new Array<Stringable>();
if (args[0] !== undefined && args[0].length != 0) {
const entity = await client.getEntity(args[0]);
info.push((await whois(entity, client)).trim() + "\n\n");
}
const chat = await event.message.getChat();
if (chat) {
info.push(fmt`${bold("Here")}\n`);
info.push((await whois(chat, client)).trim() + "\n\n");
}
const reply = await event.message.getReplyMessage();
if (reply) {
const sender = await reply.getSender();
if (sender) {
info.push(fmt`${bold("Reply")}\n`);
info.push((await whois(sender, client)).trim() + "\n\n");
}
if (reply.forward) {
const sender = await reply.forward.getSender();
if (sender) {
info.push(fmt`${bold("Forwarder")}\n`);
info.push((await whois(sender, client)).trim() + "\n\n");
}
}
}
if (info.length == 0) {
return;
}
await updateMessage(event, fmt(["\n", ...info.map(() => "")], ...info));
}),
new CommandHandler("eval", async ({ client, event, input }) => {
const path = await Deno.makeTempFile({ suffix: ".ts" });
await Deno.writeTextFile(path, `${EVAL_HEADER}${input}${EVAL_FOOTER}`);
const { eval_ } = await import(toFileUrl(path).href);
await Deno.remove(path);
let result = JSON.stringify(
await eval_({ client, event }),
null,
4,
);
if (!result) {
await event.message.reply({
message: "No output.",
});
return;
}
if (result.startsWith('"')) {
result = result.replace(/"/g, "");
}
await event.message.reply(
longText(result, "result.txt"),
);
}, { allowEdit: true }),
],
help: fmt`${bold("Introduction")}
The util module includes some useful commands to interact with the system and get basic information of the surrounding.
${bold("Commands")}
- ping
Tells how much a ping of Telegram servers takes.
- shell, sh, cmd, exec
Runs a shell command and sends its output. Any input will be passed to the stdin of the process.
- uptime
Displays the uptime of the bot in (hh:)mm:ss format.
- version, v
Displays the versions of Xor and other software.
- whois
Fetches and displays basic information about the current chat, the provided identifier as the first argument and/or the replied message. The provided identifier can be a username, a phone number, a user/chat ID or a chat invite ID.
- eval
Runs and sends the output of JavaScript code. As of now, it passes the client as \`client | c\`, the \`NewMessageEvent\` as \`event | e\`, the message as \`message | m\`, the replied message as \`reply | r\`, xorgram-methods instance as \`methods\` and the API namespace as \`Api\`.`,
};
export default util;
|
import 'package:flutter/material.dart';
import '../../../../../__styling/spacing.dart';
import '../../../../../_models/item.dart';
import '../../../../../_widgets/others/icons.dart';
import '../../../../../_widgets/others/text.dart';
import '../_helpers/helpers.dart';
class FinanceOverview extends StatelessWidget {
const FinanceOverview({super.key, required this.item});
final Item item;
@override
Widget build(BuildContext context) {
return IgnorePointer(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//
Row(
mainAxisSize: MainAxisSize.min,
children: [
AppIcon(Icons.circle, size: 8, color: Colors.green),
tpw(),
AppText(text: 'Income :', bold: true, bgColor: item.color()),
tpw(),
Flexible(
child: AppText(
text: 'Ksh. ${formatThousands(item.totalIncome())}',
bgColor: item.color(),
fontWeight: FontWeight.w600,
),
),
],
),
//
sph(),
//
Row(
mainAxisSize: MainAxisSize.min,
children: [
AppIcon(Icons.circle, size: 8, color: Colors.red),
tpw(),
AppText(text: 'Expenses:', bold: true, bgColor: item.color()),
tpw(),
Flexible(
child: AppText(
text: 'Ksh. ${formatThousands(item.totalExpense())}',
bgColor: item.color(),
fontWeight: FontWeight.w600,
),
),
],
),
//
sph(),
//
Row(
mainAxisSize: MainAxisSize.min,
children: [
AppIcon(Icons.circle, size: 8, color: Colors.blue),
tpw(),
AppText(text: 'Savings :', bold: true, bgColor: item.color()),
tpw(),
Flexible(
child: AppText(
text: 'Ksh. ${formatThousands(item.totalSavings())}',
bgColor: item.color(),
fontWeight: FontWeight.w600,
),
),
],
),
//
],
),
);
}
}
|
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import requests
import time
import os
# Setup Selenium WebDriver
driver = webdriver.Chrome() # Assumes chromedriver is in your PATH
driver.get('https://www.hw.com/about/Faculty-Staff-Directory')
# Wait for the button and click it
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'btnAll')))
button = driver.find_element(By.ID, 'btnAll')
button.click()
# Wait for content to load
time.sleep(5)
# Get the page source after the content has loaded
html_content = driver.page_source
driver.quit()
# Parse the HTML content with BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')
# Find the unordered list that contains faculty members
directory_list = soup.find('ul', class_='directory-list')
# Base URL for constructing absolute URLs
base_url = 'https://www.hw.com'
# Create a directory to save images
os.makedirs('hw_images', exist_ok=True)
# Iterate over each list item in the unordered list
for li in directory_list.find_all('li'):
img = li.find('div', class_='image').find('img')
person_name_div = li.find('div', class_='person-name')
if img and person_name_div:
img_url = img['src']
if not img_url.startswith('http'):
img_url = base_url + img_url
img_response = requests.get(img_url)
person_name = person_name_div.get_text(strip=True).replace(' ', '_') # Formatting the filename
with open(f'hw_images/{person_name}.jpg', 'wb') as file: # Assuming the images are in JPEG format
file.write(img_response.content)
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// <unordered_set>
// class unordered_set
// template <class H2, class P2>
// void merge(unordered_set<key_type, H2, P2, allocator_type>& source);
// template <class H2, class P2>
// void merge(unordered_set<key_type, H2, P2, allocator_type>&& source);
// template <class H2, class P2>
// void merge(unordered_multiset<key_type, H2, P2, allocator_type>& source);
// template <class H2, class P2>
// void merge(unordered_multiset<key_type, H2, P2, allocator_type>&& source);
#include <unordered_set>
#include <cassert>
#include "test_macros.h"
#include "Counter.h"
template <class Set>
bool set_equal(const Set& set, Set other)
{
return set == other;
}
#ifndef TEST_HAS_NO_EXCEPTIONS
template <class T>
struct throw_hasher
{
bool& should_throw_;
throw_hasher(bool& should_throw) : should_throw_(should_throw) {}
size_t operator()(const T& p) const
{
if (should_throw_)
throw 0;
return std::hash<T>()(p);
}
};
#endif
int main(int, char**)
{
{
std::unordered_set<int> src{1, 3, 5};
std::unordered_set<int> dst{2, 4, 5};
dst.merge(src);
assert(set_equal(src, {5}));
assert(set_equal(dst, {1, 2, 3, 4, 5}));
}
#ifndef TEST_HAS_NO_EXCEPTIONS
{
bool do_throw = false;
typedef std::unordered_set<Counter<int>, throw_hasher<Counter<int>>> set_type;
set_type src({1, 3, 5}, 0, throw_hasher<Counter<int>>(do_throw));
set_type dst({2, 4, 5}, 0, throw_hasher<Counter<int>>(do_throw));
assert(Counter_base::gConstructed == 6);
do_throw = true;
try
{
dst.merge(src);
}
catch (int)
{
do_throw = false;
}
assert(!do_throw);
assert(set_equal(src, set_type({1, 3, 5}, 0, throw_hasher<Counter<int>>(do_throw))));
assert(set_equal(dst, set_type({2, 4, 5}, 0, throw_hasher<Counter<int>>(do_throw))));
}
#endif
assert(Counter_base::gConstructed == 0);
struct equal
{
equal() = default;
bool operator()(const Counter<int>& lhs, const Counter<int>& rhs) const
{
return lhs == rhs;
}
};
struct hasher
{
hasher() = default;
size_t operator()(const Counter<int>& p) const { return std::hash<Counter<int>>()(p); }
};
{
typedef std::unordered_set<Counter<int>, std::hash<Counter<int>>, std::equal_to<Counter<int>>> first_set_type;
typedef std::unordered_set<Counter<int>, hasher, equal> second_set_type;
typedef std::unordered_multiset<Counter<int>, hasher, equal> third_set_type;
{
first_set_type first{1, 2, 3};
second_set_type second{2, 3, 4};
third_set_type third{1, 3};
assert(Counter_base::gConstructed == 8);
first.merge(second);
first.merge(third);
assert(set_equal(first, {1, 2, 3, 4}));
assert(set_equal(second, {2, 3}));
assert(set_equal(third, {1, 3}));
assert(Counter_base::gConstructed == 8);
}
assert(Counter_base::gConstructed == 0);
{
first_set_type first{1, 2, 3};
second_set_type second{2, 3, 4};
third_set_type third{1, 3};
assert(Counter_base::gConstructed == 8);
first.merge(std::move(second));
first.merge(std::move(third));
assert(set_equal(first, {1, 2, 3, 4}));
assert(set_equal(second, {2, 3}));
assert(set_equal(third, {1, 3}));
assert(Counter_base::gConstructed == 8);
}
assert(Counter_base::gConstructed == 0);
}
{
std::unordered_set<int> first;
{
std::unordered_set<int> second;
first.merge(second);
first.merge(std::move(second));
}
{
std::unordered_multiset<int> second;
first.merge(second);
first.merge(std::move(second));
}
}
return 0;
}
|
package com.example.rpcollegemobile
import android.util.Log
import com.example.rpcollegemobile.itemEvent.Event
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.json.JSONArray
import org.json.JSONException
import java.io.IOException
import java.util.*
class Repository {
fun loadEventSync(callback: (List<Event>) -> Unit) {
Thread {
try {
val call = Network.getEventCall()
val response = call.execute()
if (response.isSuccessful) {
val responseBodyString = response.body?.string() as String
val event: List<Event> = parseResponse(responseBodyString)
callback(event)
} else {
Log.e("Event Server", "Server error response")
callback(listOf())
}
} catch (e: IOException) {
Log.e("Event Server", "${e.message}", e)
callback(listOf())
}
}.start()
}
private lateinit var successfulCallback: (List<Event>) -> Unit
private lateinit var failureCallback: (e: Throwable) -> Unit
fun loadEventAsync(
successfulCallback: (List<Event>) -> Unit,
failureCallback: (e: Throwable) -> Unit
): Call {
this.successfulCallback = successfulCallback
this.failureCallback = failureCallback
val call = Network.getEventCall()
call.enqueue(asyncCallback)
return call
}
private val asyncCallback = object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("Event Server", "${e.message}", e)
failureCallback(e)
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
val responseBodyString = response.body?.string() as String
val event: List<Event> = parseResponse(responseBodyString)
successfulCallback(event)
} else {
Log.e("Event Server", "Server error responses")
failureCallback(Throwable("Server error responses"))
}
}
}
private fun parseResponse(response: String): List<Event> {
try {
val eventArray = JSONArray(response)
return (0 until eventArray.length()).map { index ->
eventArray.getJSONObject(index)
}.map { eventObject ->
val id = eventObject.getInt("ATP_ID")
val activityType = eventObject.getString("ACTIVITY_TYPE")
val name = eventObject.getString("NAME")
val subdivision = eventObject.getString("SUBDIVISION")
val local = eventObject.getInt("LOCAL")
val contWorId = eventObject.getInt("CONT_WOR_ID")
val contWorName = eventObject.getString("CONT_WOR_NAME")
val planDate = eventObject.getString("PLAN_DATE")
val place = eventObject.getString("PLACE")
val execDate = eventObject.getString("EXEC_DATE")
val responsibleWorkers = eventObject.getString("RESPONSIBLE_WORKERS")
val signed = eventObject.getInt("SIGNED")
val canceled = eventObject.getInt("CANCELED")
val planStartTime = eventObject.getString("PLAN_START_TIME")
val planEndTime = eventObject.getString("PLAN_END_TIME")
val planDateTimeStr = eventObject.getString("PLAN_DATE_TIME_STR")
//Log.e("id", id.toString())
Log.e("name", name)
Log.e("activiviviviviv", activityType)
Log.e("local", local.toString())
Event(
id = id,
name = name,
activityType = activityType,
subdivision = subdivision,
local = local,
contWorId = contWorId,
contWorName = contWorName,
planDate = planDate,
place = place,
execDate = execDate,
responsibleWorkers = responsibleWorkers,
signed = signed,
canceled = canceled,
planStartTime = planStartTime,
planEndTime = planEndTime,
planDateTimeStr = planDateTimeStr
)
}
} catch (e: JSONException) {
return emptyList()
}
}
}
|
<template>
<el-dialog
v-model="showSettings"
:before-close="handleClose"
width="calc(var(--app-width) * 0.8)"
>
<template #header>
<span class="el-dialog__title">
{{ $t('moderator.organism.settings.facilitatorSettings.header') }}
</span>
<br />
<br />
<p>
{{ $t('moderator.organism.settings.facilitatorSettings.info') }}
</p>
</template>
<el-table
v-if="roles && roles.length > 0"
:data="roles"
style="width: 100%"
max-height="250"
>
<el-table-column
prop="username"
:label="$t('moderator.organism.settings.facilitatorSettings.email')"
/>
<el-table-column
:label="$t('moderator.organism.settings.facilitatorSettings.role')"
>
<template #default="scope">
{{ $t(`enum.userType.${scope.row.role}`) }}
</template>
</el-table-column>
<el-table-column width="120">
<template #default="scope">
<span v-on:click="editUser(scope.$index)">
<font-awesome-icon class="icon link" icon="pen" />
</span>
<span v-on:click="deleteUser(scope.$index)">
<font-awesome-icon class="icon link" icon="trash" />
</span>
</template>
</el-table-column>
</el-table>
<br />
<br />
<ValidationForm
:form-data="formData"
:use-default-submit="false"
v-on:submitDataValid="save"
v-on:reset="reset"
>
<el-form-item
prop="email"
:rules="[defaultFormRules.ruleEmail, defaultFormRules.ruleRequired]"
>
<span class="layout__level">
<el-input
v-model="formData.email"
name="email"
autocomplete="on"
:placeholder="
$t('moderator.organism.settings.facilitatorSettings.info')
"
/>
<span>
<el-select v-model="formData.role">
<el-option
:value="UserType.FACILITATOR"
:label="$t(`enum.userType.${UserType.FACILITATOR}`)"
/>
<el-option
:value="UserType.MODERATOR"
:label="$t(`enum.userType.${UserType.MODERATOR}`)"
/>
<el-option
v-if="noOwner"
:value="UserType.OWNER"
:label="$t(`enum.userType.${UserType.OWNER}`)"
/>
</el-select>
</span>
<span style="margin-right: 0">
<el-button type="primary" native-type="submit" circle>
<font-awesome-icon icon="check" style="font-size: 1.5rem" />
</el-button>
</span>
</span>
</el-form-item>
<el-form-item
:label="
$t('moderator.organism.settings.facilitatorSettings.allowAnonymous')
"
prop="allowAnonymous"
class="allow"
>
<el-switch v-model="formData.allowAnonymous" />
<router-link
v-if="formData.allowAnonymous"
:to="`/public-screen/${sessionId}/everyone`"
target="_blank"
>
<el-button type="info">
<template #icon>
<font-awesome-icon :icon="['fac', 'presentation']" />
</template>
{{
$t('moderator.organism.settings.facilitatorSettings.publicScreen')
}}
</el-button>
</router-link>
</el-form-item>
<el-form-item
prop="stateMessage"
:rules="[defaultFormRules.ruleStateMessage]"
>
<el-input
v-model="formData.stateMessage"
class="hide"
input-style="display: none"
/>
</el-form-item>
</ValidationForm>
</el-dialog>
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component';
import { Prop, Watch } from 'vue-property-decorator';
import myUpload from 'vue-image-crop-upload/upload-3.vue';
import { defaultFormRules, ValidationRuleDefinition } from '@/utils/formRules';
import { ValidationData } from '@/types/ui/ValidationRule';
import ValidationForm, {
ValidationFormCall,
} from '@/components/shared/molecules/ValidationForm.vue';
import FromSubmitItem from '@/components/shared/molecules/FromSubmitItem.vue';
import * as sessionRoleService from '@/services/session-role-service';
import * as sessionService from '@/services/session-service';
import { SessionRole } from '@/types/api/SessionRole';
import UserType from '@/types/enum/UserType';
import { getSingleTranslatedErrorMessage } from '@/services/exception-service';
import * as authService from '@/services/auth-service';
import EndpointAuthorisationType from '@/types/enum/EndpointAuthorisationType';
import { Session } from '@/types/api/Session';
import * as cashService from '@/services/cash-service';
@Options({
components: {
ValidationForm,
FromSubmitItem,
'my-upload': myUpload,
},
emits: ['update:showModal'],
})
/* eslint-disable @typescript-eslint/no-explicit-any*/
export default class FacilitatorSettings extends Vue {
defaultFormRules: ValidationRuleDefinition = defaultFormRules;
@Prop({ default: false }) showModal!: boolean;
@Prop({ default: '' }) sessionId!: string;
session!: Session;
roles: SessionRole[] = [];
own = '';
ownRole = '';
noOwner = false;
formData: ValidationData = {
email: '',
role: UserType.FACILITATOR,
allowAnonymous: false,
};
showSettings = false;
UserType = UserType;
mounted(): void {
this.own = authService.getUserData() || '';
this.reset();
}
handleClose(done: { (): void }): void {
this.reset();
done();
this.$emit('update:showModal', false);
}
reset(): void {
this.formData.email = '';
this.formData.role = UserType.FACILITATOR;
this.formData.call = ValidationFormCall.CLEAR_VALIDATE;
}
@Watch('showModal', { immediate: true })
async onShowModalChanged(showModal: boolean): Promise<void> {
this.showSettings = showModal;
this.reset();
}
roleCash!: cashService.SimplifiedCashEntry<SessionRole[]>;
@Watch('sessionId', { immediate: true })
async onSessionIdChanged(): Promise<void> {
this.deregisterAll();
sessionService.registerGetById(
this.sessionId,
this.updateSession,
EndpointAuthorisationType.MODERATOR,
60 * 60
);
this.roleCash = sessionRoleService.registerGetList(
this.sessionId,
this.updateRole,
EndpointAuthorisationType.MODERATOR,
60 * 60
);
}
updateSession(session: Session): void {
this.session = session;
this.formData.allowAnonymous = session.allowAnonymous;
this.dataLoaded = true;
}
updateRole(roles: SessionRole[]): void {
if (this.own) {
const role = roles.find((role) => role.username === this.own);
if (role) {
this.ownRole = role.role;
}
}
this.noOwner = !roles.find((role) => role.role === UserType.OWNER);
this.roles = roles.filter(
(role) => role.username !== this.own && role.role !== UserType.OWNER
);
}
deregisterAll(): void {
cashService.deregisterAllGet(this.updateSession);
cashService.deregisterAllGet(this.updateRole);
}
unmounted(): void {
this.deregisterAll();
}
dataLoaded = false;
@Watch('formData.allowAnonymous', { immediate: true })
async onAllowAnonymousChanged(): Promise<void> {
if (this.dataLoaded) {
await this.saveAnonymous();
}
}
async saveAnonymous(): Promise<void> {
if (this.session.allowAnonymous !== this.formData.allowAnonymous) {
this.session.allowAnonymous = this.formData.allowAnonymous;
sessionService.put(this.session);
}
}
async save(): Promise<void> {
if (!this.roles.find((role) => role.username === this.formData.email)) {
await sessionRoleService
.post(this.sessionId, {
username: this.formData.email,
role: this.formData.role,
})
.then(
(data) => {
this.roles.push(data);
this.roleCash.refreshData();
this.reset();
},
(error) => {
this.formData.stateMessage = getSingleTranslatedErrorMessage(error);
}
);
} else {
await sessionRoleService
.put(this.sessionId, {
username: this.formData.email,
role: this.formData.role,
})
.then((data) => {
const role = this.roles.find(
(role) => role.username === this.formData.email
);
if (role) role.role = data.role;
this.roleCash.refreshData();
this.reset();
});
}
}
async deleteUser(index: number): Promise<void> {
await sessionRoleService
.remove(this.sessionId, this.roles[index].username)
.then((result) => {
if (result) {
const index = this.roles.findIndex(
(role) => role.username === this.formData.email
);
if (index > -1) this.roles.splice(index, 1);
this.roleCash.refreshData();
}
});
}
async editUser(index: number): Promise<void> {
this.formData.email = this.roles[index].username;
this.formData.role = this.roles[index].role;
}
}
</script>
<style lang="scss" scoped>
.el-form-item .el-form-item {
margin-bottom: 1rem;
}
.el-button.is-circle {
padding: 0.7rem;
}
.awesome-icon {
margin-left: 0.5em;
}
.el-table::v-deep(.cell) {
span {
margin-right: 0.5rem;
}
}
.allow.el-form-item::v-deep(.el-form-item__content) {
.el-form-item__content {
display: flex;
justify-content: space-between;
}
}
</style>
|
package com.krillinator.recap_1_navigation_composedestination.ui.composables
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Preview
@Composable
fun InputFormsUI() {
var input by remember {
mutableStateOf("")
}
// TODO - Themes
// TODO - Break 14:24
Surface(
shadowElevation = 12.dp,
modifier = Modifier
.padding(24.dp)
) {
Column(
modifier = Modifier
.padding(top = 24.dp)
.padding(horizontal = 24.dp)
.padding(bottom = 60.dp)
) {
InputTitleUI(title = "Hello World")
Column(
horizontalAlignment = Alignment.CenterHorizontally,
) {
UnderlinedBreak()
InputFieldUI("Username", "Username",input = input, onValueChangeInput = { input = it })
InputFieldUI("Password", "Password",input = input, onValueChangeInput = { input = it })
Button(onClick = { /*TODO*/ }) {
Text(text = "Submit")
}
}
}
}
}
/* TODO - How do we begin?
* #1 - No Content...
* #1.5 - How should size be related? Match Parent?
* #2 - Where will InputFormsUI exist?
* #3 - What IS InputFormsUI?
* - Important because, delegation of Responsibility
* */
|
package com.infras.dauth.ui.fiat.transaction.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.infras.dauth.R
import com.infras.dauth.app.BaseViewModel
import com.infras.dauth.ext.isAreaCode
import com.infras.dauth.ext.isMail
import com.infras.dauth.ext.isPhone
import com.infras.dauth.ext.isVerifyCode
import com.infras.dauth.manager.AppManagers
import com.infras.dauth.repository.FiatTxRepository
import com.infras.dauth.repository.SignInRepository
import com.infras.dauthsdk.login.model.CountryListParam
import com.infras.dauthsdk.login.model.CountryListRes
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class VerifySetProfileViewModel : BaseViewModel() {
private val repo = SignInRepository()
private val fiatRepo = FiatTxRepository()
private val resourceManager get() = AppManagers.resourceManager
private val _commonEvent = Channel<VerifySetProfileEvent>(capacity = Channel.UNLIMITED)
val commonEvent: Flow<VerifySetProfileEvent> = _commonEvent.receiveAsFlow()
val showTab = MutableLiveData(0)
val phoneContent = MutableLiveData("")
val phoneCodeContent = MutableLiveData("")
val mailContent = MutableLiveData("")
val mailCodeContent = MutableLiveData("")
private val areaSelected = MutableLiveData(0)
val areaCodes = MutableLiveData<List<CountryListRes.CountryInfo>>()
private fun resultString(result: Boolean): String {
return resourceManager.getString(
if (result) {
R.string.success
} else {
R.string.failure
}
)
}
fun sendEmailVerifyCode(account: String) {
viewModelScope.launch {
val result = showLoading { repo.sendEmailVerifyCode(account) }
val toast = resultString(result)
toast(toast)
}
}
private suspend fun bindEmail(email: String, code: String) {
val result = showLoading { repo.bindEmail(email, code) }
val success = result != null && result.isSuccess()
if (success) {
_commonEvent.send(VerifySetProfileEvent.BindEmailSuccess)
}
val toast = resourceManager.getResponseDigest(result)
toast(toast)
}
fun sendSms(phone: String, area: String) {
viewModelScope.launch {
val result = showLoading { repo.sendPhoneVerifyCode(phone, area) }
val toast = resultString(result)
toast(toast)
}
}
private suspend fun bindPhone(phone: String, area: String, verifyCode: String) {
val result = showLoading {
repo.bindPhone(
phone = phone,
areaCode = area,
verifyCode = verifyCode
)
}
val success = result != null && result.isSuccess()
if (success) {
_commonEvent.send(VerifySetProfileEvent.BindPhoneSuccess)
}
val toast = resourceManager.getResponseDigest(result)
toast(toast)
}
fun handleContinue() = viewModelScope.launch {
if (showTab.value == 0) {
val mail = mailContent.value.orEmpty()
if (!mail.isMail()) {
toast("mail format error")
return@launch
}
val mailCode = mailCodeContent.value.orEmpty()
if (!mailCode.isVerifyCode()) {
toast("code format error")
return@launch
}
bindEmail(email = mail, code = mailCode)
} else {
val phone = phoneContent.value.orEmpty()
if (!phone.isPhone()) {
toast("phone format error")
return@launch
}
val phoneCode = phoneCodeContent.value.orEmpty()
if (!phoneCode.isVerifyCode()) {
toast("code format error")
return@launch
}
val pos = areaSelected.value!!
val codes = areaCodes.value!!.map { it.phoneAreaCode }
val areaCode = if (pos >= 0 && pos < codes.size) {
codes[pos].removePrefix("+")
} else {
""
}
if (!areaCode.isAreaCode()) {
toast("area code format error")
return@launch
}
bindPhone(phone, areaCode, phoneCode)
}
}
fun selectAreaCode(pos: Int) {
areaSelected.value = pos
}
fun fetchCountry() {
viewModelScope.launch {
val r = showLoading {
fiatRepo.countryList(CountryListParam())
}
if (r != null && r.isSuccess()) {
val countryInfoList = withContext(Dispatchers.IO) {
r.data?.list.orEmpty()
.asSequence()
.filter { it.isSupport }
.filter { it.phoneAreaCode.isNotEmpty() }
.filter { it.countryCode.isNotEmpty() }
.filter { it.countryName.isNotEmpty() }
.sortedBy { it.countryName }
.toMutableList()
}
areaCodes.value = countryInfoList
}
}
}
}
sealed class VerifySetProfileEvent {
object BindEmailSuccess : VerifySetProfileEvent()
object BindPhoneSuccess : VerifySetProfileEvent()
}
|
// Import the express router as shown in the lecture code
// Note: please do not forget to export the router!
import { Router } from "express";
import { ObjectId } from "mongodb";
import { events } from "../data/index.js";
import {
checkString,
checkDate,
checkTime,
timeToMinutes,
} from "../helpers.js";
export const eventsRouter = Router();
eventsRouter
.route("/")
.get(async (req, res) => {
//code here for GET
try {
const allObjIdEvents = await events.getAll();
const allEvents = allObjIdEvents.map((event) => ({
_id: event._id.toString(),
eventName: event.eventName,
}));
return res.json(allEvents);
} catch (e) {
return res.status(404).json({ error: e });
}
})
.post(async (req, res) => {
//code here for POST
try {
const data = req.body;
if (!data) throw "input is required";
let {
eventName,
description: eventDescription,
eventLocation,
contactEmail,
maxCapacity,
priceOfAdmission,
eventDate,
startTime,
endTime,
publicEvent,
} = data;
if (!eventLocation) throw "eventLocation is required";
if (!maxCapacity) throw "maxCapacity is required";
if (!priceOfAdmission && priceOfAdmission !== 0)
throw "priceOfAdmission is required";
if (publicEvent === undefined) throw "publicEvent is required";
eventName = checkString(eventName, "eventName");
if (eventName.length < 5)
throw "the length of eventName must longer than 5";
eventDescription = checkString(eventDescription, "eventDescription");
if (eventDescription.length < 25)
throw "the eventDescription must have at least 25 characters";
contactEmail = checkString(contactEmail, "contactEmail");
if (
!contactEmail.match(/^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/)
)
throw "the contactEmail is invalid";
eventDate = checkDate(eventDate, "eventDate");
if (new Date(eventDate) - new Date() < 0)
throw "eventTime must be greater than the current date";
startTime = checkTime(startTime, "startTime");
endTime = checkTime(endTime, "endTime");
const startTimeMins = timeToMinutes(startTime);
const endTimeMins = timeToMinutes(endTime);
if (endTimeMins - startTimeMins < 0)
throw "startTime must be earlier than endTime";
if (endTimeMins - startTimeMins < 30)
throw "the events time at least last 30 minutes";
if (typeof publicEvent !== "boolean")
throw "the value of publicEvent must be boolean false or true";
if (typeof maxCapacity !== "number")
throw "the type of maxCapacity must be number";
if (maxCapacity % 1) throw "maxCapacity must be integer";
if (typeof priceOfAdmission !== "number")
throw "the type of priceOfAdmission must be number";
if (maxCapacity <= 0) throw "maxCapacity must larger than 0";
if (priceOfAdmission < 0) throw "priceOdAdmission must be positive or 0";
if (
priceOfAdmission !== 0 &&
!priceOfAdmission.toString().match(/^\d+\.\d{0,2}$/)
)
throw "the length of priceOfAdmission cannot longer than two decimal place";
if (typeof eventLocation !== "object" || Array.isArray(eventDescription))
throw "the type of eventLocation must be object";
let { streetAddress, city, state, zip } = eventLocation;
if (!streetAddress) throw "streetAddress are not supplied";
streetAddress = checkString(streetAddress, "streetAddress");
city = checkString(city, "city");
state = checkString(state, "state");
zip = checkString(zip, "zip");
if (streetAddress.length < 3)
throw "streetAddress must have at least 3 characters";
if (city.length < 3)
throw "city must have at least 3 characters";
const usStateAbbreviations = [
"AL",
"AK",
"AZ",
"AR",
"CA",
"CO",
"CT",
"DE",
"FL",
"GA",
"HI",
"ID",
"IL",
"IN",
"IA",
"KS",
"KY",
"LA",
"ME",
"MD",
"MA",
"MI",
"MN",
"MS",
"MO",
"MT",
"NE",
"NV",
"NH",
"NJ",
"NM",
"NY",
"NC",
"ND",
"OH",
"OK",
"OR",
"PA",
"RI",
"SC",
"SD",
"TN",
"TX",
"UT",
"VT",
"VA",
"WA",
"WV",
"WI",
"WY",
];
if (!usStateAbbreviations.includes(state))
throw "state must be a valid state abbreviation";
if (!zip.match(/^[0-9]{5}$/gi)) throw "zip must consist of five numbers";
const newEvent = await events.create(
eventName,
eventDescription,
eventLocation,
contactEmail,
maxCapacity,
priceOfAdmission,
eventDate,
startTime,
endTime,
publicEvent
);
return res.status(200).json(newEvent);
} catch (e) {
return res.status(400).json({ error: e });
}
});
eventsRouter
.route("/:eventId")
.get(async (req, res) => {
//code here for GET
let eventId = req.params.eventId;
let id;
try {
id = checkString(eventId, "eventId");
if (!ObjectId.isValid(id)) throw "the eventId is not valid!";
} catch (e) {
return res.status(400).json({ error: e });
}
try {
const eventsInfo = await events.get(id);
} catch (e) {
return res.status(404).json({ error: e });
}
try {
const eventsInfo = await events.get(id);
return res.status(200).json(eventsInfo);
} catch (e) {}
})
.delete(async (req, res) => {
//code here for DELETE
let eventId = req.params.eventId;
let id;
try {
id = checkString(eventId, "eventId");
if (!ObjectId.isValid(id)) throw "the eventId is not valid!";
} catch (e) {
return res.status(400).json({ error: e });
}
try {
const eventsInfo = await events.get(id);
} catch (e) {
return res.status(404).json({ error: e });
}
try {
const deleteInfo = await events.remove(id);
return res.status(200).json(deleteInfo);
} catch (e) {
return res.json({ error: e });
}
})
.put(async (req, res) => {
//code here for PUT
const eventId = req.params.eventId;
const data = req.body;
let id;
try {
id = checkString(eventId, "eventId");
} catch (e) {
return res.status(400).json({ error: e });
}
try {
const targetEvent = await events.get(id);
} catch (e) {
return res.status(404).json({ error: e });
}
try {
if (!data) throw "input is required";
let {
eventName,
description: eventDescription,
eventLocation,
contactEmail,
maxCapacity,
priceOfAdmission,
eventDate,
startTime,
endTime,
publicEvent,
} = data;
if (!eventLocation) throw "eventLocation is required";
if (!maxCapacity) throw "maxCapacity is required";
if (!priceOfAdmission && priceOfAdmission !== 0)
throw "priceOfAdmission is required";
if (publicEvent === undefined) throw "publicEvent is required";
eventName = checkString(eventName, "eventName");
if (eventName.length < 5)
throw "the length of eventName must longer than 5";
eventDescription = checkString(eventDescription, "eventDescription");
if (eventDescription.length < 25)
throw "the eventDescription must have at least 25 characters";
contactEmail = checkString(contactEmail, "contactEmail");
if (
!contactEmail.match(/^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/)
)
throw "the contactEmail is invalid";
eventDate = checkDate(eventDate, "eventDate");
if (new Date(eventDate) - new Date() < 0)
throw "eventTime must be greater than the current date";
startTime = checkTime(startTime, "startTime");
endTime = checkTime(endTime, "endTime");
const startTimeMins = timeToMinutes(startTime);
const endTimeMins = timeToMinutes(endTime);
if (endTimeMins - startTimeMins < 0)
throw "startTime must be earlier than endTime";
if (endTimeMins - startTimeMins < 30)
throw "the events time at least last 30 minutes";
if (typeof publicEvent !== "boolean")
throw "the value of publicEvent must be boolean false or true";
if (typeof maxCapacity !== "number")
throw "the type of maxCapacity must be number";
if (maxCapacity % 1) throw "maxCapacity must be integer";
const targetEvent = await events.get(eventId);
if (targetEvent.attendees.length >= maxCapacity)
throw "the number of attendees in the event exceeds the maxCapacity to be updated so the maxCapacity cannot be updated";
const { attendees, totalNumberOfAttendees } = targetEvent;
if (typeof priceOfAdmission !== "number")
throw "the type of priceOfAdmission must be number";
if (maxCapacity <= 0) throw "maxCapacity must larger than 0";
if (priceOfAdmission < 0) throw "priceOdAdmission must be positive or 0";
if (
priceOfAdmission !== 0 &&
!priceOfAdmission.toString().match(/^\d+\.\d{0,2}$/)
)
throw "the length of priceOfAdmission cannot longer than two decimal place";
if (typeof eventLocation !== "object" || Array.isArray(eventDescription))
throw "the type of eventLocation must be object";
let { streetAddress, city, state, zip } = eventLocation;
if (!streetAddress) throw "streetAddress are not supplied";
streetAddress = checkString(streetAddress, "streetAddress");
city = checkString(city, "city");
state = checkString(state, "state");
zip = checkString(zip, "zip");
if (streetAddress.length < 3)
throw "streetAddress must have at least 3 characters";
if (!city.match(/[a-z]{3,}/gi))
throw "city must have at least 3 characters";
const usStateAbbreviations = [
"AL",
"AK",
"AZ",
"AR",
"CA",
"CO",
"CT",
"DE",
"FL",
"GA",
"HI",
"ID",
"IL",
"IN",
"IA",
"KS",
"KY",
"LA",
"ME",
"MD",
"MA",
"MI",
"MN",
"MS",
"MO",
"MT",
"NE",
"NV",
"NH",
"NJ",
"NM",
"NY",
"NC",
"ND",
"OH",
"OK",
"OR",
"PA",
"RI",
"SC",
"SD",
"TN",
"TX",
"UT",
"VT",
"VA",
"WA",
"WV",
"WI",
"WY",
];
if (!usStateAbbreviations.includes(state))
throw "state must be a valid state abbreviation";
if (!zip.match(/^[0-9]{5}$/gi)) throw "zip must consist of five numbers";
const newEvent = await events.update(
id,
eventName,
eventDescription,
eventLocation,
contactEmail,
maxCapacity,
priceOfAdmission,
eventDate,
startTime,
endTime,
publicEvent,
attendees,
totalNumberOfAttendees
);
return res.status(200).json(newEvent);
} catch (e) {
return res.status(400).json({ error: e });
}
});
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,700;0,800;1,100;1,300;1,400;1,500;1,700;1,800&display=swap"
rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="styles.css" />
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<title>Barber Shop</title>
</head>
<body>
<div class="bg-home">
<header>
<nav class="header-content container">
<div class="header-icons" data-aos="fade-down">
<a href="https://www.instagram.com/julio_rodrigues84/">
<i class="fa-brands fa-instagram fa-2x" > </i>
</a>
<a href="#">
<i class="fa-brands fa-facebook fa-2x" > </i>
</a>
<a href="https://www.linkedin.com/in/julio-rodrigues84/">
<i class="fa-brands fa-linkedin-in fa-2x" > </i>
</a>
</div>
<div class="header-logo" data-aos="fade-up" data-aos-delay="350">
<img
data-aos="flip-up"
data-aos-delay="350"
data-aos-duration="1500"
src="assets/logo.svg"
alt="logo da barbearia"
/>
</div>
<div data-aos="fade-down" >
<a class="header-button" href="mailto:juliorodrigues84@live.com">
Entre em contato
</a>
</div>
</nav>
<main class="hero container" data-aos="fade-up" data-aos-delay="400">
<h1>Estilo é um reflexo da sua atitude e sua personalidade</h1>
<p>Horário de atendimento: 09 as 18</p>
<a
href="http://wa.me/5515998250732" class="button-contact" target="_blank">
Agende um horário
</a>
</main>
</header>
</div>
<section class="about">
<div class="container about-content">
<div data-aos="zoom-in" data-aos-delay="100">
<img
src="assets/images.svg"
alt="imagem da barbearia"
/>
</div>
<div class="about-description"
data-aos="zoom-out" data-aos-delay="250"
>
<h2>Sobre</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt iste commodi optio quaerat? Laboriosam eveniet nulla error itaque dolores. Molestiae nostrum labore debitis soluta nesciunt sed delectus illo pariatur quam.</p>
<p>Horário de funcionamento <strong>09:00</strong> as <strong>19:00</strong></p>
</div>
</div>
</section>
<section class="services">
<div class="services-content container">
<h2>Serviços</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem laudantium repellendus ipsa unde dicta error aliquam accusantium! Reiciendis, esse? Tenetur amet veniam excepturi id
repellendus tempora pariatur culpa odio distinctio!
</p>
</div>
<section class="haircuts">
<div class="haircut" data-aos="fade-up" data-aos-delay="150">
<img src="assets/corte1.png" alt="corte normal"
/>
<div class="haircut-info">
<strong>Corte Normal</strong>
<button>
R$60,00
</button>
</div>
</div>
<div class="haircut" data-aos="fade-up" data-aos-delay="300">
<img
src="assets/corte2.png"
alt="barba completa"
/>
<div class="haircut-info">
<strong>Barba Completa</strong>
<button>
R$50,00
</button>
</div>
</div>
<div class="haircut" data-aos="fade-up" data-aos-delay="450">
<img
src="assets/corte3.png"
alt="corte e barba"
/>
<div class="haircut-info">
<strong>Cabelo e barba</strong>
<button>
R$95,00
</button>
</div>
</div>
</section>
</section>
<div class="services">
<h2>Venha conhecer</h2>
</div>
<iframe
width="100%"
src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d14632.077137657687!2d-47.4574764!3d-23.5318088!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94c58a65fcb4e499%3A0x97dd13700a6c9e23!2sIguatemi%20Business%20Esplanada!5e0!3m2!1spt-BR!2sbr!4v1696898734950!5m2!1spt-BR!2sbr" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"
referrerpolicy="no-referrer-when-downgrade"></iframe>
<footer class="footer">
<div class="footer-icons">
<a href="https://www.instagram.com/julio_rodrigues84/">
<i class="fa-brands fa-instagram fa-2x" > </i>
</a>
<a href="#">
<i class="fa-brands fa-facebook fa-2x" > </i>
</a>
<a href="https://www.linkedin.com/in/julio-rodrigues84/">
<i class="fa-brands fa-linkedin-in fa-2x" > </i>
</a>
</div>
<div>
<img
src="assets/logo.svg"
alt="logo barbearia"
/>
</div>
<p>Copyright 2023 | Júlio Rodrigues - Todos os direitos reservados.</p>
</footer>
<a href="http://wa.me/5515998250732"
class="btn-whatsapp"
target="_blank"
data-aos="zoom-in-up" data-aos-delay="500"
>
<img src="assets/whatssapp.svg" alt="Botão WhatsApp">
<span class="tooltip-text">Agende seu horario</span>
</a>
<script src="script.js"></script>
</body>
</html>
|
<h3>3. Longest Substring Without Repeating Characters</h3>
<br>
Given a string <code>s</code>, find the length of the <strong>longest substring</strong> without repeating characters.<br>
<br>
<b>Example 1:</b><br>
<br>
<pre>
<strong>Input:</strong> s = "abcabcbb"
<strong>Output:</strong> 3
<strong>Explanation:</strong> The answer is "abc", with the length of 3.
</pre>
<br>
<b>Example 2:</b><br>
<br>
<pre>
<strong>Input:</strong> s = "bbbbb"
<strong>Output:</strong> 1
<strong>Explanation:</strong> The answer is "b", with the length of 1.
</pre>
<br>
<b>Example 3:</b><br>
<br>
<pre>
<strong>Input:</strong> s = "pwwkew"
<strong>Output:</strong> 3
<strong>Explanation:</strong> The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
</pre>
<br>
<b>Constraints:</b><br>
<br>
<li><code>0 <= s.length <= 5 * 10<sup>4</sup></code></li>
<li><code>s</code> consists of English letters, digits, symbols and spaces.</li>
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.views.image;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class ImageLoadEvent extends Event<ImageLoadEvent> {
@IntDef({ON_ERROR, ON_LOAD, ON_LOAD_END, ON_LOAD_START, ON_PROGRESS})
@Retention(RetentionPolicy.SOURCE)
@interface ImageEventType {}
public static final int ON_ERROR = 1;
public static final int ON_LOAD = 2;
public static final int ON_LOAD_END = 3;
public static final int ON_LOAD_START = 4;
public static final int ON_PROGRESS = 5;
private final int mEventType;
private final @Nullable String mErrorMessage;
private final @Nullable String mSourceUri;
private final int mWidth;
private final int mHeight;
private final int mLoaded;
private final int mTotal;
public static final ImageLoadEvent createLoadStartEvent(int viewId) {
return new ImageLoadEvent(viewId, ON_LOAD_START);
}
/**
* @param loaded Amount of the image that has been loaded. It should be number of bytes, but
* Fresco does not currently provides that information.
* @param total Amount that `loaded` will be when the image is fully loaded.
*/
public static final ImageLoadEvent createProgressEvent(
int viewId, @Nullable String imageUri, int loaded, int total) {
return new ImageLoadEvent(viewId, ON_PROGRESS, null, imageUri, 0, 0, loaded, total);
}
public static final ImageLoadEvent createLoadEvent(
int viewId, @Nullable String imageUri, int width, int height) {
return new ImageLoadEvent(viewId, ON_LOAD, null, imageUri, width, height, 0, 0);
}
public static final ImageLoadEvent createErrorEvent(int viewId, Throwable throwable) {
return new ImageLoadEvent(viewId, ON_ERROR, throwable.getMessage(), null, 0, 0, 0, 0);
}
public static final ImageLoadEvent createLoadEndEvent(int viewId) {
return new ImageLoadEvent(viewId, ON_LOAD_END);
}
private ImageLoadEvent(int viewId, @ImageEventType int eventType) {
this(viewId, eventType, null, null, 0, 0, 0, 0);
}
private ImageLoadEvent(
int viewId,
@ImageEventType int eventType,
@Nullable String errorMessage,
@Nullable String sourceUri,
int width,
int height,
int loaded,
int total) {
super(viewId);
mEventType = eventType;
mErrorMessage = errorMessage;
mSourceUri = sourceUri;
mWidth = width;
mHeight = height;
mLoaded = loaded;
mTotal = total;
}
public static String eventNameForType(@ImageEventType int eventType) {
switch (eventType) {
case ON_ERROR:
return "topError";
case ON_LOAD:
return "topLoad";
case ON_LOAD_END:
return "topLoadEnd";
case ON_LOAD_START:
return "topLoadStart";
case ON_PROGRESS:
return "topProgress";
default:
throw new IllegalStateException("Invalid image event: " + Integer.toString(eventType));
}
}
@Override
public String getEventName() {
return ImageLoadEvent.eventNameForType(mEventType);
}
@Override
public short getCoalescingKey() {
// Intentionally casting mEventType because it is guaranteed to be small
// enough to fit into short.
return (short) mEventType;
}
@Override
public void dispatch(RCTEventEmitter rctEventEmitter) {
WritableMap eventData = null;
switch (mEventType) {
case ON_PROGRESS:
eventData = Arguments.createMap();
eventData.putInt("loaded", mLoaded);
eventData.putInt("total", mTotal);
break;
case ON_LOAD:
eventData = Arguments.createMap();
eventData.putMap("source", createEventDataSource());
break;
case ON_ERROR:
eventData = Arguments.createMap();
eventData.putString("error", mErrorMessage);
break;
}
rctEventEmitter.receiveEvent(getViewTag(), getEventName(), eventData);
}
private WritableMap createEventDataSource() {
WritableMap source = Arguments.createMap();
source.putString("uri", mSourceUri);
source.putDouble("width", mWidth);
source.putDouble("height", mHeight);
return source;
}
}
|
/*
Eversion, a CRPG engine.
Copyright (c) 2002-2012 Utkan Güngördü (utkan@freeconsole.org)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef EVERSION__GAME_H
#define EVERSION__GAME_H
#include <vector>
#include "entity.h"
#include "globals.h"
#include "map.h"
#include "font.h"
#include "window.h"
#include "textbox.h"
namespace eversion {
// game Singleton:
class game
{
private:
static game *lpGame;
bool alive;
//view-port related variables
map themap;
::SDL_Rect scene;
point2D<s32> cam;
std::vector<entity*> entities;
font thefont;
textbox textWin;
//entity related vairables
size_t focus; //index of the entity followed by cam
game() : alive(true) { }
public:
~game();
static game *instance();
// Functions related to initializations
// Main initialization function of the game
void init();
private:
void initScene(s32 w, s32 h);
// Game-Logic functions
void updateControls();
void updateKeyb();
void updateMouse();
public:
// GameOver flag controls
bool isAlive() { return alive; }
//void isOver(bool _endGame) { endGame = _endGame; } // change the flag
void endGame() { alive = false; }
// Graphics Drawing functions
void drawScene();
void drawEntities();
::SDL_Rect getSceneRect() { return scene; }
font& getFont() { return thefont; }
void moveCam(s32 x, s32 y) { cam.x+=x; cam.y+=y; normalizeCam(); }
void moveCam(const point2D<s32> &p) { moveCam(p.x,p.y); }
void normalizeCam();
point2D<s32> getCam() { return cam; }
// Game-Logic functions
void update();
char checkObstruction(entity* ent, entity::direction_t d);//-3=map_bounds,-2=map_obs, -1=entity, 0=no-obst
bool thereEntity(s32 x, s32 y);
void spawnEntity(char *img, s32 tx, s32 ty, s32 w=32, s32 h=32, s32 s=4, entity::direction_t d=entity::down);
};
}
#endif //EVERSION__GAME_H
|
/*--------------- 1ra Area: Codigo de Usuario -----------------------*/
//-------> importaciones, paquetes
package analizadores;
import java_cup.runtime.Symbol;
import java.util.LinkedList;
//------> Codigo para el parser,variables, metodos
parser code
{:
public String resultado="";
public static LinkedList<TError> TablaES = new LinkedList<TError>();
//Metodo al que se llama automaticamente ante algun error sintactico
public void syntax_error(Symbol s)
{
String lexema = s.value.toString();
int fila = s.right;
int columna = s.left;
System.out.println("!!!!!!! Error Sintactico Recuperado !!!!!!!");
System.out.println("\t\tLexema: "+lexema);
System.out.println("\t\tFila: "+fila);
System.out.println("\t\tColumna: "+columna);
TError datos = new TError(lexema,fila,columna,"Error Sintactico","Caracter no esperado");
TablaES.add(datos);
}
//Metodo al que se llama en el momento en que ya no es posible una recuperacion de errores
public void unrecovered_syntax_error(Symbol s) throws java.lang.Exception
{
String lexema = s.value.toString();
int fila = s.right;
int columna = s.left;
System.out.println("!!!!!!! Error Sintactico, Panic Mode !!!!!!! ");
System.out.println("\t\tLexema: "+lexema);
System.out.println("\t\tFila: "+fila);
System.out.println("\t\tColumna: "+columna);
TError datos = new TError(lexema,fila,columna,"Error Sintactico","Caracter no esperado");
TablaES.add(datos);
}
:}
//------> Codigo para las acciones gramaticales
action code
{:
:}
/*--------------- 2da Area: Declaraciones -----------------------*/
//------> declaracion de terminales
terminal $,alfanumerio,letras,cadena_texto,identificador,mas,menos,por,div,para,parc,asig,comp,dist,menor,mayor,or,and,Labre,Lcierra,Cabre,Cciera,Pcoma,Pabre,Pcierra,set,IF,ELSE,WHILE,PUTW,puts;
terminal String num;
//------> declaracion de no terminales
non terminal String INICIO,Expresion,Declaracion,Declaraciones,Cuerpo,bloqueSentencias,Sentencia,sentencias;
non terminal Condicion,sentif,sentElse,sentWhile,sentAsignacion,sentPutw,sentPuts,sentBreak;
//----> precedencia de menor a mayor
precedence left mas, menos;
precedence left por, div;
precedence left and, or;
start with INICIO;
INICIO ::= Declaraciones Cuerpo | Cuerpo;
Declaraciones::= Declaracion Declaraciones | Declaracion;
Declaracion::= set identificador Pcoma|;
//Cuerpo::= MAIN Pabre Pcierra Labre bloqueSentencias Lcierra ;
Cuerpo:: Declaraciones| bloqueSentencias;
bloqueSentencias::= sentencias | ;
sentencias::= Sentencia sentencias | Sentencia;
Expresion::= Expresion:a mas Expresion:b {: int val1= Integer.parseInt(a);
int val2= Integer.parseInt(b);
int r = val1+val2;
RESULT = String.valueOf(r); :}
|Expresion:a menos Expresion:b {: int val1= Integer.parseInt(a);
int val2= Integer.parseInt(b);
int r = val1-val2;
RESULT = String.valueOf(r); :}
|Expresion:a div Expresion:b {: int val1= Integer.parseInt(a);
int val2= Integer.parseInt(b);
int r = val1/val2;
RESULT = String.valueOf(r); :}
|Expresion:a por Expresion:b {: int val1= Integer.parseInt(a);
int val2= Integer.parseInt(b);
int r = val1*val2;
RESULT = String.valueOf(r); :}
|identificador
|para Expresion:a {: RESULT = a; :} parc
|num:a {: RESULT = a; :};
Condicion::=Condicion or Condicion|
Condicion and Condicion|
Expresion comp Expresion|
Expresion mayor Expresion|
Expresion menor Expresion|
Expresion dist Expresion|
Pabre Condicion Pcierra;
sentif::= IF Labre Condicion Lcierra
Labre bloqueSentencias Lcierra sentElse;
sentElse::= ELSE Labre bloqueSentencias Lcierra|;
sentWhile::= WHILE Pabre Condicion Pcierra
Labre bloqueSentencias Lcierra;
sentAsignacion::=identificador asig Expresion Pcoma;
sentPutw::= PUTW Pabre Expresion Pcierra Pcoma;
sentPuts::= puts Pabre cadena_texto Pcierra | puts Pabre $ identificador Pcierra |
puts Labre cadena_texto Lcierra ;
sentBreak::= BREAK Pcoma;
Sentencia::=sentif|
sentWhile|
sentAsignacion|
sentPutw|
sentPuts|
sentBreak;
|
Feature: As an admin
I need to be able to specify a padding time for services
So that my staff has enough time between appointments.
Scenario: I add a service with no padding
Given I am logged in as admin
And I am on "/manage-services"
When I follow "New Service"
And I fill in "name" with "training"
And I fill in "padding" with "0"
And I check "durations-30"
And press "save"
When I follow "btn-edit" for "training"
Then field "padding" should have value "0"
Scenario: I add a service with 30m padding
Given I am logged in as admin
And I am on "/manage-services"
When I follow "New Service"
And I fill in "name" with "training"
And I fill in "padding" with "30"
And I check "durations-30"
And press "save"
When I follow "btn-edit" for "training"
Then field "padding" should have value "30"
Scenario: I add a service with 1hr padding
Given I am logged in as admin
And I am on "/manage-services"
When I follow "New Service"
And I fill in "name" with "training"
And I fill in "padding" with "60"
And I check "durations-30"
And press "save"
When I follow "btn-edit" for "training"
Then field "padding" should have value "60"
Scenario: I edit a service's padding from 30 to 60
Given I am logged in as admin
And I am on "/manage-services"
When I follow "New Service"
And I fill in "name" with "training"
And I fill in "padding" with "30"
And I check "durations-30"
And press "save"
And I follow "btn-edit" for "training"
And I fill in "padding" with "60"
And press "save"
And I follow "btn-edit" for "training"
Then field "padding" should have value "60"
|
local ensure_packer = function()
local fn = vim.fn
local install_path = fn.stdpath('data') .. '/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({ 'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path })
vim.cmd [[packadd packer.nvim]]
return true
end
return false
end
local packer_bootstrap = ensure_packer()
return require('packer').startup(function(use)
use 'wbthomason/packer.nvim'
use 'lambdalisue/suda.vim' -- write sudo if not in sudo
use 'alx741/vinfo' -- vim GNU info implementation <C-]> follow tag
--use 'HiPhish/info.vim' -- vim GNU info implementation
use 'linty-org/readline.nvim' -- readline navigation for :, / or ?
use 'folke/tokyonight.nvim' -- tokyo theme
use 'shaunsingh/nord.nvim' -- nord theme
--use 'mbbill/undotree' -- undo any history
--use 'edluffy/hologram.nvim' -- images in nvim
use 'uga-rosa/ccc.nvim' -- color picker with :CccPick
use 'lervag/vimtex' -- latex thingi...
use 'lukas-reineke/indent-blankline.nvim' -- indent show
use 'ghostbuster91/nvim-next' -- repeable movements ;, for all commands
use 'folke/which-key.nvim' -- key help floating while typing
--use 'michaeljsmith/vim-indent-object' -- python textobject
use {
'glacambre/firenvim',
run = function() vim.fn['firenvim#install'](0) end
}
--use 'ellisonleao/glow.nvim' -- highlight marker, markdown files etc
use {
'iamcco/markdown-preview.nvim',
run = function() vim.fn['mkdp#util#install']() end,
}
--use{
-- 'anuvyklack/pretty-fold.nvim',
-- config = function() require('pretty-fold').setup() end
--}
--use { -- colorize depending on color code
-- 'norcalli/nvim-colorizer.lua',
-- config = function() require('colorizer').setup() end
--}
use {
'luukvbaal/nnn.nvim',
config = function() require('nnn').setup() end
}
use { -- git time stamps
'lewis6991/gitsigns.nvim',
requires = { 'nvim-lua/plenary.nvim' },
config = function() require('gitsigns').setup() end
}
use { -- highlight fF colors
'kevinhwang91/nvim-fFHighlight',
config = function() require('fFHighlight').setup() end
}
-- use {
-- 'Pocco81/HighStr.nvim', -- highlight string colors
-- config = function()
-- require('high-str').setup({
-- verbosity = 0,
-- saving_path = '/tmp/highstr/',
-- highlight_colors = {
-- -- color_id = {'bg_hex_code',<'fg_hex_code'/'smart'>}
-- color_0 = {'#0c0d0e', 'smart'}, -- Cosmic charcoal
-- color_1 = {'#e5c07b', 'smart'}, -- Pastel yellow
-- color_2 = {'#7FFFD4', 'smart'}, -- Aqua menthe
-- color_3 = {'#8A2BE2', 'smart'}, -- Proton purple
-- color_4 = {'#FF4500', 'smart'}, -- Orange red
-- color_5 = {'#008000', 'smart'}, -- Office green
-- color_6 = {'#0000FF', 'smart'}, -- Just blue
-- color_7 = {'#FFC0CB', 'smart'}, -- Blush pink
-- color_8 = {'#FFF9E3', 'smart'}, -- Cosmic latte
-- color_9 = {'#7d5c34', 'smart'}, -- Fallow brown
-- }
-- })
-- end
-- }
use { -- debug ui
'rcarriga/nvim-dap-ui',
requires = { 'mfussenegger/nvim-dap' },
}
use { -- MASON, formatter/linter, debugger, lsp
'williamboman/mason.nvim',
requires = {
{ 'jose-elias-alvarez/null-ls.nvim' },
{ 'jay-babu/mason-null-ls.nvim' },
{ 'mfussenegger/nvim-dap' },
{ 'jay-babu/mason-nvim-dap.nvim' },
{ 'neovim/nvim-lspconfig' },
{ 'williamboman/mason-lspconfig.nvim' },
},
}
-- Clang config start
use 'p00f/clangd_extensions.nvim'
-- Clang config end
-- Rust config start
use {
'simrat39/rust-tools.nvim',
requires = { 'nvim-lua/plenary.nvim' },
}
-- Rust config end
use { -- COQ
'windwp/nvim-autopairs',
requires = {
{ 'windwp/nvim-ts-autotag' },
{ 'ms-jpq/coq_nvim', branch = 'coq' },
{ 'ms-jpq/coq.artifacts' },
{ 'ms-jpq/coq.thirdparty' },
run = ':COQdeps',
},
}
use {
'nvim-telescope/telescope.nvim',
requires = {
{ 'nvim-lua/plenary.nvim' },
{ 'debugloop/telescope-undo.nvim' },
{ 'nvim-telescope/telescope-dap.nvim' },
},
}
use { -- fancy line
'nvim-lualine/lualine.nvim',
requires = { 'kyazdani42/nvim-web-devicons', opt = true }
}
use { -- fancy startup screen. Telescope >> fancy fuzyfinder
'startup-nvim/startup.nvim',
requires = {
'nvim-telescope/telescope.nvim',
'nvim-lua/plenary.nvim'
},
}
use { -- highlight code
'nvim-treesitter/nvim-treesitter',
requires = {
'nvim-treesitter/nvim-treesitter-textobjects',
},
run = ':TSUpdate',
}
-- Automatically set up your configuration after cloning packer.nvim
-- Put this at the end after all plugins
if packer_bootstrap then
require('packer').sync()
end
end)
-- https://github.com/wbthomason/packer.nvim#requirements for config
-- :PackerSync
--use {
-- 'myusername/example', -- The plugin location string
--
-- -- The following keys are all optional
-- disable = boolean, -- Mark a plugin as inactive
-- as = string, -- Specifies an alias under which to install the plugin
-- installer = function, -- Specifies custom installer. See "custom installers" below.
-- updater = function, -- Specifies custom updater. See "custom installers" below.
-- after = string or list, -- Specifies plugins to load before this plugin. See "sequencing" below
-- rtp = string, -- Specifies a subdirectory of the plugin to add to runtimepath.
-- opt = boolean, -- Manually marks a plugin as optional.
-- bufread = boolean, -- Manually specifying if a plugin needs BufRead after being loaded
-- branch = string, -- Specifies a git branch to use
-- tag = string, -- Specifies a git tag to use. Supports '*' for "latest tag"
-- commit = string, -- Specifies a git commit to use
-- lock = boolean, -- Skip updating this plugin in updates/syncs. Still cleans.
-- run = string, function, or table, -- Post-update/install hook. See "update/install hooks".
-- requires = string or list, -- Specifies plugin dependencies. See "dependencies".
-- rocks = string or list, -- Specifies Luarocks dependencies for the plugin
-- config = string or function, -- Specifies code to run after this plugin is loaded.
-- -- The setup key implies opt = true
-- setup = string or function, -- Specifies code to run before this plugin is loaded. The code is ran even if
-- -- the plugin is waiting for other conditions (ft, cond...) to be met.
--
-- -- The following keys all imply lazy-loading and imply opt = true
-- cmd = string or list, -- Specifies commands which load this plugin. Can be an autocmd pattern.
-- ft = string or list, -- Specifies filetypes which load this plugin.
-- keys = string or list, -- Specifies maps which load this plugin. See "Keybindings".
-- event = string or list, -- Specifies autocommand events which load this plugin.
-- fn = string or list -- Specifies functions which load this plugin.
-- cond = string, function, or list of strings/functions, -- Specifies a conditional test to load this plugin
-- module = string or list -- Specifies Lua module names for require. When requiring a string which starts
-- -- with one of these module names, the plugin will be loaded.
-- module_pattern = string/list -- Specifies Lua pattern of Lua module names for require. When
-- -- requiring a string which matches one of these patterns, the plugin will be loaded.
--}
|
#Start
#options(stringsAsFactors=F)#有意思,全局设置不转换为因子
#清除所有变量
rm(list=ls())
#运行开始
timestart<-Sys.time() #记录开始运行时间
options(stringsAsFactors=F, quote="",unzip = "internal")#有意思,全局设置不转换为因子
options("repos" = c(CRAN = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))
options(BioC_mirror = "https://mirrors.tuna.tsinghua.edu.cn/bioconductor")
workDir="/Users/lwy/Desktop/重跑v2/data13/3" #工作目录
setwd(workDir)
list.files() #查看工作目录下的文件
File1_0<-read.table("expTime.txt",header=T,row.names=1, sep="\t",check.names = F, quote="")#quote=""
str(File1_0)
# 'data.frame': 163 obs. of 4 variables:
# $ futime : num 0.00274 0.03288 0.03288 0.03836 0.04384 ...
# $ fustat : int 0 0 1 1 1 0 1 0 1 1 ...
# $ RiskScore: num 0.107 0.538 1.934 -3.284 -0.141 ...
# $ Stage : int 0 0 0 0 0 1 0 0 0 0 ...
#得转化为因子
File1_0$Stage <- factor (File1_0$Stage)
str(File1_0)
abc <- File1_0
# ###goodness of fit_______________####这一段不知道有何用处,出了一堆奇奇怪怪的散点图
# library(survival)
# library(survminer)
# fit<-coxph(Surv(futime,fustat)~RiskScore+Stage , data = abc)
# ggcoxdiagnostics(fit, type = "schoenfeld")
# ggcoxdiagnostics(fit, type = "schoenfeld", ox.scale="time")
# ggcoxdiagnostics(fit, type = "deviance")
# ggcoxdiagnostics(fit, type = "martingale")
####C-index#####
abc <- File1_0
names(abc)
library(rms)
library(survival)
set.seed(1)# the method of validate is using random
fit.cph <- cph(Surv(futime, fustat)~ RiskScore+Stage,data=abc,
x=TRUE,y=TRUE,surv=TRUE)
fit.cph
v<-validate(fit.cph, dxy=TRUE, B=1000)
Dxy = v[rownames(v)=="Dxy", colnames(v)=="index.corrected"]
orig_Dxy = v[rownames(v)=="Dxy", colnames(v)=="index.orig"]
bias_corrected_c_index <- abs(Dxy)/2+0.5
orig_c_index <- abs(orig_Dxy)/2+0.5
bias_corrected_c_index #HCC数据显示为 0.6863544
orig_c_index #HCC数据显示为 0.6935687
library(rms)
#install.packages("CsChange")
library(CsChange) ###how c-index changed from model1 to model2###
dd<- datadist(abc)
options(datadist="dd")
model1=cph(Surv(futime, fustat)~ RiskScore+Stage,abc)
model2=cph(Surv(futime, fustat)~ Stage,abc)
CsChange(model1,model2,data=abc,nb=500)
#这一段也很奇怪
source("stdca.R",encoding="utf-8")
####nomogram__________________________######
library(nomogramEx)
library(rms)
abc <- File1_0
attach(abc)
ddist<-datadist(Stage, RiskScore )
options(datadist='ddist')
f<- cph(formula(Surv(futime, fustat)~Stage+RiskScore),#此处决定列线图各变量顺序
data = abc, x=TRUE, y=TRUE, surv=TRUE, time.inc=3) #哪怕前面有了attach,还是需要有data=abc数据框
#data = abc,
surv <- Survival(f)
nomo <- nomogram(f, fun=list(function(x) surv(1,x),function(x) surv(3,x),function(x) surv(5,x)),
lp=FALSE,funlabel=c("1-year Survival Prob","3-year Survival Prob","5-year Survival Prob"))
str(nomo)
pdf(file = "LIHC-Nomo-lwd=20.pdf"
, width = 21
, height = 8
#, onefile
#, family = "Times"#默认"Helvetica"无衬线体sans-serif font,
#可以改为"Times"衬线体,monospaced font (to "Courier").
# , title
# , fonts
# , version
# , paper
# , encoding
# , bg
# , fg
# , pointsize
# , pagecentre
# , colormodel
# , useDingbats
# , useKerning
# , fillOddEven
# , compress
)
plot(nomo,cex.axis = 1.2,cex.var = 1.2, lwd=20,
label.every=2,
col.grid=gray(c(0.8,0.95))
)
dev.off()
#
detach(abc)
##c-plot___________________________________________###
library(nomogramEx)
library(rms)
library(survival)
ddist <- datadist(abc)
options(datadist='ddist')
units(abc$futime) <- "Years"
#####1years________________________________####
fcox1 <- cph(Surv(futime, fustat) ~ RiskScore+Stage,
surv=T,x=T, y=T,time.inc = 1,data=abc) #time.inc = 1表示第1年
cal1 <- calibrate(fcox1, cmethod="KM", method="boot", u=1, m=100, B=500)
pdf("COAD-Cplot-1y.pdf")
plot(cal1,lwd=3,lty=1,cex=0.000001,
errbar.col=c(rgb(0,118,192,maxColorValue=255)),riskdist=F,
xlab="Predicted Probability of 1-Year Survival",
ylab="Actual Proportion of 1-Year Survival",cex.lab=1.5,cex.axis=1.5,
col=c(rgb(192,98,83,maxColorValue=255)))
lines(cal1[,c("mean.predicted","KM")],type="b",lwd=3,col=c(rgb(192,98,83,maxColorValue=255)),pch=16)
abline(0,1,lty=3,lwd=2,col=c(rgb(0,118,192,maxColorValue=255)))
dev.off()
#####3years________________________________####
fcox3 <- cph(Surv(futime, fustat) ~ RiskScore+Stage,
surv=T,x=T, y=T,time.inc = 3,data=abc)
cal3 <- calibrate(fcox3, cmethod="KM", method="boot", u=3, m=100, B=500)
pdf("COAD-Cplot-3y.pdf")
plot(cal3,lwd=3,lty=1,cex=0.000001,
errbar.col=c(rgb(0,118,192,maxColorValue=255)),riskdist=F,
xlab="Predicted Probability of 3-Year Survival",
ylab="Actual Proportion of 3-Year Survival",cex.lab=1.5,cex.axis=1.5,
col=c(rgb(192,98,83,maxColorValue=255)))
lines(cal3[,c("mean.predicted","KM")],type="b",lwd=3,col=c(rgb(192,98,83,maxColorValue=255)),pch=16)
abline(0,1,lty=3,lwd=2,col=c(rgb(0,118,192,maxColorValue=255)))
dev.off()
#####2years________________________________####
fcox2 <- cph(Surv(futime, fustat) ~ RiskScore+Stage,
surv=T,x=T, y=T,time.inc = 2,data=abc)
cal2 <- calibrate(fcox5, cmethod="KM", method="boot", u=2, m=100, B=500)
pdf("COAD-Cplot-2y.pdf")
plot(cal5,lwd=3,lty=1,cex=0.000001,
errbar.col=c(rgb(0,118,192,maxColorValue=255)),riskdist=F,
xlab="Predicted Probability of 5-Year Survival",
ylab="Actual Proportion of 5-Year Survival",cex.lab=1.5,cex.axis=1.5,
col=c(rgb(192,98,83,maxColorValue=255)))
lines(cal5[,c("mean.predicted","KM")],type="b",lwd=3,col=c(rgb(192,98,83,maxColorValue=255)),pch=16)
abline(0,1,lty=3,lwd=2,col=c(rgb(0,118,192,maxColorValue=255)))
dev.off()
|
const axios = require("axios");
const { JSDOM } = require("jsdom");
const getProductUrl = (product_id) =>
`https://www.amazon.com/gp/product/ajax/?asin=${product_id}&m=&smid=&sourcecustomerorglistid=&sourcecustomerorglistitemid=&sr=8-5&pc=dp&experienceId=aodAjaxMain`;
const selectors = {
image: "#aod-asin-image-id",
title: "#aod-asin-title-block",
condition: "#aod-offer-heading h4",
conditionDescription: "#aod-other-offer-condition-text",
price: ".a-price .a-offscreen",
soldBy: "#aod-offer-soldBy .a-col-right .a-size-small",
pinnedElement: "#aod-pinned-offer",
offerListElement: "#aod-offer-list",
offerItem: "#aod-offer-",
};
async function getPrices(product_id) {
const productUrl = getProductUrl(product_id);
const { data: html } = await axios.get(productUrl, {
headers: {
authority: `www.amazon.com`,
accept: `text/html,*/*`,
"user-agent": `Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36`,
pragma: `no-cache`,
},
});
const dom = new JSDOM(html);
const getOffer = (element) => {
//returns object
if (!element) {
return;
}
var condition = element.querySelector(selectors["condition"]).textContent;
condition = condition.replace(/[\n\s]/g, "").trim();
const price = element.querySelector(selectors["price"]).textContent;
const conditionDescription =
condition !== "New"
? element
.querySelector(selectors["conditionDescription"])
.textContent.trim()
: null;
const soldBy = element
.querySelector(selectors["soldBy"])
.textContent.trim();
return { price, condition, conditionDescription, soldBy };
};
const getElement = (selector) => {
return dom.window.document.querySelector(selector);
};
const image = getElement(selectors["image"]).getAttribute("src");
var title = getElement(selectors["title"]).textContent;
title =
title.length > 50 ? `${title.trim().slice(0, 50)}` + "..." : title.trim();
const pinnedElement = getElement(selectors["pinnedElement"]);
const pinnedInfo = getOffer(pinnedElement);
const offerListElement = getElement(selectors["offerListElement"]);
const offersToRetrieve = 5;
const offers = [];
for (var i = 1; i < offersToRetrieve; i++) {
offers.push(
getOffer(offerListElement.querySelector(`${selectors["offerItem"]}${i}`))
);
}
const result = {
image,
title,
pinnedInfo,
offers,
productUrl,
};
console.log(result);
}
getPrices("B088QSDB7S");
|
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
namespace CartLogic
{
public class ShoppingCartInterface : MonoBehaviour
{
[SerializeField]
private TMP_Text addedItems;
[SerializeField]
private TMP_Text prices;
[SerializeField]
private ShoppingCart cartContent;
/**
* @brief Unity event function that is called when the script instance is being loaded.
Registers an event handler to update the shopping cart interface when the cart content changes.
Called when the script instance is being loaded. Initializes the interface and subscribes to the OnContentChanged event of the shopping cart.
*/
private void Awake()
{
cartContent.OnContentChanged += items =>
{
addedItems.text = string.Join("\n", items
.GroupBy(i => i.ItemName)
.Select(grouping => $"{grouping.Count()}x {grouping.Key}"));
//addedItems.text = items.GroupBy(i => i.itemName).JoinString("\n", grouping => $"{grouping.Count()}x {grouping.Key}");
prices.text = $"{items.Sum(component => component.ItemPrice):F2} Lei";
};
}
}
}
|
package frame;
import dao.BookDao;
import model.Book;
import util.Connect;
import util.StringNull;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
/**
* 删除图书界面
*/
public class DeleteBookInterface extends JFrame {
/**
*
*/
private static final long serialVersionUID = -3112379638608650243L;
private JPanel contentPane;
private final JLabel LabelId = new JLabel("图书编号:");
private final JLabel LabelId_1 = new JLabel("请输入待删除图书的图书编号:");
private final JTextField textField = new JTextField();
private final JButton ButtonConfim = new JButton("确认删除");
private final JLabel LabelWarn = new JLabel("警告:删除图书会清空该图书的所有库存!");
private BookDao bookDao = new BookDao();
private Connect conutil = new Connect();
/**
* Create the frame.
*/
public DeleteBookInterface() {
this.textField.setBounds(118, 46, 122, 30);
this.textField.setColumns(10);
setResizable(false);
setTitle("图书删除");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 455, 255);
contentPane = new JPanel();
contentPane.setToolTipText("");
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setLocationRelativeTo(null);
this.LabelId.setFont(new Font("SansSerif", Font.PLAIN, 20));
this.LabelId.setBounds(6, 44, 100, 29);
contentPane.add(this.LabelId);
this.LabelId_1.setFont(new Font("SansSerif", Font.PLAIN, 16));
this.LabelId_1.setBounds(6, 18, 224, 23);
contentPane.add(this.LabelId_1);
contentPane.add(this.textField);
this.ButtonConfim.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteBook();
}
});
this.ButtonConfim.setBounds(105, 142, 151, 60);
contentPane.add(this.ButtonConfim);
this.LabelWarn.setFont(new Font("SansSerif", Font.BOLD, 18));
this.LabelWarn.setBounds(7, 96, 353, 26);
contentPane.add(this.LabelWarn);
}
protected void deleteBook() {
String bookId = this.textField.getText();
if (StringNull.isEmpty(bookId)) {
JOptionPane.showMessageDialog(null, "图书编号不能为空!");
return;
}
Connection con = null;
try {
con = conutil.loding();
Book book = new Book(Integer.parseInt(bookId));
ResultSet rs = bookDao.query2(con, book);
if (rs.next()) {
bookDao.delete(con, Integer.parseInt(bookId));
JOptionPane.showMessageDialog(null, "删除成功!");
return;
} else {
JOptionPane.showMessageDialog(null, "删除失败!未找到该编号的书籍");
return;
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "删除失败!未知错误!");
return;
} finally {
try {
conutil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
/* eslint-disable @typescript-eslint/naming-convention */
import { DeleteObjectCommand, GetObjectCommand, ListObjectsCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import { type Readable } from 'node:stream';
import {
type GetObjectDataPayload,
type S3Service,
type PutObjectPayload,
type GetObjectsKeysPayload,
type CheckIfObjectExistsPayload,
type DeleteObjectPayload,
} from './s3Service.js';
import { type S3Client } from '../../clients/s3Client/s3Client.js';
import { S3ServiceError } from '../../errors/s3ServiceError.js';
export class S3ServiceImpl implements S3Service {
public constructor(private readonly s3Client: S3Client) {}
public async putObject(payload: PutObjectPayload): Promise<void> {
const { bucket, objectKey, data } = payload;
const command = new PutObjectCommand({
Bucket: bucket,
Key: objectKey,
Body: data,
});
try {
await this.s3Client.send(command);
} catch (error) {
throw new S3ServiceError({
bucket,
objectKey,
error,
});
}
}
public async deleteObject(payload: DeleteObjectPayload): Promise<void> {
const { bucket, objectKey } = payload;
const command = new DeleteObjectCommand({
Bucket: bucket,
Key: objectKey,
});
try {
await this.s3Client.send(command);
} catch (error) {
throw new S3ServiceError({
bucket,
objectKey,
error,
});
}
}
public async getObjectData(payload: GetObjectDataPayload): Promise<Readable | undefined> {
const { bucket, objectKey } = payload;
const command = new GetObjectCommand({
Bucket: bucket,
Key: objectKey,
});
try {
const result = await this.s3Client.send(command);
return result.Body as Readable | undefined;
} catch (error) {
throw new S3ServiceError({
bucket,
objectKey,
error,
});
}
}
public async getObjectsKeys(payload: GetObjectsKeysPayload): Promise<string[]> {
const { bucket } = payload;
const command = new ListObjectsCommand({
Bucket: bucket,
});
try {
const result = await this.s3Client.send(command);
if (!result.Contents) {
return [];
}
return result.Contents.map((metadata) => metadata.Key as string);
} catch (error) {
throw new S3ServiceError({
bucket,
error,
});
}
}
public async checkIfObjectExists(payload: CheckIfObjectExistsPayload): Promise<boolean> {
const { bucket, objectKey } = payload;
const objectsKeys = await this.getObjectsKeys({ bucket });
return objectsKeys.includes(objectKey);
}
}
|
<?php
/**
* @author Jaap Jansma <jaap.jansma@civicoop.org>
* @license AGPL-3.0
*/
namespace Civi\ActionProvider\Condition;
use \Civi\ActionProvider\Parameter\ParameterBagInterface;
use \Civi\ActionProvider\Parameter\ParameterBag;
use Civi\ActionProvider\Parameter\Specification;
use \Civi\ActionProvider\Parameter\SpecificationBag;
use CRM_ActionProvider_ExtensionUtil as E;
class ParametersDontMatch extends AbstractCondition {
/**
* @param \Civi\ActionProvider\Parameter\ParameterBagInterface $parameterBag
*
* @return bool
*/
public function isConditionValid(ParameterBagInterface $parameterBag) {
$parameter1 = $parameterBag->getParameter('parameter1');
$parameter2 = $parameterBag->getParameter('parameter2');
if ($parameter1 == $parameter2) {
return false;
}
return true;
}
/**
* Returns the specification of the configuration options for the actual condition.
*
* @return SpecificationBag
*/
public function getConfigurationSpecification() {
return new SpecificationBag(array());
}
/**
* Returns the specification of the parameters of the actual condition.
*
* @return SpecificationBag
*/
public function getParameterSpecification() {
return new SpecificationBag(array(
new Specification('parameter1', 'String', E::ts('Parameter 1')),
new Specification('parameter2', 'String', E::ts('Parameter 2')),
));
}
/**
* Returns the human readable title of this condition
*/
public function getTitle() {
return E::ts('Parameters don\'t match');
}
}
|
import 'package:flutter/material.dart';
import '../services/bookmark_service.dart';
import '../models/job_model.dart';
class BookmarkScreen extends StatefulWidget {
@override
_BookmarkScreenState createState() => _BookmarkScreenState();
}
class _BookmarkScreenState extends State<BookmarkScreen> {
late Future<List<Jobs>> _futureBookmarks;
@override
void initState() {
super.initState();
_futureBookmarks = BookmarkService.getBookmarks();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bookmarks'),
),
body: FutureBuilder<List<Jobs>>(
future: _futureBookmarks,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
Jobs job = snapshot.data![index];
return ListTile(
title: Text(job.jobTitle ?? ''),
subtitle: Text(job.companyName ?? ''),
onTap: () {
// Navigate to job detail page
},
);
},
);
}
},
),
);
}
}
|
# Copyright © 2023 Apple Inc.
import io
import itertools
import numpy as np
import os
from urllib import request
import zipfile
def load_dataset(dataname):
if dataname == "ptb":
return ptb()
elif dataname == "wikitext2":
return wikitext(dataset="2")
else:
return wikitext(dataset="103")
def _load(save_dir, filenames):
# *NB* First file is expected to be the training set
with open(os.path.join(save_dir, filenames[0]), "r") as fid:
vocab = set(t for l in fid.readlines() for t in l.strip().split(" "))
eos = "<eos>"
vocab.add(eos)
vocab = {v: i for i, v in enumerate(vocab)}
def to_array(dataset):
with open(os.path.join(save_dir, dataset), "r") as fid:
lines = (l.strip().split(" ") for l in fid.readlines())
return np.array(
[vocab[w] for line in lines for w in itertools.chain(line, [eos])],
dtype=np.uint32,
)
datasets = [to_array(fn) for fn in filenames]
return vocab, *datasets
def wikitext(dataset="2", save_dir="/tmp"):
"""
Load the WikiText-* language modeling dataset:
https://paperswithcode.com/dataset/penn-treebank
"""
if dataset not in ("2", "103"):
raise ValueError(f'Dataset must be either "2" or "103", got {dataset}')
filenames = ["wiki.train.tokens", "wiki.valid.tokens", "wiki.test.tokens"]
dataname = f"wikitext-{dataset}"
data_dir = os.path.join(save_dir, dataname)
if not os.path.exists(data_dir):
base_url = "https://s3.amazonaws.com/research.metamind.io/wikitext/"
zip_file_url = base_url + dataname + "-v1.zip"
r = request.urlopen(zip_file_url)
with zipfile.ZipFile(io.BytesIO(r.read())) as zf:
zf.extractall(save_dir)
return _load(data_dir, filenames)
def ptb(save_dir="/tmp"):
"""
Load the PTB language modeling dataset:
https://paperswithcode.com/dataset/penn-treebank
"""
filenames = [
"ptb.train.txt",
"ptb.valid.txt",
"ptb.test.txt",
]
def download_and_save(save_dir):
base_url = "https://raw.githubusercontent.com/wojzaremba/lstm/master/data/"
for name in filenames:
out_file = os.path.join(save_dir, name)
if not os.path.exists(out_file):
request.urlretrieve(base_url + name, out_file)
save_dir = os.path.join(save_dir, "ptb")
if not os.path.exists(save_dir):
os.mkdir(save_dir)
download_and_save(save_dir)
return _load(save_dir, filenames)
if __name__ == "__main__":
vocab, train, val, test = ptb()
assert len(vocab) == 10000, "PTB: Wrong vocab size"
vocab, train, val, test = wikitext()
assert len(vocab) == 33279, "WikiText: Wrong vocab size"
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using CompactDiscDAO;
using Microsoft.Owin.Security.OAuth;
using Microsoft.Practices.Unity;
using Newtonsoft.Json.Serialization;
namespace CompactDiscRest
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var container = new UnityContainer();
container.RegisterType<ICompactDiscService, TransactionalCompactDiscService>(new HierarchicalLifetimeManager());
container.RegisterType<CompactDiscDao, EFCompactDiscDao>(new HierarchicalLifetimeManager());
config.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
//config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
|
package EP2021;
public class Bebida {
private String nome;
private String[] ingredientes;
private double preco;
public Bebida(String nome, String[] ingredientes, double preco){
this.nome = nome;
this.ingredientes = ingredientes;
this.preco = preco;
}
public String getNome(){
return nome;
}
public String[] getIngredientes(){
return ingredientes;
}
public double getPreco(){
return preco;
}
public void setNome(String nome){
this.nome = nome;
}
public void setIngredientes(String[] ingredientes){
this.ingredientes = ingredientes;
}
public void setPreco(double preco){
this.preco = preco;
}
public Bebida nome(String nome) {
setNome(nome);
return this;
}
public Bebida ingredientes(String[] ingredientes) {
setIngredientes(ingredientes);
return this;
}
public Bebida preco(double preco) {
setPreco(preco);
return this;
}
@Override
public int hashCode(){
final int prime = 31;
int result = 1;
long temp;
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result + ((ingredientes == null) ? 0 : ingredientes.hashCode());
temp = Double.doubleToLongBits(preco);
result = prime * result + (int) ( temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
Bebida other = (Bebida) obj;
if(nome == null){
if(other.nome != null)
return false;
}else if(!nome.equals(other.nome))
return false;
return true;
}
@Override
public String toString(){
return "{" +
" nome='" + getNome() + "'" +
", ingredientes='" + getIngredientes() + "'" +
", preco='" + getPreco() + "'" +
"}";
}
}
|
<template>
<div>
<a-card>
<div v-show="!addSocsoModal && !editSocsoModal">
<ChosenAlertBox
permissionNameAdd="setup_payroll_socso_add"
permissionNameDelete="setup_payroll_socso_delete"
:isActive="true"
position="right"
:totalSelected="selectedRowKeys.length"
@open="openModal()"
@delete="handleDelete(selectedRowKeys)"
/>
<s-table
permissionName="setup_payroll_socso_view"
:row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
:data="loadData"
:columns="columns"
ref="table"
rowKey="id"
:pagination="{
'show-total': (total, range) => $tc('table.column.total-items', total),
showSizeChanger: true,
showQuickJumper: true
}"
>
<a-switch
:disabled="!$store.getters.permissions.includes('setup_payroll_socso_update-status')"
key="status"
slot="status"
slot-scope="val, record"
:default-checked="val === 'Enable' ? true : false"
@change="e => handleStatus(e, record.id)"
/>
<span slot="action" slot-scope="text, record">
<a v-action:setup_payroll_socso_view-edit-details @click="editModal(record)">{{ $t('table.dialog.view') }}</a>
</span>
</s-table>
</div>
<add-socso-modal @refreshTable="$refs.table.refresh()"/>
<edit-socso-modal :model="mdl" @refreshTable="$refs.table.refresh()" />
</a-card>
</div>
</template>
<script>
import ChosenAlertBox from '@/components/Table/ChosenAlertBox.vue'
import EditableTable from '@/components/Table/EditableTable.vue'
import { i18nRender } from '@/locales'
import AddSocsoModal from './AddSocsoModal.vue'
import EditSocsoModal from './EditSocsoModal.vue'
import { STable } from '@/components'
import InfoCircle from '@/assets/info-circle.svg'
const columns = [
{
title: i18nRender('table.column.socso-type'),
dataIndex: 'socsoType',
key: 'socsoType',
ellipsis: true
},
{
title: i18nRender('table.column.descriptions'),
dataIndex: 'descriptions',
key: 'descriptions',
ellipsis: true
},
{
title: i18nRender('table.column.status'),
dataIndex: 'status',
key: 'status',
scopedSlots: { customRender: 'status' }
},
{
title: i18nRender('table.column.action'),
dataIndex: 'action',
key: 'action',
scopedSlots: { customRender: 'action' }
}
]
export default {
name: 'Socso',
components: { ChosenAlertBox, EditableTable, AddSocsoModal, EditSocsoModal, STable },
computed: {
addSocsoModal: {
get () {
return this.$store.state.modal.addSocsoModal
},
set () {
// just to prevent error log when @cancel
}
},
editSocsoModal: {
get () {
return this.$store.state.modal.editSocsoModal
},
set () {
// just to prevent error log when @cancel
}
}
},
data () {
return {
columns,
selectedRowKeys: [],
mdl: null,
fields: [ 'socsoType', 'descriptions' ],
queryParam: {},
loadData: async (parameter) => {
const { pageNo, pageSize } = parameter
const _parameter = {
page: pageNo - 1,
size: pageSize
}
const params = Object.assign(_parameter, this.queryParam)
const data = await this.$store.dispatch('api/setup/payroll/socso/fetchList', params)
return data
}
}
},
methods: {
openModal () {
this.$store.commit('modal/TOGGLE_ADD_SOCSO_MODAL')
},
editModal (data) {
this.$store.commit('modal/TOGGLE_EDIT_SOCSO_MODAL')
this.mdl = { ...data }
},
onSelectChange (selectedRowKeys) {
console.log('selectedRowKeys changed: ', selectedRowKeys)
this.selectedRowKeys = selectedRowKeys
},
handleDelete(selectedKeys) {
if (!selectedKeys.length) return
this.$confirm({
title: this.$t('table.dialog.delete-confirm'),
okText: this.$t('table.dialog.yes'),
cancelText: this.$t('table.dialog.no'),
icon: () => <img style={{ float: 'left', marginRight: '16px' }} src={InfoCircle} />,
onOk: async () => {
try {
await this.$store.dispatch('api/setup/payroll/socso/deleteSocso', {
entityIds: selectedKeys
})
this.$notification.open({
message: this.$t('notification.socso.deleted'),
icon: <a-icon type="check-circle" theme="twoTone" two-tone-color="#52c41a" />
})
this.onSelectChange([])
} catch (e) {
this.$message.error(e.response.data.message)
}
this.$refs.table.refresh()
}
})
},
async handleStatus (status, id) {
try {
await this.$store.dispatch('api/setup/payroll/socso/toggleStatus', { status, id })
this.$notification['success']({
message: status ? i18nRender('notification.socso.enabled') : i18nRender('notification.socso.disabled')
})
} catch (e) {
console.log(e)
}
}
}
}
</script>
|
package com.tool.thread.countdownlatch;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample3 {
public static void main(String[] args) {
String[] names = new String[]{"姚明", "易建联", "李宁", "邓亚萍"};
new Referee(names).start();
}
//裁判员
public static class Referee extends Thread {
private String[] names;
public Referee(String[] names) {
this.names = names;
}
@Override
public void run() {
try {
System.out.println("运动员名单" + Arrays.toString(names));
CountDownLatch countDownLatch = new CountDownLatch(names.length);
for (String name : names) {
Athletes athletes = new Athletes(countDownLatch, name);
athletes.start();
}
countDownLatch.await();
System.out.println("所有运动员都已经到齐了!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//运动员
public static class Athletes extends Thread {
private CountDownLatch countDownLatch;
private String name;
public Athletes(CountDownLatch countDownLatch, String name) {
this.countDownLatch = countDownLatch;
this.name = name;
}
@Override
public void run() {
System.out.println("运动员" + this.name + "到了");
this.countDownLatch.countDown();
}
}
}
|
import json
from unittest.mock import patch
from requests import Response
from src.sut import Sut
from tests.mocks.mock_connection_manager import MockConnectionManager
@patch("src.sut.Sut.semi_complex_method")
@patch("src.sut.ContextManagerDeps")
@patch("src.sut.NestedDependency.play")
@patch("src.sut.external_call_func")
def test_should_demo_correct_demo_value(
mock_external_call, nested_deps, context_manager_deps, semi_complex_method
):
nested_deps.return_value = 10
mock_external_call.return_value = 14
context_manager_deps.return_value = MockConnectionManager()
semi_complex_method.return_value = "I am doing no work from mock"
sut = Sut()
(
nested_dep_return_value,
external_api_value,
context_manager_value,
semi_complex_method_value,
) = sut.calculate()
assert nested_dep_return_value == 10
assert external_api_value == 14
assert context_manager_value == "I am connected from test"
assert semi_complex_method_value == "I am doing no work from mock"
@patch("src.sut.requests.get")
def test_request_api_call(mock_request_call):
mock_request_call.side_effect = mocked_requests_get
sut = Sut()
data = sut.call_api()
assert data
@patch("src.sut.requests.get")
def test_request_api_call_version2(mock_request_call):
mock_request_call.return_value = MockedResponse()
sut = Sut()
data = sut.call_api()
assert data
assert data == {"ip": "mocked_ip"}
class MockedResponse:
def json(self):
return {"ip": "mocked_ip"}
def mocked_requests_get(*args, **kwargs):
response = Response()
response.status_code = 200
response._content = str.encode(json.dumps("Mocked response"))
return response
|
package com.example.vitalize.Service;
import interfaces.IService;
import com.example.vitalize.Entity.RendezVous;
import com.example.vitalize.Entity.Users;
import com.example.vitalize.Util.MyDataBase;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class RendezVousService implements IService<RendezVous> {
Connection cnx = MyDataBase.getInstance().getConnection();
@Override
public void add(RendezVous rendezVous) {
String req = "INSERT INTO `rendez_vous` (`id_doctor`, `date`, `type`, `is_available`) VALUES (?, ?, ?, ?)";
try (PreparedStatement preparedStatement = cnx.prepareStatement(req)) {
preparedStatement.setInt(1, rendezVous.getDoctorId());
preparedStatement.setObject(2, rendezVous.getDate());
preparedStatement.setString(3, rendezVous.getType());
preparedStatement.setBoolean(4, rendezVous.isAvailable());
preparedStatement.executeUpdate();
System.out.println("RendezVous added successfully.");
} catch (SQLException e) {
System.err.println("Error occurred while adding RendezVous: " + e.getMessage());
}
}
@Override
public void update(RendezVous rendezVous) {
String req = "UPDATE `rendez_vous` SET `id_doctor` = ?, `date` = ?, `type` = ?, `is_available` = ? WHERE `rdv_id` = ?";
try (PreparedStatement preparedStatement = cnx.prepareStatement(req)) {
preparedStatement.setInt(1, rendezVous.getDoctorId());
preparedStatement.setObject(2, rendezVous.getDate());
preparedStatement.setString(3, rendezVous.getType());
preparedStatement.setBoolean(4, rendezVous.isAvailable());
preparedStatement.setInt(5, rendezVous.getRdvId());
preparedStatement.executeUpdate();
System.out.println("RendezVous updated successfully.");
} catch (SQLException e) {
System.err.println("Error occurred while updating RendezVous: " + e.getMessage());
}
}
@Override
public void delete(RendezVous rendezVous) {
String req = "DELETE FROM `rendez_vous` WHERE `rdv_id` = ?";
try (PreparedStatement preparedStatement = cnx.prepareStatement(req)) {
preparedStatement.setInt(1, rendezVous.getRdvId());
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("RendezVous deleted successfully.");
} else {
System.out.println("No RendezVous found with ID: " + rendezVous.getRdvId());
}
} catch (SQLException e) {
System.err.println("Error occurred while deleting RendezVous: " + e.getMessage());
}
}
@Override
public List<RendezVous> getAll() {
List<RendezVous> rendezVousList = new ArrayList<>();
String req = "SELECT * FROM `rendez_vous`";
try (PreparedStatement preparedStatement = cnx.prepareStatement(req)) {
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
RendezVous rendezVous = new RendezVous();
rendezVous.setRdvId(resultSet.getInt("rdv_id"));
rendezVous.setDoctorId(resultSet.getInt("id_doctor"));
rendezVous.setDate(resultSet.getObject("date", LocalDateTime.class));
rendezVous.setType(resultSet.getString("type"));
rendezVous.setAvailable(resultSet.getBoolean("is_available"));
rendezVousList.add(rendezVous);
}
} catch (SQLException e) {
System.err.println("Error occurred while fetching RendezVous: " + e.getMessage());
}
return rendezVousList;
}
@Override
public RendezVous getOne(int id) {
RendezVous rendezVous = null;
String req = "SELECT * FROM `rendez_vous` WHERE `rdv_id` = ?";
try (PreparedStatement preparedStatement = cnx.prepareStatement(req)) {
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
rendezVous = new RendezVous();
rendezVous.setRdvId(resultSet.getInt("rdv_id"));
rendezVous.setDoctorId(resultSet.getInt("id_doctor"));
rendezVous.setDate(resultSet.getObject("date", LocalDateTime.class));
rendezVous.setType(resultSet.getString("type"));
rendezVous.setAvailable(resultSet.getBoolean("is_available"));
} else {
System.out.println("No RendezVous found with ID: " + id);
}
} catch (SQLException e) {
System.err.println("Error occurred while fetching RendezVous: " + e.getMessage());
}
return rendezVous;
}
public boolean exists(RendezVous rdv) throws SQLException {
String query = "SELECT COUNT(*) FROM rendez_vous WHERE date = ? AND type = ? AND id_doctor = ?";
try (PreparedStatement statement = cnx.prepareStatement(query)) {
statement.setObject(1, rdv.getDate());
statement.setString(2, rdv.getType());
statement.setInt(3, rdv.getDoctorId());
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
int count = resultSet.getInt(1);
return count > 0;
}
}
}
return false;
}
public boolean existsForDoctor(RendezVous rdv) throws SQLException {
String query = "SELECT COUNT(*) FROM rendez_vous WHERE date = ? AND type = ? AND id_doctor = ?";
try (PreparedStatement statement = cnx.prepareStatement(query)) {
statement.setObject(1, rdv.getDate());
statement.setString(2, rdv.getType());
statement.setInt(3, rdv.getDoctorId());
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
int count = resultSet.getInt(1);
return count > 0;
}
}
}
return false;
}
public boolean existsForDifferentType(RendezVous rdv) throws SQLException {
String query = "SELECT COUNT(*) FROM rendez_vous WHERE id_doctor = ? AND date = ? AND type != ?";
try (PreparedStatement statement = cnx.prepareStatement(query)) {
statement.setInt(1, rdv.getDoctorId());
statement.setObject(2, rdv.getDate());
statement.setString(3, rdv.getType());
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
int count = resultSet.getInt(1);
return count > 0;
}
}
}
return false;
}
public List<Users> searchUsersByName(String name) {
List<Users> userList = new ArrayList<>();
String query = "SELECT * FROM users WHERE nom LIKE ? OR prenom LIKE ? ";
try (PreparedStatement statement = cnx.prepareStatement(query)) {
statement.setString(1, "%" + name + "%");
statement.setString(2, "%" + name + "%");
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
Users user = new Users();
user.setId(resultSet.getInt("id"));
user.setEmail(resultSet.getString("email"));
user.setNom(resultSet.getString("nom"));
user.setPrenom(resultSet.getString("prenom"));
user.setTel(resultSet.getString("tel"));
userList.add(user);
}
}
} catch (SQLException e) {
System.err.println("Error occurred while searching for users: " + e.getMessage());
}
return userList;
}
public String getDoctorEmail(int doctorId) throws SQLException {
String email = null;
String query = "SELECT email FROM users WHERE id = ?";
try (PreparedStatement statement = cnx.prepareStatement(query)) {
statement.setInt(1, doctorId);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
email = resultSet.getString("email");
}
}
}
return email;
}
public String getDoctorName(int doctorId) throws SQLException {
String nom = null;
String query = "SELECT nom FROM users WHERE id = ?";
try (PreparedStatement statement = cnx.prepareStatement(query)) {
statement.setInt(1, doctorId);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
nom = resultSet.getString("nom");
}
}
}
return nom;
}
}
|
/**
* \file
* \brief CryptoAuthLib Basic API - Helper Functions to
*
* \copyright (c) 2015-2020 Microchip Technology Inc. and its subsidiaries.
*
* \page License
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT,
* SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE
* OF ANY KIND WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF
* MICROCHIP HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE
* FORESEEABLE. TO THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL
* LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED
* THE AMOUNT OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR
* THIS SOFTWARE.
*/
#include "cryptoauthlib.h"
/** \brief Executes Read command, which reads the configuration zone to see if
* the specified slot is locked.
*
* \param[in] device Device context pointer
* \param[in] slot Slot to query for locked (slot 0-15)
* \param[out] is_locked Lock state returned here. True if locked.
*
* \return ATCA_SUCCESS on success, otherwise an error code.
*/
#if CALIB_READ_EN
ATCA_STATUS calib_is_slot_locked(ATCADevice device, uint16_t slot, bool* is_locked)
{
ATCA_STATUS status = ATCA_GEN_FAIL;
uint8_t data[ATCA_WORD_SIZE];
uint16_t slot_locked;
do
{
if ((slot > 15u) || (is_locked == NULL))
{
status = ATCA_TRACE(ATCA_BAD_PARAM, "Either Invalid slot or NULL pointer received");
break;
}
// Read the word with the lock bytes ( SlotLock[2], RFU[2] ) (config block = 2, word offset = 6)
if ((status = calib_read_zone(device, ATCA_ZONE_CONFIG, 0, 2 /*block*/, 6 /*offset*/, data, ATCA_WORD_SIZE)) != ATCA_SUCCESS)
{
(void)ATCA_TRACE(status, "calib_read_zone - failed");
break;
}
slot_locked = ((uint16_t)data[0]) | ((uint16_t)data[1] << 8);
*is_locked = ((slot_locked & ((uint16_t)1u << slot)) == 0u);
}
while (false);
return status;
}
/** \brief Executes Read command, which reads the configuration zone to see if
* the specified zone is locked.
*
* \param[in] device Device context pointer
* \param[in] zone The zone to query for locked (use LOCK_ZONE_CONFIG or
* LOCK_ZONE_DATA).
* \param[out] is_locked Lock state returned here. True if locked.
* \return ATCA_SUCCESS on success, otherwise an error code.
*/
ATCA_STATUS calib_is_locked(ATCADevice device, uint8_t zone, bool* is_locked)
{
ATCA_STATUS status = ATCA_GEN_FAIL;
uint8_t data[ATCA_WORD_SIZE];
do
{
if (is_locked == NULL)
{
status = ATCA_TRACE(ATCA_BAD_PARAM, "NULL pointer received");
break;
}
// Read the word with the lock bytes (UserExtra, Selector, LockValue, LockConfig) (config block = 2, word offset = 5)
if ((status = calib_read_zone(device, ATCA_ZONE_CONFIG, 0, 2 /*block*/, 5 /*offset*/, data, ATCA_WORD_SIZE)) != ATCA_SUCCESS)
{
(void)ATCA_TRACE(status, "calib_read_zone - failed");
break;
}
// Determine the index into the word_data based on the zone we are querying for
switch (zone)
{
case LOCK_ZONE_CONFIG: *is_locked = (data[3] != 0x55u); break;
case LOCK_ZONE_DATA: *is_locked = (data[2] != 0x55u); break;
default: status = ATCA_TRACE(ATCA_BAD_PARAM, "Invalid zone received"); break;
}
}
while (false);
return status;
}
#endif /* CALIB_READ_EN */
#if ATCA_CA2_SUPPORT
/** \brief Use Info command to check ECC204 Config zone lock status
*
* \param[in] device Device context pointer
* \param[out] is_locked return lock status
*
* \return ATCA_SUCCESS on success, otherwise an error code
*/
ATCA_STATUS calib_ca2_is_config_locked(ATCADevice device, bool* is_locked)
{
ATCA_STATUS status = ATCA_SUCCESS;
uint8_t buffer[4] = { 0 };
uint16_t param2;
uint8_t slot = 0;
if (NULL == is_locked)
{
return ATCA_TRACE(ATCA_BAD_PARAM, "NULL pointer encountered");
}
while (slot <= 3u)
{
param2 = ATCA_ZONE_CA2_CONFIG | ((uint16_t)slot << 1);
if (ATCA_SUCCESS != (status = calib_info_lock_status(device, param2, buffer)))
{
*is_locked = false;
break;
}
else
{
*is_locked = (1U == buffer[0]);
}
if (*is_locked)
{
slot += 1u; // increment slot
}
else
{
break;
}
}
return status;
}
/** \brief Use Info command to check ECC204 Data zone lock status
*
* \param[in] device Device context pointer
* \param[out] is_locked return lock status
*
* \return ATCA_SUCCESS on success, otherwise an error code
*/
ATCA_STATUS calib_ca2_is_data_locked(ATCADevice device, bool* is_locked)
{
ATCA_STATUS status = ATCA_SUCCESS;
uint8_t buffer[4] = { 0 };
uint16_t param2;
uint8_t slot = 0;
if (NULL == is_locked)
{
return ATCA_TRACE(ATCA_BAD_PARAM, "NULL pointer encountered");
}
while (slot <= 3u)
{
param2 = ATCA_ZONE_CA2_DATA | ((uint16_t)slot << 1);
if (ATCA_SUCCESS != (status = calib_info_lock_status(device, param2, buffer)))
{
*is_locked = false;
break;
}
else
{
*is_locked = (1U == buffer[0]);
}
if (*is_locked)
{
slot += 1u; // increment slot
}
else
{
break;
}
}
return status;
}
/** \brief Use Info command to check config/data is locked or not
*
* \param[in] device Device contect pointer
* \param[in] zone Config/Data zone
* \param[out] is_locked return lock status here
*
* \return ATCA_SUCCESS on success, otherwise an error code
*/
ATCA_STATUS calib_ca2_is_locked(ATCADevice device, uint8_t zone, bool* is_locked)
{
ATCA_STATUS status = ATCA_SUCCESS;
if (ATCA_ZONE_CONFIG == zone)
{
status = calib_ca2_is_config_locked(device, is_locked);
}
else if (ATCA_ZONE_DATA == zone)
{
status = calib_ca2_is_data_locked(device, is_locked);
}
else
{
status = ATCA_TRACE(ATCA_BAD_PARAM, "Invalid zone received");
}
return status;
}
#endif
#if CALIB_READ_EN || CALIB_READ_CA2_EN
ATCA_STATUS calib_is_locked_ext(ATCADevice device, uint8_t zone, bool* is_locked)
{
ATCA_STATUS status = ATCA_BAD_PARAM;
#if ATCA_CA2_SUPPORT
ATCADeviceType device_type = atcab_get_device_type_ext(device);
if (atcab_is_ca2_device(device_type))
{
if (LOCK_ZONE_DATA == zone)
{
zone = ATCA_ZONE_DATA;
}
status = calib_ca2_is_locked(device, zone, is_locked);
}
else
#endif
{
#if CALIB_READ_EN
status = calib_is_locked(device, zone, is_locked);
#endif
}
return status;
}
/** \brief Check if a slot is a private key
*
* \param[in] device Device context pointer
* \param[in] slot Slot to query (slot 0-15)
* \param[out] is_private return true if private
*
* \return ATCA_SUCCESS on success, otherwise an error code
*/
ATCA_STATUS calib_is_private(ATCADevice device, uint16_t slot, bool* is_private)
{
ATCA_STATUS status = ATCA_BAD_PARAM;
ATCADeviceType dev_type = atcab_get_device_type_ext(device);
if ((NULL != device) && (NULL != is_private))
{
switch (dev_type)
{
#if CALIB_READ_EN
case ATECC108A:
/* fallthrough */
case ATECC508A:
/* fallthrough */
case ATECC608:
{
uint8_t key_config[2] = { 0 };
if (ATCA_SUCCESS == (status = calib_read_bytes_zone(device, ATCA_ZONE_CONFIG, 0, ATCA_KEY_CONFIG_OFFSET((size_t)slot), key_config, sizeof(key_config))))
{
*is_private = (1u == (key_config[0] & ATCA_KEY_CONFIG_PRIVATE_MASK)) ? true : false;
}
break;
}
#endif
#if ATCA_CA2_SUPPORT
case ECC204:
/* fallthrough */
case TA010:
*is_private = (0u == slot) ? true : false;
break;
#endif
default:
*is_private = false;
break;
}
}
return status;
}
#endif
/** \brief Parse the revision field to get the device type */
ATCADeviceType calib_get_devicetype(uint8_t revision[4])
{
ATCADeviceType ret = ATCA_DEV_UNKNOWN;
switch (revision[2])
{
case 0x00:
/* fallthrough */
case 0x02:
ret = ATSHA204A;
break;
case 0x10:
ret = ATECC108A;
break;
case 0x50:
ret = ATECC508A;
break;
case 0x60:
ret = ATECC608;
break;
case 0x20:
#if ATCA_CA2_SUPPORT
ret = calib_get_devicetype_with_device_id(revision[1], revision[3]);
#endif
break;
case 0x40:
ret = ATSHA206A;
break;
default:
ret = ATCA_DEV_UNKNOWN;
break;
}
return ret;
}
#if ATCA_CA2_SUPPORT
ATCADeviceType calib_get_devicetype_with_device_id(uint8_t device_id, uint8_t device_revision)
{
ATCADeviceType device_type;
if (device_revision == 0x00u)
{
device_type = ECC204;
}
else
{
switch (device_id)
{
case ATCA_ECC204_DEVICE_ID:
device_type = ECC204;
break;
case ATCA_TA010_DEVICE_ID:
device_type = TA010;
break;
case ATCA_SHA104_DEVICE_ID:
device_type = SHA104;
break;
case ATCA_SHA105_DEVICE_ID:
device_type = SHA105;
break;
default:
device_type = ATCA_DEV_UNKNOWN;
break;
}
}
return device_type;
}
#endif
|
from pyboy import PyBoy, WindowEvent
import time
import requests
class PokemonEmulatorBackground:
def __init__(self):
self.pressAction = [
WindowEvent.PRESS_BUTTON_A, # 0
WindowEvent.PRESS_BUTTON_B, # 1
WindowEvent.PRESS_BUTTON_SELECT,# 2
WindowEvent.PRESS_BUTTON_START, # 3
WindowEvent.PRESS_ARROW_UP, # 4
WindowEvent.PRESS_ARROW_DOWN, # 5
WindowEvent.PRESS_ARROW_RIGHT, # 6
WindowEvent.PRESS_ARROW_LEFT, # 7
WindowEvent.PRESS_BUTTON_A, # 8
WindowEvent.PRESS_BUTTON_B, # 9
]
self.releaseAction = [
WindowEvent.RELEASE_BUTTON_A, # 0
WindowEvent.RELEASE_BUTTON_B, # 1
WindowEvent.RELEASE_BUTTON_SELECT,# 2
WindowEvent.RELEASE_BUTTON_START, # 3
WindowEvent.RELEASE_ARROW_UP, # 4
WindowEvent.RELEASE_ARROW_DOWN, # 5
WindowEvent.RELEASE_ARROW_RIGHT, # 6
WindowEvent.RELEASE_ARROW_LEFT, # 7
WindowEvent.RELEASE_BUTTON_A, # 8
WindowEvent.RELEASE_BUTTON_B, # 9
]
self.run_emulator()
def send_discord_message(self, webhook_url, message, image_path):
with open(image_path, 'rb') as f:
files = {'file': f}
payload = {
'content': message,
}
response = requests.post(webhook_url, data=payload, files=files)
if response.status_code == 204:
print("Message with image sent successfully!")
else:
print(f"Failed to send message with image. Status code: {response.status_code}, Response: {response.text}")
def run_emulator(self):
self.pyboy = PyBoy("./PokemonRed.gb")
self.pyboy.set_emulation_speed(5.0)
self.emulation_loop()
def emulation_loop(self):
webhook_url = 'Placeholder'
message_content = 'Current screen:'
image_path = './screenshot.jpg'
with open("./pi.txt", "r") as file:
content = file.read()
counter = 0
screen = 0
lasttime = time.time()
while True:
if ((time.time() - lasttime) % 60 > 59):
screen += 1
lasttime = time.time()
if screen == 15:
screen = 0
self.pyboy.screen_image().save("./screenshot.jpg")
self.send_discord_message(webhook_url, message_content, image_path)
currentDigit = int(content[counter])
counter += 1
self.pyboy.send_input(self.pressAction[currentDigit])
for i in range(24):
if i == 8:
self.pyboy.send_input(self.releaseAction[currentDigit])
self.pyboy.tick()
if __name__ == "__main__":
emulator = PokemonEmulatorBackground()
|
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import FormRaw from "./formRaw";
describe("FormRaw", () => {
it("should render without error", () => {
render(<FormRaw />);
expect(screen.getByTestId("form-raw")).toBeInTheDocument();
});
it("should render children", () => {
render(
<FormRaw>
<div data-testid='child' />
</FormRaw>
);
expect(screen.getByTestId("child")).toBeInTheDocument();
});
it("should render with className", () => {
render(<FormRaw className='test-class' />);
expect(screen.getByTestId("form-raw")).toHaveClass("test-class");
});
});
|
# 类与对象
[toc]
## 特征
1. 封装
2. 继承
3. 多态
## 类
一种复杂的**数据类型**,它是将个体**属性类型**和与这些属性有关的**操作**封装在一起的集合体,因此,定义类就是定义一种新的数据类型
<!-- 相比起结构体而言多了操作函数 -->
<!-- 对象是类的实例化 -->
> 注意:定义时系统并**不为类分配存储空间**,所以不能对类的数据成员初始化
### 类的数据隐藏
类的⼀些属性可以设置为不被外界直接操作,所以这些数据
对外界来说是不可⻅性,外⾯只有**通过类的操作函数**才能操作类
的内部数据
### 类的定义
编译时进行创建(程序运行前)
```cpp
class Name/* 类型名 */
{
private: /* 访问限定符,其后所列为私有成员 */
// 私有数据和函数成员的声明或实现;
public: /* 访问限定符,其后所列为公有成员 */
// 公有数据和函数成员的声明或实现;
protected:
// 保护数据和函数成员的声明或实现;
};
```
#### 访问限定符
> public(公共的)
> private(私有的)
> protected(保护的)
1. 其中后两种说明的成员是不能从外部进⾏访问的。每种说
明符可在类体中使⽤多次。它们的**作⽤域**是从该说明符出现
开始到下⼀个说明符之前或类体结束之前结束
2. 若无访问说明符,系统将默认其为 private 成员
3. 访问说明符 private 和 protected 体现了类具有**封装性**,实现数据成员的**隐藏**特性
#### 成员函数
在类的定义中,引进了成员函数 (member function),也就是
说函数也成了类中的⼀部分。类把数据(事物的属性)和函数
(事物的⾏为——操作)(也称为⽅法)封装为⼀个整体
成员函数 可以直接使⽤ 类定义中的任⼀成员,可以处理
数据成员,也可调⽤函数成员。
调用成员函数时,它将使用被用来调用它的对象的数据成员
公有函数集定义了类的 接⼝(interface)(对外开放)
<!-- 所创建的每个新对象都有自己的存储空间,用于存储其内部变量和类成员;但同一个类的所有对象共享同一组方法,即每种方法只有一个副本 -->
```cpp
// 1. 一般较长的成员函数我们只在类定义时给出起原型,随后在外部给出其功能的具体定义
functionType className::memberFun (/* arguments */) {
/* function */
}
// '::' 作用域运算符(scope resolution operator),又称 范围运算符。 它指出该函数属于哪一个类的成员函数
// 2. 对于较短的成员函数,我们也可以直接在类里面进行定义,我们称这样的成员函数为内联成员函数
// 根据改写规则,在类声明中定义方法等同于用哦该原型替换内部的方法定义,然后在类声明后面将定义改写为内联函数
class className {
private :
dataType : Data;
public :
functionType funName(/* arguments */) {
/* function */
}
};
```
## 对象
### 对象是类的实例化
类只是一种数据类型,定义某个类只是声明了一种新的数据类型,告诉编译系统该数据类型的结构形式,此时计算机并没有为它分配内存,只有在定义对象后,系统才为该对象分配内存
### 对象的创建
1. 直接创建(静态创建)
创建于程序**编译时**(程序运行时)
```cpp
className obj1,obj2;
```
2. 动态创建
创建于程序**运行时**
### 内存中对象的空间布局
原则上,对象在内存中的存储形式和结构⼀样,同类的每个
对象都被分配⼀段能保存其所有成员的存储单位,但为了节省
内存,在创建对象时只为每个对象的数据成员分配内存,⽽成
员函数只是⼀次性存放在静态存储区中,为所有对象所共享
(因为代码指令都是⼀样的)
### 对象内的数据成员与函数成员的访问
1. 成员访问运算符 '.'
2. 指向运算符 '->'
### 对象数组
<!-- 字符串数组本质上也是对象数组 -->
```cpp
class Test {
/*……*/
};
Test test[N];
```
### 对象指针
> 在建立对象时,编译系统会为每一个对象分配一定的存储空间,以存放其成员。对象空间的起始地址就是对象的指针。
```cpp
// 可以定义一个指针变量,用来存放对象的指针
class Test {
// content
};
Test test(//arguments);
Test *p = test;
```
每个成员函数中都包含一个特殊的指针,该指针称为**this**,它是指向本类对象的指针(谁调用指向谁)
this指针是**隐式使用**的,它是作为参数被传递给成员函数的
也可以用 ***this** 表示**被调用的成员函数所在的对象**,即当前的对象
```cpp
// 我们所写
class className {
private :
dataType data;
public :
className(tData) {
data = tData;
}
~className() {/* blank */}
void memberFun(void);
};
className :: memberFun(void) {
cout << data << endl;
}
className test(testData);
test.memberFun();
// 经过C++编译系统处理
// 以下转变过程都是由编译系统自动实现的,当然,如有需要也可以显式地使用 this指针
class className {
private :
dataType data;
public :
className(tData) {
data = tData;
}
~className() {/* blank */}
void memberFun(void);
};
className :: memberFun(className *this) { // 隐式转换
cout << this -> data << endl;
}
className test(testData);
test.memberFun(&test); // 隐式转换
```
# 构造函数与析构函数
## 构造函数
每个对对象在创建的时候都会自动调用一个初始化函数,并且只能够调用一次,这样的函数称为**构造函数(constructor)**
### 构造函数的特征
1. **函数名与类名相同**
2. 构造函数**无函数返回类型说明**
3. 程序运行时,当新的对象被建立,该对象所属的类的构造函数自动被调用,在该对象的生存期中也**只调用这一次**
4. 构造函数可以**重载**。类定义中可以有多个构造函数,它们由不同的参数表区分,系统在自动调用时按一般函数重载的规则**选一个**进行执行
5. 构造函数可以在**类中定义**,也可以在**类外定义**
6. 如果类说明中没有给出构造函数,则C++编译器自动给出一个**缺省**的构造函数
但只要我们定义了⼀个构造函数,系统就不会⾃动⽣成缺
省的构造函数。缺省的构造函数,也可以由程序员⾃⼰来编,
只要构造函数是⽆参的或者只要各参数均有缺省值的,C++ 编
译器都认为是缺省的构造函数
如果对象的数据成员 **全为公有的**,在缺省构造函数⽅式下,
也可以在对象名后加“=”加“{}”,在花括号中顺序填⼊全体数据
成员的**初始值**。
<!-- 缺省:默认 -->
```cpp
class className {
private :
dataType1 Data1;
dataType2 Data2;
dataType3 Data3;
public :
className(dataType1 data1, dataType2 data2, dataType3 data3) {
Data1 = data1; Data2 = data2; Data3 = data3; // 具体情况具体写
cout << "constructor work" << endl;
}
};
// 显式调用构造函数
className A = className(/*parameter list*/);
// 隐式调用
className B(/*parameter list*/);
// 在C++11中,也可将列表初始化的语法用于类
className C = {/*parameter list*/};
// or
// className C {/*parameter list*/};
// 构造函数不仅仅可以用于初始化新对象
A = className(/*parameter list*/); // A 对象已经存在,因此这条语句不是对A对象进行初始化,而是通过让构造程序创建一个新的临时对啊ing,然后将其内容复制给 A。随后程序将调用析构函数,以删除该临时对象
```
[Practice_28](../Practice/Practice_28.cpp)
## 析构函数
当⼀个对象定义时,C++ ⾃动调⽤构造函数建⽴该对象并进
⾏初始化,那么当⼀个对象的⽣命周期结束时,C++ 也会⾃动调
⽤⼀个函数 **注销** 该对象并进⾏善后⼯作,这个特殊的成员函数即 **析构函数(destructor)**
### 析构函数的特征
1. **析构函数名与类名相同**,但在前⾯加上字符 **~**,如
~Student()
2. 析构函数 **⽆函数返回类型**,与构造函数在这⽅⾯是⼀样的。但析构函数**不带任何参数**。
3. ⼀个类有**只有⼀个**析构函数,析构函数**可以缺省**。
4. 对象**注销时**,系统⾃动调⽤析构函数。
```cpp
~className() {
cout << "destructor work" << endl;
}
```
### 复制构造函数
使用同一类的另一个对象来初始化该对象,这个拷贝过程只需要拷贝数据成员,这时使用的构造函数称为 **复制构造函数(Copy Constructor)**
```cpp
// 在类外部定义
className::className(const className &objName) {
/* 复制过程 */
}
// 在类内部定义
class className {
public:
className(const className &objName) {
/* copy */
}
};
// 同类对象之间可以直接用'='进行拷贝,在默认情况下,将一个对象赋给同类型的另一个对象时,C++将源对象的每个数据成员的内容复制到目标对象中相应的数据成员中
// 注意复制构造函数的参数采用的是引用的方式,如果把一个真实的类对象作为参数传递到复制构造 函数,会引起无穷递归
// 在类定义中如果没有显式给出复制构造函数时,并不是不用复制构造函数,而是由系统自动调用缺省的复制构造函数
```
[为什么复制构造函数的参数一定要为引用值](Practice_39.cpp)
复制构造函数的另一个使用方面:
1. 当函数的形参是类的对象,调用函数时,进行形参与实参结合时使用
2. 当函数的返回值时类的对象,建立一个临时对象用以接受返回的对象<!-- 局部对象在离开建立它的函数时就消亡了,所以不能够直接返回的局部对象,所以在这种情况时,编译系统会在调用函数的表达式中创建一个无名临时对象,该临时对象的生存周期只在函数掉用处的表达式中。所谓return对象,实际上是调用复制构造函数把该对象的值拷贝入临时对象中 -->
### 构造函数和析构函数的调用
对于不同作用域的对象类型,构造函数和析构函数的调用如下:
1. 对全局定义的对象,当程序进入入口函数 main之前对象就已经定义,这时要调用构造函数。整个程序结束时调用析构函数
2. 对于局部定义的对象,每当程序控制流到达该对象定义处时,调用构造函数。当程序控制走出该局部域时,调用析构函数
3. 对于静态局部定义的对象,当程序控制首次到达该对象时调用构造函数,当整个程序结束时调用析构函数
# 成员对象
在定义类的对象时不仅要对对象中的普通数据成员进行初始化,也要对对象成员进行初始化
```cpp
// C++中对含对象成员的类对象的构造函数的格式
// 类名::构造函数名(参数总表):
// 对象成员1(参数表1(表中的参数来自于参数总表)),
// 对象成员2(参数表2),
// ……
// 对象成员n(参数表n)
// {普通数据成员初始化}
// 实例见Practice_3
// 对于不含对象成员的类对象的初始化,也可以套⽤以上的
// 格式,把部分只需要直接赋初值的变量初始化写在冒号的右边
// 构造函数名(参数表):变量1(初值1),……,变量n(初值n)
// { // 见 Practice_4
// ……
// }
```
# 字符串类
> string是在C++标准库中声明的一个字符串类,每一个字符串变量都是string类的一个对象
## 字符串变量的定义与引用
```cpp
string str;
str = "Hello World!";
```
## 字符串变量的输入和输出
```cpp
string str;
cin >> str;
cout << str << endl;
```
## 字符串变量的运算
1. 字符串复制可直接采用赋值的方式
2. 字符串连接可直接使用加号
3. 字符串比较可直接使用关系运算符
```cpp
// example
#include<string>
using namespace std;
int main() {
string str1 = "Hello World";
string str2 = str1;
string str3 = "!";
cout << str1 + str3 << endl;
cout << str1 > str3 << endl;
return 0;
}
```
## 字符串数组
```cpp
string str[5] = {"Hello"," ","World","!"};
```
# 友元
<!-- 类具有封装性,类中的私有成员或保护成员数据⼀般只能
通过该类中的成员函数才能访问,⽽程序中其他函数是⽆法直
接访问私有数据的。类的封装机制带来的好处是明显的,但若
绝对不允许外部函数访问类的私有成员的话,确实也有很多不
便之处,如果频繁地通过成员函数来访问的话,过多的参数传
递、类型检查,会影响程序的运⾏效率。 -->
友元(friend)函数,允许在类外的普通函数访问该类中的任何成员
<!-- 注意:只有在类声明中的原型才能够使用friend关键字。除非函数定义也是原型,否则不能再函数定义中使用该关键字 -->
## 使用情景
1. 运算符重载的某些场合需要使用友元
2. 两个类需要共享数据的时候
## 使用友元函数的优缺点
优点:能够提高效率,使表达更为简单清晰
缺点:友元函数破坏了封装机制,因此除非不得已的情况尽量不使用友元函数
## 普通非类成员函数作为友元
```cpp
friend 类型说明 友元函数名 (参数表);
// 例见 Practice_6.cpp
```
[Practice_6](../Practice/Practice_6.cpp)
## 类的成员函数作为友元
```cpp
friend funType className::friendFun(/**/);
// 例见 Practice_7.cpp 与 Practice_8.cpp
```
[Practice_7](Practice_7.cpp)
## 使用友元函数的注意点
1. 友元函数是一种声明在类体内的普通函数,不是类的成员函数,在函数体中访问对象的成员,必须用对象名加运算符“.”加对象成员名。但友元函数可以访问类中的**所有成员**,一般函数只能访问类中的公有成员
---
2. 友元函数声明**不受类中的访问权限关键字限制**,可以把它放在类的公有、私有、保护部分,但结果一样
---
3. 一个类的成员函数做另一个类的友元函数时,必须先定义它 <!-- 可参考Practice_7 & 8 -->
## 类作为友元
```cpp
// 见 Practice_9.cpp
class A {
、、、
friend class B; // 声明 B 作为 A 的友元类
};
```
[Practice_9](Practice_9.cpp)
## 使用友元类的注意事项
1. 友元关系是单向的
2. 友元关系不具有传递性
# 动态内存分配
通常定义变量(或对象),编译器在 编译时 都可以根据该变量(或对象)的类型知道所需内存空间的⼤⼩为他们分配确定的存储空间。这种内存分配称为 **静态存储分配**
---
有些操作只有在程序运⾏时才能确定,这样编译器在编译时就⽆法为他们预定存储空间,只能在程序运⾏时,系统根据运⾏时的要求进⾏内存分配,这种⽅法称为 **动态存储分配**。所有动态存储分配都在堆区中进⾏。
<!-- 动态存储区,即 **堆(heap)** 或 **自由存储区** -->
## new运算符
调用new运算符将会 **返回** 一个指向所分配类型变量(对象)的**指针** 。对所创建的变量或对象,都是通过该指针来间接操作的,而 动态创建的对象本身没有名字
## 堆内存的分配与释放
当程序运⾏到需要⼀个动态分配的变量或对象时,必须向系
统 **申请取得** 堆中的⼀块所需⼤⼩的存贮空间,⽤于存贮该变量
或对象。当不再使⽤该变量或对象时,也就是它的⽣命结束时,
要 **显式释放** 它所占⽤的存贮空间,这样系统就能对该堆空间进
⾏再次分配,做到重复使⽤有限的资源。
在 C++中,申请和释放堆中分配的存贮空间,分别使⽤
**new** 和 **delete** 的两个运算符来完成,其使⽤的格式如下:
```cpp
pointerName = new dataType(/* initial value */);
delete pointerName;
```
一般定义变量和对象时要用标识符命名,称**命名对象**,而动态的称**无名对象**。堆区时不会自动再分配时做初始化的,所以必须用初始化式(initializer)来**显式初始化**、
```cpp
// example
// initialization
int *pi = new int(0);
// deallocation
delete pi;
// 注意:动态内存释放(dynamic memory deallocation)并不意味着指针 pi被撤销,它本身仍然存在,该指针所占的内存空间并未释放
// 注意:只能用delete来释放用new分配的内存。然而,对空指针使用delete是安全的
```
## 数组的动态分配
```cpp
pointerName = new type[/* expression */];
// 下标表达式不是必须为常量表达式,它可以在运行时确定
// 不可对动态数组进行初始化,系统只会调用缺省的构造函数
delete [] pointerName;
// 若 delete 语句中少了⽅括号,因编译器认为该指针是指向数组第⼀个元素的指针,
// 会产⽣ 回收不彻底 的问题(只回收了第⼀个元素所占空间),
// 加了⽅括号后就转化为指向数组的指针,回收整个数组。
// delete []的⽅括号中 不需要 填 数组元素个数,系统⾃知。即使写了,编译器也忽略。
```
## 动态内存分配使用的几个问题
1. 动态分配失败。返回⼀个**空指针(NULL)**,表示发⽣了异常,堆资源不⾜,分配失败。
---
2. 指针删除与堆空间释放。删除⼀个指针 p(delete p;)实际意思是删除了 p **所指的⽬标**(变量或对象等),释放了它所占的堆空间,⽽不是删除p本身,释放堆空间后,p 成了**空悬指针**。
---
3. 内存泄漏(memory leak)和重复释放。new 与 delete 是配对使⽤的,如果 new 返回的指针值丢失,则所分配的堆空间⽆法回收,称**内存泄漏**,同⼀空间重复释放也是危险的,因为 该空间可能已另分配,
---
4. 动态分配的变量或对象的⽣命期。⽆名对象的⽣命期并不依赖于建⽴它的作⽤域,⽐如在函数中建⽴的动态对象在函数返回后仍可使⽤。我们也称堆空间为**自由空间**(free store)就是这个原因。但必须记住释放该对象所占堆空间,并**只能释放⼀次**,在函数内建⽴,⽽在函数外释放是⼀件很容易失控的事,往往会容易出错。
## 在构造函数中使用 new 时应该注意的事项
1. 如果在构造函数中使用 new 初始化对象的指针成员,则应该在析构函数中使用 delete
2. new 和 delete 必须相互兼容。new 对应于 delete,new[] 对应于 delete[]
3. 如果有多个构造函数,则必须以相同的方式使用 new,要么都带中括号,要么都不带。因为只有一个析构函数,所有的构造函数都必须与它兼容。然而,可以在一个析构函数中使用 new 初始化指针,而在另一个函数中将指针初始化为空,这是因为 delete 可以用于空指针
## 堆对象与构造函数
<!-- 基于堆对象的链表结构见 Practice_11.cpp -->
[Practice_11](Practice_11.cpp)
```cpp
// 通过 new 建立的对象需要调用构造函数,通过 delete 删除对象也要调用析构函数
className *pc; // 定义一个类的指针
pc = new className(); // 分配堆空间,构造一个无名的对象并调用构造函数
// new 后面的类类型也可以有参数,这些参数即是构造函数的参数
delete pc; // 先析构,然后释放内存
```
### 堆对象的生命周期
堆对象的生命周期并不依赖于建立它的作用域,除非程序结束,堆对象(无名对象)的生命周期不会会到期,并且需要显式调用 delete 语句析构堆对象(C++自动调用其析构函数)
# 浅拷贝和深拷贝
## 浅拷贝
**缺省拷贝构造函数**,可用一个类对象初始化另一个类对象,称为缺省的**按成员拷贝**,即**浅拷贝**
## 深拷贝
如果类中有⼀个数据成员为指针,该类的⼀个对象 obj1 中的这个指针 p 指向了动态分配的⼀个堆对象如果⽤ obj1 按成员拷⻉给另⼀个对象 obj2,这时 obj2.p 也指向同⼀个堆对象。这就会发⽣**数据交叉**,并当析构时,发⽣内存⼆次释放的问题。
这时就要重新定义拷⻉的构造函数,
给每个对象指针 p 独⽴分配⼀个堆对象,
称**深拷⻉**。
**这时先拷贝对象主体,再为 obj2 分配⼀个堆对象最后⽤ obj1 的堆对象拷⻉ obj2 的堆对象**
**定义拷贝(copy structor)**和**拷贝赋值操作符(copy Assignment Operator)**实现深拷贝
[Practice_15](./Practice_15_simple_deep_colone.cpp)
[运算符](%E8%BF%90%E7%AE%97%E7%AC%A6.md)
<!-- 见 Practice_15.cpp 与 运算符.md -->
# 链表与栈
## 栈(Stack)
<!-- 又称作 后进先出的线性表(LIFO: last in first out) -->
### 栈的定义
只允许在表的一端进行插入和删除的线性表
栈占用一段**连续**的内存空间,有两个端点,**允许进行插入和删除的一端称为栈顶(top),而另一端固定的叫栈底(bottom)**
### 栈的应用
> push 压入或进栈
> pop 弹出或出栈
### 栈类的数据定义
<!-- 见 Practice_16 -->
# 静态成员
<!-- 在有些应用中,希望程序中若干个同类的对象共享某个数据,这时候可以将共享数据成员在类中用关键字 **static** 修饰为 **静态类成员(static class member)**。 类的静态成员为其所有成员共享,不管有多少对象,静态成员只有一份存于公共内存中。 -->
在类定义中,用关键字 **static** 修饰的数据成员为**静态数据成员**。而该静态数据的存储空间是在编译时分配的,在定义对象时不再为静态成员分配空间。
静态数据实际上是**该类所有对象所共有的**,它更像在⾯向
过程程序设计时的全局变量,可提供同⼀类的所有对象之间信
息交换的捷径,正因为静态数据成员不属于类的某⼀特定对象,
⽽是 **属于整个类** 的,所以访问使⽤时可⽤以下格式:
```cpp
className :: staticClassMember
```
静态数据的初始化是在类外进行的
```cpp
dataType className :: staticClassMember = initialValue
// 对静态成员数据的定义性说明在文件作用域中只能实行一次
// C++静态数据成员缺省值为 ‘0’
```
<!-- 例见 Practice_17.cpp -->
## 静态成员函数
[Practice_17](Practice_17.cpp)
```cpp
// 静态成员函数基本相当于:一个带有命名空间的全局函数
// 静态函数与类的实例无关,只跟类有关,不需要this指针
// 因为静态成员函数独立于具体对象存在,所以一般使用静态成员函数来访问静态数据成员,若需要访问非静态数据成员,需要通过对象名进行访问
// 如果静态成员函数在类定义之外定义,则不能在定义是再加 static, 因为 static 不属于数据类型组成部分,这一点与友元函数相似
class className {
static void function(void);
}
className :: function(void) {
}
// 见 Practice_17.cpp
```
# 类的作用域
类定义的花括号之间区域叫做 **类作⽤域**,在类中说明 的
成员变量,其可⻅性在该类域内。类域是介于⽂件域和函数域
之间的作⽤域,类体内可以定义函数,因此类域⽐函数域⼤,
⼀个⽂件可以包含若⼲的类,所以类域⽐⽂件域⼩。
## 嵌套类
在一个类中定义的类称为嵌套类,包含嵌套类的类称为外围类
定义嵌套类是为了隐藏类名,限制该类创建对象的范围,从而减少全局标识符,提高类的抽象能力
```cpp
class Outer {
private :
/* blank */
public :
class Inner {
private :
dataType data;
public :
/* blank */
};
};
```
### 说明
1. 从作⽤域⻆度来看,嵌套类被隐藏在外围类中,所以该类名只能在外围类中使⽤,如果在外围类作⽤域外使⽤,则需加名字限定
---
2. 从访问权限⻆度来看,嵌套类名和外围类的成员名具有相同的访问权限,⼀般设置嵌套类为 public
---
3. 从嵌套类和外围类的关系⻆度来看,嵌套类的成员不是外围类的成员,嵌套类中的成员函数不能访问外围类中的成员,反之也是。
## 局部类
在一个函数体内定义的类为局部类,局部类只能在它的函数体内使用,超过该函数体则不可见
### 注意
1. 在局部类中不能说明静态成员
2. 局部类中所有成员函数都必须定义在函数体内
|
<?php
namespace App\Controller;
use App\Entity\FriendsRequest;
use App\Entity\User;
use App\Repository\FriendsRequestRepository;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class UserFriendsController extends AbstractController
{
#[Route(path: '/user/friends', name: 'app_user_friends_search', methods: ['GET'])]
public function displayFriends(Request $request, UserRepository $userRepository): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_login');
}
$user = $this->getUser();
return $this->render('user/friends.html.twig');
}
#[Route(path: '/user/friends/list', name: 'app_user_friends_list', methods: ['GET'])]
public function displayFriendsList(Request $request): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_login');
}
$user = $this->getUser();
$friends = $user->getFriends();
return $this->render('user/friendsList.html.twig', [
'friends' => $friends,
]);
}
#[Route(path: '/user/friends/{username}', name: 'app_user_friends_add', methods: ['POST'])]
public function addFriend(EntityManagerInterface $entityManager, UserRepository $userRepository, FriendsRequestRepository $friendsRequestRepository, string $username): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_login');
}
$user = $this->getUser();
if ($user->getUsername() === $username) {
throw new \InvalidArgumentException('Vous ne pouvez pas vous ajouter vous-même comme ami.');
}
$receiver = $userRepository->findOneBy(['username' => $username]);
if (!$receiver) {
throw $this->createNotFoundException('L\'utilisateur demandé n\'existe pas.');
}
$existingRequest = $friendsRequestRepository->findOneBy([
'sender' => $receiver,
'receiver' => $user,
'accepted' => false
]);
if ($existingRequest) {
$existingRequest->setAccepted(true);
} else {
$friendRequest = new FriendsRequest();
$friendRequest->setSender($user);
$friendRequest->setReceiver($receiver);
$entityManager->persist($friendRequest);
}
$entityManager->flush();
return new Response('Demande d\'ami envoyée avec succès.');
}
#[Route(path: '/user/search', name: 'app_user_search', methods: ['GET'])]
public function searchUsers(Request $request, UserRepository $userRepository): JsonResponse
{
$query = $request->query->get('query', '');
$users = $userRepository->searchUsersByName($query);
$usersData = [];
$currentUser = $this->getUser();
$friends = $currentUser->getFriends();
$sentFriendRequests = $currentUser->getSentFriendRequests();
foreach ($users as $user) {
if ($user->getId() !== $currentUser->getId() &&
!$friends->contains($user) &&
!$sentFriendRequests->exists(function($key, $element) use ($user) {
return $element->getReceiver() === $user;
})) {
$usersData[] = [
'id' => $user->getId(),
'username' => $user->getUsername(),
'image' => $user->getProfileImage(),
];
}
}
return $this->json($usersData);
}
#[Route(path: '/user/friends/requests', name: 'app_user_friends_requests', methods: ['GET'])]
public function displayFriendRequests(): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_login');
}
$user = $this->getUser();
$receivedFriendRequests = $user->getReceivedFriendRequests()->toArray();
$unacceptedFriendRequests = array_filter($receivedFriendRequests, function($request) {
return !$request->isAccepted();
});
return $this->render('user/friendsRequest.html.twig', [
'receivedFriendRequests' => $unacceptedFriendRequests,
]);
}
#[Route(path: '/user/friends/{id}/remove', name: 'app_user_friends_remove', methods: ['POST'])]
public function removeFriend(EntityManagerInterface $entityManager, int $id): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_login');
}
$friend = $entityManager->getRepository(User::class)->find($id);
if (!$friend) {
throw $this->createNotFoundException('L\'ami n\'existe pas.');
}
$user = $this->getUser();
$friendRequestToRemove = $user->removeFriend($friend);
$friendRequestToRemoveFromFriend = $friend->removeFriend($user);
if ($friendRequestToRemove) {
$entityManager->remove($friendRequestToRemove);
}
if ($friendRequestToRemoveFromFriend) {
$entityManager->remove($friendRequestToRemoveFromFriend);
}
$entityManager->flush();
return $this->redirectToRoute('app_user_friends_list');
}
#[Route(path: '/user/friends/requests/{id}/accept', name: 'app_user_friends_requests_accept', methods: ['POST'])]
public function acceptFriendRequest(EntityManagerInterface $entityManager, int $id): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_login');
}
$friendRequest = $entityManager->getRepository(FriendsRequest::class)->find($id);
if (!$friendRequest) {
throw $this->createNotFoundException('La demande d\'ami n\'existe pas.');
}
$friendRequest->setAccepted(true);
$entityManager->flush();
return $this->redirectToRoute('app_user_friends_requests');
}
#[Route(path: '/user/friends/requests/{id}/decline', name: 'app_user_friends_requests_decline', methods: ['POST'])]
public function declineFriendRequest(EntityManagerInterface $entityManager, int $id): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_login');
}
$friendRequest = $entityManager->getRepository(FriendsRequest::class)->find($id);
if (!$friendRequest) {
throw $this->createNotFoundException('La demande d\'ami n\'existe pas.');
}
$entityManager->remove($friendRequest);
$entityManager->flush();
return $this->redirectToRoute('app_user_friends_requests');
}
}
|
export type errorAuthTypes = {
E400: {
status: number;
message: {
phone_numberAlreadyUsed: string;
emailAlreadyUsed: string;
nicknameAlreadyUsed: string;
phone_number_not_valid: string;
email_not_valid: string;
nickname_not_valid: string;
};
};
};
export type errorNoAuthTypes = {
status: number;
message: string;
};
export const ERROR_REGISTER: errorAuthTypes = {
E400: {
status: 400,
message: {
phone_numberAlreadyUsed: "user with this phone number already exists.",
emailAlreadyUsed: "user with this email address already exists.",
nicknameAlreadyUsed: "A user with that nickname already exists.",
phone_number_not_valid: "Enter a valid phone number.",
email_not_valid: "Enter a valid email address.",
nickname_not_valid: "Enter a valid nickname.",
},
},
};
export const ERROR_NO_AUTH: errorNoAuthTypes = {
status: 401,
message: "Authentication credentials were not provided.",
};
export const parseErrorMessage = (error: any): string => {
let errorMessage = "Une erreur est survenue. Veuillez réessayer.";
if (!error) {
return errorMessage;
}
console.log("error?.data e: ", error?.data);
if (error.status && error.status === ERROR_REGISTER.E400.status) {
if (error.data) {
if (error.data.phone_number) {
if (
error.data.phone_number[0] ===
ERROR_REGISTER.E400.message.phone_numberAlreadyUsed
) {
return (errorMessage =
"Un utilisateur avec ce numéro de téléphone existe déjà.");
}
if (
error.data.phone_number[0] ===
ERROR_REGISTER.E400.message.phone_number_not_valid
) {
return (errorMessage =
"Veuillez entrer un numéro de téléphone valide.");
}
}
if (error.data.email) {
if (
error.data.email[0] === ERROR_REGISTER.E400.message.emailAlreadyUsed
) {
return (errorMessage =
"Un utilisateur avec cette adresse email existe déjà.");
}
if (
error.data.email[0] === ERROR_REGISTER.E400.message.email_not_valid
) {
return (errorMessage = "Veuillez entrer une adresse email valide.");
}
}
if (error.data.nickname) {
if (
error.data.nickname[0] ===
ERROR_REGISTER.E400.message.nicknameAlreadyUsed
) {
return (errorMessage = "Un utilisateur avec ce pseudo existe déjà.");
}
if (
error.data.nickname[0] ===
ERROR_REGISTER.E400.message.nickname_not_valid
) {
return (errorMessage = "Veillez entrer un pseudo valide.");
}
}
} else {
return errorMessage;
}
}
if (error?.status === ERROR_NO_AUTH.status) {
if (error?.data.detail === ERROR_NO_AUTH.message) {
return (errorMessage =
"Vous devez être connecté pour effectuer cette action ou votre session a expiré, veuillez vous reconnecter.");
}
}
return errorMessage;
};
|
'use client';
import {
Row,
createColumnHelper,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from '@tanstack/react-table';
import { getExplorerURI } from '@webb-tools/api-provider-environment/transaction/utils';
import { chainsConfig } from '@webb-tools/dapp-config/chains';
import { ChainChip, Table, fuzzyFilter } from '@webb-tools/webb-ui-components';
import { FC } from 'react';
import {
ActivityCell,
DestinationCell,
HeaderCell,
NumberCell,
TimeCell,
} from '../tableCells';
import { PoolTransactionType, PoolTransactionsTableProps } from './types';
const columnHelper = createColumnHelper<PoolTransactionType>();
const columns = [
columnHelper.accessor('activity', {
header: () => <HeaderCell title="Pool Type" className="justify-start" />,
cell: (props) => <ActivityCell activity={props.row.original.activity} />,
}),
columnHelper.accessor('tokenAmount', {
header: () => <HeaderCell title="Token Amount" className="justify-start" />,
cell: (props) => (
<NumberCell
value={props.row.original.tokenAmount}
suffix={props.row.original.tokenSymbol}
className="justify-start"
isProtected={props.row.original.activity === 'transfer'}
/>
),
}),
columnHelper.accessor('sourceTypedChainId', {
header: () => <HeaderCell title="Source" className="justify-start" />,
cell: (props) => (
<ChainChip
chainName={chainsConfig[props.getValue()].name}
chainType={chainsConfig[props.getValue()].group}
// shorten the title to last word of the chain name
title={chainsConfig[props.getValue()].name.split(' ').pop()}
/>
),
}),
columnHelper.accessor('destinationTypedChainId', {
header: () => <HeaderCell title="Destination" className="justify-start" />,
cell: (props) => <DestinationCell />,
}),
columnHelper.accessor('time', {
header: () => <HeaderCell title="Time" className="justify-end" />,
cell: (props) => (
<TimeCell time={props.row.original.time} className="text-right" />
),
}),
];
const PoolTransactionsTable: FC<PoolTransactionsTableProps> = ({
data,
pageSize,
}) => {
const table = useReactTable({
data,
columns,
initialState: {
pagination: {
pageSize,
},
},
filterFns: {
fuzzy: fuzzyFilter,
},
globalFilterFn: fuzzyFilter,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
});
const onRowClick = (row: Row<PoolTransactionType>) => {
const sourceTypedChainId = row.original.sourceTypedChainId;
const txHash = row.original.txHash;
const blockExplorerUrl =
chainsConfig[sourceTypedChainId]?.blockExplorers?.default?.url;
if (blockExplorerUrl !== undefined) {
const txExplorerURI = getExplorerURI(
blockExplorerUrl,
txHash,
'tx',
'web3'
);
window.open(txExplorerURI, '_blank');
}
};
return (
<div className="overflow-hidden border rounded-lg border-mono-40 dark:border-mono-160">
<Table
tableClassName="block overflow-x-auto max-w-[-moz-fit-content] max-w-fit max-w-fit md:table md:max-w-none"
thClassName="border-t-0 bg-mono-0"
trClassName="cursor-pointer"
paginationClassName="bg-mono-0 dark:bg-mono-180 pl-6"
tableProps={table}
isPaginated
totalRecords={data.length}
onRowClick={onRowClick}
/>
</div>
);
};
export default PoolTransactionsTable;
|
import { Injectable } from '@angular/core';
import { AuthData } from '../models/auth.model';
import { HttpClient } from '@angular/common/http';
import { map, mergeMap, MonoTypeOperatorFunction, Observable, Subscriber, tap } from 'rxjs';
import { PlanOnServer } from './server.service.model/planOnServer.model';
import { AuthDataOnServer } from './server.service.model/authOnServer.model';
import { DataOnServer } from './server.service.model/dataOnServer.model';
@Injectable()
export class ServerService {
private static decodeTokenOnServer(token: string): AuthDataOnServer {
return JSON.parse(atob(token.split('.')[1]));
}
private static log<T>(msg: string): MonoTypeOperatorFunction<T> {
return tap((res: T) => {
console.log(msg, res);
});
}
private _secretKey: string = 'SECRET_KEY';
constructor(private _httpClient: HttpClient) {
}
public checkLogin(login: string): Observable<boolean> {
return this._httpClient
.get<AuthDataOnServer[]>(`http://localhost:3000/users?login=${login}`)
.pipe(map((d: AuthDataOnServer[]) => d.length === 0))
.pipe(ServerService.log<boolean>('Проверено наличие логина в базе. Логин уже в базе:'));
}
public postUser(data: AuthData): Observable<AuthDataOnServer> {
return this._httpClient.post<AuthDataOnServer>('http://localhost:3000/users',
{
'login': data.login,
'password': data.password
},
{
headers: { 'ContentType': 'application/json' }
})
.pipe(ServerService.log<AuthDataOnServer>('На сервере создан новый пользователь:'));
}
public getToken(data: AuthData): Observable<string | null> {
return this._httpClient
.get<AuthDataOnServer[]>(`http://localhost:3000/users?login=${data.login}&password=${data.password}`)
.pipe(map((d: AuthDataOnServer[]) => d.length === 1 ? this.encodeTokenOnServer(d[0]) : null))
.pipe(ServerService.log<string | null>(`Запрошен токен для пользователя ${data.login}. Токен:`));
}
public checkToken(token: string): Observable<boolean> {
return new Observable<boolean>((subscriber: Subscriber<boolean>) => subscriber.next(this.checkTokenOnServer(token)))
.pipe(ServerService.log<boolean>(`Проверен на подлинность токен ${token}. Токен подлинный:`));
}
public getPlansIDs(token: string): Observable<number[]> {
if (!this.checkTokenOnServer(token)) {
return new Observable<[]>((subscriber: Subscriber<[]>) => subscriber.next([]))
.pipe(ServerService.log<[]>(`Запрошены id планов с сервера. Токен ${token} не действителен:`));
}
return this._httpClient
.get<DataOnServer[]>(`http://localhost:3000/plans?user=${ServerService.decodeTokenOnServer(token).id}`)
.pipe(map((res: DataOnServer[]) => {
return res.map((d: DataOnServer) => d.id);
}))
.pipe(ServerService.log<number[]>('Запрошены и приняты id планов с сервера:'));
}
public getPlan(token: string, id: number): Observable<PlanOnServer | null> {
if (!this.checkTokenOnServer(token)) {
return new Observable<null>((subscriber: Subscriber<null>) => subscriber.next(null))
.pipe(ServerService.log<null>(`Запрошен план с сервера. Токен ${token} не действителен:`));
}
return this.getPlansIDs(token)
.pipe(mergeMap((res: number[]) => {
if (res.includes(+id)) {
return this._httpClient
.get<DataOnServer>(`http://localhost:3000/plans/${id}`)
.pipe(ServerService.log<DataOnServer>(`Для токена ${token} запрошен план c id = ${id} с сервера:`))
.pipe(map((p: DataOnServer) => p.data));
} else {
return new Observable<null>((subscriber: Subscriber<null>) => subscriber.next(null))
.pipe(ServerService.log<null>(`План с ID ${id} не принадлежит токену ${token}:`));
}
}));
}
public createPlan(token: string): Observable<number | null> {
if (!this.checkTokenOnServer(token)) {
return new Observable<null>((subscriber: Subscriber<null>) => subscriber.next(null))
.pipe(ServerService.log<null>(`Попытка создать план на сервере. Токен ${token} не действителен:`));
}
return this._httpClient.post<DataOnServer>('http://localhost:3000/plans',
{
data: new PlanOnServer(0, [], []),
user: ServerService.decodeTokenOnServer(token).id
},
{
headers: {
'ContentType': 'application/json'
}
})
.pipe(ServerService.log<DataOnServer>(`На сервере создан новый план:`))
.pipe(map((res: DataOnServer) => res.id));
}
public putPlan(token: string, id: number, plan: PlanOnServer): Observable<PlanOnServer | null> {
if (!this.checkTokenOnServer(token)) {
return new Observable<null>((subscriber: Subscriber<null>) => subscriber.next(null))
.pipe(ServerService.log<null>(`Попытка обновить план на сервере. Токен ${token} не действителен:`));
}
return this.getPlansIDs(token)
.pipe(mergeMap((res: number[]) => {
if (res.includes(+id)) {
return this._httpClient
.put<DataOnServer>(`http://localhost:3000/plans/${id}`,
{
data: plan,
user: ServerService.decodeTokenOnServer(token).id
},
{
headers: { 'ContentType': 'application/json' }
})
.pipe(ServerService.log<DataOnServer>('Обновлен план на сервере:'))
.pipe(map((p: DataOnServer) => p.data));
} else {
return new Observable<null>((subscriber: Subscriber<null>) => subscriber.next(null))
.pipe(ServerService.log<null>(`План с ID ${id} не принадлежит токену ${token}:`));
}
}));
}
public deletePlan(token: string, id: number): Observable<PlanOnServer | null> {
if (!this.checkTokenOnServer(token)) {
return new Observable<null>((subscriber: Subscriber<null>) => subscriber.next(null))
.pipe(ServerService.log<null>(`Попытка удалить план с сервера. Токен ${token} не действителен:`));
}
return this.getPlansIDs(token)
.pipe(mergeMap((res: number[]) => {
if (res.includes(+id)) {
return this._httpClient
.delete<DataOnServer>(`http://localhost:3000/plans/${id}`)
.pipe(ServerService.log<DataOnServer>('С сервера удален план:'))
.pipe(map((p: DataOnServer) => p.data));
} else {
return new Observable<null>((subscriber: Subscriber<null>) => subscriber.next(null))
.pipe(ServerService.log<null>(`План с ID ${id} не принадлежит токену ${token}:`));
}
}));
}
private encodeTokenOnServer(data: AuthDataOnServer): string {
const header: string = btoa(JSON.stringify({ 'alg': 'MY', 'typ': 'JWT' }));
const payload: string = btoa(JSON.stringify(data));
const signature: string = this.hashOnServer(`${header}.${payload}`);
return `${header}.${payload}.${signature}`;
}
private checkTokenOnServer(token: string): boolean {
const [header, payload, signature]: string[] = token.split('.');
const check: string = this.hashOnServer(`${header}.${payload}`);
return signature === check;
}
private hashOnServer(message: string): string {
return message.replace('.', this._secretKey.replace('.', ''));
}
}
|
// Copyright 2013-2023, University of Colorado Boulder
/**
* Visual representation of H3O+/OH- ratio.
*
* Particles are drawn as flat circles, directly to Canvas for performance.
* In the pH range is close to neutral, the relationship between number of particles and pH is log.
* Outside that range, we can't possibly draw that many particles, so we fake it using a linear relationship.
*
* Note: The implementation refers to 'majority' or 'minority' species throughout.
* This is a fancy was of saying 'the particles that has the larger (or smaller) count'.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
import DerivedProperty from '../../../../axon/js/DerivedProperty.js';
import Bounds2 from '../../../../dot/js/Bounds2.js';
import dotRandom from '../../../../dot/js/dotRandom.js';
import Range from '../../../../dot/js/Range.js';
import Utils from '../../../../dot/js/Utils.js';
import { Shape } from '../../../../kite/js/imports.js';
import PhetFont from '../../../../scenery-phet/js/PhetFont.js';
import { CanvasNode, Circle, Node, NodeOptions, Text } from '../../../../scenery/js/imports.js';
import NullableIO from '../../../../tandem/js/types/NullableIO.js';
import NumberIO from '../../../../tandem/js/types/NumberIO.js';
import phScale from '../../phScale.js';
import PHModel, { PHValue } from '../model/PHModel.js';
import PHScaleColors from '../PHScaleColors.js';
import PHScaleConstants from '../PHScaleConstants.js';
import PHScaleQueryParameters from '../PHScaleQueryParameters.js';
import Beaker from '../model/Beaker.js';
import ModelViewTransform2 from '../../../../phetcommon/js/view/ModelViewTransform2.js';
import PickRequired from '../../../../phet-core/js/types/PickRequired.js';
import { EmptySelfOptions } from '../../../../phet-core/js/optionize.js';
import TReadOnlyProperty from '../../../../axon/js/TReadOnlyProperty.js';
// constants
const TOTAL_PARTICLES_AT_PH_7 = 100;
const MAX_MAJORITY_PARTICLES = 3000;
const MIN_MINORITY_PARTICLES = 5; // any non-zero number of particles will be set to this number
const LOG_PH_RANGE = new Range( 6, 8 ); // in this range, number of particles is computed using log
const H3O_RADIUS = 3;
const OH_RADIUS = H3O_RADIUS;
const MAJORITY_ALPHA = 0.55; // alpha of the majority species, [0-1], transparent-opaque
const MINORITY_ALPHA = 1.0; // alpha of the minority species, [0-1], transparent-opaque
const H3O_STROKE = 'black'; // optional stroke around H3O+ particles
const H3O_LINE_WIDTH = 0.25; // width of stroke around H3O+ particles, ignored if H3O_STROKE is null
const OH_STROKE = 'black'; // optional stroke around OH- particles
const OH_LINE_WIDTH = 0.25; // width of stroke around OH- particles, ignored if OH_STROKE is null
type SelfOptions = EmptySelfOptions;
type RatioNodeOptions = SelfOptions & PickRequired<NodeOptions, 'tandem' | 'visibleProperty'>;
export default class RatioNode extends Node {
private readonly pHProperty: TReadOnlyProperty<PHValue>;
private readonly particlesNode: ParticlesCanvas;
private readonly ratioText: Text | null;
private readonly beakerBounds: Bounds2;
public constructor( beaker: Beaker,
pHProperty: TReadOnlyProperty<PHValue>,
totalVolumeProperty: TReadOnlyProperty<number>,
modelViewTransform: ModelViewTransform2,
providedOptions: RatioNodeOptions ) {
const options = providedOptions;
super();
this.pHProperty = pHProperty;
// bounds of the beaker, in view coordinates
this.beakerBounds = modelViewTransform.modelToViewBounds( beaker.bounds );
// parent for all particles
this.particlesNode = new ParticlesCanvas( this.beakerBounds );
this.addChild( this.particlesNode );
// Show the ratio of particles
this.ratioText = null;
if ( PHScaleQueryParameters.showRatio ) {
this.ratioText = new Text( '?', {
font: new PhetFont( 30 ),
fill: 'black'
} );
this.addChild( this.ratioText );
}
// call before registering for Property notifications, because 'visible' significantly affects initialization time
this.mutate( options );
// sync view with model
pHProperty.link( this.update.bind( this ) );
// This Property was added for PhET-iO, to show the actual H3O+/OH- ratio of the solution. It is not used
// elsewhere, hence the eslint-disable comment below. See https://github.com/phetsims/ph-scale/issues/112
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const ratioProperty = new DerivedProperty( [ pHProperty ],
pH => {
if ( pH === null ) {
return null;
}
else {
const concentrationH3O = PHModel.pHToConcentrationH3O( pH )!;
assert && assert( concentrationH3O !== null );
const concentrationOH = PHModel.pHToConcentrationOH( pH )!;
assert && assert( concentrationOH !== null && concentrationOH !== 0 );
return concentrationH3O / concentrationOH;
}
}, {
tandem: options.tandem.createTandem( 'ratioProperty' ),
phetioFeatured: true,
phetioValueType: NullableIO( NumberIO ),
phetioDocumentation: 'the H<sub>3</sub>O<sup>+</sup>/OH<sup>-</sup> ratio of the solution in the beaker, null if the beaker is empty',
phetioHighFrequency: true
} );
// clip to the shape of the solution in the beaker
totalVolumeProperty.link( totalVolume => {
if ( totalVolume === 0 ) {
this.clipArea = null;
}
else {
const solutionHeight = this.beakerBounds.getHeight() * totalVolume / beaker.volume;
this.clipArea = Shape.rectangle( this.beakerBounds.minX, this.beakerBounds.maxY - solutionHeight, this.beakerBounds.getWidth(), solutionHeight );
}
this.particlesNode.invalidatePaint(); //WORKAROUND: #25, scenery#200
} );
// Update this Node when it becomes visible.
this.visibleProperty.link( visible => visible && this.update() );
}
/**
* Updates the number of particles when the pH (as displayed on the meter) changes.
* If total volume changes, we don't create more particles, we just expose more of them.
*/
private update(): void {
// don't update if not visible
if ( !this.visible ) { return; }
let pH = this.pHProperty.value;
if ( pH !== null ) {
pH = Utils.toFixedNumber( pH, PHScaleConstants.PH_METER_DECIMAL_PLACES );
}
let numberOfH3O = 0;
let numberOfOH = 0;
if ( pH !== null ) {
// compute number of particles
if ( LOG_PH_RANGE.contains( pH ) ) {
// number of particles varies logarithmically in this range
numberOfH3O = Math.max( MIN_MINORITY_PARTICLES, computeNumberOfH3O( pH ) );
numberOfOH = Math.max( MIN_MINORITY_PARTICLES, computeNumberOfOH( pH ) );
}
else {
// number of particles varies linearly in this range
// N is the number of particles to add for each 1 unit of pH above or below the thresholds
const N = ( MAX_MAJORITY_PARTICLES - computeNumberOfOH( LOG_PH_RANGE.max ) ) / ( PHScaleConstants.PH_RANGE.max - LOG_PH_RANGE.max );
let pHDiff;
if ( pH > LOG_PH_RANGE.max ) {
// strong base
pHDiff = pH - LOG_PH_RANGE.max;
numberOfH3O = Math.max( MIN_MINORITY_PARTICLES, ( computeNumberOfH3O( LOG_PH_RANGE.max ) - pHDiff ) );
numberOfOH = computeNumberOfOH( LOG_PH_RANGE.max ) + ( pHDiff * N );
}
else {
// strong acid
pHDiff = LOG_PH_RANGE.min - pH;
numberOfH3O = computeNumberOfH3O( LOG_PH_RANGE.min ) + ( pHDiff * N );
numberOfOH = Math.max( MIN_MINORITY_PARTICLES, ( computeNumberOfOH( LOG_PH_RANGE.min ) - pHDiff ) );
}
}
// convert to integer values
numberOfH3O = Utils.roundSymmetric( numberOfH3O );
numberOfOH = Utils.roundSymmetric( numberOfOH );
}
// update particles
this.particlesNode.setNumberOfParticles( numberOfH3O, numberOfOH );
// update ratio counts
if ( this.ratioText ) {
this.ratioText.string = `${numberOfH3O} / ${numberOfOH}`;
this.ratioText.centerX = this.beakerBounds.centerX;
this.ratioText.bottom = this.beakerBounds.maxY - 20;
}
}
}
// Creates a random x-coordinate inside some {Bounds2} bounds. Integer values improve Canvas performance.
function createRandomX( bounds: Bounds2 ): number {
return dotRandom.nextIntBetween( bounds.minX, bounds.maxX );
}
// Creates a random y-coordinate inside some {Bounds2} bounds. Integer values improve Canvas performance.
function createRandomY( bounds: Bounds2 ): number {
return dotRandom.nextIntBetween( bounds.minY, bounds.maxY );
}
// Computes the number of H3O+ particles for some pH.
function computeNumberOfH3O( pH: PHValue ): number {
if ( pH === null ) {
return 0;
}
else {
const concentrationH3O = PHModel.pHToConcentrationH3O( pH )!;
assert && assert( concentrationH3O !== null, 'concentrationH3O is not expected to be null when pH !== null' );
return Utils.roundSymmetric( concentrationH3O * ( TOTAL_PARTICLES_AT_PH_7 / 2 ) / 1E-7 );
}
}
// Computes the number of OH- particles for some pH.
function computeNumberOfOH( pH: PHValue ): number {
if ( pH === null ) {
return 0;
}
else {
const concentrationOH = PHModel.pHToConcentrationOH( pH )!;
assert && assert( concentrationOH !== null, 'concentrationOH is not expected to be null when pH !== null' );
return Utils.roundSymmetric( concentrationOH * ( TOTAL_PARTICLES_AT_PH_7 / 2 ) / 1E-7 );
}
}
/**
* Draws all particles directly to Canvas.
*/
class ParticlesCanvas extends CanvasNode {
private readonly beakerBounds: Bounds2;
private particleCountH3O: number;
private particleCountOH: number;
// x and y coordinates for particles
private readonly xH3O: Float32Array;
private readonly yH3O: Float32Array;
private readonly xOH: Float32Array;
private readonly yOH: Float32Array;
// majority and minority images for each particle type
private imageH3OMajority: HTMLCanvasElement | null;
private imageH3OMinority: HTMLCanvasElement | null;
private imageOHMajority: HTMLCanvasElement | null;
private imageOHMinority: HTMLCanvasElement | null;
/**
* @param beakerBounds - beaker bounds in view coordinate frame
*/
public constructor( beakerBounds: Bounds2 ) {
super( { canvasBounds: beakerBounds } );
this.beakerBounds = beakerBounds;
this.particleCountH3O = 0;
this.particleCountOH = 0;
// use typed array if available, it will use less memory and be faster
const ArrayConstructor = window.Float32Array || window.Array;
// pre-allocate arrays for particles x and y coordinates, to eliminate allocation in critical code
this.xH3O = new ArrayConstructor( MAX_MAJORITY_PARTICLES );
this.yH3O = new ArrayConstructor( MAX_MAJORITY_PARTICLES );
this.xOH = new ArrayConstructor( MAX_MAJORITY_PARTICLES );
this.yOH = new ArrayConstructor( MAX_MAJORITY_PARTICLES );
// Generate majority and minority {HTMLCanvasElement} for each particle type
this.imageH3OMajority = null;
new Circle( H3O_RADIUS, {
fill: PHScaleColors.H3O_PARTICLES.withAlpha( MAJORITY_ALPHA ),
stroke: H3O_STROKE,
lineWidth: H3O_LINE_WIDTH
} )
.toCanvas( ( canvas, x, y, width, height ) => {
this.imageH3OMajority = canvas;
} );
this.imageH3OMinority = null;
new Circle( H3O_RADIUS, {
fill: PHScaleColors.H3O_PARTICLES.withAlpha( MINORITY_ALPHA ),
stroke: H3O_STROKE,
lineWidth: H3O_LINE_WIDTH
} )
.toCanvas( ( canvas, x, y, width, height ) => {
this.imageH3OMinority = canvas;
} );
this.imageOHMajority = null;
new Circle( OH_RADIUS, {
fill: PHScaleColors.OH_PARTICLES.withAlpha( MAJORITY_ALPHA ),
stroke: OH_STROKE,
lineWidth: OH_LINE_WIDTH
} )
.toCanvas( ( canvas, x, y, width, height ) => {
this.imageOHMajority = canvas;
} );
this.imageOHMinority = null;
new Circle( OH_RADIUS, {
fill: PHScaleColors.OH_PARTICLES.withAlpha( MINORITY_ALPHA ),
stroke: OH_STROKE,
lineWidth: OH_LINE_WIDTH
} )
.toCanvas( ( canvas, x, y, width, height ) => {
this.imageOHMinority = canvas;
} );
}
/**
* Sets the number of particles to display. Called when the solution's pH changes.
*/
public setNumberOfParticles( particleCountH3O: number, particleCountOH: number ): void {
if ( particleCountH3O !== this.particleCountH3O || particleCountOH !== this.particleCountOH ) {
/*
* paintCanvas may be called when other things in beakerBounds change,
* and we don't want the particle positions to change when the pH remains constant.
* So generate and store particle coordinates here, reusing the arrays.
* See https://github.com/phetsims/ph-scale/issues/25
*/
let i;
for ( i = 0; i < particleCountH3O; i++ ) {
this.xH3O[ i ] = createRandomX( this.beakerBounds );
this.yH3O[ i ] = createRandomY( this.beakerBounds );
}
for ( i = 0; i < particleCountOH; i++ ) {
this.xOH[ i ] = createRandomX( this.beakerBounds );
this.yOH[ i ] = createRandomY( this.beakerBounds );
}
// remember how many entries in coordinate arrays are significant
this.particleCountH3O = particleCountH3O;
this.particleCountOH = particleCountOH;
this.invalidatePaint(); // results in paintCanvas being called
}
}
/**
* Paints particles to the Canvas.
*/
public override paintCanvas( context: CanvasRenderingContext2D ): void {
// draw majority species behind minority species
if ( this.particleCountH3O > this.particleCountOH ) {
this.drawParticles( context, this.imageH3OMajority!, this.particleCountH3O, this.xH3O, this.yH3O );
this.drawParticles( context, this.imageOHMinority!, this.particleCountOH, this.xOH, this.yOH );
}
else {
this.drawParticles( context, this.imageOHMajority!, this.particleCountOH, this.xOH, this.yOH );
this.drawParticles( context, this.imageH3OMinority!, this.particleCountH3O, this.xH3O, this.yH3O );
}
}
/**
* Draws one species of particle. Using drawImage is faster than arc.
*/
private drawParticles( context: CanvasRenderingContext2D, image: HTMLCanvasElement, particleCount: number,
xCoordinates: Float32Array, yCoordinates: Float32Array ): void {
assert && assert( image, 'HTMLCanvasElement is not loaded yet' );
// images are generated asynchronously, so test just in case they aren't available when this is first called
if ( image ) {
for ( let i = 0; i < particleCount; i++ ) {
context.drawImage( image, xCoordinates[ i ], yCoordinates[ i ] );
}
}
}
}
phScale.register( 'RatioNode', RatioNode );
|
package com.group.libraryapp.domain;
import jakarta.persistence.*;
import java.util.List;
@Entity
public class User {
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
List<UserLoanHistory> userLoanHistories;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(unique = true, nullable = false, length = 20)
private String name;
private Integer age;
public User(Integer age, String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("잘못된 name(%s)이 들어 왔습니다.");
}
this.age = age;
this.name = name;
}
protected User() {
}
public void updateName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public void removeOneHistory(String bookName) {
this.userLoanHistories.removeIf(userLoanHistory -> bookName.equals(userLoanHistory.getBookName()));
}
public void loanBook(String bookName) {
this.userLoanHistories.add(new UserLoanHistory(this, bookName));
}
public void returnBook(String bookName) {
UserLoanHistory targetHistory = this.userLoanHistories.stream()
.filter(history -> history.getBookName()
.equals(bookName))
.findFirst()
.orElseThrow(IllegalArgumentException::new);
targetHistory.doReturn();
}
}
|
package com.george.school.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* <p>
* 系统用户表
* </p>
*
* @author George Chan
* @since 2020-07-21
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("sys_user")
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id")
private String id;
/**
* 登录用户名
*/
@TableField("username")
private String username;
/**
* 登录密码
*/
@TableField("password")
private String password;
/**
* 昵称
*/
@TableField("nickname")
private String nickname;
/**
* 手机号
*/
@TableField("mobile")
private String mobile;
/**
* 邮箱地址
*/
@TableField("email")
private String email;
/**
* QQ
*/
@TableField("qq")
private String qq;
/**
* 生日
*/
@TableField("birthday")
private LocalDate birthday;
/**
* 性别(1-男 2-女)
*/
@TableField("gender")
private Integer gender;
/**
* 头像地址
*/
@TableField("avatar")
private String avatar;
/**
* 用户类型(0-学生 1-老师 3-管理员 4-系统管理员)
*/
@TableField("user_type")
private Integer userType;
/**
* 注册IP
*/
@TableField("reg_ip")
private String regIp;
/**
* 最近登录IP
*/
@TableField("last_login_ip")
private String lastLoginIp;
/**
* 最近登录时间
*/
@TableField("last_login_time")
private LocalDateTime lastLoginTime;
/**
* 登录次数
*/
@TableField("login_count")
private Integer loginCount;
/**
* 用户备注
*/
@TableField("remark")
private String remark;
/**
* 用户状态(0-正常 1-锁定)
*/
@TableField("status")
private Integer status;
/**
* 所在组织id
*/
@TableField("org_id")
private String orgId;
/**
* 注册时间
*/
@TableField("create_time")
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField("update_time")
private LocalDateTime updateTime;
/**
* 删除标记
*/
@TableField("delete_flag")
private Integer deleteFlag;
}
|
/**
** \file tree/eseq.hh
** \brief Intermediate representation: eseq.hh
**/
#pragma once
#include <iosfwd>
#include <tree/exp.hh>
#include <tree/seq.hh>
#include <tree/stm.hh>
namespace tree
{
class Eseq : public Exp
{
public:
/** \brief Build a list of expressions.
**
** \param stm Statement list
** \param exp Last expression
*/
Eseq(const rStm& stm, const rExp& exp);
/** \name Accessors.
** \{ */
/// Statement list
rStm stm_get() const;
/// Last expression
rExp exp_get() const;
/** \} */
/** \name Printing.
** \{ */
std::ostream& tag_print(std::ostream&) const override;
std::ostream& dump(std::ostream& ostr) const override;
/** \} */
/// Iterating.
void for_each_child(std::function<void(const rTree&)> f) override;
/// Variant for matching.
virtual ExpVariant variant(const rExp& ref) override;
private:
const rStm stm_;
const rExp exp_;
};
} // namespace tree
#include <tree/eseq.hxx>
|
// Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
// A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
//-----------------------------
// Example 1:
// Input: s = "abc", t = "ahbgdc"
// Output: true
// Example 2:
// Input: s = "axc", t = "ahbgdc"
// Output: false
//-----------------------------
// create two pointers
// run a while loop with the pointers being less then the length of their input
// if s[pointer1] === t[pointer2]
// then increase bother pointers
// increase pointer 2
// if pointer1 is the same length of its input -> return true else false
//-----------------------------
// Time complexity: O(n) + Space complexity: O(n)
const isSubsequence = function (s, t) {
let p1 = 0
let p2 = 0
while(p1 < s.length && p2 < t.length) {
if(s[p1] === t[p2]) {
p1++
p2++
} else {
p2++
}
}
return p1 === s.length
};
console.log(isSubsequence("abc", "ahbgdc")) // true
|
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.locals.pretty = true;
//우리가 설치한 jade 템플릿 엔진과 우리가 만드는 app의 프레임워크인 express를 연결하는 코드
app.set('view engine', 'jade');
app.set('views', './views');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }))
//form에 따라서 적당한 url을 자동으로 만들어 서버로 보내준다
app.get('/form', function(req, res){
res.render('form');
});
app.get('form_receiver', function(req, res){
var title = req.query.title;
var description = req.query.description;
res.send(title+','+description);
});
app.post('/form_receiver', function(req, res){
var title = req.body.title;
var description = req.body.description;
res.send(title+','+description);
})
//쿼리스트링을 Express에서 다루는 방법
//쿼리스트링은 app에게 정보를 전달할 때 사용하는 URL의 국제적인 표준
//전달된 값은 req영역. req.query.xxx를 통해서 가져올 수 있다.
app.get('/topic/:id', function(req, res){
var topics = [
'Javascript is...',
'Nodejs is...',
'Express is...'
];
var as = `
<a href="topic?id=0">JavaScript</a><br>
<a href="topic?id=1">Nodejs</a><br>
<a href="topic?id=2">Express</a><br><br>
${topics[req.params.id]}
`
//res.send(req.query.id+','+req.query.name); //URL: localhost:3000/topic?id&name=egoing 구문
res.send(topics[req.query.id]);
})
app.get('/topic/:id/:mode', function(req, res){
res.send(req.params.id+','+req.params.mode)
})
app.get('/')
app.get('/template', function(req, res){
//temp라는 템플릿을 호출(views디렉토리)해서 렌더링한 결과를 사용자에게 response하는 구문
//,이후에 렌더할 객체?를 적어주면, temp.jade에서 사용이 가능하다
res.render('temp', {time: Date(), _title:'Jade'});
})
app.get('/', function(req, res){
res.send('Hello home page');
});
app.get('/dynamic', function(req, res){
var lis = '';
for(var i=0; i<5; i++){
lis = lis + '<li>coding</li>';
}
var time = Date();
var output = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Hello, Dynamic !
<ul>
${lis}
<ul>
${time}
</body>
</html>`
res.send(output)
})
app.get('/route', function(req, res){
res.send('Hello Router, <img src="/route.png">')
})
app.get('/login', function(req, res){
res.send('Login please');
})
app.listen(3000, function(){
console.log('Conneted 3000 port!');
});
|
import React from "react";
import { Booking } from "@/types/Booking";
import useModalStore from "@/stores/useModal";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useMutation } from "@tanstack/react-query";
import createHmac from "create-hmac";
import axios from "axios";
type Props = {};
const BookingForm = (props: Props) => {
const { closeModal } = useModalStore();
const apiPost = useMutation({
mutationFn: ({ data, sign }: { data: Booking; sign: string }) => {
return axios.post("/api/booking", data, {
headers: {
"Content-Type": "application/json",
"x-sign": sign,
},
});
},
});
const today = new Date();
const minDate = today.toISOString().split("T")[0];
const maxDate = new Date(
today.getFullYear(),
today.getMonth() + 1,
today.getDate()
)
.toISOString()
.split("T")[0];
const initialValues: Booking = {
name: "",
email: "",
phone: "",
note: "",
date: "",
time: "",
};
const validation = useFormik<Booking>({
initialValues,
onSubmit: (values) => {
if (apiPost.isPending) return;
const sign = createHmac("sha256", "shhhh")
.update(JSON.stringify(values))
.digest("hex");
apiPost.mutate({ data: values, sign });
},
validationSchema: Yup.object({
name: Yup.string().required("Name is required"),
email: Yup.string().email("Invalid email").required("Email is required"),
phone: Yup.string()
.length(10, "Phone number must be exactly 10 digits")
.required("Phone is required"),
date: Yup.string().required("Date is required"),
time: Yup.string()
.required("Time is required")
.test(
"is-greater",
"Booking time must be greater than current time",
function (value) {
const { date, time } = this.parent;
const bookingDateTime = new Date(`${date}T${time}`);
return bookingDateTime.getTime() > new Date().getTime();
}
)
.test(
"is-before-closing",
"Booking time must be before closing time (11:00 PM)",
function (value) {
const { date, time } = this.parent;
const bookingDateTime = new Date(`${date}T${time}`);
const closingTime = new Date(`${date}T23:00`);
return bookingDateTime.getTime() < closingTime.getTime();
}
),
}),
});
React.useEffect(() => {
if (apiPost.isSuccess) {
validation.resetForm();
closeModal();
}
}, [apiPost.isSuccess]);
console.log(apiPost.error);
return (
<div className="bg-white p-4 w-96">
{apiPost.isError && (
<div className="bg-red-400 w-full">
{(apiPost.error as any).response.data.error}
</div>
)}
<h1 className="text-2xl font-bold">Booking Form</h1>
<form onSubmit={validation.handleSubmit}>
<div className="flex flex-col space-y-2">
<input
type="text"
placeholder="Name"
className="border p-2"
disabled={apiPost.isPending}
{...validation.getFieldProps("name")}
/>
{validation.touched.name && validation.errors.name ? (
<div className="text-red-500">{validation.errors.name}</div>
) : null}
<input
type="email"
placeholder="Email"
className="border p-2"
disabled={apiPost.isPending}
{...validation.getFieldProps("email")}
/>
{validation.touched.email && validation.errors.email ? (
<div className="text-red-500">{validation.errors.email}</div>
) : null}
<input
type="text"
placeholder="Phone"
className="border p-2"
disabled={apiPost.isPending}
{...validation.getFieldProps("phone")}
/>
{validation.touched.phone && validation.errors.phone ? (
<div className="text-red-500">{validation.errors.phone}</div>
) : null}
<div className="flex flex-row w-full">
<input
type="date"
min={minDate}
max={maxDate}
placeholder="Date"
className="border p-2 w-1/2"
{...validation.getFieldProps("date")}
/>
<input
min="08:00"
max="23:00"
type="time"
placeholder="Time"
className="border p-2 w-1/2"
{...validation.getFieldProps("time")}
/>
</div>
{validation.touched.time && validation.errors.time ? (
<div className="text-red-500 w-full">{validation.errors.time}</div>
) : null}
<textarea
placeholder="Note"
className="border p-2"
disabled={apiPost.isPending}
{...validation.getFieldProps("note")}
/>
<button
disabled={apiPost.isPending}
type="submit"
className="bg-blue-500 text-white p-2 rounded"
>
{apiPost.isPending ? "Submitting..." : "Submit"}
</button>
</div>
</form>
<button
onClick={() => closeModal()}
disabled={apiPost.isPending}
className="bg-red-500 text-white p-2 rounded mt-2 w-full"
>
Close
</button>
</div>
);
};
export default BookingForm;
|
import { Component, Inject } from '@angular/core';
import { OKTA_AUTH, OktaAuthStateService } from '@okta/okta-angular';
import OktaAuth, { UserClaims } from '@okta/okta-auth-js';
@Component({
selector: 'app-login-status',
templateUrl: './login-status.component.html',
styleUrls: ['./login-status.component.css']
})
export class LoginStatusComponent {
isAuthenticated = false;
userClaims: UserClaims;
constructor(
private oktaAuthStateService: OktaAuthStateService,
@Inject(OKTA_AUTH) private oktaAuth: OktaAuth
)
{
this.oktaAuthStateService.authState$.subscribe(
authState => {
this.isAuthenticated = authState.isAuthenticated;
if(this.isAuthenticated) {
this.oktaAuth.getUser().then(result => this.userClaims = result);
}
}
);
}
logout() {
this.oktaAuth.signOut();
this.isAuthenticated = false;
this.userClaims = null;
}
}
|
import React from 'react';
import './App.css';
import BusinessList from './components/BusinessList/BusinessList';
import SearchBar from './components/SearchBar/SearchBar';
import Yelp from './util/Yelp';
class App extends React.Component {
constructor (props){
super(props);
this.state = {
businesses: []
};
this.searchYelp.bind(this);
}
searchYelp(term, location, sortBy){
Yelp.search(term,location,sortBy).then(businesses => this.setState({ businesses: businesses }))
}
render() {
return (
<div className='App'>
<h1>ravenous</h1>
<SearchBar searchYelp={this.searchYelp} />
<BusinessList businesses={this.state.businesses} />
</div>
);
}
}
export default App;
|
import { TatumOneSDK } from '@tatumio/one'
import { REPLACE_ME_WITH_TATUM_API_KEY } from '@tatumio/shared-testing-common'
const oneSDK = TatumOneSDK({ apiKey: REPLACE_ME_WITH_TATUM_API_KEY })
export async function oneBlockchainExample() {
// Get transaction details by hash
// https://apidoc.tatum.io/tag/Harmony#operation/OneGetTransaction
const transaction = await oneSDK.blockchain.get(
'0x73e25d4f202b983b97afeea547c6b3b7fda8a88161ee2d94198e35f41f8c9dfa',
)
console.log(`Transaction: ${JSON.stringify(transaction)}`)
// Get block by hash
// https://apidoc.tatum.io/tag/Harmony#operation/OneGetBlock
const block = await oneSDK.blockchain.getBlock(
'0x041676cff3ecac486c9e076176554987aa073bd9bd56f4a078a58ade01ea467a',
)
console.log(`Block: ${JSON.stringify(block)}`)
// Get current block
// https://apidoc.tatum.io/tag/Harmony#operation/OneGetCurrentBlock
const currentBlock = await oneSDK.blockchain.getCurrentBlock()
console.log(`Current block: ${JSON.stringify(currentBlock)}`)
// Get transaction count of an address
// https://apidoc.tatum.io/tag/Harmony#operation/OneGetTransactionCount
const transactionsCount = await oneSDK.blockchain.getTransactionsCount(
'one1s3va3rguafv8gnf5mfnm76qxq5z9jjt4z4kjyf',
)
console.log(`Transactions count: ${transactionsCount}`)
}
|
import { AuthEntity } from '@joinus/domain';
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsBoolean, IsDate, IsOptional, IsString, ValidateNested } from 'class-validator';
import { RoleDto } from '../../role';
import { UserDto } from '../../user/dto/user.dto';
export class AuthDto implements AuthEntity {
@IsString()
@ApiProperty({ example: 'uuid' })
uuid!: string;
@ValidateNested()
@Type(() => UserDto)
@IsOptional()
@ApiProperty({})
user?: UserDto;
@ValidateNested()
@Type(() => RoleDto)
@IsOptional()
@ApiProperty()
role?: RoleDto;
@IsBoolean()
@ApiProperty({ example: false })
isEmailVerified!: boolean;
@IsBoolean()
@ApiProperty({ example: true })
isPhoneVerified!: boolean;
@IsDate()
@Type(() => Date)
@ApiProperty({ example: '2020-01-01T00:00:00.000Z' })
createdAt!: Date;
}
|
import { SimpleGrid, Spinner, Text } from "@chakra-ui/react";
import React from "react";
import InfiniteScroll from "react-infinite-scroll-component";
import useGames from "../hooks/useGames";
import GameCard from "./GameCard";
import GameCardContainer from "./GameCardContainer";
import SkelitonCard from "./SkelitonCard";
const GameGrid = () => {
const {
data,
error,
isLoading,
isFetchingNextPage,
fetchNextPage,
hasNextPage,
} = useGames();
const skeletons = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const fetchedGamesCount =
data?.pages.reduce((total, page) => total + page.results.length, 0) || 0;
if (error) <Text>{error.message}</Text>;
return (
<>
<InfiniteScroll
dataLength={fetchedGamesCount}
hasMore={true}
next={fetchNextPage}
loader={<Spinner />}
>
<SimpleGrid
columns={{ sm: 1, md: 2, lg: 3, xl: 4 }}
spacing={6}
padding="10px"
>
{isLoading &&
skeletons.map((idx) => (
<GameCardContainer key={idx}>
<SkelitonCard />
</GameCardContainer>
))}
{data?.pages.map((page, index) => (
<React.Fragment key={index}>
{page.results.map((game) => (
<GameCardContainer key={game.id}>
<GameCard game={game} />
</GameCardContainer>
))}
</React.Fragment>
))}
</SimpleGrid>
</InfiniteScroll>
</>
);
};
export default GameGrid;
|
//Code1
function arrayFunction() {
const newArray = [];
const fruitsArray = ['Apple','Banana','Pear','Strawberry'];
console.log(fruitsArray); }
//code2
function arrayFunction2() {
const newArray2 = [];
const fruitsArray2 = ['Apple','Banana','Pear','Strawberry'];
//array index starts at 0
// access items in array with this notation:
console.log(fruitsArray2[0]); // Apple
console.log(fruitsArray2[1]); // Banana
console.log(fruitsArray2[2]); // Pear
console.log(fruitsArray2[3]); // Strawberry
console.log(fruitsArray2[4]); // undefined, nothing at position 4
}
//Code3
// can also write arrays like this:
const anotherArray = ["code3","first",
"second",
"third",
"fourth"];
console.log(anotherArray);
//code4
const countingArray = ['two','three','four'];
console.log("Starting array:");
console.log(countingArray);
// add item to array
// add to end
countingArray.push('one hundred');
console.log(countingArray);
// add to start
countingArray.unshift('one');
console.log(countingArray);
// add to middle
countingArray.splice(2,0,'add first item');
console.log(countingArray);
countingArray.splice(3,0,'add second item');
console.log(countingArray);
/*
add to middle and replace the exsiting item
(in the splice the first number indicate
position and second number indicate if you want replace or only
add or remove if it is 1 means replace if it 0 means add only
and if it is 2 means remove)
*/
countingArray.splice(2,1,'the item been replaced');
console.log(countingArray);
//code5
const countingArray2 = ['two','three','four','five','six','seven'];
console.log("Starting array:");
console.log(countingArray2);
// removing items from array
// remove from end
countingArray2.pop();
console.log(countingArray2);
// remove from beginning
countingArray2.shift();
console.log(countingArray2);
/*
remove from the middle
(in the splice the first number indicate
position and second number indicate if you want replace or only
add or remove if it is 1 means replace if it 0 means add only
and if it is 2 means remove)
*/
countingArray2.splice(4,2);
console.log(countingArray2);
|
import Layout from './components/layout/Layout';
import { Route, Routes } from 'react-router-dom';
import Products from './pages/Products';
import ProductDetail from './pages/ProductDetail';
import Cart from './pages/Cart';
import Login from './pages/Login';
import Register from './pages/Register';
import NotFound from './pages/NotFound';
import UserRoute from './components/UserRoute';
import AuthRoute from './components/AuthRoutes';
import { createContext } from 'react';
import Alert from './components/Alert';
import UserProvider from './provider/userProvider';
import AlertProvider from './provider/AlertProvider';
export const UserContext = createContext();
function App() {
return (
<UserProvider>
<AlertProvider>
<Alert />
<Layout>
<Routes>
<Route
path="/"
element={
<UserRoute>
<Products />
</UserRoute>
}
/>
<Route
path="/:id"
element={
<UserRoute>
<ProductDetail />
</UserRoute>
}
/>
<Route
path="/cart"
element={
<UserRoute>
<Cart />
</UserRoute>
}
/>
<Route
path="/login"
element={
<AuthRoute>
<Login />
</AuthRoute>
}
/>
<Route
path="/register"
element={
<AuthRoute>
<Register />
</AuthRoute>
}
/>
<Route path="*" element={<NotFound />} />
</Routes>
</Layout>
</AlertProvider>
</UserProvider>
);
}
export default App;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.