text
stringlengths 184
4.48M
|
|---|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day Night</title>
</head>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root{
--sun-light: #ffff4394;
--moon-light: #ffffff75;
}
.section{
width: 100vw;
height: 100vh;
margin: auto;
display: flex;
flex-direction: column;
align-items: center;
background: #004d5f;
}
#domain{
color: #e7e7e7;
font-family: Poppins;
margin-top: 10px;
font-size: 27px;
}
/* Switch start */
.switch{
width: 55px;
height: 30px;
margin-top: 10px;
z-index: 20;
}
.switch div{
border: 2px solid #f3a515;
width: 100%;
height: 29px;
border-radius: 20px;
background: #f3a515;
cursor: pointer;
transition: border-color 0.3s linear, background 0.3s linear;
}
.switch div.off{
background: #011c31;
border-color: #011c31;
transition: border-color 0.3s linear, background 0.3s linear;
}
.switch div span{
display: block;
width: 25px;
height: 25px;
border-radius: 50%;
background: #fff;
transform: translateX(0);
transition: transform 0.3s linear;
}
.switch div span.off{
transform: translateX(100%);
transition: transform 0.3s linear;
}
/* Switch End */
.container{
/* border: 2px solid #000; */
max-width: 1566px;
max-height: 866px;
background-color: #ffc04a;
position: relative;
z-index: 1;
overflow: hidden;
transition: background-color 1.5s linear;
width: 500px;
height: 500px;
border-radius: 50px;
border: 4px solid rgb(247, 239, 224);
margin-top: 50px;
}
.container::before{
content: "";
position: absolute;
z-index: 1;
width: 100%;
height: 100%;
background: url(img/stars-1.png) no-repeat center top;
background-size: 100% 50%;
opacity: 0;
transition: opacity 1s linear, filter 1s linear;
}
.inner-img{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 20;
}
#grass{
position: absolute;
bottom: 7%;
width: 100%;
height: 5.1%;
z-index: 20;
background: url(img/grass2.png) repeat-x center center/contain;
filter: brightness(0.0);
}
#land{
position: absolute;
bottom: 0;
width: 100%;
height: 8%;
z-index: 20;
background: #000;
}
#tree{
position: absolute;
bottom: 7%;
left: 0%;
width: 100%;
height: 70%;
z-index: 20;
background: url('img/tree4.png') no-repeat -41% bottom/contain;
}
#sun{
z-index: 20;
position: absolute;
top: 46px;
right: 58px;
width: 110px;
height: 110px;
opacity: 0.5;
overflow: hidden;
border-radius: 50%;
box-shadow:
0 0 5px 4px #ffffcd,
0 0 10px 5px #ffffcd,
0 0 15px 6px #ffffcd,
0 0 40px var(--sun-light),
0 0 50px var(--sun-light),
0 0 60px var(--sun-light),
0 0 70px var(--sun-light),
0 0 80px var(--sun-light),
0 0 90px var(--sun-light),
0 0 100px var(--sun-light),
0 0 110px var(--sun-light);
transition:
right 1.2s ease-out 1s,
box-shadow 1s linear;
}
#sun img{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50.7%, -50.25%);
height: 137%;
width: 137%;
}
.cloud-container{
z-index: 20;
opacity: 1;
transition: opacity 1.5s linear;
}
.cloud-container div{
/* border: 1px solid red; */
position: absolute;
top: 0;
left: 0;
height: 58px;
width: 115px;
background: url('img/cloud1.png') no-repeat center center/contain;
opacity: 0.4;
z-index: 3;
}
.cloud-container div:nth-child(1){top: 13%;left: 10%;opacity: 0.2;}
.cloud-container div:nth-child(2){top: 33%;left: 49%;}
.cloud-container div:nth-child(3){top: 18%;left: 24%;}
.cloud-container div:nth-child(4){top: 23%;left: -1%;}
.cloud-container div:nth-child(5){top: 39%;left: 72%;}
.cloud-container div:nth-child(6){top: 30%;left: 84%;opacity: 0.3;}
.birds{
position: absolute;
width: 200px;
height: 200px;
background: url('img/birds2.png') no-repeat center center/contain;
transform: scaleX(-1);
z-index: 20;
filter: brightness(0);
transition: transform 1.1s linear 1s;
}
.bird-1{
top: -3%;
left: 10%;
}
.bird-2{
top: 23%;
left: 56%;
}
.bats{
position: absolute;
z-index: 20;
background: url('img/bats2.png') no-repeat center center/contain;
width: 150px;
height: 150px;
transform: scale(0) translateY(200px);
transition: transform 1.0s linear;
}
.bat-1{
top: 29%;
left: 71%;
}
.bat-3{
top: 17%;
left: 41%;
}
.boy-sit{
position: absolute;
bottom: 5%;
left: 22.0%;
width: 14%;
height: 19%;
background: url('img/sitting-boy1.png') no-repeat center center/contain;
filter: brightness(0);
transition: opacity 1s linear 0.5s;
}
.stand-boy{
position: absolute;
bottom: 6%;
left: 47%;
width: 14%;
height: 22%;
background: url(img/stand-boy2.png) no-repeat center center/contain;
filter: brightness(0);
opacity: 0;
transition: opacity 1s linear;
}
.house{
position: absolute;
bottom: 4%;
right: -10%;
width: 167px;
height: 180px;
background: url(img/house1.png) no-repeat center center/contain;
filter: brightness(0.1);
transition: opacity 1s linear, filter 1s linear;
}
.moon{
position: absolute;
top: 40px;
left: 105%;
width: 100px;
height: 100px;
border-radius: 50%;
background: url('img/moon2.png') no-repeat center center/109%;
/* background: url('https://www.nicepng.com/png/detail/233-2337879_clip-art-royalty-free-download-realistic-moon-png.png') no-repeat center center/109%; */
box-shadow:
0 0 10px var(--moon-light),
0 0 20px var(--moon-light),
0 0 30px var(--moon-light),
0 0 40px var(--moon-light);
transition:
left 1s ease-in,
box-shadow 1s linear;
}
/* Night start*/
.container.night{
/* background: linear-gradient(to top, #395163, #213748); */
background: #405c71;
transition: background 1s linear 0.3s;
}
.container.night::before{
opacity: 1;
filter: brightness(2);
transition: opacity 1s linear, filter 1s linear;
}
.container.night #sun{
right: 120%;
box-shadow: 0 0 0 var(--sun-light);
transition:
right 1s ease-in,
box-shadow 1s linear;
}
.container.night .moon{
left: 58%;
transition:
left 1s ease-out 1s,
box-shadow 1s linear 0.5s;
box-shadow:
0 0 10px 6px var(--moon-light),
0 0 20px var(--moon-light),
0 0 30px var(--moon-light),
0 0 50px var(--moon-light),
0 0 60px var(--moon-light),
0 0 70px var(--moon-light),
0 0 80px var(--moon-light),
0 0 90px var(--moon-light),
inset 0 0 90px #fff;
}
.container.night .cloud-container{
opacity: 0.2;
transition: opacity 1.5s linear;
}
.container.night .birds{
transform: scale(0) translateY(200px);
transition: transform 1.3s linear;
}
.container.night .bats{
transform: scale(1) translateY(0px);
transition: transform 1.0s linear 01s;
}
.container.night .boy-sit{
opacity: 0;
transition: opacity 0.8s linear 0.5s;
}
.container.night .stand-boy{
opacity: 1;
transition: opacity 1.2s linear 1s;
}
.container.night .house{
filter: brightness(0.8);
transition: filter 1s linear 0.4s;
}
/* night end */
</style>
<body>
<div class="section">
<div class="container">
<div id="grass"></div>
<div id="land"></div>
<div id="tree"></div>
<div id="sun">
<img src="img/sun-1.png" alt="">
</div>
<div class="cloud-container">
<div class="cloud"></div>
<div class="cloud"></div>
<div class="cloud"></div>
<div class="cloud"></div>
<div class="cloud"></div>
<div class="cloud"></div>
</div>
<div id="tree"></div>
<div class="birds bird-1"></div>
<div class="birds bird-2"></div>
<div class="bats bat-1"></div>
<div class="bats bat-3"></div>
<div class="boy-sit"></div>
<div class="stand-boy"></div>
<div class="house"></div>
<div class="moon"></div>
</div>
<h3 id="domain">Day and Night Animation</h3>
<div class="switch">
<div onclick="toggle_swich()">
<span></span>
</div>
</div>
</div>
<script>
let box = document.querySelector('.container');
let switch_btn = document.querySelector('.switch div');
let switch_ball = document.querySelector('.switch div span');
function toggle_swich(){
switch_ball.classList.toggle("off");
switch_btn.classList.toggle("off");
box.classList.toggle("night");
}
</script>
</body>
</html>
|
import React, { FC, useContext } from 'react';
import { StyleSheet, View } from 'react-native';
import { TouchableWithoutFeedback } from 'react-native-gesture-handler';
import LinearGradient from 'react-native-linear-gradient';
import GradientText from 'components/GradientText';
import { ProfileContext } from 'screens/profile/ProfileScreen';
import { gradientColorFormation, normalize } from 'utils';
import { HOMEPAGE } from '../../constants/constants';
const OutlineButton: FC<{
title?: string;
icon?: Element;
selected: boolean;
onPress: () => void;
}> = props => {
const { primaryColor, secondaryColor } = useContext(ProfileContext);
const { title, icon, onPress, selected } = props;
const colorData = selected
? gradientColorFormation(secondaryColor)
: gradientColorFormation(primaryColor);
return (
<TouchableWithoutFeedback onPress={onPress}>
{selected ? (
<LinearGradient colors={colorData} style={[styles.outlineButton, styles.outLineSpace]}>
{title ? (
<GradientText
colors={gradientColorFormation(selected ? primaryColor : secondaryColor)}
style={[styles.outlineButtonText]}>
{title === HOMEPAGE ? 'Home' : title}
</GradientText>
) : (
<View style={styles.iconPadding}>{icon}</View>
)}
</LinearGradient>
) : (
<LinearGradient
colors={gradientColorFormation(secondaryColor)}
style={[styles.outlineButton, { borderColor: secondaryColor }]}>
<LinearGradient
colors={gradientColorFormation(primaryColor)}
style={styles.innerContainer}>
{title ? (
<GradientText
colors={gradientColorFormation(secondaryColor)}
style={[styles.outlineButtonText]}>
{title === HOMEPAGE ? 'Home' : title}
</GradientText>
) : (
<View style={styles.iconPadding}>{icon}</View>
)}
</LinearGradient>
</LinearGradient>
)}
</TouchableWithoutFeedback>
);
};
const styles = StyleSheet.create({
outlineButton: {
height: '100%',
justifyContent: 'center',
padding: 3,
marginRight: 10,
borderRadius: 999,
// borderWidth: 3,
},
outlineButtonText: {
fontSize: normalize(13),
fontWeight: 'bold',
},
innerContainer: {
alignItems: 'center',
height: '100%',
borderRadius: 20,
flex: 1,
justifyContent: 'center',
paddingHorizontal: 10,
},
iconPadding: {
paddingHorizontal: 8,
},
outLineSpace: { paddingHorizontal: 10 },
});
export default OutlineButton;
|
<!--color goes from transparent to blue if mobile nav dropdown is clicked or a certain scroll threshold is met-->
<div [style.background-color] = "(!navbarTransparent||showMobileNav) ? '#6666ff' : 'transparent' " class="navbar">
<div class="navContainer">
<p class="navLogo">Kangaroo</p>
<!--change the class to nav-inactive if mobile nav has not been clicked yet (this will hide the dropdown). The nav-active class is only defined in the mobile viewport-->
<nav [ngClass]="showMobileNav? 'nav-active' : ''">
<!--Display navbar content according to whether the user is logged in or not-->
<ul *ngIf = "!isLoggedIn()" class="navbarLinks">
<li>
<a (click) = "scrollToElement('start')" style="cursor:pointer">Home</a>
</li>
<li>
<a href="/demo">Demo</a>
</li>
<li>
<a (click) = "scrollToElement('features')" style="cursor:pointer">Features</a>
</li>
<li>
<a (click) = "scrollToElement('about')" style="cursor:pointer">About</a>
</li>
<!--only visible in mobile-->
<li class="navButtonMobileLi">
<a (click) = "openRegModal(); mobileNavClick();" class="navButton" style="background-color: #7957d5;">Register</a>
<a (click) = "openLoginModal(); mobileNavClick();" class="navButton" style="background-color: #f5f5f5; color: black;">Login</a>
</li>
</ul>
<ul *ngIf = "isLoggedIn()" class="navbarLinks">
<li>
<a href="/my-planner">My Planner</a>
</li>
<li>
<a href="/my-account">My Account</a>
</li>
<!--only visible in mobile-->
<li class="navButtonMobileLi">
<a (click) = "logOut()" class="navButton" style="background-color: #7957d5;">Log Out</a>
</li>
</ul>
</nav>
<div class="mobileMenu" id="mobileMenu">
<!--change icon depending on whether the mobile nav has been clicked or not-->
<fa-icon *ngIf="showMobileNav" (click)= "mobileNavClick()" [icon]="faTimes"></fa-icon>
<fa-icon *ngIf="!showMobileNav" (click)= "mobileNavClick()" [icon]="faBars"></fa-icon>
</div>
<!--display:none in mobile, only visible in browser-->
<!--Display navbar content according to whether the user is logged in or not-->
<div *ngIf = "!isLoggedIn()" class="navButtonDiv">
<button (click) = "openRegModal()" class="navButton" style="background-color: #7957d5;">Register</button>
<button (click) = "openLoginModal()" class="navButton" style="background-color: #f5f5f5; color: black;">Login</button>
</div>
<div *ngIf = "isLoggedIn()" class="navButtonDiv">
<button (click) = "logOut()" class="navButton" style="background-color: #7957d5;">Log Out</button>
</div>
</div>
</div>
<!--registration form is hidden instead of removed from DOM, this is because of an error with the google recaptcha that occurs when this item is removed from DOM-->
<div [hidden] = "!displayRegModal" (click) = "closeRegModal($event)" class="modal">
<div class="modalContent">
<div class="modalHeader">
<span (click) = "closeRegModal($event)" class="close">×</span>
<h2>Create An Account</h2>
</div>
<div class="modalBody">
<div class="form1">
<label>User Name:</label><br>
<input type="text" (focusout) = "checkUsernameAvailability()" [(ngModel)] = "regInfo.userName"><br>
<p class="dangerText" *ngIf = "regErr == 'missing field'&®Info.userName==''">This field is required</p>
<p class="dangerText" *ngIf = "!usernameAvailability">This username is already taken, please choose another</p>
<label>Email:</label><br>
<input type="email" (focusout) = "checkEmailAvailability()" [(ngModel)] = "regInfo.email"><br>
<p class="dangerText" *ngIf = "regErr == 'missing field'&®Info.email==''">This field is required</p>
<p class="dangerText" *ngIf = "regErr == 'invalid email'">Please enter a valid email address</p>
<p class="dangerText" *ngIf = "!emailAvailability">There is already an account registered under this email. Please log in.</p>
<label>Password:</label><br>
<input type="password" [(ngModel)] = "regInfo.password"><br>
<p class="dangerText" *ngIf = "regErr == 'missing field'&®Info.password==''">This field is required</p>
<label>Confirm Password:</label><br>
<input type="password" [(ngModel)] = "regInfo.confirmPassword"><br>
<p class="dangerText" *ngIf = "regInfo.confirmPassword!=regInfo.password">Passwords do not match</p>
<!--add google captcha, validated in the backend-->
<div class="captcha"><re-captcha [(ngModel)]="regInfo.captcha" siteKey="6Lemkv0UAAAAAEC7_tzjFjD4icTFhiRL_fbYd0Po"></re-captcha></div>
<p class="dangerText" *ngIf = "regErr == 'missing field'&®Info.captcha==''">This field is required</p>
</div>
</div>
<div class="modalFooter">
<button (click) = "sendEmailVerification()" class="button1">Next</button>
</div>
</div>
</div>
<!--verification form only added to DOM when the variable for rendering it is true (modal is open)-->
<div *ngIf = "displayVerificationModal" class="modal">
<div class="modalContent">
<div class="modalHeader">
<h2>Verify Email</h2>
</div>
<div class="modalBody">
<div class="form1">
<p class="infoText">Since the only means of account recovery is through your email. Please confirm your email before proceeding. Closing this modal will cancel your registration. <br><br> Please enter the code sent to your email below</p>
<label>Email:</label><br>
<input type="email" (focusout) = "checkEmailAvailability()" [(ngModel)] = "regInfo.email"><br>
<p class="dangerText" *ngIf = "regErr == 'missing field'&®Info.email==''">This field is required</p>
<p class="dangerText" *ngIf = "regErr == 'invalid email'">Please enter a valid email address</p>
<p class="dangerText" *ngIf = "!emailAvailability">There is already an account registered under this email. Please log in.</p>
<p class="dangerText" style="color: blue;" *ngIf = "regResp == 'email sent'">New verification code email has been sent</p>
<button (click) = "resendEmailVerification()" class="button2">Re-send Code</button><br>
<label>Validation Code:</label>
<input type="text" [(ngModel)] = "regInfo.verificationCode"><br>
<p class="dangerText" *ngIf = "regErr == 'missing field'&®Info.verificationCode==''">This field is required</p>
<p class="dangerText" *ngIf = "regErr == 'invalid authorization code'">The entered verification code is incorrect</p>
</div>
</div>
<div class="modalFooter">
<button (click) = "closeVerificationModal()" class="button1">Cancel</button>
<button (click) = "validateVerificationCode()" class="button1">Submit</button>
</div>
</div>
</div>
<!--login form only added to DOM when the variable for rendering it is true (modal is open)-->
<div *ngIf = "displayLoginModal" (click) = "closeLoginModal($event)" class="modal">
<div class="modalContent">
<div class="modalHeader">
<span (click) = "closeLoginModal($event)" class="close">×</span>
<h2>Login</h2>
</div>
<div class="modalBody">
<div class="form1">
<label>Username:</label><br>
<input type="text" [(ngModel)] = "regInfo.userName"><br>
<p class="dangerText" *ngIf = "regErr == 'missing field'&®Info.userName==''">This field is required</p>
<label>Password:</label><br>
<input type="password" [(ngModel)] = "regInfo.password"><br>
<p class="dangerText" *ngIf = "regErr == 'missing field'&®Info.password==''">This field is required</p>
<p class="dangerText" *ngIf = "regErr == 'invalid login credentials'">Invalid login credentials</p>
<p (click) = "displayLoginModal = false; displayPasswordResetModal = true" class="infoText" style="color: blue; cursor: pointer;">Forgot Password</p>
</div>
</div>
<div class="modalFooter">
<button (click) = "login()" class="button1">Login</button>
</div>
</div>
</div>
<!--password reset form only added to DOM when the variable for rendering it is true (modal is open)-->
<div *ngIf = "displayPasswordResetModal" (click) = "closePasswordResetModal($event)" class="modal">
<div class="modalContent">
<div class="modalHeader">
<span (click) = "closePasswordResetModal($event)" class="close">×</span>
<h2>Password Reset</h2>
</div>
<div class="modalBody">
<div class="form1">
<p class="infoText">Please enter the email under which your account is registered</p>
<label>Email:</label><br>
<input type="text" [(ngModel)] = "regInfo.email"><br>
<p class="dangerText" *ngIf = "regErr == 'missing field'&®Info.email==''">This field is required</p>
<p class="dangerText" *ngIf = "regErr == 'invalid email'">Please enter a valid email address</p>
<p class="dangerText" *ngIf = "regErr == 'Unable to send email reset request'">Unable to send email reset request</p>
<p class="dangerText" style="color: blue;" *ngIf = "regResp == 'Password reset link has been sent to your email address'">Password reset link has been sent to your email address</p>
</div>
</div>
<div class="modalFooter">
<button (click) = "passwordReset()" class="button1">Submit</button>
</div>
</div>
</div>
|
// auction.test.js
const { createAuction, getAuctionById, placeBid, getBidsForAuction } = require('../../src/auction');
describe('Auction Module Tests', () => {
beforeEach(() => {
// Limpa os dados antes de cada teste
auctions = [];
bids = [];
});
test('Criar e obter leilão por ID', () => {
createAuction({ id: 1, name: 'Leilão de Teste', startingPrice: 50 });
const auction = getAuctionById(1);
expect(auction).toEqual({ id: 1, name: 'Leilão de Teste', startingPrice: 50 });
});
test('Criar e obter lances para o leilão', () => {
createAuction({ id: 1, name: 'Leilão de Teste', startingPrice: 50 });
placeBid(1, 1, 60);
placeBid(1, 2, 70);
const bids = getBidsForAuction(1);
expect(bids).toEqual([{ auctionId: 1, userId: 1, amount: 60 }, { auctionId: 1, userId: 2, amount: 70 }]);
});
test('Criar e obter lances para o leilão', () => {
createAuction({ id: 1, name: 'Leilão de Teste', startingPrice: 50 });
placeBid(1, 1, 20);
placeBid(1, 2, 70);
const bids = getBidsForAuction(1);
expect(bids).toEqual([{ auctionId: 1, userId: 1, amount: 20 }, { auctionId: 1, userId: 2, amount: 70 }]);
});
test('Criar e obter lances para o leilão', () => {
createAuction({ id: 1, name: 'Leilão de Teste', startingPrice: 50 });
placeBid(9, 1, 60);
placeBid(1, 2, 70);
const bids = getBidsForAuction(1);
expect(bids).toEqual([{ auctionId: 9, userId: 1, amount: 60 }, { auctionId: 1, userId: 2, amount: 70 }]);
});
// Adicione mais testes conforme necessário
});
|
#include<iostream>
#include<string>
using namespace std;
/*
생성자 초기화 방법
1. 기본 생성자를 명시적으로 정의하여 멤버 변수들을 초기화
2. 복수(다중) 생성자를 통해 매개 변수타입을 받아 멤버 변수를 다르게 초기화
3. default 생성자를 통해 기본 생성자를 명시적으로 선언하고, 기본 생성자를 컴파일러가 자동으로 생성
4. 생성자 초기화 리스트를 이용하여 변수를 초기화
*/
class Class0{
public:
void print(){
cout << number << ", " << str << endl;
}
double getdouble(){
return d;
}
protected:
double d = 2.25;
private:
int number;
string str;
};
class Class01 : public Class0{
public:
void print(){
cout << getdouble() << endl;
cout << d << endl;
}
};
class Class1{
public:
Class1(){
number1 = 1;
number2 = 2;
name = "null";
}
Class1(int num1, int num2){
number1 = num1;
number2 = num2;
}
class1(string name){
this->name = name;
}
void print(){
cout << number1 << ", " << number2 << ", " << name << endl;
}
private:
int number1;
int number2;
string name;
};
class Class2{
public:
Class2() : number1(10), name("name"){
number2 = 30;
}
Class2(int num1, int num2, string name){
number1 = num1;
number2 = num2;
this->name = name;
}
void print(){
cout << number1 << ", " << number2 << ", " << name << endl;
}
private:
int number1;
int number2;
string name;
};
int main(){
Class0 c0;
c0.print();
cout << c0.getdouble() << endl;;
Class01 c01;
c01.print();
Class1 c1;
c1.print();
Class1 *c2 = new Class1(999,110);
c2->print();
Class2 c3;
c3.print();
return 0;
}
|
package com.exito.app.test.automation.e2e.stepdefinitions.features.cuenta.registro;
import com.exito.app.test.automation.e2e.models.scena.Libreto;
import com.exito.app.test.automation.e2e.models.scena.screenplay.Protagonista;
import com.exito.app.test.automation.e2e.stepdefinitions.features.inicio.InicioStepDefinition;
import com.exito.app.test.automation.e2e.stepdefinitions.javadoc.StepDefinitionsJavaDoc;
import com.exito.app.test.automation.e2e.tasks.features.cuenta.registro.ConfirmarRegistro;
import com.exito.app.test.automation.e2e.tasks.features.cuenta.registro.DiligenciarRegistro;
import io.cucumber.java.es.Cuando;
import io.cucumber.java.es.Dado;
/**
* Para mas informacion:
* @see StepDefinitionsJavaDoc#CLASE
*/
public class RegistroCuentaStepDefinition
{
/**
* Para mas informacion:
* @see StepDefinitionsJavaDoc#DADO
*/
@Dado("^que \"(.*)\" se encuentra registrando su cuenta.*")
public static void dadoQueSeEncuentraRegistrandoSuCuenta(String actor)
{
/**
* @see StepDefinitionsJavaDoc#ENLAZAR_ESCENA_PREVIA_PANTALLA_ANTERIOR
*/
InicioStepDefinition.dadoQueSeEncuentraSobreLaPortadaInicial(actor);
InicioStepDefinition.cuandoSeDirigeParaRegistrarse();
}
/**
* Para mas informacion:
* @see StepDefinitionsJavaDoc#CUANDO
*/
@Cuando("^diligencia el registro de su cuenta.*")
public static void cuandoDiligenciaElRegistroDeSuCuenta(Libreto libreto)
{
/**
* @see StepDefinitionsJavaDoc#ENLAZAR_TAREAS
*/
Protagonista.enEscena().attemptsTo(
DiligenciarRegistro.deLaCuenta(libreto.getParametrosRegistroCuenta())
);
}
/**
* Para mas informacion:
* @see StepDefinitionsJavaDoc#CUANDO
*/
@Cuando("^confirma el registro de su cuenta.*")
public static void cuandoConfirmaElRegistroDeSuCuenta(Libreto libreto)
{
/**
* @see StepDefinitionsJavaDoc#ENLAZAR_TAREAS
*/
Protagonista.enEscena().attemptsTo(
ConfirmarRegistro.deLaCuenta(libreto.getParametrosRegistroCuenta())
);
}
}
|
Professional JSP, 2nd Edition - Code Download Notes
The war bundle contains .war files for most chapters from Professional JSP,
2nd Edition (ISBN 1-86100495-8). Source code is not included - for that,
download the companion source bundle from http://www.wrox.com/.
We can't redistribute the Java API for XML Parsing (JAXP) and so there
are no .war files included for chapters 12 and 21 - unfortunately you'll
have to build these yourself from the source bundle.
Quick Start
Full instructions follow but you can get started by following these steps:
* Follow the Tomcat 4.0 setup instructions on pages 974-7.
* Copy the .war files for the chapters you are interested in from the
wars directory into Tomcat's webapps directory. A .war file is
effectively just a .zip file in a particular format - you can open it
with a zip tool such as WinZip.
* Restart Tomcat.
* Browse to http://localhost:8080/chNN/ where NN is the chapter number
you are interested in.
Chapter 6 Additional Setup Notes
To use the extended example (pages 219-224):
* Edit URL.properties so that the last two lines read:
NEW_RECORD=/jsp/newRecordBind.jsp
SUMMARY=/jsp/summaryBind.jsp
in place of:
NEW_RECORD=/jsp/newRecord.jsp
SUMMARY=/jsp/summary.jsp
Chapter 13 Additional Setup Notes
If using MS Access database:
* Set up a System DSN named presidential_election for the database
OnlineVotingApp.mdb, which is in the ch13/data directory. Instructions
are on pages 478-9.
If using mySQL database:
* Create and populate database by following the instructions on
pages 479-81. The scripts createtables.sql and populatetables.sql
are in the ch13/data directory.
* Edit the .jsp files as indicated within the files themselves
to comment out the Access-specific code and uncomment the mySQL-
specific code.
Chapter 14 Additional Setup Notes
Setting up context:
* To enable separate logging for the ch14 web application add the following
entry to server.xml, as described on page 522:
<Context path="/ch14" docBase="ch14" debug="0" reloadable="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_ch14_log." suffix="txt" timestamp="true"/>
</Context>
NOTE: Per-context logging configuration is broken in Tomcat 4.0 Beta 3
but should work correctly in subsequent beta releases.
Filter configuration:
* Edit web.xml as described in the chapter to enable and disable filters
and experiment with filter ordering. By default the "Simple Filter"
(p. 522-5) is enabled and all others are disabled; adjust the commenting
out of web.xml entries to experiment with other filters. Note that the
format of web.xml requires that all <filter> entries precede
<filter-mapping> entries, and that the ordering of <filter-mapping>
elements is significant.
Chapter 15 Additional Setup Notes
Setting up context:
* To enable separate logging for the ch15 web application add the following
entry to server.xml, as described on page 537:
<Context path="/ch15" docBase="ch15" debug="0" reloadable="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_ch15_log." suffix="txt" timestamp="true"/>
</Context>
NOTE: Per-context logging configuration is broken in Tomcat 4.0 Beta 3
but should work correctly in subsequent beta releases.
Filter configuration:
* Edit web.xml as described in the chapter to enable and disable filters
and experiment with filter ordering. By default the "Visual Auditing"
filter (p. 538-46) is enabled and all others are disabled; adjust the
commenting out of web.xml entries to experiment with other filters.
Note that the format of web.xml requires that all <filter> entries
precede <filter-mapping> entries, and that the ordering of
<filter-mapping> elements is significant.
Database setup (XSLT Filter):
* Set up a System DSN named travel for the database traveldeals.mdb,
which is in the ch15/data directory. Instructions are on page 572.
Chapter 16 Additional Setup Notes
Adding a user:
* As described on page 615, add an entry to tomcat-users.xml (found in
CATALINA_HOME/conf):
<user name="justin" password="justin" roles="user"/>
Configuring Tomcat to use HTTPS:
* Follow the instructions on pages 608-9.
Chapter 20 Additional Setup Notes
The code in this chapter was designed to use an Oracle database, however
we are including MS Access databases for you to use in the absence of
Oracle:
* Set up a System DSN named widget for the database widget.mdb, and
one named fwidget for fwidget.mdb. Both files are in the ch20/data
directory.
If you have Oracle then edit the source files appropriately to comment
out the Access-specific code and substitute the commented-out Oracle
code.
Chapter 24 Additional Setup Notes
Prerequisites
* These instructions that follow assume you are running on Microsoft Windows
and have installed :
- JDK 1.3
- jBoss 2.2.1 (or 2.1)
- Tomcat 4
This example has been tested with jBoss 2.2.1 (and 2.1) and various
versions of Tomcat 4 (including Beta 3) running in separate JVMs.
Compiling the Code
* If you have an SMTP server available to test the JavaMail example
(p. 966-9), edit src/com/wrox/store/ejb/mail/MailBean.java and replace
smtp.yourdomain.com with its DNS name.
* Ensure that the CATALINA_HOME and JBOSS_HOME environment variables are
set.
* Run ant in this directory. This will build ch24.jar and ch24.war, in the
../wars directory.
Deploying the EJBs to jBoss
* Start jBoss.
* Copy ch24.jar file into the %JBOSS_HOME%/deploy directory.
* To test that the deployment was successful (and to upload some sample
data), run the upload.bat and test.bat files.
Deploying the web application to Tomcat
* Copy ch24.war into the %CATALINA_HOME%/webapps/ directory.
* (Optional) Open up the %CATALINA_HOME%/conf/server.xml file and add
the following underneath the "tomcat examples context":
<Context path="/wrox" docBase="wrox" debug="0"/>
Running the example
* Start up both jBoss and Tomcat.
* Point a web browser to http://localhost:8080/wrox/
Appendix G Additional Setup Notes
Tomcat-IIS integration:
* This section requires Tomcat 3.2.x rather than Tomcat 4.0. Download
from http://jakarta.apache.org/tomcat/ and follow the instructions on
pages 1099-1103.
MS Access database:
* Set up a System DSN named countrydb for the database countrydb.mdb,
which is in the appendixG/data directory. Instructions are on pages 478-9.
Jacob Java-COM bridge:
* Please follow the setup instructions on page 1141. jacob.dll can be
found in the appendixG/jacob directory.
Java in .NET:
* Please follow the setup instructions on pages 1144-5.
|
import { ipcMain, dialog, OpenDialogOptions } from 'electron';
import { writeFile, readFile } from 'fs-extra';
import { join, parse, dirname } from 'path';
import Papa from 'papaparse';
import { getBrowserWindow } from '.';
export const SAMPLE_NETWORK_PATH = join(__dirname, '../../complex-example.case')
const saveDialogOptions = {
properties: ['createDirectory', 'showOverwriteConfirmation'],
filters: [
{ name: 'Case', extensions: ['case'] }
]
};
export const ensureFilePath = async (filePath: string | null, options: Object) => {
if (filePath) { return filePath; }
const { canceled, filePath: path } = await dialog.showSaveDialog(getBrowserWindow(), options);
if (canceled) {
return;
}
getBrowserWindow()?.webContents.send('file-saved', path);
return path;
}
export const openFile = async (filePath: string) => {
console.log('Opening file: ', filePath);
const data = await readFile(filePath, 'utf8');
getBrowserWindow()?.webContents.send('file-opened', JSON.parse(data), filePath);
}
export const saveFile = async ({ data, filePath }) => {
const path = await ensureFilePath(filePath, saveDialogOptions);
if (!path) { return; }
await writeFile(path, data, 'utf8');
getBrowserWindow()?.webContents.send('file-saved', path);
return;
}
const saveCSV = async ({ edges, nodes, filePath }) => {
const path = await ensureFilePath(filePath, saveDialogOptions);
const browserWindow = await getBrowserWindow();
if (!path) { return; }
if (!browserWindow) { return; }
const cwd = dirname(path);
const dialogOptions: OpenDialogOptions = {
title: 'Select location for CSV files',
buttonLabel: 'Save',
defaultPath: cwd,
properties: ['openDirectory', 'createDirectory'],
};
const { canceled, filePaths } = await dialog.showOpenDialog(browserWindow, dialogOptions);
if (canceled) { return; }
const { name } = parse(path);
const dir = filePaths[0];
const nodesFilePath = join(dir, `${name}_nodes.csv`);
const edgesFilePath = join(dir, `${name}_edges.csv`);
console.log('Exporting CSV:', {
dir,
filePaths,
name,
path,
nodesFilePath,
edgesFilePath,
})
await writeFile(nodesFilePath, Papa.unparse(nodes), 'utf8');
await writeFile(edgesFilePath, Papa.unparse(edges), 'utf8');
}
export const registerListeners = async () => {
ipcMain.handle('open-sample-protocol', async () => {
console.log('Open sample protocol');
await openFile(SAMPLE_NETWORK_PATH);
})
ipcMain.on('trigger-save-response', async (_, response) => {
console.log('trigger-save-response', response);
await saveFile(response);
})
ipcMain.on('trigger-save-csv-response', async (_, response) => {
await saveCSV(response);
})
ipcMain.on('trigger-save-screenshot-response', async (_, response) => {
const options = {
properties: ['createDirectory', 'showOverwriteConfirmation'],
defaultPath: 'ScriptNet Export.png',
filters: [
{ name: 'Images', extensions: ['png'] }
]
};
const { canceled, filePath } = await dialog.showSaveDialog(getBrowserWindow(), options);
if (canceled) { return; }
const buffer = Buffer.from(response, "base64");
await writeFile(filePath, buffer);
});
return;
}
|
//#define GENERATE_ENUMERABLE
//#define GENERATE_CTOR
#define GENERATE_ASSPAN
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace FixedLengthArray
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FixedLengthIntPtrArray2 : IFixedLengthArray<IntPtr>
, IEquatable<FixedLengthIntPtrArray2>
, IEquatableByRef<FixedLengthIntPtrArray2>
{
public const int ConstLength = 2;
public readonly int Length => ConstLength;
readonly int IReadOnlyCollection<IntPtr>.Count => ConstLength;
#if GENERATE_CTOR
public FixedLengthIntPtrArray2(
IntPtr field0
, IntPtr field1
)
{
Field0 = field0;
Field1 = field1;
}
#endif
public IntPtr Field0;
public IntPtr Field1;
public IntPtr this[int index]
{
#if GENERATE_ASSPAN
readonly get => FixedLengthArrayExtension.AsReadOnlySpan(in this)[index];
set => FixedLengthArrayExtension.AsSpan(ref this)[index] = value;
#else
readonly get => index switch
{
0 => Field0,
1 => Field1,
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
set
{
switch (index)
{
case 0: Field0 = value; break;
case 1: Field1 = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
#endif
}
#if GENERATE_ASSPAN
public readonly override bool Equals(object other)
=> other is FixedLengthIntPtrArray2 array
? FixedLengthArrayExtension.Equals(in this, array)
: false;
public readonly bool Equals(in FixedLengthIntPtrArray2 other)
=> FixedLengthArrayExtension.Equals(in this, in other);
readonly bool IEquatable<FixedLengthIntPtrArray2>.Equals(FixedLengthIntPtrArray2 other)
=> this.Equals(in other);
public static bool operator ==(in FixedLengthIntPtrArray2 left, in FixedLengthIntPtrArray2 right)
=> left.Equals(right);
public static bool operator !=(in FixedLengthIntPtrArray2 left, in FixedLengthIntPtrArray2 right)
=> !(left == right);
#endif
public override readonly int GetHashCode()
{
#if GENERATE_ASSPAN
int hash = 0;
var span = FixedLengthArrayExtension.AsReadOnlySpan(this);
for(int i = 0; i < span.Length; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)span[i].GetHashCode(), i));
}
return hash;
#else
int hash = 0;
for(int i = 0; i < ConstLength; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)this[i].GetHashCode(), i));
}
return hash;
#endif
}
readonly IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
{
for(var i = 0; i < ConstLength; i++)
{
yield return this[i];
}
}
readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> (this as IEnumerable<IntPtr>).GetEnumerator();
#if GENERATE_ASSPAN
public readonly ReadOnlySpan<IntPtr>.Enumerator GetEnumerator()
=> FixedLengthArrayExtension.AsReadOnlySpan(this).GetEnumerator();
public static implicit operator ReadOnlySpan<IntPtr>(in FixedLengthIntPtrArray2 self)
=> self.AsReadOnlySpan();
#endif
}
public static partial class FixedLengthArrayExtension
{
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Span<IntPtr> AsSpan(this ref FixedLengthIntPtrArray2 array)
=> FixedLengthArray.CreateSpan(ref array.Field0, array.Length);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<IntPtr> AsReadOnlySpan(this in FixedLengthIntPtrArray2 array)
=> FixedLengthArray.CreateReadOnlySpan(array.Field0, array.Length);
#endif
public static bool Equals(in FixedLengthIntPtrArray2 array1, in FixedLengthIntPtrArray2 array2)
{
for(int i = 0; i < array1.Length;i++ )
{
if(array1[i] != array2[i])
return false;
}
return true;
}
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ref IntPtr At(this ref FixedLengthIntPtrArray2 array, int index)
=> ref AsSpan(ref array)[index];
public static void CopyTo(this in FixedLengthIntPtrArray2 array, Span<IntPtr> destination)
=> AsReadOnlySpan(array).CopyTo(destination);
public static void Fill(this ref FixedLengthIntPtrArray2 array, IntPtr value = default)
=> AsSpan(ref array).Fill(value);
#else
public static ref IntPtr At(this ref FixedLengthIntPtrArray2 array, int index)
{
switch (index)
{
case 0: return ref array.Field0;
case 1: return ref array.Field1;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
public static void CopyTo(this in FixedLengthIntPtrArray2 array, IntPtr[] dest, int offset = 0)
{
for(int i = 0; i < array.Length;i++ )
{
dest[offset + i] = array[i];
}
}
public static void Fill(this ref FixedLengthIntPtrArray2 array, IntPtr value = default)
{
for(int i = 0; i < array.Length;i++ )
{
array[i] = value;
}
}
#endif
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FixedLengthIntPtrArray3 : IFixedLengthArray<IntPtr>
, IEquatable<FixedLengthIntPtrArray3>
, IEquatableByRef<FixedLengthIntPtrArray3>
{
public const int ConstLength = 3;
public readonly int Length => ConstLength;
readonly int IReadOnlyCollection<IntPtr>.Count => ConstLength;
#if GENERATE_CTOR
public FixedLengthIntPtrArray3(
IntPtr field0
, IntPtr field1
, IntPtr field2
)
{
Field0 = field0;
Field1 = field1;
Field2 = field2;
}
#endif
public IntPtr Field0;
public IntPtr Field1;
public IntPtr Field2;
public IntPtr this[int index]
{
#if GENERATE_ASSPAN
readonly get => FixedLengthArrayExtension.AsReadOnlySpan(in this)[index];
set => FixedLengthArrayExtension.AsSpan(ref this)[index] = value;
#else
readonly get => index switch
{
0 => Field0,
1 => Field1,
2 => Field2,
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
set
{
switch (index)
{
case 0: Field0 = value; break;
case 1: Field1 = value; break;
case 2: Field2 = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
#endif
}
#if GENERATE_ASSPAN
public readonly override bool Equals(object other)
=> other is FixedLengthIntPtrArray3 array
? FixedLengthArrayExtension.Equals(in this, array)
: false;
public readonly bool Equals(in FixedLengthIntPtrArray3 other)
=> FixedLengthArrayExtension.Equals(in this, in other);
readonly bool IEquatable<FixedLengthIntPtrArray3>.Equals(FixedLengthIntPtrArray3 other)
=> this.Equals(in other);
public static bool operator ==(in FixedLengthIntPtrArray3 left, in FixedLengthIntPtrArray3 right)
=> left.Equals(right);
public static bool operator !=(in FixedLengthIntPtrArray3 left, in FixedLengthIntPtrArray3 right)
=> !(left == right);
#endif
public override readonly int GetHashCode()
{
#if GENERATE_ASSPAN
int hash = 0;
var span = FixedLengthArrayExtension.AsReadOnlySpan(this);
for(int i = 0; i < span.Length; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)span[i].GetHashCode(), i));
}
return hash;
#else
int hash = 0;
for(int i = 0; i < ConstLength; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)this[i].GetHashCode(), i));
}
return hash;
#endif
}
readonly IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
{
for(var i = 0; i < ConstLength; i++)
{
yield return this[i];
}
}
readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> (this as IEnumerable<IntPtr>).GetEnumerator();
#if GENERATE_ASSPAN
public readonly ReadOnlySpan<IntPtr>.Enumerator GetEnumerator()
=> FixedLengthArrayExtension.AsReadOnlySpan(this).GetEnumerator();
public static implicit operator ReadOnlySpan<IntPtr>(in FixedLengthIntPtrArray3 self)
=> self.AsReadOnlySpan();
#endif
}
public static partial class FixedLengthArrayExtension
{
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Span<IntPtr> AsSpan(this ref FixedLengthIntPtrArray3 array)
=> FixedLengthArray.CreateSpan(ref array.Field0, array.Length);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<IntPtr> AsReadOnlySpan(this in FixedLengthIntPtrArray3 array)
=> FixedLengthArray.CreateReadOnlySpan(array.Field0, array.Length);
#endif
public static bool Equals(in FixedLengthIntPtrArray3 array1, in FixedLengthIntPtrArray3 array2)
{
for(int i = 0; i < array1.Length;i++ )
{
if(array1[i] != array2[i])
return false;
}
return true;
}
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ref IntPtr At(this ref FixedLengthIntPtrArray3 array, int index)
=> ref AsSpan(ref array)[index];
public static void CopyTo(this in FixedLengthIntPtrArray3 array, Span<IntPtr> destination)
=> AsReadOnlySpan(array).CopyTo(destination);
public static void Fill(this ref FixedLengthIntPtrArray3 array, IntPtr value = default)
=> AsSpan(ref array).Fill(value);
#else
public static ref IntPtr At(this ref FixedLengthIntPtrArray3 array, int index)
{
switch (index)
{
case 0: return ref array.Field0;
case 1: return ref array.Field1;
case 2: return ref array.Field2;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
public static void CopyTo(this in FixedLengthIntPtrArray3 array, IntPtr[] dest, int offset = 0)
{
for(int i = 0; i < array.Length;i++ )
{
dest[offset + i] = array[i];
}
}
public static void Fill(this ref FixedLengthIntPtrArray3 array, IntPtr value = default)
{
for(int i = 0; i < array.Length;i++ )
{
array[i] = value;
}
}
#endif
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FixedLengthIntPtrArray4 : IFixedLengthArray<IntPtr>
, IEquatable<FixedLengthIntPtrArray4>
, IEquatableByRef<FixedLengthIntPtrArray4>
{
public const int ConstLength = 4;
public readonly int Length => ConstLength;
readonly int IReadOnlyCollection<IntPtr>.Count => ConstLength;
#if GENERATE_CTOR
public FixedLengthIntPtrArray4(
IntPtr field0
, IntPtr field1
, IntPtr field2
, IntPtr field3
)
{
Field0 = field0;
Field1 = field1;
Field2 = field2;
Field3 = field3;
}
#endif
public IntPtr Field0;
public IntPtr Field1;
public IntPtr Field2;
public IntPtr Field3;
public IntPtr this[int index]
{
#if GENERATE_ASSPAN
readonly get => FixedLengthArrayExtension.AsReadOnlySpan(in this)[index];
set => FixedLengthArrayExtension.AsSpan(ref this)[index] = value;
#else
readonly get => index switch
{
0 => Field0,
1 => Field1,
2 => Field2,
3 => Field3,
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
set
{
switch (index)
{
case 0: Field0 = value; break;
case 1: Field1 = value; break;
case 2: Field2 = value; break;
case 3: Field3 = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
#endif
}
#if GENERATE_ASSPAN
public readonly override bool Equals(object other)
=> other is FixedLengthIntPtrArray4 array
? FixedLengthArrayExtension.Equals(in this, array)
: false;
public readonly bool Equals(in FixedLengthIntPtrArray4 other)
=> FixedLengthArrayExtension.Equals(in this, in other);
readonly bool IEquatable<FixedLengthIntPtrArray4>.Equals(FixedLengthIntPtrArray4 other)
=> this.Equals(in other);
public static bool operator ==(in FixedLengthIntPtrArray4 left, in FixedLengthIntPtrArray4 right)
=> left.Equals(right);
public static bool operator !=(in FixedLengthIntPtrArray4 left, in FixedLengthIntPtrArray4 right)
=> !(left == right);
#endif
public override readonly int GetHashCode()
{
#if GENERATE_ASSPAN
int hash = 0;
var span = FixedLengthArrayExtension.AsReadOnlySpan(this);
for(int i = 0; i < span.Length; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)span[i].GetHashCode(), i));
}
return hash;
#else
int hash = 0;
for(int i = 0; i < ConstLength; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)this[i].GetHashCode(), i));
}
return hash;
#endif
}
readonly IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
{
for(var i = 0; i < ConstLength; i++)
{
yield return this[i];
}
}
readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> (this as IEnumerable<IntPtr>).GetEnumerator();
#if GENERATE_ASSPAN
public readonly ReadOnlySpan<IntPtr>.Enumerator GetEnumerator()
=> FixedLengthArrayExtension.AsReadOnlySpan(this).GetEnumerator();
public static implicit operator ReadOnlySpan<IntPtr>(in FixedLengthIntPtrArray4 self)
=> self.AsReadOnlySpan();
#endif
}
public static partial class FixedLengthArrayExtension
{
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Span<IntPtr> AsSpan(this ref FixedLengthIntPtrArray4 array)
=> FixedLengthArray.CreateSpan(ref array.Field0, array.Length);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<IntPtr> AsReadOnlySpan(this in FixedLengthIntPtrArray4 array)
=> FixedLengthArray.CreateReadOnlySpan(array.Field0, array.Length);
#endif
public static bool Equals(in FixedLengthIntPtrArray4 array1, in FixedLengthIntPtrArray4 array2)
{
for(int i = 0; i < array1.Length;i++ )
{
if(array1[i] != array2[i])
return false;
}
return true;
}
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ref IntPtr At(this ref FixedLengthIntPtrArray4 array, int index)
=> ref AsSpan(ref array)[index];
public static void CopyTo(this in FixedLengthIntPtrArray4 array, Span<IntPtr> destination)
=> AsReadOnlySpan(array).CopyTo(destination);
public static void Fill(this ref FixedLengthIntPtrArray4 array, IntPtr value = default)
=> AsSpan(ref array).Fill(value);
#else
public static ref IntPtr At(this ref FixedLengthIntPtrArray4 array, int index)
{
switch (index)
{
case 0: return ref array.Field0;
case 1: return ref array.Field1;
case 2: return ref array.Field2;
case 3: return ref array.Field3;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
public static void CopyTo(this in FixedLengthIntPtrArray4 array, IntPtr[] dest, int offset = 0)
{
for(int i = 0; i < array.Length;i++ )
{
dest[offset + i] = array[i];
}
}
public static void Fill(this ref FixedLengthIntPtrArray4 array, IntPtr value = default)
{
for(int i = 0; i < array.Length;i++ )
{
array[i] = value;
}
}
#endif
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FixedLengthIntPtrArray5 : IFixedLengthArray<IntPtr>
, IEquatable<FixedLengthIntPtrArray5>
, IEquatableByRef<FixedLengthIntPtrArray5>
{
public const int ConstLength = 5;
public readonly int Length => ConstLength;
readonly int IReadOnlyCollection<IntPtr>.Count => ConstLength;
#if GENERATE_CTOR
public FixedLengthIntPtrArray5(
IntPtr field0
, IntPtr field1
, IntPtr field2
, IntPtr field3
, IntPtr field4
)
{
Field0 = field0;
Field1 = field1;
Field2 = field2;
Field3 = field3;
Field4 = field4;
}
#endif
public IntPtr Field0;
public IntPtr Field1;
public IntPtr Field2;
public IntPtr Field3;
public IntPtr Field4;
public IntPtr this[int index]
{
#if GENERATE_ASSPAN
readonly get => FixedLengthArrayExtension.AsReadOnlySpan(in this)[index];
set => FixedLengthArrayExtension.AsSpan(ref this)[index] = value;
#else
readonly get => index switch
{
0 => Field0,
1 => Field1,
2 => Field2,
3 => Field3,
4 => Field4,
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
set
{
switch (index)
{
case 0: Field0 = value; break;
case 1: Field1 = value; break;
case 2: Field2 = value; break;
case 3: Field3 = value; break;
case 4: Field4 = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
#endif
}
#if GENERATE_ASSPAN
public readonly override bool Equals(object other)
=> other is FixedLengthIntPtrArray5 array
? FixedLengthArrayExtension.Equals(in this, array)
: false;
public readonly bool Equals(in FixedLengthIntPtrArray5 other)
=> FixedLengthArrayExtension.Equals(in this, in other);
readonly bool IEquatable<FixedLengthIntPtrArray5>.Equals(FixedLengthIntPtrArray5 other)
=> this.Equals(in other);
public static bool operator ==(in FixedLengthIntPtrArray5 left, in FixedLengthIntPtrArray5 right)
=> left.Equals(right);
public static bool operator !=(in FixedLengthIntPtrArray5 left, in FixedLengthIntPtrArray5 right)
=> !(left == right);
#endif
public override readonly int GetHashCode()
{
#if GENERATE_ASSPAN
int hash = 0;
var span = FixedLengthArrayExtension.AsReadOnlySpan(this);
for(int i = 0; i < span.Length; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)span[i].GetHashCode(), i));
}
return hash;
#else
int hash = 0;
for(int i = 0; i < ConstLength; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)this[i].GetHashCode(), i));
}
return hash;
#endif
}
readonly IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
{
for(var i = 0; i < ConstLength; i++)
{
yield return this[i];
}
}
readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> (this as IEnumerable<IntPtr>).GetEnumerator();
#if GENERATE_ASSPAN
public readonly ReadOnlySpan<IntPtr>.Enumerator GetEnumerator()
=> FixedLengthArrayExtension.AsReadOnlySpan(this).GetEnumerator();
public static implicit operator ReadOnlySpan<IntPtr>(in FixedLengthIntPtrArray5 self)
=> self.AsReadOnlySpan();
#endif
}
public static partial class FixedLengthArrayExtension
{
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Span<IntPtr> AsSpan(this ref FixedLengthIntPtrArray5 array)
=> FixedLengthArray.CreateSpan(ref array.Field0, array.Length);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<IntPtr> AsReadOnlySpan(this in FixedLengthIntPtrArray5 array)
=> FixedLengthArray.CreateReadOnlySpan(array.Field0, array.Length);
#endif
public static bool Equals(in FixedLengthIntPtrArray5 array1, in FixedLengthIntPtrArray5 array2)
{
for(int i = 0; i < array1.Length;i++ )
{
if(array1[i] != array2[i])
return false;
}
return true;
}
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ref IntPtr At(this ref FixedLengthIntPtrArray5 array, int index)
=> ref AsSpan(ref array)[index];
public static void CopyTo(this in FixedLengthIntPtrArray5 array, Span<IntPtr> destination)
=> AsReadOnlySpan(array).CopyTo(destination);
public static void Fill(this ref FixedLengthIntPtrArray5 array, IntPtr value = default)
=> AsSpan(ref array).Fill(value);
#else
public static ref IntPtr At(this ref FixedLengthIntPtrArray5 array, int index)
{
switch (index)
{
case 0: return ref array.Field0;
case 1: return ref array.Field1;
case 2: return ref array.Field2;
case 3: return ref array.Field3;
case 4: return ref array.Field4;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
public static void CopyTo(this in FixedLengthIntPtrArray5 array, IntPtr[] dest, int offset = 0)
{
for(int i = 0; i < array.Length;i++ )
{
dest[offset + i] = array[i];
}
}
public static void Fill(this ref FixedLengthIntPtrArray5 array, IntPtr value = default)
{
for(int i = 0; i < array.Length;i++ )
{
array[i] = value;
}
}
#endif
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FixedLengthIntPtrArray6 : IFixedLengthArray<IntPtr>
, IEquatable<FixedLengthIntPtrArray6>
, IEquatableByRef<FixedLengthIntPtrArray6>
{
public const int ConstLength = 6;
public readonly int Length => ConstLength;
readonly int IReadOnlyCollection<IntPtr>.Count => ConstLength;
#if GENERATE_CTOR
public FixedLengthIntPtrArray6(
IntPtr field0
, IntPtr field1
, IntPtr field2
, IntPtr field3
, IntPtr field4
, IntPtr field5
)
{
Field0 = field0;
Field1 = field1;
Field2 = field2;
Field3 = field3;
Field4 = field4;
Field5 = field5;
}
#endif
public IntPtr Field0;
public IntPtr Field1;
public IntPtr Field2;
public IntPtr Field3;
public IntPtr Field4;
public IntPtr Field5;
public IntPtr this[int index]
{
#if GENERATE_ASSPAN
readonly get => FixedLengthArrayExtension.AsReadOnlySpan(in this)[index];
set => FixedLengthArrayExtension.AsSpan(ref this)[index] = value;
#else
readonly get => index switch
{
0 => Field0,
1 => Field1,
2 => Field2,
3 => Field3,
4 => Field4,
5 => Field5,
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
set
{
switch (index)
{
case 0: Field0 = value; break;
case 1: Field1 = value; break;
case 2: Field2 = value; break;
case 3: Field3 = value; break;
case 4: Field4 = value; break;
case 5: Field5 = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
#endif
}
#if GENERATE_ASSPAN
public readonly override bool Equals(object other)
=> other is FixedLengthIntPtrArray6 array
? FixedLengthArrayExtension.Equals(in this, array)
: false;
public readonly bool Equals(in FixedLengthIntPtrArray6 other)
=> FixedLengthArrayExtension.Equals(in this, in other);
readonly bool IEquatable<FixedLengthIntPtrArray6>.Equals(FixedLengthIntPtrArray6 other)
=> this.Equals(in other);
public static bool operator ==(in FixedLengthIntPtrArray6 left, in FixedLengthIntPtrArray6 right)
=> left.Equals(right);
public static bool operator !=(in FixedLengthIntPtrArray6 left, in FixedLengthIntPtrArray6 right)
=> !(left == right);
#endif
public override readonly int GetHashCode()
{
#if GENERATE_ASSPAN
int hash = 0;
var span = FixedLengthArrayExtension.AsReadOnlySpan(this);
for(int i = 0; i < span.Length; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)span[i].GetHashCode(), i));
}
return hash;
#else
int hash = 0;
for(int i = 0; i < ConstLength; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)this[i].GetHashCode(), i));
}
return hash;
#endif
}
readonly IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
{
for(var i = 0; i < ConstLength; i++)
{
yield return this[i];
}
}
readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> (this as IEnumerable<IntPtr>).GetEnumerator();
#if GENERATE_ASSPAN
public readonly ReadOnlySpan<IntPtr>.Enumerator GetEnumerator()
=> FixedLengthArrayExtension.AsReadOnlySpan(this).GetEnumerator();
public static implicit operator ReadOnlySpan<IntPtr>(in FixedLengthIntPtrArray6 self)
=> self.AsReadOnlySpan();
#endif
}
public static partial class FixedLengthArrayExtension
{
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Span<IntPtr> AsSpan(this ref FixedLengthIntPtrArray6 array)
=> FixedLengthArray.CreateSpan(ref array.Field0, array.Length);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<IntPtr> AsReadOnlySpan(this in FixedLengthIntPtrArray6 array)
=> FixedLengthArray.CreateReadOnlySpan(array.Field0, array.Length);
#endif
public static bool Equals(in FixedLengthIntPtrArray6 array1, in FixedLengthIntPtrArray6 array2)
{
for(int i = 0; i < array1.Length;i++ )
{
if(array1[i] != array2[i])
return false;
}
return true;
}
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ref IntPtr At(this ref FixedLengthIntPtrArray6 array, int index)
=> ref AsSpan(ref array)[index];
public static void CopyTo(this in FixedLengthIntPtrArray6 array, Span<IntPtr> destination)
=> AsReadOnlySpan(array).CopyTo(destination);
public static void Fill(this ref FixedLengthIntPtrArray6 array, IntPtr value = default)
=> AsSpan(ref array).Fill(value);
#else
public static ref IntPtr At(this ref FixedLengthIntPtrArray6 array, int index)
{
switch (index)
{
case 0: return ref array.Field0;
case 1: return ref array.Field1;
case 2: return ref array.Field2;
case 3: return ref array.Field3;
case 4: return ref array.Field4;
case 5: return ref array.Field5;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
public static void CopyTo(this in FixedLengthIntPtrArray6 array, IntPtr[] dest, int offset = 0)
{
for(int i = 0; i < array.Length;i++ )
{
dest[offset + i] = array[i];
}
}
public static void Fill(this ref FixedLengthIntPtrArray6 array, IntPtr value = default)
{
for(int i = 0; i < array.Length;i++ )
{
array[i] = value;
}
}
#endif
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FixedLengthIntPtrArray7 : IFixedLengthArray<IntPtr>
, IEquatable<FixedLengthIntPtrArray7>
, IEquatableByRef<FixedLengthIntPtrArray7>
{
public const int ConstLength = 7;
public readonly int Length => ConstLength;
readonly int IReadOnlyCollection<IntPtr>.Count => ConstLength;
#if GENERATE_CTOR
public FixedLengthIntPtrArray7(
IntPtr field0
, IntPtr field1
, IntPtr field2
, IntPtr field3
, IntPtr field4
, IntPtr field5
, IntPtr field6
)
{
Field0 = field0;
Field1 = field1;
Field2 = field2;
Field3 = field3;
Field4 = field4;
Field5 = field5;
Field6 = field6;
}
#endif
public IntPtr Field0;
public IntPtr Field1;
public IntPtr Field2;
public IntPtr Field3;
public IntPtr Field4;
public IntPtr Field5;
public IntPtr Field6;
public IntPtr this[int index]
{
#if GENERATE_ASSPAN
readonly get => FixedLengthArrayExtension.AsReadOnlySpan(in this)[index];
set => FixedLengthArrayExtension.AsSpan(ref this)[index] = value;
#else
readonly get => index switch
{
0 => Field0,
1 => Field1,
2 => Field2,
3 => Field3,
4 => Field4,
5 => Field5,
6 => Field6,
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
set
{
switch (index)
{
case 0: Field0 = value; break;
case 1: Field1 = value; break;
case 2: Field2 = value; break;
case 3: Field3 = value; break;
case 4: Field4 = value; break;
case 5: Field5 = value; break;
case 6: Field6 = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
#endif
}
#if GENERATE_ASSPAN
public readonly override bool Equals(object other)
=> other is FixedLengthIntPtrArray7 array
? FixedLengthArrayExtension.Equals(in this, array)
: false;
public readonly bool Equals(in FixedLengthIntPtrArray7 other)
=> FixedLengthArrayExtension.Equals(in this, in other);
readonly bool IEquatable<FixedLengthIntPtrArray7>.Equals(FixedLengthIntPtrArray7 other)
=> this.Equals(in other);
public static bool operator ==(in FixedLengthIntPtrArray7 left, in FixedLengthIntPtrArray7 right)
=> left.Equals(right);
public static bool operator !=(in FixedLengthIntPtrArray7 left, in FixedLengthIntPtrArray7 right)
=> !(left == right);
#endif
public override readonly int GetHashCode()
{
#if GENERATE_ASSPAN
int hash = 0;
var span = FixedLengthArrayExtension.AsReadOnlySpan(this);
for(int i = 0; i < span.Length; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)span[i].GetHashCode(), i));
}
return hash;
#else
int hash = 0;
for(int i = 0; i < ConstLength; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)this[i].GetHashCode(), i));
}
return hash;
#endif
}
readonly IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
{
for(var i = 0; i < ConstLength; i++)
{
yield return this[i];
}
}
readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> (this as IEnumerable<IntPtr>).GetEnumerator();
#if GENERATE_ASSPAN
public readonly ReadOnlySpan<IntPtr>.Enumerator GetEnumerator()
=> FixedLengthArrayExtension.AsReadOnlySpan(this).GetEnumerator();
public static implicit operator ReadOnlySpan<IntPtr>(in FixedLengthIntPtrArray7 self)
=> self.AsReadOnlySpan();
#endif
}
public static partial class FixedLengthArrayExtension
{
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Span<IntPtr> AsSpan(this ref FixedLengthIntPtrArray7 array)
=> FixedLengthArray.CreateSpan(ref array.Field0, array.Length);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<IntPtr> AsReadOnlySpan(this in FixedLengthIntPtrArray7 array)
=> FixedLengthArray.CreateReadOnlySpan(array.Field0, array.Length);
#endif
public static bool Equals(in FixedLengthIntPtrArray7 array1, in FixedLengthIntPtrArray7 array2)
{
for(int i = 0; i < array1.Length;i++ )
{
if(array1[i] != array2[i])
return false;
}
return true;
}
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ref IntPtr At(this ref FixedLengthIntPtrArray7 array, int index)
=> ref AsSpan(ref array)[index];
public static void CopyTo(this in FixedLengthIntPtrArray7 array, Span<IntPtr> destination)
=> AsReadOnlySpan(array).CopyTo(destination);
public static void Fill(this ref FixedLengthIntPtrArray7 array, IntPtr value = default)
=> AsSpan(ref array).Fill(value);
#else
public static ref IntPtr At(this ref FixedLengthIntPtrArray7 array, int index)
{
switch (index)
{
case 0: return ref array.Field0;
case 1: return ref array.Field1;
case 2: return ref array.Field2;
case 3: return ref array.Field3;
case 4: return ref array.Field4;
case 5: return ref array.Field5;
case 6: return ref array.Field6;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
public static void CopyTo(this in FixedLengthIntPtrArray7 array, IntPtr[] dest, int offset = 0)
{
for(int i = 0; i < array.Length;i++ )
{
dest[offset + i] = array[i];
}
}
public static void Fill(this ref FixedLengthIntPtrArray7 array, IntPtr value = default)
{
for(int i = 0; i < array.Length;i++ )
{
array[i] = value;
}
}
#endif
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FixedLengthIntPtrArray8 : IFixedLengthArray<IntPtr>
, IEquatable<FixedLengthIntPtrArray8>
, IEquatableByRef<FixedLengthIntPtrArray8>
{
public const int ConstLength = 8;
public readonly int Length => ConstLength;
readonly int IReadOnlyCollection<IntPtr>.Count => ConstLength;
#if GENERATE_CTOR
public FixedLengthIntPtrArray8(
IntPtr field0
, IntPtr field1
, IntPtr field2
, IntPtr field3
, IntPtr field4
, IntPtr field5
, IntPtr field6
, IntPtr field7
)
{
Field0 = field0;
Field1 = field1;
Field2 = field2;
Field3 = field3;
Field4 = field4;
Field5 = field5;
Field6 = field6;
Field7 = field7;
}
#endif
public IntPtr Field0;
public IntPtr Field1;
public IntPtr Field2;
public IntPtr Field3;
public IntPtr Field4;
public IntPtr Field5;
public IntPtr Field6;
public IntPtr Field7;
public IntPtr this[int index]
{
#if GENERATE_ASSPAN
readonly get => FixedLengthArrayExtension.AsReadOnlySpan(in this)[index];
set => FixedLengthArrayExtension.AsSpan(ref this)[index] = value;
#else
readonly get => index switch
{
0 => Field0,
1 => Field1,
2 => Field2,
3 => Field3,
4 => Field4,
5 => Field5,
6 => Field6,
7 => Field7,
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
set
{
switch (index)
{
case 0: Field0 = value; break;
case 1: Field1 = value; break;
case 2: Field2 = value; break;
case 3: Field3 = value; break;
case 4: Field4 = value; break;
case 5: Field5 = value; break;
case 6: Field6 = value; break;
case 7: Field7 = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
#endif
}
#if GENERATE_ASSPAN
public readonly override bool Equals(object other)
=> other is FixedLengthIntPtrArray8 array
? FixedLengthArrayExtension.Equals(in this, array)
: false;
public readonly bool Equals(in FixedLengthIntPtrArray8 other)
=> FixedLengthArrayExtension.Equals(in this, in other);
readonly bool IEquatable<FixedLengthIntPtrArray8>.Equals(FixedLengthIntPtrArray8 other)
=> this.Equals(in other);
public static bool operator ==(in FixedLengthIntPtrArray8 left, in FixedLengthIntPtrArray8 right)
=> left.Equals(right);
public static bool operator !=(in FixedLengthIntPtrArray8 left, in FixedLengthIntPtrArray8 right)
=> !(left == right);
#endif
public override readonly int GetHashCode()
{
#if GENERATE_ASSPAN
int hash = 0;
var span = FixedLengthArrayExtension.AsReadOnlySpan(this);
for(int i = 0; i < span.Length; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)span[i].GetHashCode(), i));
}
return hash;
#else
int hash = 0;
for(int i = 0; i < ConstLength; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)this[i].GetHashCode(), i));
}
return hash;
#endif
}
readonly IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
{
for(var i = 0; i < ConstLength; i++)
{
yield return this[i];
}
}
readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> (this as IEnumerable<IntPtr>).GetEnumerator();
#if GENERATE_ASSPAN
public readonly ReadOnlySpan<IntPtr>.Enumerator GetEnumerator()
=> FixedLengthArrayExtension.AsReadOnlySpan(this).GetEnumerator();
public static implicit operator ReadOnlySpan<IntPtr>(in FixedLengthIntPtrArray8 self)
=> self.AsReadOnlySpan();
#endif
}
public static partial class FixedLengthArrayExtension
{
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Span<IntPtr> AsSpan(this ref FixedLengthIntPtrArray8 array)
=> FixedLengthArray.CreateSpan(ref array.Field0, array.Length);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<IntPtr> AsReadOnlySpan(this in FixedLengthIntPtrArray8 array)
=> FixedLengthArray.CreateReadOnlySpan(array.Field0, array.Length);
#endif
public static bool Equals(in FixedLengthIntPtrArray8 array1, in FixedLengthIntPtrArray8 array2)
{
for(int i = 0; i < array1.Length;i++ )
{
if(array1[i] != array2[i])
return false;
}
return true;
}
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ref IntPtr At(this ref FixedLengthIntPtrArray8 array, int index)
=> ref AsSpan(ref array)[index];
public static void CopyTo(this in FixedLengthIntPtrArray8 array, Span<IntPtr> destination)
=> AsReadOnlySpan(array).CopyTo(destination);
public static void Fill(this ref FixedLengthIntPtrArray8 array, IntPtr value = default)
=> AsSpan(ref array).Fill(value);
#else
public static ref IntPtr At(this ref FixedLengthIntPtrArray8 array, int index)
{
switch (index)
{
case 0: return ref array.Field0;
case 1: return ref array.Field1;
case 2: return ref array.Field2;
case 3: return ref array.Field3;
case 4: return ref array.Field4;
case 5: return ref array.Field5;
case 6: return ref array.Field6;
case 7: return ref array.Field7;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
public static void CopyTo(this in FixedLengthIntPtrArray8 array, IntPtr[] dest, int offset = 0)
{
for(int i = 0; i < array.Length;i++ )
{
dest[offset + i] = array[i];
}
}
public static void Fill(this ref FixedLengthIntPtrArray8 array, IntPtr value = default)
{
for(int i = 0; i < array.Length;i++ )
{
array[i] = value;
}
}
#endif
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FixedLengthIntPtrArray16 : IFixedLengthArray<IntPtr>
, IEquatable<FixedLengthIntPtrArray16>
, IEquatableByRef<FixedLengthIntPtrArray16>
{
public const int ConstLength = 16;
public readonly int Length => ConstLength;
readonly int IReadOnlyCollection<IntPtr>.Count => ConstLength;
#if GENERATE_CTOR
public FixedLengthIntPtrArray16(
IntPtr field0
, IntPtr field1
, IntPtr field2
, IntPtr field3
, IntPtr field4
, IntPtr field5
, IntPtr field6
, IntPtr field7
, IntPtr field8
, IntPtr field9
, IntPtr field10
, IntPtr field11
, IntPtr field12
, IntPtr field13
, IntPtr field14
, IntPtr field15
)
{
Field0 = field0;
Field1 = field1;
Field2 = field2;
Field3 = field3;
Field4 = field4;
Field5 = field5;
Field6 = field6;
Field7 = field7;
Field8 = field8;
Field9 = field9;
Field10 = field10;
Field11 = field11;
Field12 = field12;
Field13 = field13;
Field14 = field14;
Field15 = field15;
}
#endif
public IntPtr Field0;
public IntPtr Field1;
public IntPtr Field2;
public IntPtr Field3;
public IntPtr Field4;
public IntPtr Field5;
public IntPtr Field6;
public IntPtr Field7;
public IntPtr Field8;
public IntPtr Field9;
public IntPtr Field10;
public IntPtr Field11;
public IntPtr Field12;
public IntPtr Field13;
public IntPtr Field14;
public IntPtr Field15;
public IntPtr this[int index]
{
#if GENERATE_ASSPAN
readonly get => FixedLengthArrayExtension.AsReadOnlySpan(in this)[index];
set => FixedLengthArrayExtension.AsSpan(ref this)[index] = value;
#else
readonly get => index switch
{
0 => Field0,
1 => Field1,
2 => Field2,
3 => Field3,
4 => Field4,
5 => Field5,
6 => Field6,
7 => Field7,
8 => Field8,
9 => Field9,
10 => Field10,
11 => Field11,
12 => Field12,
13 => Field13,
14 => Field14,
15 => Field15,
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
set
{
switch (index)
{
case 0: Field0 = value; break;
case 1: Field1 = value; break;
case 2: Field2 = value; break;
case 3: Field3 = value; break;
case 4: Field4 = value; break;
case 5: Field5 = value; break;
case 6: Field6 = value; break;
case 7: Field7 = value; break;
case 8: Field8 = value; break;
case 9: Field9 = value; break;
case 10: Field10 = value; break;
case 11: Field11 = value; break;
case 12: Field12 = value; break;
case 13: Field13 = value; break;
case 14: Field14 = value; break;
case 15: Field15 = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
#endif
}
#if GENERATE_ASSPAN
public readonly override bool Equals(object other)
=> other is FixedLengthIntPtrArray16 array
? FixedLengthArrayExtension.Equals(in this, array)
: false;
public readonly bool Equals(in FixedLengthIntPtrArray16 other)
=> FixedLengthArrayExtension.Equals(in this, in other);
readonly bool IEquatable<FixedLengthIntPtrArray16>.Equals(FixedLengthIntPtrArray16 other)
=> this.Equals(in other);
public static bool operator ==(in FixedLengthIntPtrArray16 left, in FixedLengthIntPtrArray16 right)
=> left.Equals(right);
public static bool operator !=(in FixedLengthIntPtrArray16 left, in FixedLengthIntPtrArray16 right)
=> !(left == right);
#endif
public override readonly int GetHashCode()
{
#if GENERATE_ASSPAN
int hash = 0;
var span = FixedLengthArrayExtension.AsReadOnlySpan(this);
for(int i = 0; i < span.Length; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)span[i].GetHashCode(), i));
}
return hash;
#else
int hash = 0;
for(int i = 0; i < ConstLength; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)this[i].GetHashCode(), i));
}
return hash;
#endif
}
readonly IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
{
for(var i = 0; i < ConstLength; i++)
{
yield return this[i];
}
}
readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> (this as IEnumerable<IntPtr>).GetEnumerator();
#if GENERATE_ASSPAN
public readonly ReadOnlySpan<IntPtr>.Enumerator GetEnumerator()
=> FixedLengthArrayExtension.AsReadOnlySpan(this).GetEnumerator();
public static implicit operator ReadOnlySpan<IntPtr>(in FixedLengthIntPtrArray16 self)
=> self.AsReadOnlySpan();
#endif
}
public static partial class FixedLengthArrayExtension
{
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Span<IntPtr> AsSpan(this ref FixedLengthIntPtrArray16 array)
=> FixedLengthArray.CreateSpan(ref array.Field0, array.Length);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<IntPtr> AsReadOnlySpan(this in FixedLengthIntPtrArray16 array)
=> FixedLengthArray.CreateReadOnlySpan(array.Field0, array.Length);
#endif
public static bool Equals(in FixedLengthIntPtrArray16 array1, in FixedLengthIntPtrArray16 array2)
{
for(int i = 0; i < array1.Length;i++ )
{
if(array1[i] != array2[i])
return false;
}
return true;
}
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ref IntPtr At(this ref FixedLengthIntPtrArray16 array, int index)
=> ref AsSpan(ref array)[index];
public static void CopyTo(this in FixedLengthIntPtrArray16 array, Span<IntPtr> destination)
=> AsReadOnlySpan(array).CopyTo(destination);
public static void Fill(this ref FixedLengthIntPtrArray16 array, IntPtr value = default)
=> AsSpan(ref array).Fill(value);
#else
public static ref IntPtr At(this ref FixedLengthIntPtrArray16 array, int index)
{
switch (index)
{
case 0: return ref array.Field0;
case 1: return ref array.Field1;
case 2: return ref array.Field2;
case 3: return ref array.Field3;
case 4: return ref array.Field4;
case 5: return ref array.Field5;
case 6: return ref array.Field6;
case 7: return ref array.Field7;
case 8: return ref array.Field8;
case 9: return ref array.Field9;
case 10: return ref array.Field10;
case 11: return ref array.Field11;
case 12: return ref array.Field12;
case 13: return ref array.Field13;
case 14: return ref array.Field14;
case 15: return ref array.Field15;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
public static void CopyTo(this in FixedLengthIntPtrArray16 array, IntPtr[] dest, int offset = 0)
{
for(int i = 0; i < array.Length;i++ )
{
dest[offset + i] = array[i];
}
}
public static void Fill(this ref FixedLengthIntPtrArray16 array, IntPtr value = default)
{
for(int i = 0; i < array.Length;i++ )
{
array[i] = value;
}
}
#endif
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FixedLengthIntPtrArray32 : IFixedLengthArray<IntPtr>
, IEquatable<FixedLengthIntPtrArray32>
, IEquatableByRef<FixedLengthIntPtrArray32>
{
public const int ConstLength = 32;
public readonly int Length => ConstLength;
readonly int IReadOnlyCollection<IntPtr>.Count => ConstLength;
#if GENERATE_CTOR
public FixedLengthIntPtrArray32(
IntPtr field0
, IntPtr field1
, IntPtr field2
, IntPtr field3
, IntPtr field4
, IntPtr field5
, IntPtr field6
, IntPtr field7
, IntPtr field8
, IntPtr field9
, IntPtr field10
, IntPtr field11
, IntPtr field12
, IntPtr field13
, IntPtr field14
, IntPtr field15
, IntPtr field16
, IntPtr field17
, IntPtr field18
, IntPtr field19
, IntPtr field20
, IntPtr field21
, IntPtr field22
, IntPtr field23
, IntPtr field24
, IntPtr field25
, IntPtr field26
, IntPtr field27
, IntPtr field28
, IntPtr field29
, IntPtr field30
, IntPtr field31
)
{
Field0 = field0;
Field1 = field1;
Field2 = field2;
Field3 = field3;
Field4 = field4;
Field5 = field5;
Field6 = field6;
Field7 = field7;
Field8 = field8;
Field9 = field9;
Field10 = field10;
Field11 = field11;
Field12 = field12;
Field13 = field13;
Field14 = field14;
Field15 = field15;
Field16 = field16;
Field17 = field17;
Field18 = field18;
Field19 = field19;
Field20 = field20;
Field21 = field21;
Field22 = field22;
Field23 = field23;
Field24 = field24;
Field25 = field25;
Field26 = field26;
Field27 = field27;
Field28 = field28;
Field29 = field29;
Field30 = field30;
Field31 = field31;
}
#endif
public IntPtr Field0;
public IntPtr Field1;
public IntPtr Field2;
public IntPtr Field3;
public IntPtr Field4;
public IntPtr Field5;
public IntPtr Field6;
public IntPtr Field7;
public IntPtr Field8;
public IntPtr Field9;
public IntPtr Field10;
public IntPtr Field11;
public IntPtr Field12;
public IntPtr Field13;
public IntPtr Field14;
public IntPtr Field15;
public IntPtr Field16;
public IntPtr Field17;
public IntPtr Field18;
public IntPtr Field19;
public IntPtr Field20;
public IntPtr Field21;
public IntPtr Field22;
public IntPtr Field23;
public IntPtr Field24;
public IntPtr Field25;
public IntPtr Field26;
public IntPtr Field27;
public IntPtr Field28;
public IntPtr Field29;
public IntPtr Field30;
public IntPtr Field31;
public IntPtr this[int index]
{
#if GENERATE_ASSPAN
readonly get => FixedLengthArrayExtension.AsReadOnlySpan(in this)[index];
set => FixedLengthArrayExtension.AsSpan(ref this)[index] = value;
#else
readonly get => index switch
{
0 => Field0,
1 => Field1,
2 => Field2,
3 => Field3,
4 => Field4,
5 => Field5,
6 => Field6,
7 => Field7,
8 => Field8,
9 => Field9,
10 => Field10,
11 => Field11,
12 => Field12,
13 => Field13,
14 => Field14,
15 => Field15,
16 => Field16,
17 => Field17,
18 => Field18,
19 => Field19,
20 => Field20,
21 => Field21,
22 => Field22,
23 => Field23,
24 => Field24,
25 => Field25,
26 => Field26,
27 => Field27,
28 => Field28,
29 => Field29,
30 => Field30,
31 => Field31,
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
set
{
switch (index)
{
case 0: Field0 = value; break;
case 1: Field1 = value; break;
case 2: Field2 = value; break;
case 3: Field3 = value; break;
case 4: Field4 = value; break;
case 5: Field5 = value; break;
case 6: Field6 = value; break;
case 7: Field7 = value; break;
case 8: Field8 = value; break;
case 9: Field9 = value; break;
case 10: Field10 = value; break;
case 11: Field11 = value; break;
case 12: Field12 = value; break;
case 13: Field13 = value; break;
case 14: Field14 = value; break;
case 15: Field15 = value; break;
case 16: Field16 = value; break;
case 17: Field17 = value; break;
case 18: Field18 = value; break;
case 19: Field19 = value; break;
case 20: Field20 = value; break;
case 21: Field21 = value; break;
case 22: Field22 = value; break;
case 23: Field23 = value; break;
case 24: Field24 = value; break;
case 25: Field25 = value; break;
case 26: Field26 = value; break;
case 27: Field27 = value; break;
case 28: Field28 = value; break;
case 29: Field29 = value; break;
case 30: Field30 = value; break;
case 31: Field31 = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
#endif
}
#if GENERATE_ASSPAN
public readonly override bool Equals(object other)
=> other is FixedLengthIntPtrArray32 array
? FixedLengthArrayExtension.Equals(in this, array)
: false;
public readonly bool Equals(in FixedLengthIntPtrArray32 other)
=> FixedLengthArrayExtension.Equals(in this, in other);
readonly bool IEquatable<FixedLengthIntPtrArray32>.Equals(FixedLengthIntPtrArray32 other)
=> this.Equals(in other);
public static bool operator ==(in FixedLengthIntPtrArray32 left, in FixedLengthIntPtrArray32 right)
=> left.Equals(right);
public static bool operator !=(in FixedLengthIntPtrArray32 left, in FixedLengthIntPtrArray32 right)
=> !(left == right);
#endif
public override readonly int GetHashCode()
{
#if GENERATE_ASSPAN
int hash = 0;
var span = FixedLengthArrayExtension.AsReadOnlySpan(this);
for(int i = 0; i < span.Length; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)span[i].GetHashCode(), i));
}
return hash;
#else
int hash = 0;
for(int i = 0; i < ConstLength; i++)
{
hash = FixedLengthArray.Combine(hash, (int)FixedLengthArray.RotateToLeft((uint)this[i].GetHashCode(), i));
}
return hash;
#endif
}
readonly IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator()
{
for(var i = 0; i < ConstLength; i++)
{
yield return this[i];
}
}
readonly System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> (this as IEnumerable<IntPtr>).GetEnumerator();
#if GENERATE_ASSPAN
public readonly ReadOnlySpan<IntPtr>.Enumerator GetEnumerator()
=> FixedLengthArrayExtension.AsReadOnlySpan(this).GetEnumerator();
public static implicit operator ReadOnlySpan<IntPtr>(in FixedLengthIntPtrArray32 self)
=> self.AsReadOnlySpan();
#endif
}
public static partial class FixedLengthArrayExtension
{
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Span<IntPtr> AsSpan(this ref FixedLengthIntPtrArray32 array)
=> FixedLengthArray.CreateSpan(ref array.Field0, array.Length);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<IntPtr> AsReadOnlySpan(this in FixedLengthIntPtrArray32 array)
=> FixedLengthArray.CreateReadOnlySpan(array.Field0, array.Length);
#endif
public static bool Equals(in FixedLengthIntPtrArray32 array1, in FixedLengthIntPtrArray32 array2)
{
for(int i = 0; i < array1.Length;i++ )
{
if(array1[i] != array2[i])
return false;
}
return true;
}
#if GENERATE_ASSPAN
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ref IntPtr At(this ref FixedLengthIntPtrArray32 array, int index)
=> ref AsSpan(ref array)[index];
public static void CopyTo(this in FixedLengthIntPtrArray32 array, Span<IntPtr> destination)
=> AsReadOnlySpan(array).CopyTo(destination);
public static void Fill(this ref FixedLengthIntPtrArray32 array, IntPtr value = default)
=> AsSpan(ref array).Fill(value);
#else
public static ref IntPtr At(this ref FixedLengthIntPtrArray32 array, int index)
{
switch (index)
{
case 0: return ref array.Field0;
case 1: return ref array.Field1;
case 2: return ref array.Field2;
case 3: return ref array.Field3;
case 4: return ref array.Field4;
case 5: return ref array.Field5;
case 6: return ref array.Field6;
case 7: return ref array.Field7;
case 8: return ref array.Field8;
case 9: return ref array.Field9;
case 10: return ref array.Field10;
case 11: return ref array.Field11;
case 12: return ref array.Field12;
case 13: return ref array.Field13;
case 14: return ref array.Field14;
case 15: return ref array.Field15;
case 16: return ref array.Field16;
case 17: return ref array.Field17;
case 18: return ref array.Field18;
case 19: return ref array.Field19;
case 20: return ref array.Field20;
case 21: return ref array.Field21;
case 22: return ref array.Field22;
case 23: return ref array.Field23;
case 24: return ref array.Field24;
case 25: return ref array.Field25;
case 26: return ref array.Field26;
case 27: return ref array.Field27;
case 28: return ref array.Field28;
case 29: return ref array.Field29;
case 30: return ref array.Field30;
case 31: return ref array.Field31;
default: throw new ArgumentOutOfRangeException(nameof(index));
}
}
public static void CopyTo(this in FixedLengthIntPtrArray32 array, IntPtr[] dest, int offset = 0)
{
for(int i = 0; i < array.Length;i++ )
{
dest[offset + i] = array[i];
}
}
public static void Fill(this ref FixedLengthIntPtrArray32 array, IntPtr value = default)
{
for(int i = 0; i < array.Length;i++ )
{
array[i] = value;
}
}
#endif
}
}
|
@extends('layouts.bar')
@section('navbar')
@include('layouts.navbar')
@endsection
@section('sidebar')
@include('layouts.sidebar')
@endsection
@section('plugins')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
@endsection
@section('content')
<header class="bg-gray-200 p-3">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Detail Company {{ $company->nama_company }}
</h2>
</header>
<div class="formContainer m-3 border rounded p-3">
<form action="{{ route('company.update', ['id' => $company->cid]) }}" method="post">
@csrf
<div class="formContainer grid grid-cols-2 gap-0.5">
<div class="namaCompany">
<label for="" class="block text-sm font-medium text-gray-700">Nama Company</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring
focus:ring-indigo-200 focus:ring-opacity-50 border p-1"
name="tb_nama_company" id="tb_nama_company" placeholder="" value="{{ $company->nama_company }}">
</div>
<div class="penanggungJawab">
<div class="penanggungJawab">
<label for="tb_user_id" class="block text-sm font-medium text-gray-700">Penanggung Jawab</label>
<select name="tb_user_id" id="tb_user_id"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 border p-1">
@foreach ($usersData as $user)
<option value="{{ $user->id }}" @if ($user->id == $company->user_id) selected @endif>
{{ $user->name }}
</option>
@endforeach
</select>
</div>
</div>
<div class="kodeCompany">
<label for="" class="block text-sm font-medium text-gray-700">Kode Company</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring
focus:ring-indigo-200 focus:ring-opacity-50 border p-1"
name="tb_kode_company" id="tb_kode_company" placeholder="" value="{{ $company->kode_company }}">
</div>
<div class="partnerCompany">
<label for="" class="block text-sm font-medium text-gray-700">Partner Company</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring
focus:ring-indigo-200 focus:ring-opacity-50 border p-1"
name="tb_partner_company" id="tb_partner_company" placeholder=""
value="{{ $company->partner_company }}">
</div>
<div class="taglineCompany">
<label for="" class="block text-sm font-medium text-gray-700">Tagline Company</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring
focus:ring-indigo-200 focus:ring-opacity-50 border p-1ne_company"
id="tb_tagline_company" name="tb_tagline_company" placeholder=""
value="{{ $company->tagline_company }}">
</div>
<div class="jalan">
<label for="" class="block text-sm font-medium text-gray-700">Jalan</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring
focus:ring-indigo-200 focus:ring-opacity-50 border p-1"
name="tb_jalan" id="tb_jalan" placeholder="" value="{{ $company->jalan }}">
</div>
<div class="jalan_ext">
<label for="" class="block text-sm font-medium text-gray-700">Jalan 2</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring
focus:ring-indigo-200 focus:ring-opacity-50 border p-1"
name="tb_jalan_ext" id="tb_jalan_ext" placeholder="" value="{{ $company->jalan_ext }}">
</div>
<div class="blok">
<label for="" class="block text-sm font-medium text-gray-700">Blok</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300
focus:ring focus:ring-indigo-200 focus:ring-opacity-50 border p-1"
name="tb_blok" id="tb_blok" placeholder="" value="{{ $company->blok }}">
</div>
<div class="rt">
<label for="" class="block text-sm font-medium text-gray-700">RT</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300
focus:ring focus:ring-indigo-200 focus:ring-opacity-50 border p-1"
name="tb_rt" id="tb_rt" placeholder="" value="{{ $company->rt }}">
</div>
<div class="rw">
<label for="" class="block text-sm font-medium text-gray-700">RW</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300
focus:ring focus:ring-indigo-200 focus:ring-opacity-50 border p-1"
name="tb_rw" id="tb_rw" placeholder="" value="{{ $company->rw }}">
</div>
<div class="provinsi">
<label for="" class="block text-sm font-medium text-gray-700">Provinsi</label>
<select onchange="loadKota(event);" name="tb_prov" id="tb_prov"
class="border rounded-md py-2 px-3 w-full">
<option disabled selected>Pilih Provinsi</option>
</select>
</div>
<div class="kota">
<label for="" class="block text-sm font-medium text-gray-700">Kota/Kabupaten</label>
<select onchange="loadKecamatan(event);" name="tb_kota" id="tb_kota"
class="border rounded-md py-2 px-3 w-full">
<option disabled selected>Pilih Kota/Kabupaten</option>
</select>
</div>
<div class="kecamatan">
<label for="" class="block text-sm font-medium text-gray-700">Kecamatan</label>
<select onchange="loadKelurahan(event);" name="tb_kecamatan" id="tb_kecamatan"
class="border rounded-md py-2 px-3 w-full">
<option disabled selected>Pilih Kecamatan</option>
</select>
</div>
<div class="kelurahan">
<label for="" class="block text-sm font-medium text-gray-700">Kelurahan</label>
<select name="tb_kelurahan" id="tb_kelurahan" class="border rounded-md py-2 px-3 w-full">
<option disabled selected>Pilih Kelurahan</option>
</select>
</div>
<div class="kodepos">
<label for="" class="block text-sm font-medium text-gray-700">Kode Pos</label>
<input type="text"
class="mt-1 block w-full rounded-md shadow-sm focus:border-indigo-300
focus:ring focus:ring-indigo-200 focus:ring-opacity-50 border border-gray-300 p-1"
name="tb_kodepos" id="tb_kodepos" placeholder="" value="{{ $company->kode_pos }}">
</div>
<div class="external_id">
<label for="" class="block text-sm font-medium text-gray-700">ID External</label>
<input type="text"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300
focus:ring focus:ring-indigo-200 focus:ring-opacity-50 border p-1"
name="tb_external_id" id="tb_external_id" placeholder=""
value="{{ $company->external_company_id }}">
</div>
</div>
<div class="buttonContainer flex justify-center p-4">
<button type="submit"
class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">Submit</button>
</div>
</form>
</div>
@endsection
@section('script')
<script>
$(document).ready(function() {
var id_prov_init;
var id_kota_init;
var id_kecamatan_init;
var id_kelurahan_init;
$.ajax({
url: "https://www.emsifa.com/api-wilayah-indonesia/api/provinces.json",
type: "GET",
dataType: "json",
success: function(result) {
$.each(result, function(key, value) {
if (value.name == '{{ $company->provinsi }}') {
$('#tb_prov').append('<option selected data-id="' + value.id +
'">' + value
.name + '</option>');
id_prov_init = value.id;
}
$('#tb_prov').append('<option data-id="' + value.id + '">' + value
.name + '</option>');
});
}
}).done(function() {
$.ajax({
url: "https://www.emsifa.com/api-wilayah-indonesia/api/regencies/" +
id_prov_init +
".json",
type: "GET",
dataType: "json",
success: function(result) {
$.each(result, function(key, value) {
if (value.name == '{{ $company->kota_kabupaten }}') {
$('#tb_kota').append('<option selected data-id="' +
value.id +
'">' + value
.name + '</option>');
id_kota_init = value.id;
}
$('#tb_kota').append('<option data-id="' + value.id + '">' +
value
.name + '</option>');
});
}
}).done(function() {
$.ajax({
url: "https://www.emsifa.com/api-wilayah-indonesia/api/districts/" +
id_kota_init +
".json",
type: "GET",
dataType: "json",
success: function(result) {
$.each(result, function(key, value) {
if (value.name ==
'{{ $company->kecamatan }}') {
$('#tb_kecamatan').append(
'<option selected data-id="' +
value.id +
'">' + value
.name + '</option>');
id_kecamatan_init = value.id;
}
$('#tb_kecamatan').append('<option data-id="' +
value.id + '">' +
value
.name + '</option>');
});
}
}).done(function() {
$.ajax({
url: "https://www.emsifa.com/api-wilayah-indonesia/api/villages/" +
id_kecamatan_init +
".json",
type: "GET",
dataType: "json",
success: function(result) {
$.each(result, function(key, value) {
if (value.name ==
'{{ $company->kelurahan }}') {
$('#tb_kelurahan').append(
'<option selected data-id="' +
value.id +
'">' + value
.name + '</option>');
id_kelurahan_init = value.id;
}
$('#tb_kelurahan').append(
'<option data-id="' + value
.id + '">' +
value
.name + '</option>');
});
}
})
})
})
});
});
</script>
<script>
var loadKota = function(event) {
var id_prov = $('#tb_prov').find(':selected').data('id');
$.ajax({
url: "https://www.emsifa.com/api-wilayah-indonesia/api/regencies/" + id_prov +
".json",
type: "GET",
dataType: "json",
success: function(result) {
$('#tb_kota').empty();
$('#tb_kecamatan').empty();
$('#tb_kelurahan').empty();
$('#tb_kota').append('<option disabled selected>Pilih Kota/Kabupaten</option>');
$('#tb_kecamatan').append('<option disabled selected>Pilih Kecamatan</option>');
$('#tb_kelurahan').append('<option disabled selected>Pilih Kelurahan</option>');
$.each(result, function(key, value) {
$('#tb_kota').append('<option data-id="' + value.id + '">' + value
.name + '</option>');
});
}
});
};
var loadKecamatan = function(event) {
var id_kota = $('#tb_kota').find(':selected').data('id');
$.ajax({
url: "https://www.emsifa.com/api-wilayah-indonesia/api/districts/" + id_kota +
".json",
type: "GET",
dataType: "json",
success: function(result) {
$('#tb_kecamatan').empty();
$('#tb_kecamatan').append('<option disabled selected>Pilih Kecamatan</option>');
$('#tb_kelurahan').empty();
$('#tb_kelurahan').append('<option disabled selected>Pilih Kelurahan</option>');
$.each(result, function(key, value) {
$('#tb_kecamatan').append('<option data-id="' + value.id + '">' + value
.name + '</option>');
});
}
});
}
var loadKelurahan = function(event) {
var id_kecamatan = $('#tb_kecamatan').find(':selected').data('id');
$.ajax({
url: "https://www.emsifa.com/api-wilayah-indonesia/api/villages/" + id_kecamatan +
".json",
type: "GET",
dataType: "json",
success: function(result) {
$('#tb_kelurahan').empty();
$('#tb_kelurahan').append('<option disabled selected>Pilih Kelurahan</option>');
$.each(result, function(key, value) {
$('#tb_kelurahan').append('<option data-id="' + value.id + '">' + value
.name + '</option>');
});
}
});
}
</script>
@endsection
|
Feature: To verify the bulk status update of applications in RMS
@RMS @RMSBulkStatusUpdate @id:1 @RMSApplications
Scenario: To verify change status gives error message on not selecting any applications
Given I login into RMS as an "Enterprise" user
When I am on application inbox page
And I click on the bulk status change button on the top panel without selecting any profile
Then I should see an error message "Please select atleast one resume(s) for which you want to change the status"
@RMS @RMSBulkStatusUpdate @id:2 @RMSApplications
Scenario: To verify change status gives error message on not selecting any applications
Given I login into RMS as an "Enterprise" user
When I am on application inbox page
And I select profile 1 on profile listing page
And I click on the bulk status update from the top panel
Then I should be able to see the status change drop down in the modal
And I should be able to see the "mark as rejected" checkbox
@RMS @RMSBulkStatusUpdate @id:3 @RMSApplications
Scenario: To verify selecting multiple applications and changing there status,gives a success message:- Success! Application Status have been successfully changed to Prospect-New
Given I login into RMS as an "Enterprise" user
When I am on application inbox page
And I select profile 1 on profile listing page
And I click on the bulk status update from the top panel
Then I should be able to see the status change drop down in the modal
When I select the status of the profiles to "Prospect-something"
And I click on update on the layout
Then I should be able to see the success message as "Success! Application Status have been successfully changed to Prospect"
@RMS @RMSBulkStatusUpdate @id:4 @RMSApplications
Scenario: To verify no of applications selected are reflected on change status light box
Given I login into RMS as an "Enterprise" user
When User is on "applicationInbox" page
And I select multiple profiles on the profile listing page
And I click on the bulk status update from the top panel
Then I should be able to see the number of selected profiles in the status change pop up
@RMS @RMSBulkStatusUpdate @id:5 @RMSApplications
Scenario: To verify On marking as rejected ,Candidate on respective stage is marked as rejected
Given I login into RMS as an "Enterprise" user
When User is on "applicationInbox" page
And User select the first candidate checkbox
And I click on the bulk status update from the top panel
Then I should be able to see the status change drop down in the modal
When I check the Mark as Rejected checkbox
And I click on update on the layout
Then I should be able to see the status of the selected candidate as "Rejected"
@RMS @RMSBulkStatusUpdate @id:6 @RMSApplications
Scenario: To verify changed status reflected on view application page
Given I login into RMS as an "Enterprise" user
When User is on "applicationInbox" page
And I select profile 1 on profile listing page
And I click on the bulk status update from the top panel
Then I should be able to see the status change drop down in the modal
When I select the status of the profiles to "Applied-Matching"
And I click on update on the layout
Then I should be able to see the success message as "Success! Application Status have been successfully changed to Applied-Matching"
@RMS @RMSBulkStatusUpdate @id:7 @RMSApplications
Scenario: To verify On clicking 'Cancel' the changes are ignore and control returns to previous page.
Given I login into RMS as an "Enterprise" user
When User is on "applicationInbox" page
And User select the first candidate checkbox
And I click on the bulk status update from the top panel
Then I should be able to see the status change drop down in the modal
When I click on the cancel button on the modal layout
Then I should not see the success message "Success! Application Status have been successfully changed to Prospect"
@RMS @RMSBulkStatusUpdate @id:8 @RMSApplications
Scenario: To check the unavailability of the option to change status in bulk on candidate profile page
Given I login into RMS as an "Enterprise" user
When User is on "applicationInbox" page
And I select multiple profiles on the profile listing page
And I click on the bulk status update from the top panel
Then I should not see the option of bulk status change on the top panel and text "This option is not available when making status changes for applications across multiple requirements."
|
package com.santinuin.springboot.backend.chat.controllers;
import com.santinuin.springboot.backend.chat.models.documents.Mensaje;
import com.santinuin.springboot.backend.chat.models.service.ChatService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import java.util.Date;
import java.util.List;
import java.util.Random;
@Controller
public class ChatController {
private String[] colores = {"red", "green", "blue", "magenta", "purple", "orange"};
private final ChatService chatService;
private final SimpMessagingTemplate webSocket;
public ChatController(ChatService chatService, SimpMessagingTemplate webSocket) {
this.chatService = chatService;
this.webSocket = webSocket;
}
@MessageMapping("/mensaje")
@SendTo("/chat/mensaje")
public Mensaje recibeMensaje(Mensaje mensaje){
mensaje.setFecha(new Date().getTime());
if(mensaje.getTipo().equals("NUEVO_USUARIO")){
mensaje.setColor(colores[new Random().nextInt(colores.length)]);
mensaje.setTexto("nuevo usuario");
} else{
chatService.guardar(mensaje);
}
return mensaje;
}
@MessageMapping("/escribiendo")
@SendTo("/chat/escribiendo")
public String estaEscribiendo(String username){
return username.concat(" está escribiendo ...");
}
@MessageMapping("/historial")
public void historial(String clienteId){
webSocket.convertAndSend("/chat/historial/" + clienteId, chatService.obtenerUltimos10Mensajes());
}
}
|
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import * as passport from 'passport';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(
session({
secret: 'keyboard cat', // put in an .env file. then dont use in memory for production there can be a memory leak. You can use redis
resave: false,
saveUnitialized: false,
cookie: { maxAge: 3600000 },
}),
);
app.use(passport.initialize());
app.use(passport.session());
await app.listen(3000);
}
bootstrap();
|
<template>
<div class="payment-methods">
<BaseTop title="Payment Methods">
<template v-slot>
<BaseButton redirect="/new-payment-method">
<template v-slot>
New
</template>
</BaseButton>
</template>
</BaseTop>
<BaseTable :titles="['Name', 'Installments', 'Actions']">
<template v-slot:body>
<tr v-for="p in $store.state.payment_methods" :key="p.id" @click="redirect(p.id)">
<td>
{{p.name}}
</td>
<td>
{{p.installments}}
</td>
<td>
</td>
</tr>
</template>
</BaseTable>
</div>
</template>
<script>
import BaseTop from '@/components/BaseTop.vue'
import BaseButton from '@/components/BaseButton.vue'
import BaseTable from '@/components/BaseTable.vue'
import router from '@/router'
export default {
data() {
return {
payment_methods: []
}
},
components: {
BaseTop,
BaseButton,
BaseTable
},
methods: {
redirect(id) {
router.push('/payment-method/'+id)
}
},
created() {
this.$store.dispatch('getPaymentMethods')
},
beforeCreate() {
if( !this.$store.state.token ){
router.push('/login')
}
}
}
</script>
|
---
icon: pulse
order: 900
---
{width=600}
DataWars' projects are all about creating interesting and engaging activities. An activity in general contains:
* **Title**: a short, descriptive, ideally imperative description of the objectives of the activity
* **Description**: A free text (unlimited) description to help the student achieve the objectives of the activity, can include images or videos.
* **Solution** (optional, strongly recommended): A solution that will be revealed upon request. Solutions can contain anything: text, code, images, GIFs, videos, etc. Although it's optional, MOST activities SHOULD contain a solution.
* **Hints** (optional): A series of hints that can help the user. Also can contain any type of text, images, etc.
* **Expected outcome** (optional): An example of what the outcome of the activity should be. It can be a screenshot of the dataframe, a table with the SQL results, an example of executing a function, etc.
There are different types of activities (read more in [Activity Types](activity-types.md)):
* Multiple choice
* Input
* Code/interactive with and without user input
|
import { Injectable, EventEmitter } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { RespuestaPosts, Post, RespuestaPost } from '../../interfaces/interfaces';
import { UsuarioService } from './usuario.service';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
const URL = environment.url;
@Injectable({
providedIn: 'root'
})
export class PostsService {
paginaPost = 0;
nuevoPost = new EventEmitter<Post>();
constructor(
private http: HttpClient,
private usuarioService: UsuarioService,
private fileTransfer: FileTransfer
) { }
getPost( pull: boolean = false) {
if( pull ) {
this.paginaPost = 0;
}
this.paginaPost ++;
return this.http.get<RespuestaPosts>(`${URL}/post/?pagina=${this.paginaPost}`);
}
crearPost( post ) {
const headers = new HttpHeaders({
'x-token': this.usuarioService.token
});
return new Promise( resolve => {
this.http.post<RespuestaPost>(`${URL}/post`, post, {headers} ).subscribe( resp => {
console.log(resp);
if ( resp.ok ) {
this.nuevoPost.emit( resp.post );
resolve( true );
}
}, err => {
if ( err ) {
resolve( false );
}
});
});
}
subirImagen( img: string ) {
const options: FileUploadOptions = {
fileKey: 'image',
headers: {
'x-token': this.usuarioService.token
}
};
const fileTransfer: FileTransferObject = this.fileTransfer.create();
fileTransfer.upload( img, `${URL}/post/upload`, options )
.then( data => {
console.log(data);
}).catch( err => {
console.log('error en carga', err);
});
}
}
|
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruit Burst</title>
<link rel="icon" type="image/x-icon" href="./images/logo.png">
<!-- font awesome -->
<script src="https://kit.fontawesome.com/d0caab4d70.js" crossorigin="anonymous"></script>
<!-- tailwind and daisyUi -->
<link href="https://cdn.jsdelivr.net/npm/daisyui@3.9.3/dist/full.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.tailwindcss.com"></script>
<!-- lato google font -->
<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=Lato:wght@400;700&display=swap" rel="stylesheet">
<!-- custom styles -->
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: '#F85559',
}
}
}
}
</script>
<style>
.font-lato {
font-family: 'Lato', sans-serif;
}
</style>
</head>
<body class="font-lato">
<header>
<!-- NavBar section -->
<nav class="container mx-auto md:mt-5 px-5">
<div
class="navbar md:bg-primary rounded-full md:p-4 lg:p-6 md:text-white justify-around items-center mx-auto md:flex-row-reverse flex-row lg:flex-row">
<div class="navbar-start hidden md:flex">
<ul class="menu menu-horizontal px-1 text-base xl:text-lg font-normal ">
<li><a>Home</a></li>
<li><a>About Us</a></li>
<li><a>Shop</a></li>
<li><a>All Fruits</a></li>
</ul>
</div>
<div class="navbar-center flex-row-reverse md:flex-row justify-around">
<div class="dropdown dropdown-bottom dropdown-end">
<label tabindex="0" class="btn btn-ghost md:hidden ">
<!-- <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" fill="none" viewBox="0 0 24 24"
stroke="currentColor"> -->
<svg class="swap-off fill-current" xmlns="http://www.w3.org/2000/svg" width="32" height="32"
viewBox="0 0 512 512">
<path d="M64,384H448V341.33H64Zm0-106.67H448V234.67H64ZM64,128v42.67H448V128Z" />
</svg>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h8m-8 6h16" />
</svg>
</label>
<ul tabindex="0"
class="dropdown-content z-50 menu p-2 font-normal shadow bg-base-100 rounded-box w-52 text-black">
<li><a>Home</a></li>
<li><a>About Us</a></li>
<li><a>Shop</a></li>
<li><a>All Fruits</a></li>
</ul>
</div>
<a class="btn btn-ghost normal-case text-2xl md:text-xl lg:text-4xl font-bold"><img class="w-10"
src="./images/logo.png" alt="">Fruit Burst</a>
</div>
<div class="navbar-end hidden lg:flex">
<div class="form-control">
<div class="relative">
<input type="text" placeholder="Search here"
class="input rounded-full w-80 p-7 text-black font-medium text-xl" />
<div class="absolute top-0 right-0 p-4 text-black">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 " fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
</div>
</div>
</div>
</div>
</nav>
<!-- Banner Carousel section-->
<section class="container mx-auto my-5 md:my-12 lg:my-24 relative ">
<div class="carousel w-full relative">
<div id="slide1" class="carousel-item relative w-full ">
<img src="./images/banner1.png" class="w-full brightness-50" />
<div class="absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2 z-20">
<a href="#slide4" class="btn btn-circle">❮</a>
<a href="#slide2" class="btn btn-circle">❯</a>
</div>
<div
class="absolute w-full p-3 md:p-5 lg:p-10 xl:p-16 2xl:p-20 text-white flex flex-col items-center text-center z-10">
<h2 class="text-2xl md:text-4xl lg:text-5xl xl:text-6xl 2xl:text-7xl font-extrabold mb-3 md:mb-8">Exotic
tastes at your <br> doorstep</h2>
<p class="text-xl hidden md:block font-medium mb-8">We supply highly quality organic products</p>
<button
class=" px-7 rounded-lg py-2 bg-primary text-white hover:text-gray-700 text-base md:text-base border-0">Shop
Now</button>
</div>
</div>
<div id="slide2" class="carousel-item relative w-full">
<img src="./images/banner2.png" class="w-full brightness-50" />
<div class="absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2 z-20">
<a href="#slide1" class="btn btn-circle">❮</a>
<a href="#slide3" class="btn btn-circle">❯</a>
</div>
<div
class="absolute w-full p-3 md:p-5 lg:p-10 xl:p-16 2xl:p-20 text-white flex flex-col items-center text-center z-10">
<h2 class="text-2xl md:text-4xl lg:text-5xl xl:text-6xl 2xl:text-7xl font-extrabold mb-3 md:mb-8">Exotic
tastes at your <br> doorstep</h2>
<p class="text-xl hidden md:block font-medium mb-8">We supply highly quality organic products</p>
<button class="px-7 rounded-lg py-2 bg-primary text-white hover:text-gray-700 text-base border-0">Shop
Now</button>
</div>
</div>
<div id="slide3" class="carousel-item relative w-full">
<img src="./images/banner3.png" class="w-full brightness-50" />
<div class="absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2 z-20">
<a href="#slide2" class="btn btn-circle">❮</a>
<a href="#slide4" class="btn btn-circle">❯</a>
</div>
<div
class="absolute w-full p-3 md:p-5 lg:p-10 xl:p-16 2xl:p-20 text-white flex flex-col items-center text-center z-10">
<h2 class="text-2xl md:text-4xl lg:text-5xl xl:text-6xl 2xl:text-7xl font-extrabold mb-3 md:mb-8">Exotic
tastes at your <br> doorstep</h2>
<p class="text-xl hidden md:block font-medium mb-8">We supply highly quality organic products</p>
<button class="px-7 rounded-lg py-2 bg-primary text-white hover:text-gray-700 text-base border-0">Shop
Now</button>
</div>
</div>
<div id="slide4" class="carousel-item relative w-full">
<img src="./images/banner4.png" class="w-full brightness-50" />
<div class="absolute flex justify-between transform -translate-y-1/2 left-5 right-5 top-1/2 z-20">
<a href="#slide3" class="btn btn-circle">❮</a>
<a href="#slide1" class="btn btn-circle">❯</a>
</div>
<div
class="absolute w-full p-3 md:p-5 lg:p-10 xl:p-16 2xl:p-20 text-white flex flex-col items-center text-center z-10">
<h2 class="text-2xl md:text-4xl lg:text-5xl xl:text-6xl 2xl:text-7xl font-extrabold mb-3 md:mb-8">Exotic
tastes at your <br> doorstep</h2>
<p class="text-xl hidden md:block font-medium mb-8">We supply highly quality organic products</p>
<button class="px-7 rounded-lg py-2 bg-primary text-white hover:text-gray-700 text-base border-0">Shop
Now</button>
</div>
</div>
</div>
<!-- fruits -->
<div
class="lg:flex justify-evenly lg:w-[900px] xl:w-[1200px] shadow-lg bg-white p-5 rounded-lg absolute -bottom-20 left-40 hidden ">
<div class="flex items-center flex-col">
<img src="./images/fruit1.png" alt="">
<p class="text-xl font-medium">Grape</p>
</div>
<div class="flex items-center flex-col">
<img src="./images/fruit2.png" alt="">
<p class="text-xl font-medium">Orange</p>
</div>
<div class="flex items-center flex-col">
<img src="./images/fruit3.png" alt="">
<p class="text-xl font-medium">Mango</p>
</div>
<div class="flex items-center flex-col">
<img src="./images/fruit4.png" alt="">
<p class="text-xl font-medium">Strawberry</p>
</div>
<div class="flex items-center flex-col">
<img src="./images/fruit5.png" alt="">
<p class="text-xl font-medium">Pomegranate</p>
</div>
</div>
</section>
</header>
<main >
<!-- deal of the day section -->
<section class="container mx-auto mt-20 md:mt-32 lg:mt-48 mb-24 p-10 md:p-5 flex flex-col justify-center ">
<!-- caption -->
<div class="flex flex-col md:flex-row gap-10 justify-between items-center text-center md:text-left space-y-10">
<div class="flex-1">
<h2 class="text-5xl font-extrabold mb-6">Deal of the day</h2>
<p class="font-medium">Contrary to popular belief, is not simply random text. It has roots in a piece of
classical Latin literature from 45 BC, making it over 2000 years old.</p>
</div>
<div class="flex-1 grid grid-flow-col gap-5 text-center auto-cols-max justify-end font-extrabold">
<div class="flex flex-col">
<span class="countdown font-mono text-5xl">
<span style="--value:29";></span>
</span>
days
</div>
<div class="flex flex-col">
<span class="countdown font-mono text-5xl">
<span style="--value:15;"></span>
</span>
hours
</div>
<div class="flex flex-col">
<span class="countdown font-mono text-5xl">
<span style="--value:25;"></span>
</span>
min
</div>
<div class="flex flex-col">
<span class="countdown font-mono text-5xl">
<span style="--value:8;"></span>
</span>
sec
</div>
</div>
</div>
<div class="grid gap-16 grid-cols-1 md:grid-cols-2 lg:grid-cols-4 mt-16 ">
<!-- card 1 -->
<div class="border rounded-lg text-center p-6">
<img class="mx-auto" src="./images/fruit6.png" alt="">
<p class="text-2xl font-bold mt-10 mb-6">12.90$ - 18.85$</p>
<hr>
<p class="font-medium text-gray-500 my-6">Apples</p>
<div class="rating rating-sm rating-half mb-6">
<input type="radio" name="rating-10" class="rating-hidden" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" checked />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
</div>
<div>
<!-- Open the modal using ID.showModal() method -->
<a class="font-medium text-primary cursor-pointer hover:underline"
onclick="my_modal_1.showModal()">Details</a>
<dialog id="my_modal_1" class="modal">
<div class="modal-box w-96">
<img class="mx-auto" src="./images/fruit6.png" alt="">
<p class="font-extrabold text-4xl my-6">Apples</p>
<p class="my-6">Professional employees are there for you to pick the most amazing and fresh fruits.</p>
<div class="rating rating-xl rating-half mb-6">
<input type="radio" name="rating-10" class="rating-hidden" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" checked />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
</div>
<div class="modal-action justify-center">
<form method="dialog">
<!-- if there is a button in form, it will close the modal -->
<div class="flex gap-10">
<button class="btn bg-white border-primary font-extrabold">Close</button>
<button class="btn bg-primary text-white hover:text-black font-extrabold ">Buy Now</button>
</div>
</form>
</div>
</div>
</dialog>
</div>
</div>
<!-- card 2 -->
<div class="border rounded-lg text-center p-6">
<img class="mx-auto" src="./images/fruit7.png" alt="">
<p class="text-2xl font-bold mt-10 mb-6">12.90$ - 18.85$</p>
<hr>
<p class="font-medium text-gray-500 my-6">Orange</p>
<div class="rating rating-sm rating-half mb-6">
<input type="radio" name="rating-10" class="rating-hidden" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" checked />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
</div>
<div>
<!-- Open the modal using ID.showModal() method -->
<a class="font-medium text-primary cursor-pointer hover:underline"
onclick="my_modal_2.showModal()">Details</a>
<dialog id="my_modal_2" class="modal">
<div class="modal-box w-96">
<img class="mx-auto" src="./images/fruit7.png" alt="">
<p class="font-extrabold text-4xl my-6">Orange</p>
<p class="my-6">Professional employees are there for you to pick the most amazing and fresh fruits.</p>
<div class="rating rating-xl rating-half mb-6">
<input type="radio" name="rating-10" class="rating-hidden" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" checked />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
</div>
<div class="modal-action justify-center">
<form method="dialog">
<!-- if there is a button in form, it will close the modal -->
<div class="flex gap-10">
<button class="btn bg-white border-primary font-extrabold">Close</button>
<button class="btn bg-primary text-white hover:text-black font-extrabold ">Buy Now</button>
</div>
</form>
</div>
</div>
</dialog>
</div>
</div>
<!-- card 3 -->
<div class="border rounded-lg text-center p-6">
<img class="mx-auto" src="./images/fruit8.png" alt="">
<p class="text-2xl font-bold mt-10 mb-6">12.90$ - 18.85$</p>
<hr>
<p class="font-medium text-gray-500 my-6">Red Dragon</p>
<div class="rating rating-sm rating-half mb-6">
<input type="radio" name="rating-10" class="rating-hidden" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" checked />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
</div>
<div>
<!-- Open the modal using ID.showModal() method -->
<a class="font-medium text-primary cursor-pointer hover:underline"
onclick="my_modal_3.showModal()">Details</a>
<dialog id="my_modal_3" class="modal">
<div class="modal-box w-96">
<img class="mx-auto" src="./images/fruit8.png" alt="">
<p class="font-extrabold text-4xl my-6">Red Dragon</p>
<p class="my-6">Professional employees are there for you to pick the most amazing and fresh fruits.</p>
<div class="rating rating-xl rating-half mb-6">
<input type="radio" name="rating-10" class="rating-hidden" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" checked />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
</div>
<div class="modal-action justify-center">
<form method="dialog">
<!-- if there is a button in form, it will close the modal -->
<div class="flex gap-10">
<button class="btn bg-white border-primary font-extrabold">Close</button>
<button class="btn bg-primary text-white hover:text-black font-extrabold ">Buy Now</button>
</div>
</form>
</div>
</div>
</dialog>
</div>
</div>
<!-- card 4 -->
<div class="border rounded-lg text-center p-6">
<img class="mx-auto" src="./images/fruit9.png" alt="">
<p class="text-2xl font-bold mt-10 mb-6">12.90$ - 18.85$</p>
<hr>
<p class="font-medium text-gray-500 my-6">Banana</p>
<div class="rating rating-sm rating-half mb-6">
<input type="radio" name="rating-10" class="rating-hidden" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" checked />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
</div>
<div>
<!-- Open the modal using ID.showModal() method -->
<a class="font-medium text-primary cursor-pointer hover:underline"
onclick="my_modal_4.showModal()">Details</a>
<dialog id="my_modal_4" class="modal">
<div class="modal-box w-96">
<img class="mx-auto" src="./images/fruit9.png" alt="">
<p class="font-extrabold text-4xl my-6">Banana</p>
<p class="my-6">Professional employees are there for you to pick the most amazing and fresh fruits.</p>
<div class="rating rating-xl rating-half mb-6">
<input type="radio" name="rating-10" class="rating-hidden" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" checked />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-1" />
<input type="radio" name="rating-10" class="bg-primary mask mask-star-2 mask-half-2" />
</div>
<div class="modal-action justify-center">
<form method="dialog">
<!-- if there is a button in form, it will close the modal -->
<div class="flex gap-10">
<button class="btn bg-white border-primary font-extrabold">Close</button>
<button class="btn bg-primary text-white hover:text-black font-extrabold ">Buy Now</button>
</div>
</form>
</div>
</div>
</dialog>
</div>
</div>
</div>
<button class="max-w-[200px] mx-auto btn font-bold bg-primary text-white hover:text-black text-xl mt-10">Shop All</button>
</section>
<!-- my team section -->
<section class="container mx-auto my-10 md:my-12 lg:my-24">
<div class="bg-[url('./images/team.png')] bg-cover bg-center rounded-lg m-5">
<div class=" text-white w-full p-10 md:p-20 lg:p-32 bg-black bg-opacity-40 rounded-lg ">
<div class="text-center mb-10">
<h2 class="text-2xl md:text-3xl lg:text-4xl xl:text-5xl font-extrabold mb-6">Meet the team section</h2>
<p class="font-medium">Contrary to popular belief, is not simply random text. It has roots in a piece of
classical <br>
Latin literature from 45 BC, making it over 2000 years old.</p>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 items-center justify-between gap-10 mt-24">
<div class="flex flex-col items-center">
<img class="w-36 mb-8" src="./images/member1.png" alt="">
<h3 class="text-2xl font-bold mb-3">Awlad Hossain</h3>
<p class="font-medium mb-4">Fruits Expert</p>
<div class="flex gap-3 text-primary">
<a href="#"><i class="fa-brands fa-facebook"></i></a>
<a href="#"><i class="fa-brands fa-twitter"></i></a>
<a href="#"><i class="fa-brands fa-linkedin"></i></a>
</div>
</div>
<div class="flex flex-col items-center">
<img class="w-36 mb-8" src="./images/member2.png" alt="">
<h3 class="text-2xl font-bold mb-3">Safia Chowdhury</h3>
<p class="font-medium mb-4">Fruits Expert</p>
<div class="flex gap-3 text-primary">
<a href="#"><i class="fa-brands fa-facebook"></i></a>
<a href="#"><i class="fa-brands fa-twitter"></i></a>
<a href="#"><i class="fa-brands fa-linkedin"></i></a>
</div>
</div>
<div class="flex flex-col items-center">
<img class="w-36 mb-8" src="./images/member3.png" alt="">
<h3 class="text-2xl font-bold mb-3">Rokib Hossain</h3>
<p class="font-medium mb-4">Fruits Expert</p>
<div class="flex gap-3 text-primary">
<a href="#"><i class="fa-brands fa-facebook"></i></a>
<a href="#"><i class="fa-brands fa-twitter"></i></a>
<a href="#"><i class="fa-brands fa-linkedin"></i></a>
</div>
</div>
<div class="flex flex-col items-center">
<img class="w-36 mb-8" src="./images/member4.png" alt="">
<h3 class="text-2xl font-bold mb-3">Chaity</h3>
<p class="font-medium mb-4">Fruits Expert</p>
<div class="flex gap-3 text-primary">
<a href="#"><i class="fa-brands fa-facebook"></i></a>
<a href="#"><i class="fa-brands fa-twitter"></i></a>
<a href="#"><i class="fa-brands fa-linkedin"></i></a>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Why Choose Us -->
<section class="my-24 mx-5">
<div class="container mx-auto">
<div class="text-center mb-10">
<h2 class="text-5xl font-extrabold mb-6">Why Choose Us</h2>
<p class="font-medium">Contrary to popular belief, is not simply random text. It has roots in a piece of
classical <br>
Latin literature from 45 BC, making it over 2000 years old.</p>
</div>
<div class="flex gap-5 flex-col lg:flex-row justify-around items-center">
<div class="order-2 lg:order-1 space-y-5">
<div class="flex flex-col lg:flex-row items-center text-center lg:text-left gap-5">
<i class="fa-solid fa-users text-2xl bg-gray-200 rounded-full p-3"></i>
<div>
<h2 class="text-2xl font-extrabold mb-4">Dedicated Team</h2>
<hr style="height: 2px;" class="w-28 font-extrabold mx-auto lg:mx-0 bg-gray-400 mb-3">
<p class="font-medium">Professional employees are there for you to pick <br>
the most amazing and fresh fruits.</p>
</div>
</div>
<div class="flex flex-col lg:flex-row items-center text-center lg:text-left gap-5">
<i class="fa-regular fa-heart text-2xl bg-gray-200 rounded-full px-4 py-3"></i>
<div>
<h2 class="text-2xl font-extrabold mb-4">Fresh is Best</h2>
<hr style="height: 2px;" class="w-28 font-extrabold mx-auto lg:mx-0 bg-gray-400 mb-3">
<p class="font-medium">Professional employees are there for you to pick <br>
the most amazing and fresh fruits.</p>
</div>
</div>
<div class="flex flex-col lg:flex-row items-center text-center lg:text-left gap-5">
<i class="fa-solid fa-gift text-2xl bg-gray-200 rounded-full px-4 py-3"></i>
<div>
<h2 class="text-2xl font-extrabold mb-4">Gift Certificates</h2>
<hr style="height: 2px;" class="w-28 font-extrabold mx-auto lg:mx-0 bg-gray-400 mb-3">
<p class="font-medium">Professional employees are there for you to pick <br>
the most amazing and fresh fruits.</p>
</div>
</div>
</div>
<div class="order-1 lg:order-2">
<img src="./images/whychoose1.png" alt="">
</div>
<div class="text-right order-3 space-y-5">
<div class="flex flex-col-reverse lg:flex-row items-center text-center lg:text-right gap-5">
<div>
<h2 class="text-2xl font-extrabold mb-4">Integrated Supplier</h2>
<hr style="height: 2px;" class="w-28 font-extrabold inline-block bg-gray-400 mb-3 ">
<p class="font-medium">Professional employees are there for you to pick <br>
the most amazing and fresh fruits.</p>
</div>
<i class="fa-solid fa-apple-whole text-2xl bg-gray-200 rounded-full px-4 py-3"></i>
</div>
<div class="flex flex-col-reverse lg:flex-row items-center text-center lg:text-right gap-5">
<div>
<h2 class="text-2xl font-extrabold mb-4">Sustainable Practice</h2>
<hr style="height: 2px;" class="w-28 inline-block font-extrabold bg-gray-400 mb-3">
<p class="font-medium">Professional employees are there for you to pick <br>
the most amazing and fresh fruits.</p>
</div>
<i class="fa-solid fa-ice-cream text-2xl bg-gray-200 rounded-full px-4 py-3"></i>
</div>
<div class="flex flex-col-reverse lg:flex-row items-center text-center lg:text-right gap-5">
<div>
<h2 class="text-2xl font-extrabold mb-4">The Benefits Only</h2>
<hr style="height: 2px;" class="w-28 font-extrabold inline-block bg-gray-400 mb-3 ">
<p class="font-medium">Professional employees are there for you to pick <br>
the most amazing and fresh fruits.</p>
</div>
<i class="fa-solid fa-thumbs-up text-2xl bg-gray-200 rounded-full px-4 py-3"></i>
</div>
</div>
</div>
</div>
</section>
</main>
<footer class="footer footer-center p-20 bg-gray-800 text-base-content rounded space-y-10 text-white" >
<a class="btn btn-ghost normal-case text-2xl md:text-xl lg:text-4xl font-bold flex flex-row"><img class="w-10"
src="./images/logo.png" alt="">Fruit Burst</a>
<nav class="flex flex-wrap justify-center gap-7 text-lg">
<a class="link link-hover ">Home</a>
<a class="link link-hover">About Us</a>
<a class="link link-hover">Shop</a>
<a class="link link-hover">All Fruits</a>
<a class="link link-hover">Support</a>
<a class="link link-hover">My Account</a>
</nav>
<nav>
<div class="grid grid-flow-col gap-5 md:gap-6 lg:gap-10">
<a href=""><i class="fa-brands fa-twitter text-2xl"></i></a>
<a><i class="fa-brands fa-facebook-f text-2xl"></i></a>
<a><i class="fa-brands fa-youtube text-2xl"></i></a>
<a><i class="fa-brands fa-linkedin-in text-2xl"></i></a>
<a href=""><i class="fa-brands fa-instagram text-2xl"></i></a>
<a href=""><i class="fa-brands fa-apple text-2xl"></i></a>
</div>
</nav>
</footer>
</body>
</html>
|
import React, { useState, useEffect } from "react";
import axios from "axios";
import "./Quotes.css";
const Quotes = () => {
const [formData, setFormData] = useState({
company: "",
firstName: "",
lastName: "",
email: "",
phone: "",
address: "",
address2: "",
city: "",
state: "",
zipCode: "",
freightOriginAddress: "",
freightOriginAddressLine2: "",
freightOriginCity: "",
freightOriginState: "",
freightOriginZipCode: "",
pickupDate: "",
deliveryDate: "",
additionalInformation: "",
});
useEffect(() => {
fetchUserData();
}, []);
const fetchUserData = async () => {
try {
const response = await axios.get(
`${process.env.REACT_APP_BACKEND_URL}/get-user-data`,
{
headers: {
Authentication: "Bearer " + localStorage.getItem("token"),
},
}
);
const userData = response.data;
console.log("User Data:", userData);
setFormData({
...formData,
company: userData.company || "", // Populate the company field if it exists, otherwise leave it blank
firstName: userData.firstName || "", // Populate the firstName field if it exists, otherwise leave it blank
lastName: userData.lastName || "", // Populate the lastName field if it exists, otherwise leave it blank
email: userData.email || "", // Populate the email field if it exists, otherwise leave it blank
phone: userData.phone || "", // Populate the phone field if it exists, otherwise leave it blank
address: userData.address || "", // Populate the address field if it exists, otherwise leave it blank
address2: userData.address2 || "", // Populate the addressLine2 field if it exists, otherwise leave it blank
city: userData.city || "", // Populate the city field if it exists, otherwise leave it blank
state: userData.state || "", // Populate the state field if it exists, otherwise leave it blank
zipCode: userData.zipCode || "", // Populate the zipCode field if it exists, otherwise leave it blank
freightOriginAddress: userData.freightOriginAddress || "", // Populate the freightOriginAddress field if it exists, otherwise leave it blank
freightOriginAddressLine2: userData.freightOriginAddressLine2 || "", // Populate the freightOriginAddressLine2 field if it exists, otherwise leave it blank
freightOriginCity: userData.freightOriginCity || "", // Populate the freightOriginCity field if it exists, otherwise leave it blank
freightOriginState: userData.freightOriginState || "", // Populate the freightOriginState field if it exists, otherwise leave it blank
freightOriginZipCode: userData.freightOriginZipCode || "", // Populate the freightOriginZipCode field if it exists, otherwise leave it blank
});
} catch (error) {
console.error("Error fetching user data:", error);
}
};
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = async (e) => {
e.preventDefault();
// Submit the form data to your backend API
// Example:
// await axios.post("http://localhost:8000/submit-quote", formData);
};
return (
<div className="quotes-container">
<div className="quoteform-container">
<form
action="https://formspree.io/f/mgegyrgn"
method="POST"
className="quote-form"
>
<h1 className="quoteHeader">Get a Quote!</h1>
<h3>Please enter your information below to receive a quote.</h3>
<input
type="hidden"
name="_subject"
value="New Quote Form Submission"
/>
<input type="hidden" name="_cc" value="montazuma4me@gmail.com" />
<div className="quote-group">
<label className="quote-label">Company</label>
<input
className="quote-input"
type="text"
name="company"
placeholder="Company"
value={formData.company}
onChange={handleChange}
required
/>
</div>
<div className="quote-areas btn-space">Name</div>
<div className="quote-group">
<label className="quote-label">First Name</label>
<input
className="quote-input"
type="text"
name="firstName"
placeholder="First Name"
value={formData.firstName}
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Last Name</label>
<input
className="quote-input"
type="text"
name="lastName"
placeholder="Last Name"
value={formData.lastName}
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">E-Mail</label>
<input
className="quote-input"
type="text"
name="email"
placeholder="E-Mail"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Phone Number</label>
<input
className="quote-input"
type="text"
name="phone"
placeholder="Phone Number"
value={formData.phone}
onChange={handleChange}
required
/>
</div>
<div className="quote-areas btn-space">Address</div>
<div className="quote-group">
<label className="quote-label">Street Address</label>
<input
className="quote-input"
type="text"
name="address"
placeholder="Street Address"
value={formData.address}
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Street Address 2</label>
<input
className="quote-input"
type="text"
name="addressLine2"
placeholder="Street Address 2"
value={formData.address2}
onChange={handleChange}
/>
</div>
<div className="quote-group">
<label className="quote-label">City</label>
<input
className="quote-input"
type="text"
name="city"
placeholder="City"
value={formData.city}
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">State / Province</label>
<input
className="quote-input"
type="text"
name="state"
placeholder="State/Province"
value={formData.state}
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Postal / Zip Code</label>
<input
className="quote-input"
type="text"
name="zipCode"
placeholder="Zip Code"
value={formData.zipCode}
onChange={handleChange}
required
/>
</div>
<div className="quote-areas btn-space">Origin Address</div>
<div className="quote-group">
<label className="quote-label">Origin Street Address</label>
<input
className="quote-input"
type="text"
name="originAddress"
placeholder="Origin Address"
value={formData.freightOriginAddress}
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Origin Street Address 2</label>
<input
className="quote-input"
type="text"
name="originAddress2"
placeholder="Origin Street Address 2"
value={formData.freightOriginAddressLine2}
onChange={handleChange}
/>
</div>
<div className="quote-group">
<label className="quote-label">Origin City</label>
<input
className="quote-input"
type="text"
name="originCity"
placeholder="Origin City"
value={formData.freightOriginCity}
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Origin State</label>
<input
className="quote-input"
type="text"
name="originState"
placeholder="Origin State"
value={formData.freightOriginState}
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Origin Zip Code</label>
<input
className="quote-input"
type="text"
name="originZipCode"
placeholder="Origin Zip Code"
value={formData.freightOriginZipCode}
onChange={handleChange}
required
/>
</div>
<div className="quote-areas btn-space">Product</div>
<div className="quote-group">
<label className="quote-label">Product</label>
<input
className="quote-input"
type="text"
name="product"
placeholder="Product"
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Product Value</label>
<input
className="quote-input"
type="text"
name="productValue"
placeholder="Product Value"
onChange={handleChange}
required
/>
</div>
<div className="quote-areas btn-space">Destination Address</div>
<div className="quote-group">
<label className="quote-label">Freight Destination Address</label>
<input
className="quote-input"
type="text"
name="freightDestinationAddress"
placeholder="Freight Destination Address"
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Freight Destination Address 2</label>
<input
className="quote-input"
type="text"
name="freightDestinationAddress2"
placeholder="Freight Destination Address 2"
onChange={handleChange}
/>
</div>
<div className="quote-group">
<label className="quote-label">Freight Destination City</label>
<input
className="quote-input"
type="text"
name="freightDestinationCity"
placeholder="Freight Destination City"
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Freight Destination State</label>
<input
className="quote-input"
type="text"
name="freightDestinationState"
placeholder="Freight Destination State"
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Freight Destination Zip Code</label>
<input
className="quote-input"
type="text"
name="freightDestinationZipCode"
placeholder="Freight Destination Zip Code"
onChange={handleChange}
required
/>
</div>
<div className="quote-areas btn-space">Additional Information</div>
<div className="quote-group">
<label className="quote-label">Pickup Date</label>
<input
className="quote-input"
type="text"
name="pickupDate"
placeholder="Pick Up Date"
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Delivery Date</label>
<input
className="quote-input"
type="text"
name="deliveryDate"
placeholder="Delivery Date"
onChange={handleChange}
required
/>
</div>
<div className="quote-group">
<label className="quote-label">Additional Information</label>
<input
className="quote-input"
type="text"
name="additionalInformation"
placeholder="Additional Information"
onChange={handleChange}
/>
</div>
<div className="btn-space">
<button type="submit" className="quote-submit-btn">
Submit
</button>
</div>
</form>
</div>
</div>
);
};
export default Quotes;
|
import React from "react";
import s from "./Users.module.css";
import userPhotoEmpty from "../../assets/images/user-empty.png";
import { NavLink } from "react-router-dom";
const User = ({ user, followingInProgress, unfollow, follow }) => {
return (
<div>
<span>
<div>
<NavLink to={"/profile/" + user.id}>
<img src={user.photos.small != null ? user.photos.small : userPhotoEmpty} alt="" className={s.userPhoto} />
</NavLink>
</div>
<div>
{user.followed ? (
<div className={s.youAreFollowing}>
<button
disabled={followingInProgress.some((id) => id === user.id)}
onClick={() => {
unfollow(user.id);
}}>
UnFollow
</button>
<div>You are now following {user.name}</div>
</div>
) : (
<button
disabled={followingInProgress.some((id) => id === user.id)}
onClick={() => {
follow(user.id);
}}>
Follow
</button>
)}
</div>
</span>
<span>
<span>
<div>{user.name}</div>
<div>{user.status}</div>
</span>
<span>
<div>{"u.location.country"}</div>
<div>{"u.location.city"}</div>
</span>
</span>
</div>
);
};
export default User;
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { DialogClose } from "@/components/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useForm } from "react-hook-form";
const CreateCommentForm = ({ issueId }) => {
const form = useForm({
defaultValues: {
content: "",
},
});
const onSubmit = (data) => {
console.log("create project data", data);
};
return (
<div>
<Form {...form}>
<form
className="flex gap-2 items-center"
onSubmit={form.handleSubmit(onSubmit)}
>
<FormField
control={form.control}
name="content"
render={({ field }) => (
<FormItem className="flex-1">
<div className="flex gap-2 items-center">
<div>
<Avatar>
<AvatarFallback>A</AvatarFallback>
</Avatar>
</div>
<FormControl className="flex-1">
<Input
{...field}
type="text"
className="w-[20rem]"
placeholder="write comment here..."
/>
</FormControl>
</div>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Save</Button>
</form>
</Form>
</div>
);
};
export default CreateCommentForm;
|
import 'package:flutter/material.dart';
import 'package:quran/quran.dart' as quran;
import 'package:qurantest/arnumberconverter';
import 'surah.dart';
class SearchPage extends StatefulWidget {
const SearchPage({super.key});
@override
State<SearchPage> createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
var myController = TextEditingController();
var myController1 = TextEditingController();
List<String> searchlist = [];
List<String> searchlist1 = [];
bool wordchek = false;
@override
Widget build(BuildContext context) {
Map result = quran.searchWords(searchlist);
return Scaffold(
appBar: AppBar(
// The search area here
title: Container(
width: double.infinity,
height: 40,
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(5)),
child: Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: TextField(
controller: myController,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
suffixIcon: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
/* Clear the search field */
setState(() {
if (myController.text.isNotEmpty) {
myController1 = myController;
searchlist.add(myController.text);
searchlist1.add(myController.text);
myController.clear();
} else {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(
content: Text("Text is empty"),
));
}
wordchek = !wordchek;
});
},
),
hintText: 'ابحث عن الاية ...',
hintStyle: const TextStyle(
fontFamily: 'kitab', fontSize: 20, height: 0.9),
border: InputBorder.none),
),
),
),
)),
body: Column(
children: [
SizedBox(
child: Directionality(
textDirection: TextDirection.rtl,
child: Text(
' عدد الايات '+ '(${result['occurences']})',
style: const TextStyle(fontFamily: 'kitab', fontSize: 20),
),
),
),
Expanded(
child: ListView.separated(
itemBuilder: (context, index) {
return ListTile(
subtitle: Directionality(
textDirection: TextDirection.rtl,
child: Text(
'' +
quran.getVerse(result['result'][index]['surah'],
result['result'][index]['verse'],
verseEndSymbol: false) +
result['result'][index]['verse']
.toString()
.toArabicNumbers,
style: const TextStyle(
fontFamily: 'kitab',
fontSize: 20,
color: Colors.black87),
),
),
trailing: Directionality(
textDirection: TextDirection.rtl,
child: Text(
quran.getSurahNameArabic(
result['result'][index]['surah'],
),
style: const TextStyle(
fontFamily: 'kitab',
fontSize: 20,
color: Colors.black87),
),
),
);
},
separatorBuilder: (context, index) => const Divider(
height: 1,
),
itemCount: result['occurences']),
),
],
),
);
}
}
// SafeArea(
// minimum: const EdgeInsets.all(15),
// child: ListView(
// primary: true,
// children: [
// Padding(
// padding: const EdgeInsets.all(5),
// child: Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// Text(
// 'الايات الموافقة' +
// result['occurences'].toString().toArabicNumbers +
// ' ',
// style: TextStyle(
// fontFamily: 'kitab',
// fontSize: 36,
// fontWeight: FontWeight.bold,
// ),
// ),
// ],
// ),
// ),
// const SizedBox(
// height: 5,
// ),
// RichText(
// text: (wordchek == true)
// ? TextSpan(
// text: ' ' +
// quran.getVerse(result['result'][1]['surah'],
// result['result'][1]['verse'],
// verseEndSymbol: false) +
// ' ',
// style: const TextStyle(color: Colors.black))
// : TextSpan(text: ' '),
// ),
// Text(
// searchlist.isNotEmpty ? searchlist.toString() : "---",
// style: const TextStyle(color: Colors.black),
// ),
// ],
// ),
// )
|
@model ProductViewModel
<div class="d-flex align-items-center justify-content-center">
<form method="post" style="width:1300px" enctype="multipart/form-data">
<input asp-for="Product.Id" hidden />
<div class="row">
<div class="col-10">
<div class="border p-3 mt-4">
<div class="row pb-2">
<h2 class="text-center">@(Model.Product.Id != 0 ? "Update" : "Create") Product</h2>
<hr />
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.Title" class="p-0"></label>
<input asp-for="Product.Title" class="form-control" />
<span asp-validation-for="Product.Title" class="text-danger disabled"></span>
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.Description" class="p-0"></label>
<textarea asp-for="Product.Description" class="form-control"></textarea>
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.CategoryId" class="p-0"></label>
<select asp-for="@Model.Product.CategoryId" asp-items="@Model.CategoryList" class="form-select">
<option disabled selected>--Select Category--</option>
</select>
<span asp-validation-for="Product.CategoryId" class="text-danger disabled"></span>
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.ISBN" class="p-0"></label>
<input asp-for="Product.ISBN" class="form-control" />
<span asp-validation-for="Product.ISBN" class="text-danger disabled"></span>
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.Author" class="p-0"></label>
<input asp-for="Product.Author" class="form-control" />
<span asp-validation-for="Product.Author" class="text-danger disabled"></span>
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.ListPrice" class="p-0"></label>
<input asp-for="Product.ListPrice" class="form-control" />
<span asp-validation-for="Product.ListPrice" class="text-danger disabled"></span>
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.Price" class="p-0"></label>
<input asp-for="Product.Price" class="form-control" />
<span asp-validation-for="Product.Price" class="text-danger disabled"></span>
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.Price50" class="p-0"></label>
<input asp-for="Product.Price50" class="form-control" />
<span asp-validation-for="Product.Price50" class="text-danger disabled"></span>
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.Price100" class="p-0"></label>
<input asp-for="Product.Price100" class="form-control" />
<span asp-validation-for="Product.Price100" class="text-danger disabled"></span>
</div>
<div class="mb-3 row p-1">
<label asp-for="Product.ProductImages" class="p-0"></label>
<input type="file" name="files" class="form-control" multiple />
</div>
<div class="d-flex align-items-center justify-content-center">
@if (Model.Product.Id != 0)
{
<button type="submit" class="btn btn-success" style="width:80px; margin-right:15px;">Update</button>
}
else
{
<button type="submit" class="btn btn-success" style="width:80px; margin-right:15px;">Create</button>
}
<a asp-controller="Product" asp-action="Index" class="btn btn-secondary" style="width:80px;">Back</a>
</div>
</div>
</div>
<div class="col-2">
@if (Model.Product.ProductImages != null)
{
foreach (var image in Model.Product.ProductImages)
{
<div class="border p-1 m-2 text-center">
<img src="@image.ImageUrl" width="100%"
style="border-radius:5px; border:1px solid #bbb9b9" />
<a asp-action="DeleteImage" class="btn btn-danger" asp-route-imageId="@image.Id">
<i class="bi bi-trash-fill"></i>
</a>
</div>
}
}
</div>
</div>
</form>
</div>
@section Scripts {
<script>
tinymce.init({
selector: 'textarea',
plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount',
toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | align lineheight | tinycomments | checklist numlist bullist indent outdent | emoticons charmap | removeformat',
tinycomments_mode: 'embedded',
tinycomments_author: 'Author name',
mergetags_list: [
{ value: 'First.Name', title: 'First Name' },
{ value: 'Email', title: 'Email' },
],
ai_request: (request, respondWith) => respondWith.string(() => Promise.reject("See docs to implement AI Assistant")),
});
</script>
@{
<partial name="_ValidationScriptsPartial" />
}
}
|
import { authModel } from "../../Database/authDatabase/model/authModel.js";
import { isAdmin } from "../../isAdmin/isAdmin.js";
import {
validationError,
duplicateErrorHandling,
} from "../../schemaErrorHandling/errorHandling.js";
import { tokenGenerator } from "../../tokenGenerator/tokenGenerator.js";
import bcrptjs from "bcryptjs";
import dotenv from "dotenv";
dotenv.config("../././.env");
let SECRET_KEY = process.env.SECRET_KEY;
//signup controller function starts from here
const signUp = async (req, resp) => {
try {
let query = new authModel(req.body);
let result = await query.save();
if (result) {
let token = tokenGenerator(req.body, SECRET_KEY);
let expireDate=new Date();
expireDate.setDate(expireDate.getDate()+7);
resp.cookie("token", token, { httpOnly: true,expires:expireDate });
resp.status(200).json({ message: "Your account has been created",isLogged:true });
} else {
resp.send("something went wrong! try again later");
}
} catch (error) {
console.log(error)
if (error.name === "ValidationError") {
validationError(error, resp);
} else {
duplicateErrorHandling(error, resp);
}
}
};
//signup controller function ends here
//login controller function starts from here
export const login = async (req, resp) => {
try {
console.log(req.body)
let query = await authModel.find({ user: req.body.user });
console.log(query)
if (query.length > 0) {
let checkPassword = await bcrptjs.compare(
req.body.password,
query[0].password
);
console.log(checkPassword);
if (checkPassword) {
let token = tokenGenerator(req.body, SECRET_KEY);
resp.cookie("token", token, { httpOnly: true });
await isAdmin(req,resp);
} else {
resp.status(500);
resp.json({ message: "password doesnot matched" });
}
} else {
resp.status(500);
resp.json({ message: "username doesnot matched" });
}
} catch (error) {
resp.status(500).json({message:"something went wrong"});
console.log(error);
}
};
//login controller function ends here
// logout controller function
const logout=(req,resp)=>{
let cookie=req.cookies.token;
if(cookie){
let date=new Date(0);
resp.cookie("token",{expires:date});
resp.status(200).json({message:"User is logout",isLogged:false,isAdmin:false});
}else{
resp.status(200).json({message:"token is not available"});
}
}
export { signUp,logout };
|
import { sanityRes } from "../lib/sanity"
import { groq } from 'next-sanity'
import urlFor from "../lib/sanity"
import Image from "next/image";
import Link from "next/link";
import Script from "next/script"
// TEMPLATES
import Intro from "../components/home/Intro";
import Banner from "../components/home/Banner";
import ListingCard from "../components/templates/ListingCard";
import Heading from "../components/home/Heading";
import Hero from "../components/home/Hero";
import Cards from "../components/templates/Cards";
import BlogCard from "../components/templates/BlogCard"
// STYLES
import Styles from "../styles/Home.module.css"
import PlainPage from "../components/templates/PlainPage";
import Form from "../components/templates/Form";
import Sidebar from "../components/templates/Sidebar";
import Header from "../components/templates/Header";
import Seo from "../components/global/Seo";
const pageQuery = groq`
{
'pageDesign': *[_type == 'pages' && slug.current == $slug][0],
...,
'team': *[_type == 'team'][0..6]{
name,
_id,
image,
'slug': slug.current
},
'blog': *[_type == 'blog'][0..4]{
'slug': slug.current,
title,
_id,
excerpt,
date,
mainImage
},
'listings': *[_type == 'listings'][0..6]{
'slug': slug.current,
propType,
_id,
shortTitle,
status,
price,
address,
city,
state,
zipCode,
'thumbnail': gallery.images[0],
'details': details {
bedrooms,
bathrooms,
squareFootage,
}
}
}
`
export async function getStaticPaths() {
const paths = await sanityRes.fetch(groq`
*[_type == 'pages' && defined(slug.current)][].slug.current
`)
return {
paths: paths.map((slug) => ({ params: { slug } })),
fallback: false
}
}
export async function getStaticProps(context) {
const { slug = "" } = context.params
const page = await sanityRes.fetch(pageQuery, { slug })
return {
props: {
page
}
}
}
export default function Pages({ page, idx_body }) {
const pageSection = page.pageDesign.pageBuilder
const defaultText = '#e2e2e2'
const defaultHeader = '#222222'
return (
<>
<Seo
title={page.pageDesign.seo?.title_tag}
description={page.pageDesign.seo?.meta_description}
/>
<Header
title={page.pageDesign?.title}
image={page.pageDesign?.headerImage}
altTag={page.pageDesign?.headerImage?.altTag}
/>
<div className="section">
<div className="container">
<div className="md:flex gap-10">
<div className={page.pageDesign.pageLayout === 'sidebar' ? 'md:w-2/3' : 'w-full'}>
<div className={Styles.homeSections}>
{pageSection.map((section) => {
const headerColor = {
color: section.textColor?.headerColor.hex ? section.textColor?.headerColor.hex : defaultHeader
}
const bodyColor = {
color: section.textColor?.textColor.hex ? section.textColor?.textColor.hex : defaultText
}
const backgroundStyles = {
background: `${section.background?.backgroundType === 'color' && section?.background?.color?.hex || section.background?.backgroundType === 'image' && `url(${section.background.image ? urlFor(section?.background?.image).url() : undefined})`}`,
backgroundPosition: 'center',
backgroundSize: 'cover'
};
const blockBackground = {
background: `${section.blockColors?.backgroundType === 'color' && section?.blockColors?.color?.hex || section.background?.backgroundType === 'image' && `url(${section.background.image ? urlFor(section?.background?.image).url() : undefined})`}`,
backgroundPosition: 'center',
backgroundSize: 'cover'
}
const blockHeaderColor = {
color: section.blockText?.headerColor.hex ? section.blockText?.headerColor.hex : defaultHeader
}
const blockBodyColor = {
color: section.blockText?.textColor.hex ? section.blockText?.textColor.hex : defaultText
}
if (section._type === 'plainPage') {
return (
<PlainPage
content={section.content}
key={section._key}
/>
)
}
if (section._type === 'testimonialBlock') {
return (
<div key={section._key}>
<div className="border p-4 my-2">
<div className="mb-6">{section.testimonial && <p>{section.testimonial}</p>}</div>
{section.name && <em className="font-medium">— {section.name}</em>}
</div>
</div>
)
}
if (section._type === 'contactPage') {
return (
<div className="section" key={section._key}>
<div className="container">
<Heading
heading={section.heading}
body={section.text}
textAlign="text-left"
/>
<Form />
</div>
</div>
)
}
// CODE BLOCK
if (section._type === 'codeBlock') {
return (
<div className="py-6" key={section._key}>
<div className="container">
<div
dangerouslySetInnerHTML={{ __html: `${section?.code}` }}
/>
</div>
</div>
)
}
// IHF
if (section._type === 'ihf') {
return (
<div className="py-6" key={section._key}>
<div className="container">
{idx_body}
<div
dangerouslySetInnerHTML={{
__html: `{idx_body}`
}}
/>
</div>
</div>
)
}
if (section._type === 'hero') {
return (
<div key={section._key}>
<Hero
heading={section.heading}
image={section.image}
blurData={section.image}
headerColor={headerColor}
/>
</div>
)
}
if (section._type === 'intro') {
return (
<div key={section._key} style={backgroundStyles}>
<Intro
content={section.content}
heading={section.heading}
image={section.image}
altTag={section.altTag}
headerStyle={headerColor}
textColor={bodyColor}
buttonLink={section.button?.buttonLink}
buttonText={section.button?.buttonText}
/>
</div>
)
}
// FEATURED BLOCKS
if (section._type === 'featured') {
return (
<div style={backgroundStyles} key={section._key}>
<div className="section">
<div className="container text-center">
<Heading
heading={section.heading}
body={section.text}
headerStyle={headerColor}
bodyStyle={bodyColor}
/>
<div className={`md:grid-cols-6 grid-cols-1 grid mt-10 gap-3 justify-items-center`}>
{section.blocks.map((node) => {
return (
<div className="p-6" key={node._key} style={blockBackground}>
{node.value && <h3 className="h3 mb-6" style={blockHeaderColor}>{node.value}</h3>}
{node.text && <p style={blockBodyColor}>{node.text}</p>}
</div>
)
})}
</div>
</div>
</div>
</div>
)
}
// TEAM SLIDER
if (section._type === 'teamSlider') {
return (
<div className="section" style={backgroundStyles} key={section._key}>
<div className="container">
<Heading
heading={section.heading}
body={section.text}
headerStyle={headerColor}
bodyStyle={bodyColor}
/>
<div className="grid md:grid-cols-4 grid-cols-1 gap-4 mt-10">
{res.team.map((node) => {
return (
<div key={node._id}>
<Cards
name={node.name}
image={node.image}
link={'/team/' + node.slug}
/>
</div>
)
})}
</div>
</div>
</div>
)
}
// BANNER
if (section._type === 'banner') {
return (
<div key={section._key} className={Styles.homeBanner} style={backgroundStyles}>
<Banner
heading={section.heading}
text={section.text}
textStyle={bodyColor}
headerStyle={headerColor}
buttonLink={section.button?.buttonLink}
buttonText={section.button?.buttonText}
/>
</div>
)
}
// IMAGE BLOCKS
if (section._type === 'imageBlocks') {
return (
<div className="section" style={backgroundStyles} key={section._key}>
<div className="container">
<Heading
heading={section.heading}
body={section.text}
headerStyle={headerColor}
bodyStyle={bodyColor}
/>
<div className="grid lg:grid-cols-4 md:grid-cols-2 grid-cols-1 gap-4 mt-10 justify-center text-center">
{section.blocks.map((node) => {
return (
<Link href={node.link ? node.link : ''} key={node._id}>
<a>
<div className="relative overflow-hidden" key={node._key}>
<Image
src={urlFor(node.image).url()}
alt={node.value}
layout="fixed"
height="490"
width="450"
objectFit="cover"
placeholder="blur"
blurDataURL={urlFor(node.image).width(50).height(50).quality(1).url()}
/>
<div className="overlay"></div>
<div className="absolute bottom-6 left-0 right-0 text-white px-6 py-4 justify-center text-center">
<h3 className="h3 text-white">{node.value}</h3>
</div>
</div>
</a>
</Link>
)
})}
</div>
</div>
</div>
)
}
// BLOG SLIDER
if (section._type === 'blogSlider') {
return (
<div className="section" style={backgroundStyles} key={section._key}>
<div className="container">
<Heading
heading={section.heading}
body={section.text}
headerStyle={headerColor}
bodyStyle={bodyColor}
/>
<div className="grid md:grid-cols-2 grid-cols-1 gap-4 mt-10">
{res.blog.map((node, i) => {
return (
<div key={node._id}>
<BlogCard
title={node.title}
image={node.mainImage}
link={'/blog/' + node.slug}
excerpt={node.excerpt}
/>
</div>
)
})}
</div>
</div>
</div>
)
}
// ACTIVE LISTINGS
if (section._type === 'activeListings') {
return (
<div className="section" style={backgroundStyles} key={section._key}>
<div className="container">
<Heading
heading={section.heading}
body={section.text}
headerStyle={headerColor}
bodyStyle={bodyColor}
/>
<div className="grid grid-cols-3">
{res.listings.map((node) => {
return (
<div key={node._id}>
<ListingCard
address={node.address}
city={node.city}
state={node.state}
zipCode={node.zipCode}
link={'/listings/' + node.slug}
image={node.thumbnail}
bedrooms={node.details.bedrooms}
bathrooms={node.details.bathrooms}
squareFootage={node.details.squareFootage}
price={node.price}
shortTitle={node.shortTitle}
propType={node.propType}
status={node.status}
/>
</div>
)
})}
</div>
</div>
</div>
)
}
})
}
</div>
</div>
<div className={page.pageDesign.pageLayout === 'sidebar' ? 'md:w-1/3' : 'hidden'}>
<Sidebar />
</div>
</div>
</div>
</div>
</>
)
}
|
import 'package:flutter/material.dart';
/// Flutter code sample for [SearchBar].
void main() => runApp(const SearchBarApp());
class SearchBarApp extends StatefulWidget {
const SearchBarApp({super.key});
@override
State<SearchBarApp> createState() => _SearchBarAppState();
}
class _SearchBarAppState extends State<SearchBarApp> {
// bool isDark = false;
@override
Widget build(BuildContext context) {
// final ThemeData themeData = ThemeData(
// useMaterial3: true,
// brightness: isDark ? Brightness.dark : Brightness.light);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 50,vertical: 20),
child: SearchAnchor(
builder: (BuildContext context, SearchController controller) {
return SearchBar(
controller: controller,
padding: const MaterialStatePropertyAll<EdgeInsets>(
EdgeInsets.symmetric(horizontal: 16.0)),
onTap: () {
controller.openView();
},
onChanged: (_) {
controller.openView();
},
// leading: ,
trailing: <Widget>[
Tooltip(
message: 'Search',
child: IconButton(
onPressed: () {
},
icon: const Icon(Icons.search),
),
)
],
);
},
suggestionsBuilder:
(BuildContext context, SearchController controller) {
return List<ListTile>.generate(5, (int index) {
final String item = 'item $index';
return ListTile(
title: Text(item),
onTap: () {
setState(() {
controller.closeView(item);
});
},
);
});
}),
);
}
}
|
<?php
/**
* This file is part of Totara Learn
*
* Copyright (C) 2021 onwards Totara Learning Solutions LTD
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* @author Riana Rossouw <riana.rossouw@totaralearning.com>
* @package core_course
* @category totara_notification
*/
use core_course\totara_notification\placeholder\course as course_placeholder_group;
use core_phpunit\testcase;
use totara_notification\placeholder\option;
defined('MOODLE_INTERNAL') || die();
/**
* @group totara_notification
*/
class core_course_totara_notification_course_placeholder_testcase extends testcase {
/**
* @return void
*/
protected function setUp(): void {
parent::setUp();
course_placeholder_group::clear_instance_cache();
}
protected function tearDown(): void {
parent::tearDown();
course_placeholder_group::clear_instance_cache();
}
public function test_course_placeholders(): void {
// Make devs aware they should extend this test when adding placeholders.
$option_keys = array_map(static function (option $option) {
return $option->get_key();
}, course_placeholder_group::get_options());
self::assertEqualsCanonicalizing(
['full_name', 'full_name_link'],
$option_keys,
'Please add missing placeholders to test coverage.'
);
$course = self::getDataGenerator()->create_course(['fullname' => 'A test course 1']);
$placeholder_group = course_placeholder_group::from_id($course->id);
self::assertEquals('A test course 1', $placeholder_group->do_get('full_name'));
self::assertEquals(
'<a href="https://www.example.com/moodle/course/view.php?id='
. $course->id . '">A test course 1</a>',
$placeholder_group->do_get('full_name_link')
);
}
public function test_course_placeholders_not_available(): void {
$course = self::getDataGenerator()->create_course(['fullname' => 'Another test course']);
$placeholder_group = course_placeholder_group::from_id($course->id);
self::expectException(coding_exception::class);
self::expectExceptionMessage("Invalid key 'whatever'");
$placeholder_group->do_get('whatever');
}
public function test_course_placeholders_invalid_course(): void {
$placeholder_group = course_placeholder_group::from_id(123);
self::expectException(coding_exception::class);
self::expectExceptionMessage('The course entity record is empty');
$placeholder_group->do_get('full_name');
}
public function test_course_placeholder_instances_are_cached(): void {
global $DB;
self::setAdminUser();
$course1 = self::getDataGenerator()->create_course();
$course2 = self::getDataGenerator()->create_course();
$query_count = $DB->perf_get_reads();
course_placeholder_group::from_id($course1->id);
self::assertEquals($query_count + 1, $DB->perf_get_reads());
course_placeholder_group::from_id($course1->id);
self::assertEquals($query_count + 1, $DB->perf_get_reads());
course_placeholder_group::from_id($course2->id);
self::assertEquals($query_count + 2, $DB->perf_get_reads());
course_placeholder_group::from_id($course1->id);
course_placeholder_group::from_id($course2->id);
self::assertEquals($query_count + 2, $DB->perf_get_reads());
}
public function test_course_customfield_placeholders(): void {
$generator = static::getDataGenerator();
$cf_generator = $generator->get_plugin_generator('totara_customfield');
$text_ids = $cf_generator->create_text('course', ['text1', 'text2']);
$mult_ids = $cf_generator->create_multiselect('course', ['multi1' => ['opt1', 'opt2']]);
$textarea_ids = $cf_generator->create_textarea('course', ['textarea']);
// Create course.
$course1 = $generator->create_course(['fullname' => 'Course 1']);
// Add customfield data to course 1.
$cf_generator->set_text($course1, $text_ids['text1'], 'Course 1 text 1 value', 'course', 'course');
$cf_generator->set_multiselect($course1, $mult_ids['multi1'], ['opt1', 'opt2'], 'course', 'course');
$cf_generator->set_textarea($course1, $textarea_ids['textarea'], '<p>Course 1 textarea value</p>', 'course', 'course');
$placeholder1_group = course_placeholder_group::from_id($course1->id);
self::assertEquals('Course 1 text 1 value', $placeholder1_group->do_get('cf_text1'));
self::assertEquals('', $placeholder1_group->do_get('cf_text2'));
self::assertEquals('opt1, opt2', $placeholder1_group->do_get('cf_multi1'));
self::assertEquals('Course 1 textarea value', $placeholder1_group->do_get('cf_textarea'));
static::expectExceptionMessage("Invalid key 'cf_whatever'");
$placeholder1_group->do_get('cf_whatever');
}
}
|
import React, { useEffect, useState } from "react";
import useFetch from '../CustomHooks/useFetch';
const DataFetch = () => {
const { data, isLoading, error } = useFetch(
"https://jsonplaceholder.typicode.com/todos/"
);
const loadingMessage = <p>Loading...</p>;
const errorMessage = <p>{error}</p>;
const todoElement =
data &&
data.map((todo) => {
return <p key={todo.id}>{todo.title}</p>;
});
return (
<div>
<h1>Todos</h1>
{error && errorMessage}
{isLoading && loadingMessage}
{todoElement}
</div>
);
};
export default DataFetch;
|
package clustermanager_test
import (
"context"
"errors"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/golang/mock/gomock"
. "github.com/onsi/gomega"
"github.com/aws/eks-anywhere/internal/test"
"github.com/aws/eks-anywhere/pkg/clients/kubernetes"
"github.com/aws/eks-anywhere/pkg/cluster"
"github.com/aws/eks-anywhere/pkg/clustermanager"
"github.com/aws/eks-anywhere/pkg/clustermanager/mocks"
"github.com/aws/eks-anywhere/pkg/controller/clientutil"
"github.com/aws/eks-anywhere/pkg/types"
)
type deleterTest struct {
Gomega
tb testing.TB
clientFactory *mocks.MockClientFactory
ctx context.Context
spec *cluster.Spec
client kubernetes.Client
log logr.Logger
mgmtCluster types.Cluster
}
func newDeleterTest(tb testing.TB) *deleterTest {
ctrl := gomock.NewController(tb)
return &deleterTest{
tb: tb,
Gomega: NewWithT(tb),
clientFactory: mocks.NewMockClientFactory(ctrl),
ctx: context.Background(),
spec: test.VSphereClusterSpec(tb, tb.Name()),
log: test.NewNullLogger(),
mgmtCluster: types.Cluster{
KubeconfigFile: "my-config",
},
}
}
func (a *deleterTest) buildClient(objs ...kubernetes.Object) {
a.client = test.NewFakeKubeClient(clientutil.ObjectsToClientObjects(objs)...)
a.clientFactory.EXPECT().BuildClientFromKubeconfig(a.mgmtCluster.KubeconfigFile).Return(a.client, nil)
}
func TestDeleterRunClusterDeleteSuccess(t *testing.T) {
tt := newDeleterTest(t)
tt.spec.Cluster.Namespace = "default"
tt.buildClient(tt.spec.Cluster)
a := clustermanager.NewDeleter(tt.log, tt.clientFactory,
clustermanager.WithDeleterRetryBackOff(time.Millisecond),
clustermanager.WithDeleterNoTimeouts(),
)
tt.Expect(a.Run(tt.ctx, tt.spec, tt.mgmtCluster)).To(Succeed())
}
func TestDeleterRunErrorBuildingClient(t *testing.T) {
tt := newDeleterTest(t)
tt.client = test.NewFakeKubeClientAlwaysError()
tt.clientFactory.EXPECT().BuildClientFromKubeconfig(tt.mgmtCluster.KubeconfigFile).Return(nil, errors.New("bad client"))
a := clustermanager.NewDeleter(tt.log, tt.clientFactory,
clustermanager.WithDeleterApplyClusterTimeout(0),
)
tt.Expect(a.Run(tt.ctx, tt.spec, tt.mgmtCluster)).To(MatchError(ContainSubstring("building client to delete cluster")))
}
func TestDeleterRunErrorDeleting(t *testing.T) {
tt := newDeleterTest(t)
tt.client = test.NewFakeKubeClientAlwaysError()
tt.clientFactory.EXPECT().BuildClientFromKubeconfig(tt.mgmtCluster.KubeconfigFile).Return(tt.client, nil)
a := clustermanager.NewDeleter(tt.log, tt.clientFactory,
clustermanager.WithDeleterApplyClusterTimeout(0),
)
tt.Expect(a.Run(tt.ctx, tt.spec, tt.mgmtCluster)).To(MatchError(ContainSubstring("deleting cluster")))
}
|
# YouTube Channel Video Fetcher
This repository contains a Jupyter Notebook that uses the YouTube Data API to fetch videos from a specific YouTube channel based on a minimum duration and number of videos. It also fetches transcripts for these videos using the `youtube-transcript-api`.
## Installation
To run this code, you need to install the following Python libraries:
```bash
!pip install beautifulsoup4 requests isodate youtube-transcript-api
```
## Usage
### Get Channel ID by Username
This function fetches the channel ID for a given username.
```python
def get_channel_id_by_username(username, api_key):
url = "https://youtube-v31.p.rapidapi.com/channels"
querystring = {"part": "snippet,contentDetails,statistics", "forUsername": username}
headers = {
"X-RapidAPI-Key": api_key,
"X-RapidAPI-Host": "youtube-v31.p.rapidapi.com"
}
response = requests.get(url, headers=headers, params=querystring)
if response.status_code == 200:
items = response.json().get('items', [])
if items:
return items[0]['id']
else:
print("Channel not found.")
return None
else:
print("Failed to fetch data:", response.status_code, response.text)
return None
```
### Get YouTube Videos
This function fetches videos from a YouTube channel based on minimum duration and number of videos.
```python
def get_youtube_videos(channel_id, api_key, min_minutes, count):
url = "https://youtube-v31.p.rapidapi.com/search"
min_seconds = min_minutes * 60
all_videos = []
next_page_token = None
while len(all_videos) < count:
querystring = {
"channelId": channel_id,
"part": "snippet",
"order": "date",
"maxResults": "50",
"pageToken": next_page_token
}
headers = {
"X-RapidAPI-Key": api_key,
"X-RapidAPI-Host": "youtube-v31.p.rapidapi.com"
}
response = requests.get(url, headers=headers, params=querystring)
if response.status_code == 200:
videos = response.json().get('items', [])
video_ids = [video['id']['videoId'] for video in videos if 'videoId' in video['id']]
video_details = get_video_details(video_ids, api_key)
filtered_videos = [video for video in video_details if video['duration_seconds'] >= min_seconds]
all_videos.extend(filtered_videos)
next_page_token = response.json().get('nextPageToken')
if not next_page_token:
break
else:
print("Failed to fetch data:", response.status_code, response.text)
break
return all_videos[:count]
```
### Get Video Details
This function fetches detailed information including duration for a list of video IDs.
```python
def get_video_details(video_ids, api_key):
url = "https://youtube-v31.p.rapidapi.com/videos"
video_details = []
for i in range(0, len(video_ids), 50):
querystring = {
"part": "contentDetails,snippet",
"id": ','.join(video_ids[i:i+50])
}
headers = {
"X-RapidAPI-Key": api_key,
"X-RapidAPI-Host": "youtube-v31.p.rapidapi.com"
}
response = requests.get(url, headers=headers, params=querystring)
if response.status_code == 200:
videos = response.json().get('items', [])
for video in videos:
duration = isodate.parse_duration(video['contentDetails']['duration'])
duration_seconds = duration.total_seconds()
video_details.append({
'title': video['snippet']['title'],
'url': f"https://www.youtube.com/watch?v={video['id']}",
'duration': video['contentDetails']['duration'],
'duration_seconds': duration_seconds
})
else:
print("Failed to fetch video details:", response.status_code, response.text)
break
return video_details
```
### Get Transcripts
This function fetches transcripts for a list of video URLs.
```python
def get_transcripts(video_urls):
transcripts = {}
for video_url in video_urls:
video_id = video_url.split('=')[-1]
try:
transcript_list = YouTubeTranscriptApi.get_transcript(video_id)
transcript = "\n".join([entry['text'] for entry in transcript_list])
transcripts[video_url] = transcript
except Exception as e:
transcripts[video_url] = f"Transcript not available: {e}"
return transcripts
```
### Example Usage
Replace the placeholder `api_key` with your actual RapidAPI key.
```python
api_key = "Enter your RapidAPI key"
channel_user_name = 'PowerfulJRE'
channel_id = get_channel_id_by_username(channel_user_name, api_key)
min_minutes = 10 # Minimum duration in minutes
count = 2 # Number of videos to return
videos = get_youtube_videos(channel_id, api_key, min_minutes, count)
print(f"Found {len(videos)} videos with a minimum duration of {min_minutes} minutes.")
for video in videos:
print(f"Title: {video['title']}, URL: {video['url']}, Duration: {video['duration']}")
urls = get_video_urls(videos)
transcriptions = get_transcripts(urls)
print(transcriptions)
```
### Dependencies
- `beautifulsoup4`
- `requests`
- `isodate`
- `youtube-transcript-api`
- `Rapid-api-ket`
### Contributing
Contributions are welcome. Please open an issue to discuss what you would like to change.
### Contact
For any issues, please contact [Mathavan S G](aimathavan14@gmail.com).
|
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.4;
import {ERC20} from "../../src/ERC20.sol";
import {InvariantTest} from "../utils/InvariantTest.sol";
import {MockERC20} from "../mocks/MockERC20.sol";
import {BaseTest} from "../base/BaseTest.sol";
import {InvariantERC20User} from "../accounts/ERC20User.sol";
import {InvariantOwner} from "../accounts/Owner.sol";
import {InvariantStakerManager} from "../accounts/Staker.sol";
import {Warper} from "../accounts/Warper.sol";
import {MutablePool} from "../utils/MutablePool.sol";
// Invariant 1: totalAssets <= underlying balance of contract (with rounding)
// Invariant 2: ∑ balanceOfAssets == totalAssets (with rounding)
// Invariant 3: totalSupply <= totalAssets
// Invariant 4: convertToAssets(totalSupply) == totalAssets (with rounding)
// Invariant 5: exchangeRate >= `precision`
// Invariant 6: freeAssets <= totalAssets
// Invariant 7: balanceOfAssets >= balanceOf
// Invariant 8: freeAssets <= underlying balance
// Invariant 9: issuanceRate == 0 (if post vesting)
// Invariant 10: issuanceRate > 0 (if mid vesting)
contract Invariants is BaseTest, InvariantTest {
InvariantERC20User internal _erc20User;
InvariantOwner internal _owner;
InvariantStakerManager internal _stakerManager;
MockERC20 internal _underlying;
MutablePool internal _pool;
Warper internal _warper;
function setUp() public virtual {
_underlying = new MockERC20();
_pool = new MutablePool( address(this), ERC20(address(_underlying)));
_erc20User = new InvariantERC20User(address(_pool), address(_underlying));
_stakerManager = new InvariantStakerManager(address(_pool), address(_underlying));
_owner = new InvariantOwner(address(_pool), address(_underlying));
_warper = new Warper(address(_pool));
// Required to prevent `acceptOwner` from being a target function
// TODO: Investigate hevm.store error: `hevm: internal error: unexpected failure code`
_pool.setOwner(address(_owner));
// Performs random transfers of underlying into contract
addTargetContract(address(_erc20User));
// Performs random transfers of underlying into contract
// Performs random updateVestingSchedule calls
addTargetContract(address(_owner));
// Performs random instantiations of new staker users
// Performs random deposit calls from a random instantiated staker
// Performs random withdraw calls from a random instantiated staker
// Performs random redeem calls from a random instantiated staker
addTargetContract(address(_stakerManager));
// Performs random warps forward in time
addTargetContract(address(_warper));
// Create one staker to prevent underflow on index calculations
_stakerManager.createStaker();
}
function invariant_totalAssets_lte_underlyingBalance() public {
assertTrue(_pool.totalAssets() <= _underlying.balanceOf(address(_pool)));
}
function invariant_sumBalanceOfAssets_eq_totalAssets() public {
// Only relevant if deposits exist
if (_pool.totalSupply() > 0) {
uint256 sumBalanceOfAssets;
uint256 stakerCount = _stakerManager.getStakerCount();
for (uint256 i; i < stakerCount; ++i) {
sumBalanceOfAssets += _pool.balanceOfAssets(address(_stakerManager.stakers(i)));
}
assertTrue(sumBalanceOfAssets <= _pool.totalAssets());
assertWithinDiff(sumBalanceOfAssets, _pool.totalAssets(), stakerCount); // Rounding error of one per user
}
}
function invariant_totalSupply_lte_totalAssets() public {
assertTrue(_pool.totalSupply() <= _pool.totalAssets());
}
function invariant_totalSupply_times_exchangeRate_eq_totalAssets() public {
if (_pool.totalSupply() > 0) {
assertWithinDiff(_pool.convertToAssets(_pool.totalSupply()), _pool.totalAssets(), 1); // One division
}
}
// TODO: figure out if there's a replacement for this one involving convertTo* functions. I think Invariant 3: totalSupply <= totalAssets covers this.
// function invariant_exchangeRate_gte_precision() public {
// assertTrue(_pool.exchangeRate() >= _pool.precision());
// }
function invariant_freeAssets_lte_totalAssets() public {
assertTrue(_pool.freeAssets() <= _pool.totalAssets());
}
function invariant_balanceOfAssets_gte_balanceOf() public {
for (uint256 i; i < _stakerManager.getStakerCount(); ++i) {
address staker = address(_stakerManager.stakers(i));
assertTrue(_pool.balanceOfAssets(staker) >= _pool.balanceOf(staker));
}
}
function invariant_freeAssets_lte_underlyingBalance() public {
assertTrue(_pool.freeAssets() <= _underlying.balanceOf(address(_pool)));
}
function invariant_issuanceRate_eq_zero_ifPostVesting() public {
if (block.timestamp > _pool.vestingPeriodFinish() && _pool.lastUpdated() > _pool.vestingPeriodFinish()) {
assertTrue(_pool.issuanceRate() == 0);
}
}
function invariant_issuanceRate_gt_zero_ifMidVesting() public {
if (block.timestamp <= _pool.vestingPeriodFinish()) {
assertTrue(_pool.issuanceRate() > 0);
}
}
}
|
---
title: azureActiveDirectoryTenant 资源类型
description: azureActiveDirectoryTenant 类型将另一Azure Active Directory租户标识为已连接组织的标识源。
ms.localizationpriority: medium
author: markwahl-msft
ms.prod: governance
doc_type: resourcePageType
ms.openlocfilehash: 9aeb699065a1e4bdf37dfd5f5a90985c47db24f7
ms.sourcegitcommit: fd609cb401ff862c3f5c21847bac9af967c6bf82
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 12/31/2021
ms.locfileid: "61650599"
---
# <a name="azureactivedirectorytenant-resource-type"></a>azureActiveDirectoryTenant 资源类型
命名空间:microsoft.graph
[!INCLUDE [beta-disclaimer](../../includes/beta-disclaimer.md)]
在 [connectedOrganization 的标识源中使用](connectedOrganization.md)。 `@odata.type`该值 `#microsoft.graph.azureActiveDirectoryTenant` 指示此类型将另一Azure Active Directory租户标识为已连接组织的标识源。
创建新的[connectedOrganization](../api/entitlementmanagement-post-connectedorganizations.md)时,如果调用方在 identitySources 集合中提供 domainIdentitySource,并且域对应于 Azure Active Directory 租户的注册域,则创建的生成的 connectedOrganization 将具有包含[azureActiveDirectoryTenant](azureactivedirectorytenant.md)类型的单个成员的 identitySources 集合。
## <a name="properties"></a>属性
| 属性 | 类型 | 说明 |
| :--------------------------- | :------------------------ | :---------- |
| displayName |String | 租户Azure Active Directory的名称。 只读。 |
| tenantId |String | 租户的 ID Azure Active Directory ID。 只读。 |
## <a name="relationships"></a>关系
无。
## <a name="json-representation"></a>JSON 表示形式
以下是类型的 JSON 表示形式。
<!-- {
"blockType": "resource",
"optionalProperties": [
],
"@odata.type": "microsoft.graph.azureActiveDirectoryTenant",
"baseType": "microsoft.graph.identitySource"
}-->
```json
{
"tenantId": "String (identifier)",
"displayName": "String"
}
```
<!-- uuid: 16cd6b66-4b1a-43a1-adaf-3a886856ed98
2019-02-04 14:57:30 UTC -->
<!-- {
"type": "#page.annotation",
"description": "azureActiveDirectoryTenant resource type",
"keywords": "",
"section": "documentation",
"tocPath": ""
}-->
|
//
// Sessions.swift
// F1 mac app
//
// Created by Bogdan Farca on 23.09.2021.
//
import SwiftUI
struct MainView: View {
@StateObject var dataModel = SessionsDataModel()
@StateObject var appModel = AppModel.shared
var body: some View {
NavigationView {
if appModel.appState == .loadingSessions {
VStack {
Spacer()
ProgressView()
Spacer()
}
} else {
TabView {
VStack{
HStack{
Button { dataModel.loadSessions() }
label: { Image(systemName: "arrow.clockwise").font(.system(size: 20)) }
Spacer()
Menu("Sort") {
Button {
dataModel.sessions.sort(by: { $0.sessionLength < $1.sessionLength})
} label: {
Text("By time")
}
Button {
dataModel.sessions.sort(by: { $0.laps < $1.laps})
} label: {
Text("By laps")
}
Button {
dataModel.sessions.sort(by: { $0.sessionTime < $1.sessionTime})
} label: {
Text("By date")
}
}
}
.padding(.horizontal,20)
renderSessionsList()
}
.navigationTitle("View Cars")
.tabItem {Label("Improve", systemImage: "hare") }.tag(1)
ReplayView(dataModel: dataModel).navigationTitle("Cars").tabItem { Label("Replay", systemImage: "play") }.tag(2)
CarARView().tabItem { Label("Cars", systemImage: "car") }.tag(2)
}
}
renderMessage()
.font(.headline)
.foregroundColor(.gray)
}.onAppear {
if #available(iOS 13.0, *) {
let tabBarAppearance: UITabBarAppearance = UITabBarAppearance()
tabBarAppearance.configureWithDefaultBackground()
tabBarAppearance.backgroundColor = UIColor(named: "tabColor")
UITabBar.appearance().standardAppearance = tabBarAppearance
let navigationBarAppearance: UINavigationBarAppearance = UINavigationBarAppearance()
navigationBarAppearance.configureWithDefaultBackground()
navigationBarAppearance.backgroundColor = UIColor(named: "tabColor")
UINavigationBar.appearance().standardAppearance = navigationBarAppearance
if #available(iOS 15.0, *) {
UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance
}
}
}
}
@ViewBuilder
private func renderMessage() -> some View {
switch appModel.appState {
case .loadingSessions:
VStack(spacing: 10) {
Image(systemName: "cloud")
.font(.system(size: 50))
.foregroundColor(.green)
.opacity(0.5)
Text("Loading sessions from Oracle Cloud")
}
case .waitToLoadTrack:
VStack(spacing: 10) {
Image(systemName: "arrow.left")
.font(.system(size: 50))
.foregroundColor(.green)
.opacity(0.5)
Text("Select your session from the left pane")
}
case let .error(msg):
VStack(spacing: 10) {
Image(systemName: "exclamationmark.triangle")
.font(.system(size: 50))
.foregroundColor(.red)
.opacity(0.5)
Text("Error: \(msg)")
}
default: EmptyView()
}
}
@ViewBuilder
private func renderSessionsList() -> some View {
List {
ForEach( dataModel.sessions.sorted(by: { $0.sessionTime > $1.sessionTime}), id: \.mSessionid) { session in
renderSessionRow(session)
}
}
.refreshable {
dataModel.loadSessions()
}
.listStyle(SidebarListStyle())
}
@ViewBuilder
private func renderSessionRow(_ session: Session) -> some View {
NavigationLink(destination: LapReplayView(session: session)) {
VStack(alignment: .leading) {
Text("Session by \(session.driver)")
.font(.system(size: 20))
Group {
HStack{
Image(systemName: "calendar")
Text("\(session.sessionTimeMeasurement)")
}
HStack{
Image(systemName: "clock")
Text("\(session.sessionLengthString)")
}
HStack{
Image(systemName: "arrow.clockwise")
Text("\(session.lapsString)")
}
}
.font(.system(size: 16, weight: .light))
.padding(.vertical, 2)
.opacity(0.7)
}
}
}
}
struct ReplayView : View{
@StateObject var dataModel : SessionsDataModel
@StateObject var appModel = AppModel.shared
var items: [GridItem] {
Array(repeating: .init(.adaptive(minimum: 90)), count: 2)
}
var body: some View{
ScrollView(.vertical, showsIndicators: false) {
HStack{
Button { dataModel.loadSessions() }
label: { Image(systemName: "arrow.clockwise").font(.system(size: 20)) }
Spacer()
Menu("Sort") {
Button {
dataModel.sessions.sort(by: { $0.sessionLength < $1.sessionLength})
} label: {
Text("By time")
}
Button {
dataModel.sessions.sort(by: { $0.laps < $1.laps})
} label: {
Text("By laps")
}
Button {
dataModel.sessions.sort(by: { $0.sessionTime < $1.sessionTime})
} label: {
Text("By date")
}
}
}
.padding(.horizontal,20)
.padding(.bottom, 10)
LazyVGrid(columns: items, spacing: 15) {
ForEach(dataModel.sessions, id: \.mSessionid) { session in
NavigationLink(destination: LapReplayView(session: session)) {
VStack{
Image("\(session.imageName)")
.resizable()
.aspectRatio(1.65, contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 5))
Text("\(session.sessionTimeMeasurement)")
.font(.headline)
Text("by \(session.driver)")
.font(.subheadline)
}
.foregroundColor(Color.init(uiColor: UIColor(named: "textColor") ?? UIColor.black))
.padding()
.background(
RoundedRectangle(cornerRadius: 10)
.fill(Color.init(uiColor: UIColor(named: "cellColor") ?? UIColor.white))
)
}
}
}
.padding(.horizontal)
}.background(Color.init(uiColor: UIColor(named: "backgroundColor") ?? UIColor.white))
}
}
struct CarARView : View{
let thecars = cars
var body: some View{
List{
ForEach(thecars){ car in
NavigationLink(destination: SingleCarView(car: car.imageName, carModel: car)) {
HStack{
VStack(alignment:.leading){
Text("\(car.name)")
.font(.title2)
Text("\(car.maker)")
.font(.callout)
Text(car.year)
.font(.callout)
}
Spacer()
Image(car.imageName)
.resizable()
.aspectRatio(1.65, contentMode: .fill)
.frame(width: 150, height: 100)
.clipShape(RoundedRectangle(cornerRadius: 5))
.padding(.vertical)
}
}
}
// .background(Color.init(red: 242/255, green: 241/255, blue: 246/255))
}.navigationBarTitle(Text("Cars"))
}
}
struct Sessions_Previews: PreviewProvider {
static var previews: some View {
ReplayView(dataModel: SessionsDataModel())
}
}
|
import React, { useState, useContext } from 'react'
import { Form, Button, Container, Card } from 'react-bootstrap'
import './Auth.css'
import { BASE_URL, LOGIN } from '../utils/APP_API';
//Auth
import { AuthContext } from '../Context/AuthContext';
import { Link } from 'react-router-dom';
import Nav from '../Components/Nav/Nav';
function Login() {
const AuthCtx = useContext(AuthContext)
const [loginInfo, setLoginInfo] = useState({
email: '',
password: ''
})
const [err, setErr] = useState(null)
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"email": loginInfo.email,
"password": loginInfo.password
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
function handleChange(e) {
e.preventDefault();
let value = e.target.value;
setLoginInfo(loginInfo => {
return {
...loginInfo,
[e.target.name]: value
}
})
}
async function handleSubmit(e) {
e.preventDefault()
let res = await (await fetch(LOGIN, requestOptions)).json();
if (res.status === 'success') {
AuthCtx.login(res.token);
} else {
setErr(err => res.message)
}
}
return (
<>
<Nav />
{/* //Login Box */}
<Container className='d-flex justify-content-center align-items-center text-left my-4 auth-form-container'>
<Card style={{ width: '36rem' }}>
<Card.Header><h1 className='text-center'>Login</h1></Card.Header>
<Card.Body>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" name="email" value={loginInfo.email} onChange={handleChange} />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Password" name="password" value={loginInfo.password} onChange={handleChange} />
</Form.Group>
<p>Don't have an account? <Link to='/signup'>Signup</Link></p>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</Card.Body>
</Card>
</Container>
</>
)
}
export default Login
|
;; JACAL: Symbolic Mathematics System. -*-scheme-*-
;; Copyright 1989, 1990, 1991, 1992, 1993, 1995, 1997, 2005, 2006 Aubrey Jaffer.
;;
;; 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 3 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
(require 'object->string)
(require 'hash-table)
(require 'rev4-optional-procedures)
(require 'common-list-functions)
;;; Scheme doesn't allow for definition of new types which are
;;; distinct from existing types. So we will carefully use BUNCH
;;; instead of LIST in order to distinguish the types.
;;; This requires that boolean?, pair?, symbol?, number?,
;;; string?, vector? and procedure? be disjoint as outlined in:
;;; Jonathan Rees and William Clinger, editors. The Revised^3
;;; Report on the algorithmic language Scheme, ACM SIGPLAN Notices
;;; 21(12), ACM, December 1986.
;;; If the types are not disjoint you WILL lose.
;;; The following types are mutually exclusive:
;;; SEXP, VARIABLE, EXPL, IMPL, EQLT, BUNCH
;;; INTEGERs are EXPL
;;; An EXPR is an EXPL or IMPL
;;; A LICIT is an EXPL, IMPL, or EQLT.
;;; VARIBLEs can only occur as part of EXPRS and EQLTS.
;;; SYMBOLs can only occur in SEXP.
;;; BUNCHES can contain SYMBOLs, LICITs, and BUNCHEs.
;;; An EXPL, IMPL, or EQLT, or BUNCH of these can be a
;;; lambda expression.
;;; A VAR is a vector which consists of:
;;; 0 var:sexp - s-expression ;lambda vars have leading "@"
;;; 1 var:pri - string ;ordering priority
;first char is priority override
;last char is differential order
;;; 2 var:def - poleq ;ext defining equation
;;; or - integer ;simple lambda position
;;; or - procedure ;
;;; 3 var:depends - list of vars ;vars used in var:def
;;; 4 var:shadow - var ;shadow copies of this lambda var or #f
;;;; THE REST ARE FOR FUNCTIONS ONLY
;;; 5 func-arglist ;list of (function and) argument values.
;;; 6 func-parity - list of atoms ;EVEN, ODD, 0, or #F
;;; 7 func-syms - list of lists ;of positions of arguments
;;; 8 func-anti-syms - list of lists ;of positions of arguments
;;; 9 func-dists - list of lists ;of functions which distribute
;;; 10 func-anti-dists - list of lists ;of functions which anti-distribute
;;; 11 func-idems - list ;of positions of arguments
; perserved in idempotency
(define make-var vector)
(define poly:var? vector?)
(define (var:sexp v) (vector-ref v 0))
(define (var:pri v) (char->integer (string-ref (vector-ref v 1) 0)))
(define (var:set-pri! v i) (string-set! (vector-ref v 1) 0 (integer->char i)))
(define (var:def v) (vector-ref v 2))
(define (var:set-def! v i) (vector-set! v 2 i) v)
(define (var:depends v) (vector-ref v 3))
(define (var:set-depends! v i) (vector-set! v 3 i) v)
(define (func-arglist f) (vector-ref f 5))
(define (func-set-arglist f i) (vector-set! f 5 i))
(define func? func-arglist)
(define (func-parity f) (vector-ref f 6))
(define (func-set-parity! f v) (vector-set! f 6 v))
(define (func-syms f) (vector-ref f 9))
(define (func-set-syms! f v) (vector-set! f 9 v))
(define (func-anti-syms f) (vector-ref f 10))
(define (func-set-anti-syms! f v) (vector-set! f 10 v))
(define (func-dists f) (vector-ref f 11))
(define (func-set-dists! f v) (vector-set! f 11 v))
(define (func-anti-dists f) (vector-ref f 12))
(define (func-set-anti-dists! f v) (vector-set! f 12 v))
(define (func-idems f) (vector-ref f 13))
(define (func-set-idems! f v) (vector-set! f 13 v))
(define (copy-vector v)
(define iv (make-vector (vector-length v)))
(do ((i (+ -1 (vector-length iv)) (+ -1 i)))
((negative? i) iv)
(vector-set! iv i (vector-ref v i))))
;;; The shadowed variables are kept in a list in the var:shadow slot
;;; in the var. This list has the bumped and shadowed transformations
;;; of the var for each arglist-length less than or equal
;;; (var:max-lambda-position var).
;;; For simple lambda variables (@1, @2, ...) the last shadowed
;;; variable is identical to the original except that its shadow slot
;;; is #f.
(define (var:shadow v arglist-length)
(if (not (vector-ref v 4))
(vector-set! v 4 (make-list (var:max-lambda-position v) #f)))
(let ((shadpair (memshad arglist-length (vector-ref v 4))))
(if (not (car shadpair))
(set-car! shadpair
(cond ((< arglist-length (var:min-lambda-position v))
(var:lambda-bump v (- arglist-length)))
(else (make-shadow v arglist-length)))))
(car shadpair)))
(define (memshad arglist-length shadlist)
(cond ((= 1 arglist-length) shadlist)
((null? (cdr shadlist)) shadlist)
(else (memshad (+ -1 arglist-length) (cdr shadlist)))))
(define (make-shadow v arglist-length)
(let ((nv (copy-vector v)))
(vector-set! nv 4 #f)
(vector-set!
nv 0 (if (symbol? (var:sexp nv)) ;got here because can't bump
(string->symbol
(string-append
(symbol->string (var:sexp nv)) ":"))
(do-sexp-symbols
(lambda (s)
(define st (symbol->string s))
(if (and (char=? #\@ (string-ref st 0))
(> (string-length st) 1))
(let ((i (string->number
(substring st 1 (string-length st)))))
(if (> i arglist-length)
(var:sexp (lambda-var (- i arglist-length) 0))
(string->symbol (string-append st ":"))))
s))
(var:sexp v))))
;; Now avoid priority conflicts with minimum increment.
(let* ((s (string-copy (vector-ref v 1)))
(si (+ -1 (string-length s))))
(string-set! s si (integer->char
(+ 1 (char->integer (string-ref s si)))))
(vector-set! nv 1 s))
(var:set-depends!
nv (map (lambda (var)
(if (simple-lambdavar? var) (var:shadow var arglist-length)
var))
(var:depends v)))
(if (var:def v)
(var:set-def! nv (licits:do-vars
(lambda (var)
(if (lambdavardep? var)
(if (eq? var v) nv
(var:shadow var arglist-length))
var))
(var:def v))))
(if (>= (vector-length v) 5)
(func-set-arglist nv (licits:do-vars
(lambda (var)
(if (lambdavardep? var)
(var:shadow var arglist-length) var))
(func-arglist v))))
nv))
(define (var:> v2 v1)
(string>? (vector-ref v2 1) (vector-ref v1 1)))
;(define var-tab '())
;(define var-tab-lookup (predicate->asso equal?))
;(define var-tab-define (alist-associator equal?))
;(define var-tab-for-each alist-for-each)
(define var-tab (make-hash-table 43))
(define var-tab-lookup (predicate->hash-asso equal?))
(define var-tab-define (hash-associator equal?))
(define var-tab-for-each hash-for-each)
(define (list-of-vars)
(define vars '())
(var-tab-for-each (lambda (k v) (set! vars (cons v vars))) var-tab)
vars)
(define (sexp->new-var v)
(let ((base v)
(diffs 0)
(lambda? (and (pair? v) (eq? 'lambda (car v)))))
(do () ((not (and (pair? base) (eq? 'differential (car base)))))
(set! base (cadr base))
(set! diffs (+ 2 diffs))) ;leave space for shadow priority.
(let* ((s (object->string base))
(sl (string-length s))
(arglist (if (pair? v) (map sexp->math (if lambda? (caddr v) v))
'())))
(if lambda?
(make-var
(caddr v)
(string-append (case (string-ref s 0)
((#\@) lambda-var-pri-str)
(else lambda-var-pri-str))
s
(string (integer->char diffs)))
(and (char=? #\@ (string-ref s 0))
(not (= sl 1))
(not (char=? #\^ (string-ref s 1)))
(string->number (substring s 1 sl)))
(var:build-depends arglist)
#f
arglist
#f #f #f #f #f #f ; function properties
)
(make-var
v
(string-append (case (string-ref s 0)
((#\@) lambda-var-pri-str)
(else median-pri-str))
s
(string (integer->char diffs)))
(and (char=? #\@ (string-ref s 0))
(not (= sl 1))
(not (char=? #\^ (string-ref s 1)))
(string->number (substring s 1 sl)))
(var:build-depends arglist)
#f
arglist
)))))
(define (sexp->var sexp)
(let ((vcell (var-tab-lookup sexp var-tab)))
(if vcell (cdr vcell)
(let ((val (sexp->new-var sexp)))
(set! var-tab (var-tab-define var-tab sexp val))
val))))
(define (string->var s) (sexp->var (string->symbol s)))
(define (var:build-depends args)
(let ((deps '()))
(for-each (lambda (e)
(poly:for-each-var
(lambda (v)
(cond (($var? v))
((symbol? (var:sexp v)) (set! deps (adjoin v deps)))
(else
(set! deps
(adjoin v (union
(var:depends v) deps))))))
e))
args)
deps))
(define (deferop . args)
(var->expl (sexp->var (deferedmath->sexp args))))
(define lambda-var-pri (+ -5 char-code-limit))
(define lambda-var-pri-str (string (integer->char lambda-var-pri)))
(define median-pri-str (string (integer->char (quotient char-code-limit 2))))
(define (var->string v)
(let ((sexp (var:sexp v)))
(if (symbol? sexp) (symbol->string sexp)
(math:error 'expected-simple-symbol sexp))))
(define (make-rad-var radicand exponent-reciprocal)
(let ((e (univ:monomial -1 exponent-reciprocal $)))
(set-car! (cdr e) radicand)
(let ((v (defext (sexp->var (list '^ (bunch->sexp radicand #t)
(list '/ 1 exponent-reciprocal)))
e)))
(func-set-arglist v (list _^ radicand (make-rat 1 exponent-reciprocal)))
(set! radical-defs (cons (extrule v) radical-defs))
v)))
(define (var:nodiffs v)
(do ((base (vector-ref v 0) (cadr base)))
((not (and (pair? base) (eq? 'differential (car base))))
(if (eq? base (vector-ref v 0)) v (sexp->var base)))))
(define (var:differential? v)
(not (zero? (var:diff-depth v))))
(define (var:diff-depth v)
(let ((s (vector-ref v 1)))
(quotient (char->integer (string-ref s (+ -1 (string-length s)))) 2)))
(define (var:differential v)
(sexp->var (list 'differential (var:sexp v))))
(define (var:undiff v)
(sexp->var (cadr (var:sexp v))))
(define (radicalvar? v)
(let ((ve (var:sexp v)))
(and (pair? ve) (eq? '^ (car ve)))))
(define (lambdavar? v)
(= lambda-var-pri (var:pri v)))
(define (simple-lambdavar? v)
(number? (lambda-position v)))
(define (simple-shadowed-lambdavar? v)
(and (number? (lambda-position v)) (not (vector-ref v 4))))
(define (lambdavarext? v)
(< lambda-var-pri (var:pri v) $-pri))
(define (lambdavardep? v)
(< (+ -1 lambda-var-pri) (var:pri v) $-pri))
(define ($var? v)
(char=? #\: (string-ref (vector-ref v 1) 1)))
(define (lambda-var i diff-depth)
(if (zero? diff-depth)
(let ((v (sexp->var
(string->symbol
(string-append "@" (number->string i))))))
(var:set-def! v i)
(or (vector-ref v 4) ;so simple-shadowed-lambdavar? works
(vector-set! v 4 (make-list i #f)))
v)
(var:differential (lambda-var i (+ -1 diff-depth)))))
;;; This sometimes is called with shadowed variables (:@4)
(define lambda-position var:def)
;;; currently unused
;; (define (var:sexp-string v)
;; (var->string (var:nodiffs v)))
;; (define (var:sexp-apply proc var)
;; (if (var:differential? var)
;; (var:differential (var:sexp-apply proc (var:undiff var)))
;; (apply proc var '())))
(define (extrule e)
(let ((vd (var:def e)))
(and (pair? vd) vd)))
(define (potent-extrule e)
(let ((vd (var:def e)))
(and (pair? vd) (not (eqv? 0 (cadr vd))) vd)))
(define (defext var impl)
(let ((deps (var:depends var)))
(set! deps
(if (null? deps) (remove var (var:build-depends (list impl)))
(remove (car _^) deps)))
(var:set-depends! var deps)
(var:set-pri! var (if (null? deps) 10 ;must be a constant.
(+ 1 (apply max (map var:pri deps)))))
(var:set-def! var (vsubst var $ impl))
var))
;;; IMPL is a data type consisting of a poly with major variable
;;; $. The value of the IMPL is negative of the poly solved for $.
;;; Using this representation, if poly is square-free and has no
;;; content (gcd (coefficients) = 1), we can express any
;;; algebraic function or number uniquely, even those with no standard
;;; representation (order > 4 roots).
(define (expr? p)
(or (number? p)
(and (pair? p)
(poly:var? (car p)))))
(define (impl? p) (and (pair? p) (poly:var? (car p)) ($? (car p))))
(define (rat:number? p)
(or (number? p)
(and (impl? p)
(= 3 (length p))
(number? (cadr p))
(number? (caddr p)))))
(define (expr:0? p) (or (eqv? 0 p) (and (impl? p) (eqv? 0 (rat:num p)))))
(define (expl? p)
(or (number? p)
(and (pair? p)
(poly:var? (car p))
(not ($? (car p))))))
;;; Rational impl?
(define (rat? p) (and (impl? p) (= 3 (length p))))
(define (make-rat num denom) (list $ num (poly:negate denom)))
(define (rat:num p) (poly:negate (cadr p)))
(define (rat:denom p) (caddr p))
(define (rat:unit-denom? p) (unit? (caddr p)))
(define (bunch? p)
(or (null? p)
(and (pair? p)
(not (poly:var? (car p)))
(not (eqv? $= (car p))))))
(define $= "=")
(define (eqn? p) (and (pair? p) (eqv? $= (car p))))
(define (eqns? p) (if (bunch? p) (some eqns? p) (eqn? p)))
(define (licit? p)
(or (number? p)
(and (pair? p)
(or (poly:var? (car p))
(eqv? $= (car p))))))
(define eqn->poly cdr)
(define (poly->eqn p) (cons $= p))
(define (polys->eqns p) (if (bunch? p) (map polys->eqns p) (poly->eqn p)))
(define (var->expl v) (list v 0 1))
(define (expl->impl p) (make-rat p 1))
(define (var->impl v) (make-rat (var->expl v) 1))
;;; Two paradigms for doing algebra on equations and expressions:
;;; Polynomials as expressions and Polynomials as equations.
;;; Polynomials are used as expressions in GCD.
;;; Polynomials are used as equations in ELIMINATE.
;;; licit-> polxpr poleqn
;;; eqn expl expl
;;; expl expl impl
;;; impl expl(?) impl
;;; After the operation is done, we need to convert back. For
;;; Polynomials as expressions, the result is already expl. For
;;; polynomials as equations:
;;; poleqn->licit
;;; expl eqn
;;; impl expr
(define (licit->poleqn p)
(cond ((symbol? p) (var->impl (sexp->var p)))
((eqn? p) (eqn->poly p))
((impl? p) p)
((expl? p) (expl->impl p))
(else (math:error 'cannot-be-coerced-to-poly-eqn:- p))))
(define (licits->poleqns p)
(if (bunch? p) (map licits->poleqns p) (licit->poleqn p)))
(define (poleqn->licit p)
(cond ((impl? p) (expr:norm p))
((expl? p) (poly->eqn p))
(else (math:error 'not-a-polynomial-equation p))))
(define (poleqns->licits p)
(if (bunch? p) (map poleqns->licits p) (poleqn->licit p)))
(define (licit->polxpr p)
(cond ((symbol? p) (var->expl (sexp->var p)))
((eqn? p) (eqn->poly p))
((expl? p) p)
((and (impl? p) (poly:/? (rat:num p) (rat:denom p))))
(else (math:error 'cannot-be-coerced-to-expl:- p))))
(define (licit->impl p)
(cond ((symbol? p) (var->impl (sexp->var p)))
((eqn? p) (math:error 'value-expected-equation-found:- p))
((impl? p) p)
((expl? p) (expl->impl p))
(else (math:error 'cannot-be-coerced-to-implicit:- p))))
(define (licits->impls p)
(if (bunch? p) (map licits->impls p) (licit->impl p)))
(define (expr p)
(cond ((symbol? p) (var->expl (sexp->var p)))
((expr? p) p)
(else (math:error 'cannot-be-coerced-to-expr:- p))))
(define (exprs p)
(if (bunch? p) (map exprs p) (expr p)))
(define (expl:var? p)
(and (pair? p)
(expl? p)
(equal? (cdr p) '(0 1))))
(define (expl->var p)
(cond ((symbol? p) (sexp->var p))
; ((poly:var? p) p)
((expl:var? p)
(car p))
(else (math:error 'not-a-simple-variable:- p))))
(define (variables p)
(cond ((symbol? p) (list (sexp->var p)))
; ((poly:var? p) (list p))
((expl:var? p)
(list (car p)))
((list? p) (map expl->var p))
(else (math:error 'not-a-simple-variable:- p))))
(define (plicit->integer p)
(cond ((integer? p) p)
((not (rat:number? p)) (math:error 'not-an-integer- p))
((rat:unit-denom? p) (* (rat:denom p) (rat:num p) -1))
(else (math:error 'not-an-integer- p))))
(define (unit? x) (member x '(1 -1)))
(define (expr:norm p)
(if (and (rat? p) (rat:unit-denom? p))
(poly:* (rat:num p) (rat:denom p))
p))
(define (expr:norm-or-unitcan p)
(if (and (rat? p) (rat:unit-denom? p))
(poly:* (rat:num p) (rat:denom p))
(unitcan p)))
;;; These two functions return type expl
(define (num p)
(cond ((impl? p) (rat:num p))
((expl? p) p)
(else (math:error 'cannot-extract-numerator- p))))
(define (denom p)
(cond ((rat? p) (rat:denom p))
((expl? p) 1)
(else (math:error 'cannot-extract-denominator- p))))
(define (sexp? e)
(cond ((number? e) #t)
((symbol? e) #t)
((pair? e) (symbol? (car e)))
((vector? e) #t)
(else #f)))
;;; A useful companion for ZERO?
(define (one? n) (eqv? 1 n))
|
import { useState, useEffect } from "react";
export default function NewTask(props) {
const [fetchedData, setFetchedData] = useState({});
const [randomise, setRandomise] = useState(false);
// const [taskArray, setTaskArray] = useState([]);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [timeEstimate, setTimeEstimate] = useState("");
const [type, setType] = useState("");
const [completed, setCompleted] = useState(false);
const [animtion, setAnimation] = useState(false);
useEffect(() => {
async function fetchTask() {
try {
const response = await fetch("https://www.boredapi.com/api/activity");
if (response.ok) {
const data = await response.json();
setFetchedData(data);
title !== "" && setTitle(fetchedData.activity);
} else {
setFetchedData("Error fetching data: ", response.status);
}
} catch (error) {
console.log("Error fetching data (message): ", error);
}
}
fetchTask();
}, [randomise]);
function handleSubmit(e) {
e.preventDefault();
const newTask = {
title,
description,
timeEstimate,
type,
completed,
};
console.log("Submitted Values:", title, description, timeEstimate, type);
props.taskArrayFunction(newTask);
setTitle("");
setDescription("");
setTimeEstimate("");
setType("");
// taskForm.reset();
}
// const taskForm = document.getElementById("task-form");
// const inputTitle = document.getElementById("newtask-title");
return (
<div
className="new-task"
onClick={() => {
setAnimation(!animtion);
}}
>
{/* <h1>NewTask Component</h1> */}
<form className="task-form" id="task-form" onSubmit={handleSubmit}>
<label for="title">Title:</label>
<input
maxLength={60}
required
type="text"
id="newtask-title"
name="newtask-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<br />
<label htmlFor="description">Description:</label>
<textarea
maxLength={200}
required
type="text"
id="newtask-description"
name="newtask-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<br />
<label htmlFor="timeEstimate">Time Estimate:</label>
<input
maxLength={10}
required
type="number"
id="newtask-timeEstimate"
name="newtask-timeEstimate"
value={timeEstimate}
onChange={(e) => setTimeEstimate(e.target.value)}
/>
<br />
<label htmlFor="type">Type:</label>
<select
required
name="newtask-type"
id="newtask-type"
value={type}
onChange={(e) => setType(e.target.value)}
>
<option value="">Choose task type</option>
<option>Work related</option>
<option>Hobby</option>
<option>Sports</option>
</select>
<br />
<div className="form-buttons">
{" "}
<button
onClick={() => {
console.log(title, description, timeEstimate, type);
}}
type="submit"
>
Add Task
</button>
<button
type="button"
className="randomise-btn"
onClick={() => {
setRandomise(!randomise);
setTitle(fetchedData.activity);
}}
>
Randomise
</button>
<button
onClick={() => {
setTitle("");
setDescription("");
setTimeEstimate("");
setType("");
}}
>
Clear form
</button>
</div>
</form>
</div>
);
}
|
<template>
<div>
<section>
<div class="outer-container animate__animated animate__fadeIn ">
<Back />
<article>
<section>
<b-row class="imagen__section">
<b-col
v-for="post_skin_care in post_skin_cares"
:key="post_skin_care.id"
v-bind:post="post_skin_care"
cols="12"
md="6"
lg="4"
sm="12"
>
<the-ordinary-widget
:post_skin_care="post_skin_care"
></the-ordinary-widget>
</b-col>
</b-row>
</section>
</article>
</div>
</section>
</div>
</template>
<script>
import SlicesBlock from "~/components//SlicesBlock.vue";
const TheOrdinaryWidget = () =>
import("~/components/skin-care/TheOrdinaryWidget.vue");
export default {
components: {
TheOrdinaryWidget
},
data() {
return {
title: "Falda"
};
},
head() {
return {
title: this.title,
}
},
async asyncData({ $prismic, error }) {
try {
// Query to get posts content to preview
const PostscPosts = await $prismic.api.query(
$prismic.predicates.at("document.type", "post_skin_care"),
{ orderings: "[my.post_skin_care.date desc]" }
);
// Returns data to be used in template
return {
post_skin_cares: PostscPosts.results
};
} catch (e) {
// Returns error page
error({ statusCode: 404, message: "Page not found" });
}
}
};
</script>
|
#pragma once
#include <vcs/object/hashid.h>
#include <vcs/object/object.h>
#include <optional>
#include <string_view>
namespace Vcs {
class ReferenceResolver {
public:
virtual ~ReferenceResolver() = default;
/**
* Parses an reference specification.
*
* @param ref refspec to parse.
* @return ** std::optional<HashId>
*/
std::optional<HashId> Resolve(const std::string_view ref) const;
protected:
/**
* Gets nth ancestor of a commit.
*
* @param id id of the commit object.
*/
virtual std::optional<HashId> DoGetNthAncestor(const HashId& id, const uint64_t n) const = 0;
/**
* Gets nth parent of a commit.
*
* @param id id of the commit object.
* @param n position of a parent (1-based).
*/
virtual std::optional<HashId> DoGetNthParent(const HashId& id, const uint64_t n) const = 0;
/** Lookups object by name. */
virtual std::optional<HashId> DoLookup(const std::string_view name) const = 0;
};
} // namespace Vcs
|
import { NgModule, Component } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { VideoDetailsComponent } from '../videos/video-details/video-details.component';
import { AppComponent } from './app.component';
import { VideoListComponent } from '../videos/video-list/video-list.component';
import { EditDetailsComponent } from '../videos/video-details/edit-details.component';
import { LoginPageComponent } from '../login/login-page.component';
import { RegisterPageComponent } from '../register/register-page.component';
const routes: Routes = [
{ path : 'video-details/:title/:channel', component : VideoDetailsComponent},
{ path : '', component : VideoListComponent},
{ path : 'edit-details/:title/:channel', component : EditDetailsComponent},
{ path : 'login', component : LoginPageComponent },
{ path : 'register', component : RegisterPageComponent },
{ path : '**' , redirectTo : '', pathMatch : 'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.core.validators import MinValueValidator, MaxValueValidator
# Create your models here.
class Country(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return f"{self.name}"
class Meta:
verbose_name_plural = "Countries"
class Address(models.Model):
street = models.CharField(max_length=50)
city = models.CharField(max_length=50)
def __str__(self):
return f"{self.street}, {self.city}"
class Meta:
verbose_name_plural = "Addresses"
class Author(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
address = models.OneToOneField(Address, on_delete=models.CASCADE, null=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
# book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="authors")
class Book(models.Model):
title = models.CharField(max_length=50)
rating = models.IntegerField(
validators=[MinValueValidator(1), MaxValueValidator(5)])
# author = models.CharField(max_length=50, default="unknown")
author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, related_name="books")
is_bestselling = models.BooleanField(default=False)
slug = models.SlugField(default="", null=False, db_index=True)
published_countries = models.ManyToManyField(Country, related_name="books", blank=True)
def get_absolute_url(self):
return reverse("book_detail", args=[self.slug])
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
def __str__(self):
return f"title: {self.title}, rating: {self.rating}"
|
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:rtser/page-1/main-page.dart';
import 'historyPlayAudio.dart';
import 'login-page.dart';
import 'profile.dart';
import 'record.dart';
class HistoryPage extends StatefulWidget {
@override
State<HistoryPage> createState() => _HistoryPageState();
}
class _HistoryPageState extends State<HistoryPage> {
bool isDone = false;
int _currentIndex = 2;
bool isPlaying = false;
bool showSelectableDot = false;
List<Map<String, dynamic>> historyData = [];
@override
void initState() {
super.initState();
fetchHistoryData();
}
Future<void> fetchHistoryData() async {
// Get the current user
User? user = FirebaseAuth.instance.currentUser;
if (user != null) {
DatabaseReference historyRef = FirebaseDatabase.instance
.reference()
.child('audio_files')
.child(user.uid);
try {
DataSnapshot snapshot =
await historyRef.once().then((event) => event.snapshot);
if (snapshot.value != null) {
// Extract data from snapshot
Map<dynamic, dynamic>? data =
snapshot.value as Map<dynamic, dynamic>?;
// Convert map to list of maps
List<Map<String, dynamic>> dataList = [];
data!.forEach((key, value) {
// Format the date
DateTime date = DateTime.parse(value['date']);
String formattedDate =
"${date.day.toString().padLeft(2, '0')}-${date.month.toString().padLeft(2, '0')}-${date.year}";
// Convert list_emotion to List<String>
List<String> listEmotion = [];
if (value['list_emotion'] != null) {
value['list_emotion'].forEach((emotion) {
listEmotion.add(emotion);
});
}
dataList.add({
...value,
'fileName': key,
'formattedDate': formattedDate, // Add formatted date
'isSelected': false, // Initialize isSelected to false
'list_emotion': listEmotion, // Add list_emotion field
});
});
// Print the fetched data
print("Fetched history data: $dataList");
// Update state with history data
setState(() {
historyData = dataList;
});
}
} catch (error) {
// Handle any potential errors
print("Error fetching history data: $error");
}
}
}
@override
Widget build(BuildContext context) {
double baseWidth = 360;
double fem = MediaQuery.of(context).size.width / baseWidth;
double ffem = fem * 0.97;
return Scaffold(
backgroundColor: Color(0xff06030b),
body: Padding(
padding: EdgeInsets.fromLTRB(17 * fem, 41 * fem, 0 * fem, 0 * fem),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.fromLTRB(
0 * fem,
0 * fem,
0 * fem,
3 * fem,
),
width: double.infinity,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
GestureDetector(
onTap: () {
Navigator.of(context).pop();
},
child: Container(
margin: EdgeInsets.fromLTRB(
0 * fem,
0 * fem,
70 * fem,
0.68 * fem,
),
width: 21.88 * fem,
height: 21.32 * fem,
child: Icon(
Icons.arrow_back,
size: 21.88 * fem,
color: Colors.blueAccent,
),
),
),
Container(
margin: EdgeInsets.fromLTRB(
40 * fem,
0 * fem,
70 * fem,
0 * fem,
),
child: RichText(
text: TextSpan(
text: 'History',
style: TextStyle(
fontSize: 25 * ffem,
fontWeight: FontWeight.w800,
color: Colors.blueAccent,
),
),
),
),
Container(
child: PopupMenuButton<int>(
itemBuilder: (context) => [
const PopupMenuItem(
value: 1,
child: ListTile(
leading: Icon(Icons.person),
title: Text('Profile'),
),
),
const PopupMenuItem(
value: 2,
child: ListTile(
leading: Icon(Icons.logout),
title: Text('Logout'),
),
),
],
onSelected: (value) {
switch (value) {
case 1:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfilePage(),
),
);
break;
case 2:
FirebaseAuth.instance.signOut();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => loginPage(),
),
);
break;
}
},
child: Icon(
Icons.account_circle,
size: 40 * fem,
color: Colors.white,
),
),
),
],
),
),
],
),
),
GestureDetector(
// Inside the "Done" button onTap handler:
onTap: () async {
if (isDone) {
// Get the current user
User? user = FirebaseAuth.instance.currentUser;
if (user != null) {
DatabaseReference historyRef = FirebaseDatabase.instance
.reference()
.child('audio_files')
.child(user.uid);
// Remove selected items from Firebase
for (var item in historyData) {
if (item['isSelected']) {
try {
await historyRef.child(item['fileName']).remove();
} catch (error) {
print("Error removing item from Firebase: $error");
}
}
}
}
setState(() {
// Remove selected items locally
historyData.removeWhere((item) => item['isSelected']);
// Reset selection
historyData.forEach((item) {
item['isSelected'] = false;
});
// Toggle "Done" state
isDone = !isDone;
});
} else {
// Toggle "Done" state
setState(() {
isDone = !isDone;
});
}
},
child: Container(
margin: EdgeInsets.fromLTRB(
270 * fem,
20 * fem,
0 * fem,
0 * fem,
),
width: 70 * fem,
height: 30 * fem,
child: isDone
? Container(
decoration: BoxDecoration(
color: Color(0xff407bff),
borderRadius: BorderRadius.circular(5 * fem),
),
child: Center(
child: Text(
'Done',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16 * ffem,
fontWeight: FontWeight.w600,
color: Color(0xffffffff),
),
),
),
)
: Icon(
Icons.delete,
size: 30 * fem,
color: Colors.white,
),
),
),
Container(
margin: EdgeInsets.fromLTRB(
0 * fem,
0 * fem,
14 * fem,
5 * fem,
),
padding: EdgeInsets.fromLTRB(
5 * fem,
0 * fem,
6 * fem,
15 * fem,
),
width: double.infinity,
height: 500 * fem,
child: ListView.builder(
itemCount: historyData.length,
itemBuilder: (context, index) {
var item = historyData[index];
return Container(
margin: EdgeInsets.only(bottom: 10 * fem),
padding: EdgeInsets.fromLTRB(
15 * fem,
6 * fem,
7 * fem,
5 * fem,
),
height: 70 * fem,
decoration: BoxDecoration(
color: Color(0xffffffff),
borderRadius: BorderRadius.circular(10 * fem),
boxShadow: [
BoxShadow(
color: Color(0x3f000000),
offset: Offset(2 * fem, 2 * fem),
blurRadius: 1 * fem,
),
],
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.only(right: 15 * fem),
width: 42 * fem,
height: 42 * fem,
child: Text(
getEmojiForEmotion(item['emotion']),
style: TextStyle(fontSize: 32),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RichText(
text: TextSpan(
text: item['fileName'],
style: TextStyle(
fontSize: 11 * ffem,
fontWeight: FontWeight.w600,
color: Color(0xff000000),
),
),
),
SizedBox(height: 2 * fem),
RichText(
text: TextSpan(
text: item['emotion'],
style: TextStyle(
fontSize: 10 * ffem,
fontWeight: FontWeight.w300,
color: Color(0xb2000000),
),
),
),
SizedBox(height: 2 * fem),
RichText(
text: TextSpan(
text: item['formattedDate'],
style: TextStyle(
fontSize: 10 * ffem,
fontWeight: FontWeight.w300,
color: Color(0xb2000000),
),
),
),
SizedBox(height: 2 * fem),
RichText(
text: TextSpan(
text: formatDuration(item['duration']),
style: TextStyle(
fontSize: 10 * ffem,
fontWeight: FontWeight.w300,
color: Color(0xb2000000),
),
),
),
],
),
),
Container(
margin: EdgeInsets.fromLTRB(
20 * fem, 0 * fem, 30 * fem, 1 * fem),
child: RichText(
text: TextSpan(
text: 'Score: ' + item['mark'],
style: TextStyle(
fontSize: 14 * ffem,
fontWeight: FontWeight.w600,
color: Color(0xb2000000),
),
),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 4.0),
child: isDone
? GestureDetector(
onTap: () {
setState(() {
item['isSelected'] = !item['isSelected'];
});
},
child: item['isSelected']
? Icon(
Icons.radio_button_checked,
size: 25 * fem,
color: Colors.green,
)
: Icon(
Icons
.radio_button_unchecked, // Changed to radio button icon
size: 25 * ffem,
color: Color(0xff407bff),
),
)
: GestureDetector(
onTap: () {
// Call the method to handle the play button click and pass the filename and predictedEmotions
handlePlayButtonClick(item['fileName'],
item['list_emotion'] ?? []);
},
child: Icon(
Icons.play_arrow,
size: 25 * ffem,
color: Color(0xff407bff),
),
),
),
],
),
);
},
),
)
],
),
),
bottomNavigationBar: Container(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: Colors.grey,
width: 0.1,
),
),
),
child: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
switch (index) {
case 0:
Navigator.push(
context,
MaterialPageRoute(builder: (context) => mainPage()),
);
break;
case 1:
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Record()),
);
break;
case 2:
break;
case 3:
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProfilePage()),
);
break;
}
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.mic),
label: 'SER',
),
BottomNavigationBarItem(
icon: Icon(Icons.history),
label: 'History',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
type: BottomNavigationBarType.fixed,
selectedItemColor: Colors.blue,
unselectedItemColor: Colors.grey,
selectedLabelStyle: TextStyle(color: Colors.blue),
unselectedLabelStyle: TextStyle(color: Colors.grey),
backgroundColor: Colors.white,
elevation: 5,
showSelectedLabels: true,
showUnselectedLabels: true,
selectedFontSize: 14,
unselectedFontSize: 14,
),
),
);
}
void handlePlayButtonClick(String fileName, List<String> predictedEmotions) {
// Transfer data to the historyPlayAudio page
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => historyPlayAudio(
fileName: fileName,
predictedEmotions: predictedEmotions,
),
),
);
}
String getEmojiForEmotion(String emotion) {
switch (emotion.toLowerCase()) {
case 'negative':
return '😞';
case 'positive':
return '😊';
default:
return '';
}
}
String formatDuration(String durationString) {
double seconds = double.tryParse(durationString) ?? 0.0;
int hours = (seconds / 3600).floor();
int minutes = ((seconds % 3600) / 60).floor();
int remainingSeconds = (seconds % 60).round();
String hoursString = (hours < 10) ? '0$hours' : '$hours';
String minutesString = (minutes < 10) ? '0$minutes' : '$minutes';
String secondsString =
(remainingSeconds < 10) ? '0$remainingSeconds' : '$remainingSeconds';
return '$hoursString:$minutesString:$secondsString';
}
}
|
<script lang="ts">
import { page } from '$app/stores';
import { Err, Loading } from '$components/generic';
import { CourseContent, CourseMenu } from '$components/pages/course';
import { GetAllCourseAssets, GetCourseFromParams, UpdateAsset } from '$lib/api';
import type { Asset, Course, CourseChapters } from '$lib/types/models';
import { BuildChapterStructure, IsBrowser, UpdateQueryParam } from '$lib/utils';
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
// ----------------------
// Variables
// ----------------------
// Used during the #await. It is initially set to a promise that never resolves to prevent
// the page from rendering before the course is fetched, which occurs during onMount. This
// is because the site is pre-rendered and as such we can only get the search params after
// the page is mounted
let coursePromise: Promise<Course> = new Promise(() => {});
let pageParams: URLSearchParams;
// Hold the assets + attachments for this course
let assets: Asset[];
// Holds the course assets in a chapter structure. Populated when getCourse is called in
// onMount
let chapters: CourseChapters = {};
// When an asset is selected, these will be populated
let selectedAsset: Asset | null = null;
let prevAsset: Asset | null = null;
let nextAsset: Asset | null = null;
// ----------------------
// Functions
// ----------------------
// Lookup the course based on the `id` query param. Then build a chapter structure from the assets
// and attachment
//
// If the `a` query param is not set, find the first unfinished asset and set the `a` query param,
// triggering a reactive statement, which sets the selected asset
async function getCourse(): Promise<Course> {
if (!IsBrowser) return {} as Course;
try {
const course = await GetCourseFromParams(pageParams);
if (!course) throw new Error('Course not found');
// Get the assets
assets = await GetAllCourseAssets(course.id, {
orderBy: 'chapter asc, prefix asc',
expand: true
});
if (!assets) throw new Error('Failed to get course assets');
chapters = BuildChapterStructure(assets);
// If no asset was found in the query params, find the first unfinished asset and
// update the query params. This will trigger the reactive statement that will find
// and set the selected asset
if (!pageParams || !pageParams.get('a')) {
const found = findFirstUnfinishedAsset(course, chapters);
if (found) {
UpdateQueryParam('a', found.id, true);
}
}
return course;
} catch (error) {
toast.error(error instanceof Error ? error.message : (error as string));
throw error;
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// As the query param `a` changes, this will be reactively called to
function updateSelectedAsset(id: string) {
selectedAsset = findAsset(id, chapters);
if (!selectedAsset) return;
// Set the previous and next assets
const { prev, next } = findAdjacentAssets(selectedAsset, chapters);
prevAsset = prev;
nextAsset = next;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Finds the first asset that is not finished, or if the course is completed, find the first
// asset
function findFirstUnfinishedAsset(course: Course, chapters: CourseChapters): Asset | null {
for (const chapterKey in chapters) {
const chapterAssets = chapters[chapterKey];
// Find the first asset in the current chapter that's not completed
for (const asset of chapterAssets) {
// When the course has been completed, return the first asset regardless of whether it
// is finished or not
if (course.percent === 100) return asset;
// If the asset is not completed, return it
if (!asset.completed) return asset;
}
}
// There are no assets within this course
return null;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// When the asset is a video, this will be called as the video is played and the time
// progresses. The data is stored in the backend and used when the asset is reloaded
async function updateAsset(asset: Asset) {
if (!assets) return;
try {
await UpdateAsset(asset);
} catch (error) {
toast.error(error instanceof Error ? error.message : (error as string));
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Find an asset by id
function findAsset(id: string, chapters: CourseChapters): Asset | null {
const allAssets = Object.values(chapters).flat();
const index = allAssets.findIndex((a) => a.id === id);
if (index === -1) return null;
return allAssets[index];
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Find the previous and next assets within chapters based upon a current asset. This is used
// when a video is finished to determine which asset to play next. It is also passed to the
// video player to generate the previous and next buttons
function findAdjacentAssets(
currentAsset: Asset,
chapters: CourseChapters
): { prev: Asset | null; next: Asset | null } {
// Flatten the assets and find the index of the current asset
const allAssets = Object.values(chapters).flat();
const index = allAssets.findIndex((a) => a.id === currentAsset.id);
// Determine the previous and next assets based on the index
const prevAsset = index > 0 ? allAssets[index - 1] : null;
const nextAsset = index < allAssets.length - 1 ? allAssets[index + 1] : null;
return { prev: prevAsset, next: nextAsset };
}
// ----------------------
// Reactive
// ----------------------
// When the query param `a` changes, update the selected asset
$: {
if (IsBrowser) {
const assetId = $page.url.searchParams.get('a');
if (assetId && chapters && selectedAsset?.id !== assetId) {
updateSelectedAsset(assetId);
}
}
}
// ----------------------
// Lifecycle
// ----------------------
// Due to the site being pre-rendered, we need to wait for the page to be mounted before we
// can get the search params
onMount(() => {
pageParams = $page.url.searchParams;
coursePromise = getCourse();
});
</script>
<div class="flex w-full flex-col">
{#await coursePromise}
<Loading />
{:then data}
<div class="flex h-full flex-col lg:container lg:flex-row lg:gap-10">
<CourseMenu title={data.title} id={data.id} {chapters} {selectedAsset} />
<CourseContent
{selectedAsset}
{prevAsset}
{nextAsset}
on:update={() => {
if (!selectedAsset) return;
updateAsset(selectedAsset);
chapters = { ...chapters };
}}
/>
</div>
{:catch error}
<Err errorMessage={error} />
{/await}
</div>
|
<template>
<section class="main-guest-section">
<SideBar @updateValue="updateValueFromHeader"></SideBar>
<section :class="valueFromHeader ? 'sidebar-section' : 'sidebar-section1' ">
<GuestHeader @sendValue="updateValueFromHeader"></GuestHeader>
<CategoryList></CategoryList>
<div style="height: 160px; display: flex;
align-items: center;">
<div class="story-list">
<ul>
<li class="story-item active">
<img src="@assets/featured-athlete/user.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/userstory.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/user.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/userstory.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/user.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/userstory.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/user.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/userstory.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/user.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/userstory.png" alt="" />
</li>
<li class="story-item active">
<img src="@assets/featured-athlete/user.png" alt="" />
</li>
</ul>
</div>
</div>
<!-- <Slider></Slider> -->
<div style="position: relative;">
<div class="video-container" style="height: 20%; border: 1px solid grey;width: 90%; margin-left: 50px;">
<video ref="videoPlayer" class="video" @click="togglePlay">
<source :src="require('@/assets/video.mp4')" type="video/mp4" />
Your browser does not support the video tag.
</video>
</div>
<!-- <router-link :to="{ name: 'video-detail/' + item.id } "> -->
<div class="main-box-videos">
<h2>Bronze To Radiant In One Stream! 🔥</h2>
<div class="btn-tagss">
<button>FPS</button>
<button>Gaming</button>
<button>Shooter</button>
</div>
<div class="main-videos-profile-flex">
<img class="video-profile-img" src="@assets/Profile-1.png" />
<p class="video-profile-name">Shroud</p>
</div>
</div>
<!-- </router-link> -->
</div>
<!-- -->
<div>
<div class="guest-page-navigation-tatle">
<h1>LIVE Videos</h1>
<!-- <button>See All</button> -->
</div>
<div class="main-videos-box">
<div v-for="room in roomsData" :key="room" class="main-video-box">
<div class="video-image-box">
<span>Live</span><!-- Bind the image URL dynamically -->
<router-link :to="{ name: 'live-video', params: { id: room } }">
<img src="https://costacaster-backend.instantsolutionslab.site/video/images/17115684415417.png" alt="Video Thumbnail">
</router-link>
</div>
<div class="main-box-video">
<h2>taha video</h2>
<div class="main-video-profile-flex">
<img class="video-profile-img" src="https://picsum.photos/200/300" alt="Profile Image">
<p class="video-profile-name">taha huhu</p>
</div>
</div>
</div>
</div>
</div>
<!-- -->
<TopVideos></TopVideos>
<RecentVideos></RecentVideos>
</section>
</section>
<Footer></Footer>
</template>
<script>
import CategoryList from '@components/globals/costacaster/CategoryList.vue';
import RecentVideos from '@components/globals/costacaster/RecentVideos.vue';
import TopVideos from '@components/globals/costacaster/TopVideos.vue';
import GuestHeader from '@components/globals/guest/GuestHeader.vue';
import SideBar from '@components/globals/costacaster/SideBar.vue';
import { ref } from 'vue';
import Slider from '@components/globals/costacaster/Slider.vue';
import Footer from '@components/globals/costacaster/Footer.vue';
import VueRouter from 'vue-router';
import { postData, fetchData } from '@services/base.js';
import io from 'socket.io-client';
export default {
components: {
GuestHeader,
SideBar,
CategoryList,
Slider,
Footer,
RecentVideos,
TopVideos,
},
data() {
return {
valueFromHeader: true,
seekingDisabled: false,
isPlaying: false,
response: {},
videos: [],
roomsData: [], // Array to store room IDs
}
},
mounted() {
// Fetch videos when the component is mounted
this.fetchVideos();
// Connect to socket.io server
this.socket = io('http://localhost:5000');
this.socket.on('connect', () => {
console.log('Connected to Socket.IO server');
});
// Call a method to fetch room IDs when the component is mounted
this.fetchRoomsData();
},
methods: {
leaderBoard() {
this.$router.push({ name: 'leader-board' })
},
fetchRoomsData() {
// Emit an event to request room IDs from the server
this.socket.on('rooms-data', (rooms) => {
// Update roomsData with the received room IDs
console.log('rooms are ',rooms);
this.roomsData = rooms;
});
},
getVideoThumbnail(room) {
// Replace this with the actual URL of the video thumbnail for the room ID
// This is just a placeholder
return 'https://example.com/thumbnails/' + room + '.jpg';
},
getVideoLink(room) {
// Replace this with the actual URL of the video for the room ID
// This is just a placeholder
return 'https://example.com/video/' + room;
},
async fetchVideos() {
const endpoint = '/list-videos?limit=3';
this.response = await fetchData(endpoint);
this.videos = this.response.data?.data;
console.log(this.videos);
},
handleImageError(event) {
console.error('Error loading image:', event.target.src);
// You can also set a default image or take other actions
},
updateValueFromHeader(value) {
// Update the value in the parent component
this.valueFromHeader = value;
// console.log(this.valueFromHeader, "this is value ");
},
togglePlay() {
const video = this.$refs.videoPlayer;
if (this.isPlaying) {
video.pause();
} else {
video.play();
}
this.isPlaying = !this.isPlaying;
},
handleTimeUpdate() {
if (this.seekingDisabled) {
// Prevent seeking by setting currentTime back to 0
this.$refs.videoPlayer.currentTime = 0;
this.seekingDisabled = false; // Reset seekingDisabled
}
},
},
// setup() {
// const valueFromHeader = ref('');
// function sendValueToSidebar(value) {
// valueFromHeader.value = value;
// }
// return {
// valueFromHeader,
// sendValueToSidebar,
// };
// },
openLink() {
alert("");
const link = "http://learn.shayhowe.com/assets/misc/courses/html-css/adding-media/earth.mp4"; // Replace with your desired URL
window.open(link, "_blank"); // Opens the link in a new tab or window
},
}
</script>
|
import time
import os
os.environ['HF_HOME'] = '/data/users/wplacroix/.cache/'
os.environ["TOKENIZERS_PARALLELISM"] = "false"
#os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:512"
from transformers import AutoModelForCausalLM, DataCollatorWithPadding, AutoTokenizer, BitsAndBytesConfig
import torch
from huggingface_hub import login
import numpy as np
from datasets import Dataset
from torch.utils.data import DataLoader
import torch.nn as nn
import pandas as pd
from sklearn.metrics import accuracy_score, confusion_matrix
from tqdm import tqdm
from itertools import product
import sys
class MLP(torch.nn.Module):
def __init__(self, language_model, frozen_or_not):
super(MLP, self).__init__()
self.name = "MLP"
if language_model == "bert-base-uncased":
self.lm = AutoModelForCausalLM.from_pretrained(language_model, quantization_config=bnb_config).bfloat16()
else:
self.lm = AutoModelForCausalLM.from_pretrained(language_model, quantization_config=bnb_config, device_map='auto').bfloat16()
if frozen_or_not == True:
for param in self.lm.parameters():
param.requires_grad = False
self.lm_out_size = self.lm.config.hidden_size
self.hidden_size = 50
#self.dropout = torch.nn.Dropout(0.3)
self.activation = torch.nn.LeakyReLU()
self.reducer = torch.nn.Linear(self.lm_out_size+1, self.hidden_size, dtype=bnb_config.bnb_4bit_compute_dtype)
self.classifier = torch.nn.Linear(self.hidden_size+3, number_of_labels, dtype=bnb_config.bnb_4bit_compute_dtype)
def forward(self, input_ids, attention_mask, sentiment):
# lm_out is the foundation of the model output, while hidden_states[-1] gives us word embeddings
# we do mean pooling to get a single consistently sized vector for the entire sequence
"""
# TODO : move lm_out and self.lm outside of class declaration
"""
lm_out = self.lm(input_ids, attention_mask, output_hidden_states=True, labels=input_ids)
outputs = lm_out.hidden_states[-1]
# calculates perplexity as mean subword suprisal from LM output logits
logits = torch.nn.functional.softmax(lm_out.logits, dim=-1).detach()
probs = torch.gather(logits, dim=2, index=input_ids.unsqueeze(dim=2)).squeeze(-1)
subword_surp = -1 * torch.log2(probs) * attention_mask
outputs = torch.cat((outputs,
subword_surp.unsqueeze(-1)
), dim=-1).to(dtype=bnb_config.bnb_4bit_compute_dtype)
outputs = torch.mean(outputs, dim=1)
#mean_surprisal = subword_surp.sum(dim=1) / attention_mask.sum(dim=1)
# bring LM output size down so that it doesn't outweigh the additional features
outputs = self.reducer(outputs)
outputs = self.activation(outputs)
#outputs = self.dropout(outputs)
# concatenate mean-pooled LM output with the additional features
outputs = torch.cat((outputs,
sentiment,
),
dim=1).to(bnb_config.bnb_4bit_compute_dtype)
# final prediction is reduced to len(class_labels)
return self.classifier(outputs)
class CNN(nn.Module):
def __init__(self, language_model, frozen_or_not):
super(CNN, self).__init__()
self.name = "CNN"
if language_model == "bert-base-uncased":
self.lm = AutoModelForCausalLM.from_pretrained(language_model, quantization_config=bnb_config).bfloat16()
else:
self.lm = AutoModelForCausalLM.from_pretrained(language_model, quantization_config=bnb_config, device_map='auto').bfloat16()
if frozen_or_not == True:
for param in self.lm.parameters():
param.requires_grad = False
self.lm_out_size = self.lm.config.hidden_size
# keep the rest
self.out_channels = 128
self.kernel_size = 5
self.in_channels = self.lm_out_size + 1 # word embeddings + 1 for surprisal value
self.conv1 = nn.Conv1d(in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=5, padding=2)
self.relu = nn.ReLU()
self.pool = nn.MaxPool1d(kernel_size=self.kernel_size)
# Calculate the size after conv and pooling
sequence_length = max_sequence_length # Adjusted based on the input shape
conv_seq_length = sequence_length # kernel_size - 1 for Conv1d
pooled_seq_length = conv_seq_length // self.kernel_size # assuming default stride for MaxPool1d
self.flattened_size = self.out_channels * pooled_seq_length + 3
self.fc1 = nn.Linear(self.flattened_size, number_of_labels, dtype=bnb_config.bnb_4bit_compute_dtype)
self.dropout = nn.Dropout(0.9)
def forward(self, input_ids, attention_mask, sentiment):
lm_out = self.lm(input_ids, attention_mask, output_hidden_states=True, labels=input_ids)
outputs = lm_out.hidden_states[-1]
logits = torch.nn.functional.softmax(lm_out.logits, dim=-1).detach()
word_probabilities = torch.gather(logits, dim=2, index=input_ids.unsqueeze(dim=2)).squeeze(-1)
subword_surp = -1 * torch.log2(word_probabilities) * attention_mask
outputs = torch.cat((outputs,
subword_surp.unsqueeze(-1)
), dim=-1)
outputs = self.conv1(outputs.permute(0,2,1).to(torch.float))
outputs = self.pool(outputs)
outputs = self.dropout(outputs)
outputs = outputs.view(outputs.size(0), -1)
outputs = torch.cat((outputs,
sentiment,
), dim=-1).to(bnb_config.bnb_4bit_compute_dtype)
outputs = self.relu(outputs)
outputs = self.fc1(outputs)
return outputs
class LSTM(torch.nn.Module):
def __init__(self, language_model, frozen_or_not):
super(LSTM, self).__init__()
self.name = "LSTM"
if language_model == "bert-base-uncased":
self.lm = AutoModelForCausalLM.from_pretrained(language_model, quantization_config=bnb_config).bfloat16()
else:
self.lm = AutoModelForCausalLM.from_pretrained(language_model, quantization_config=bnb_config, device_map='auto').bfloat16()
if frozen_or_not == True:
for param in self.lm.parameters():
param.requires_grad = False
self.lm_out_size = self.lm.config.hidden_size
self.hidden_size = 100
self.lstm = torch.nn.LSTM(self.lm_out_size+1, self.hidden_size, num_layers=1, batch_first=True)
self.activation = torch.nn.LeakyReLU()
self.dropout = torch.nn.Dropout(0.5)
self.classifier = torch.nn.Linear(self.hidden_size+3, number_of_labels, dtype=bnb_config.bnb_4bit_compute_dtype)
def forward(self, input_ids, attention_mask, sentiment):
# lm_out is the foundation of the model output, while hidden_states[-1] gives us word embeddings
# we do mean pooling to get a single consistently sized vector for the entire sequence
lm_out = self.lm(input_ids, attention_mask, output_hidden_states=True, labels=input_ids)
outputs = lm_out.hidden_states[-1]
# calculates perplexity as subword suprisal from LM output logits
logits = torch.nn.functional.softmax(lm_out.logits, dim=-1).detach()
probs = torch.gather(logits, dim=2, index=input_ids.unsqueeze(dim=2)).squeeze(-1)
subword_surp = -1 * torch.log2(probs) * attention_mask
# stack the subword surprisal values onto the word embeddings
outputs = torch.cat((outputs,
subword_surp.unsqueeze(-1)
), dim=-1).to(torch.float)
outputs = self.lstm(outputs)[0][:,-1,:]
outputs = self.dropout(outputs)
# concatenate mean-pooled LM output with the additional features
outputs = torch.cat((outputs,
sentiment,
),
dim=-1).to(bnb_config.bnb_4bit_compute_dtype)
# final prediction is reduced to len(class_labels)
return self.classifier(outputs)
def main(architecture, language_model, frozen_or_not):
TOK_PATH = "/projects/misinfo_sp/.cache/token"
with open(TOK_PATH, "r", encoding="utf8") as f:
token = f.read().strip()
login(token)
batch_size = 16
alpha = 1
global bnb_config
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
tokenizer = AutoTokenizer.from_pretrained(language_model)
if language_model == "bert-base-uncased" or language_model == "meta-llama/Llama-2-7b-hf":
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
if language_model == "meta-llama/Llama-2-7b-hf":
#model.resize_token_embeddings(len(tokenizer))
tokenizer.pad_token = tokenizer.eos_token
def temp_tokenize(data):
return tokenizer(data["statement"])
def find_max_length():
max_sequence_length = 0
for split in ["train", "validation", "test"]:
dataframe = pd.read_pickle(f"/nethome/wplacroix/NN-SoftP/pickle_files/{split}.pkl")
dataset = Dataset.from_pandas(dataframe)
tokenized_dataset = dataset.map(temp_tokenize)
longest = max([len(x["input_ids"]) for x in tokenized_dataset])
if longest > max_sequence_length:
max_sequence_length = longest
return max_sequence_length
global max_sequence_length
max_sequence_length = find_max_length()
data_collator = DataCollatorWithPadding(tokenizer=tokenizer, padding="max_length", max_length=max_sequence_length)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def remap_labels_tokenize(data):
tokens = tokenizer(data["statement"], padding="max_length", max_length=max_sequence_length)
# label_mapping = {
# 0: 0,
# 1: 1,
# 2: 1,
# 3: 1,
# 4: 0,
# 5: 0} # Map positive class labels
# binary_labels = [label_mapping[label] for label in data["label"]]
# tokens["label"] = binary_labels
return tokens
def dataloader_from_pickle(split):
dataframe = pd.read_pickle(f"/nethome/wplacroix/NN-SoftP/pickle_files/{split}.pkl")
dataset = Dataset.from_pandas(dataframe)
tokenized_dataset = dataset.map(remap_labels_tokenize, batch_size=batch_size, batched=True)
global number_of_labels
number_of_labels = len(set(tokenized_dataset["label"]))
tokenized_dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'label', 'sentiment'])
return DataLoader(tokenized_dataset, batch_size=batch_size, shuffle=True, collate_fn=data_collator)
train_dataloader = dataloader_from_pickle("train")
val_dataloader = dataloader_from_pickle("validation")
test_dataloader = dataloader_from_pickle("test")
loss_fn = nn.CrossEntropyLoss()
if architecture == "MLP":
learning_rate = 0.001
model = MLP(language_model, frozen_or_not).to(device)
elif architecture == "CNN":
learning_rate = 0.0001
model = CNN(language_model, frozen_or_not).to(device)
elif architecture == "LSTM":
learning_rate = 0.0001
model = LSTM(language_model, frozen_or_not).to(device)
else:
raise ValueError("Invalid architecture. Please choose from {MLP, CNN, LSTM}.")
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
training_losses = []
training_accuracies = []
validation_losses = []
validation_accuracies = []
max_epochs = 100
best_epoch = 0
max_patience = 10
current_patience = 0
last_loss = 100000
for epoch_number in range(max_epochs):
model.train()
losses = []
predictions = []
targets = []
for batch_number, batch in enumerate(train_dataloader):
batch.to(device)
optimizer.zero_grad()
outputs = model(batch["input_ids"], batch["attention_mask"], batch["sentiment"])
loss = loss_fn(outputs, batch["labels"])
losses.append(loss.item())
loss.backward()
optimizer.step()
predictions.extend(outputs.detach().argmax(dim=1).to("cpu"))
targets.extend(batch["labels"].to("cpu"))
batch.to("cpu")
accuracy = accuracy_score(targets, predictions)*100
loss = np.mean(losses)
training_accuracies.append(accuracy)
training_losses.append(loss)
model.eval()
with torch.no_grad():
losses = []
predictions = []
targets = []
for batch_number, batch in enumerate(val_dataloader):
batch.to(device)
outputs = model(batch["input_ids"], batch["attention_mask"], batch["sentiment"])
loss = loss_fn(outputs, batch["labels"])
losses.append(loss.item())
predictions.extend(outputs.detach().argmax(dim=1).to("cpu"))
targets.extend(batch["labels"].to("cpu"))
accuracy = accuracy_score(targets, predictions)*100
loss = np.mean(losses)
validation_accuracies.append(accuracy)
validation_losses.append(loss)
if loss < last_loss:
last_loss = loss
best_epoch = epoch_number
current_patience = 0
else:
if current_patience == max_patience:
break
elif current_patience == 0:
PATH = f"/nethome/wplacroix/NN-SoftP/wplacroix_runs/model.pt"
torch.save({
'epoch': epoch_number,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': last_loss,
}, PATH)
current_patience += 1
checkpoint = torch.load(PATH)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
model.eval()
with torch.no_grad():
losses = []
predictions = []
targets = []
for batch_number, batch in enumerate(test_dataloader):
batch.to(device)
outputs = model(batch["input_ids"], batch["attention_mask"], batch["sentiment"])
loss = loss_fn(outputs, batch["labels"])
losses.append(loss.item())
predictions.extend(outputs.detach().argmax(dim=1).to("cpu"))
targets.extend(batch["labels"].to("cpu"))
print(f"model stopped improving at epoch {best_epoch}\n\
training losses: {training_losses}\n\
training accuracies: {training_accuracies}\n\
validation losses: {validation_losses}\n\
validation accuracies: {validation_accuracies}\n\
test accuracy: {accuracy_score(targets, predictions)*100}\n\
confusion matrix:\n {confusion_matrix(targets, predictions)}")
return
if __name__ == "__main__":
LM_antialiases = {"llama": "meta-llama/Llama-2-7b-hf",
"gemma": "google/gemma-2b",
"bert": "bert-base-uncased"}
LM_aliases = {"meta-llama/Llama-2-7b-hf": "llama-2-7b",
"google/gemma-2b": "gemma-2b",
"bert-base-uncased": "bert-base-uncased"}
# architectures_to_run = {"MLP", "CNN", "LSTM"}
# LMs_to_run = {"bert-base-uncased", "meta-llama/Llama-2-7b-hf", "google/gemma-2b"}
# to_freeze_or_not_to_freeze = {True, False}
frozen_or_not = False
language_model = "google/gemma-2b"
architecture = "MLP"
if frozen_or_not == True:
frozen = "frozen"
else:
frozen = "fine-tuned"
EXPERIMENT_NAME = f"{frozen}_{LM_aliases[language_model]}_{architecture}"#_{time.time()}"
directory = f"/nethome/wplacroix/NN-SoftP/wplacroix_runs/"
sys.stdout = open(f"{directory}{EXPERIMENT_NAME}.log", 'w')
print(EXPERIMENT_NAME)
seed = 42
torch.manual_seed(seed)
main(architecture, language_model, frozen_or_not)
sys.stdout.close()
|
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from .utils import delete_model
def run_lm_model(model_id: str, caption: str, edit_prompt: str, device: str = "cuda"):
language_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_id)
messages = [
{
"role": "system",
"content": "Follow the examples and return the expected output",
},
{
"role": "user",
"content": "Caption: a blue sky with fluffy clouds\nQuery: Make the sky stormy",
},
{
"role": "assistant",
"content": "A: sky\nB: a stormy sky with heavy gray clouds, torrential rain, gloomy, overcast",
},
{
"role": "user",
"content": "Caption: a cat sleeping on a sofa\nQuery: Change the cat to a dog",
},
{
"role": "assistant",
"content": "A: cat\nB: a dog sleeping on a sofa, cozy and comfortable, snuggled up in a warm blanket, peaceful",
},
{
"role": "user",
"content": "Caption: a snowy mountain peak\nQuery: Replace the snow with greenery",
},
{
"role": "assistant",
"content": "A: snow\nB: a lush green mountain peak in summer, clear blue skies, birds flying overhead, serene and majestic",
},
{
"role": "user",
"content": "Caption: a vintage car parked by the roadside\nQuery: Change the car to a modern electric vehicle",
},
{
"role": "assistant",
"content": "A: car\nB: a sleek modern electric vehicle parked by the roadside, cutting-edge design, environmentally friendly, silent and powerful",
},
{
"role": "user",
"content": "Caption: a wooden bridge over a river\nQuery: Make the bridge stone",
},
{
"role": "assistant",
"content": "A: bridge\nB: an ancient stone bridge over a river, moss-covered, sturdy and timeless, with clear waters flowing beneath",
},
{
"role": "user",
"content": "Caption: a bowl of salad on the table\nQuery: Replace salad with soup",
},
{
"role": "assistant",
"content": "A: bowl\nB: a bowl of steaming hot soup on the table, scrumptious, with garnishing",
},
{
"role": "user",
"content": "Caption: a book on a desk surrounded by stationery\nQuery: Remove all stationery, add a laptop",
},
{
"role": "assistant",
"content": "A: stationery\nB: a book on a desk with a laptop next to it, modern study setup, focused and productive, technology and education combined",
},
{
"role": "user",
"content": "Caption: a cup of coffee on a wooden table\nQuery: Change coffee to tea",
},
{
"role": "assistant",
"content": "A: cup\nB: a steaming cup of tea on a wooden table, calming and aromatic, with a slice of lemon on the side, inviting",
},
{
"role": "user",
"content": "Caption: a small pen on a white table\nQuery: Change the pen to an elaborate fountain pen",
},
{
"role": "assistant",
"content": "A: pen\nB: an elaborate fountain pen on a white table, sleek and elegant, with intricate designs, ready for writing",
},
{
"role": "user",
"content": "Caption: a plain notebook on a desk\nQuery: Replace the notebook with a journal",
},
{
"role": "assistant",
"content": "A: notebook\nB: an artistically decorated journal on a desk, vibrant cover, filled with creativity, inspiring and personalized",
},
{"role": "user", "content": f"Caption: {caption}\nQuery: {edit_prompt}"},
]
text = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(device)
with torch.no_grad():
generated_ids = language_model.generate(
model_inputs.input_ids, max_new_tokens=512, temperature=0.0, do_sample=False
)
generated_ids = [
output_ids[len(input_ids) :]
for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
output_generation = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[
0
]
output_generation_a, output_generation_b = output_generation.split("\n")
to_replace = output_generation_a[2:].strip()
replaced_caption = output_generation_b[2:].strip()
delete_model(language_model)
return to_replace, replaced_caption
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
import django
django.setup()
from rango.models import Category, Page
def populate():
python_pages = [
{'title': 'Official Python Tutorial',
'url':'http://docs.python.org/3/tutorial/','views':89},
{'title':'How to Think like a Computer Scientist',
'url':'http://www.greenteapress.com/thinkpython/','views':65},
{'title':'Learn Python in 10 Minutes',
'url':'http://www.korokithakis.net/tutorials/python/','views':77} ]
django_pages = [
{'title':'Official Django Tutorial',
'url':'https://docs.djangoproject.com/en/2.1/intro/tutorial01/','views':41},
{'title':'Django Rocks',
'url':'http://www.djangorocks.com/','views':10},
{'title':'How to Tango with Django',
'url':'http://www.tangowithdjango.com/','views':50} ]
other_pages = [
{'title':'Bottle',
'url':'http://bottlepy.org/docs/dev/','views':40},
{'title':'Flask',
'url':'http://flask.pocoo.org','views':55}
]
cats = {'Python': {'pages': python_pages,'views':128,'likes':64},
'Django': {'pages': django_pages,'views':64,'likes':32},
'Other Frameworks': {'pages': other_pages,'views':32,'likes':16}}
for cat, cat_data in cats.items():
c = add_cat(cat,views=cat_data['views'], likes=cat_data['likes'])
for p in cat_data['pages']:
add_page(c, p['title'], p['url'], views=p['views'])
for c in Category.objects.all():
for p in Page.objects.filter(category=c):
print(f'- {c}: {p}')
def add_page(cat, title, url, views=0):
p = Page.objects.get_or_create(category=cat, title=title)[0]
p.url=url
p.views=views
p.save()
return p
def add_cat(name,views=0,likes=0):
c = Category.objects.get_or_create(name=name)[0]
c.views=views
c.likes=likes
c.save()
return c
if __name__ == '__main__':
print("Starting Rango population script...")
populate()
|
package demo.com.myapplication.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import demo.com.myapplication.PageFragment;
/**
* Created by leobui on 10/24/2017.
*/
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 6;
private String tabTitles[] = new String[] { "Khuyến mãi", "Điện Thoại Sam Sung", "Điện Thoại Iphone", "Điện thoại Sony", "Điện thoại HTC", "Điện thoại Oppo" };
public SampleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
|
import { createBrowserRouter } from "react-router-dom";
import Layout from "../layout/Layout";
import Home from "../pages/Home/Home"
import Signin from "../pages/Authentication/Signin";
import Signup from "../pages/Authentication/Signup";
import AddItem from "../pages/AdminMenu/AddItem";
import UpdateItem from "../pages/AdminMenu/UpdateItem";
import Error from "../error/Error";
import DashboardMenu from "../pages/AdminMenu/DashboardMenu";
import DashViewDetails from "../pages/AdminMenu/DashViewDetails";
import HomeViewDetails from "../pages/Home/HomeViewDetails";
import Menu from "../pages/Menu/Menu";
const router = createBrowserRouter([
{
path: "/",
element: <Layout/>,
errorElement: <Error/>,
children: [
// Website Home
{
path: '/',
element: <Home/>
},
{
path: '/viewhomedetails/:id',
element: <HomeViewDetails/>,
loader: ({params}) => fetch(`http://localhost:4000/items/${params.id}`)
},
// Website Menu
{
path: '/menu',
element: <Menu/>,
loader: () => fetch('http://localhost:4000/items')
},
// Authentication
{
path: '/signin',
element: <Signin/>
},
{
path: '/signup',
element: <Signup/>
},
// Admin Menu Item
{
path: '/dashboardmenu',
element: <DashboardMenu/>
},
{
path: '/viewdetails/:id',
element: <DashViewDetails/>,
loader: ({params}) => fetch(`http://localhost:4000/items/${params.id}`)
},
{
path: '/addform',
element: <AddItem/>
},
{
path: '/updateform/:id',
element: <UpdateItem/>,
loader: ({params}) => fetch(`http://localhost:4000/items/${params.id}`)
}
]
},
]);
export default router
|
<script>
import KerryButton from "./KerryButton.svelte";
import { scale, fly } from 'svelte/transition';
import { quintOut } from "svelte/easing";
const flyDuration = 200;
export let title = "Dialog Title";
export let text = "This is a load of text for this modal dialog. Set the {text} prop to customise";
export let dismissText = "Dismiss";
export let show = true;
export let startCoords;
let flyValues = [
{x:-200, y:-50},
{x: 200, y: 45},
{x: 45, y: 145},
{x: 300, y: -45}
];
let flyConfig = () => {
if(startCoords) {
let offsetCoords = {
x: ((window.innerWidth / 2) - startCoords.x) * -1,
y: ((window.innerHeight / 2) - startCoords.y) * -1,
duration: flyDuration
}
console.log(offsetCoords);
return offsetCoords;
}
let randValue = Math.floor(Math.random() * flyValues.length);
return {
x: flyValues[randValue].x,
y: flyValues[randValue].y,
duration: flyDuration
}
};
let handleDismiss = (e) => {
show = false;
};
</script>
<!-- <div class="modal-capture" on:click={handleDismiss}>
<div in:fly="{flyConfig()}" out:fly="{flyConfig()}" class="dialog-container">
<header class="dialog-header">
{title}
</header>
<section class="dialog-body">
<p class="body-text">{text}</p>
</section>
<section class="buttons-row">
<span class="dialog-buttons">
<KerryButton value={dismissText} cssClass="success" on:click={handleDismiss}/>
</span>
</section>
</div>
</div> -->
{#if show}
<div transition:fly="{flyConfig()}" class="modal-capture" on:click={handleDismiss}>
<div class="dialog-container">
<span class="inline-block h-screen align-middle" aria-hidden="true">
​
</span>
<div on:click|stopPropagation={e => {}} transition:scale="{{delay: 0, duration: 500, easing: quintOut}}" class="inline-block w-full max-w-md p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white shadow-xl rounded-2xl">
<div transition:scale="{{delay: 150, duration: 300, easing: quintOut}}" class="">
<header class="dialog-header">
{title}
</header>
<section class="dialog-body">
<p class="body-text">{text}</p>
</section>
<section class="buttons-row">
<span class="dialog-buttons">
<KerryButton value={dismissText} cssClass="success" on:click={handleDismiss}/>
</span>
</section>
</div>
</div>
</div>
</div>
{/if}
<style windi:preflights windi:safelist>
.modal-capture {
@apply fixed inset-0 z-10 overflow-y-auto;
}
.dialog-container { @apply
min-h-screen px-4 text-center;
}
.dialog-header { @apply
w-full
text-3xl font-medium leading-6 text-gray-900;
}
.dialog-body { @apply
my-4
w-full;
}
.body-text { @apply
text-size-md text-gray-500;
}
.buttons-row { @apply
w-full;
}
.dialog-buttons{ @apply
float-right;
}
</style>
|
/*
* Copyright (C) 2022 Expedia, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.sdk.core.configuration.collector
import com.expediagroup.sdk.core.configuration.provider.ExpediaGroupConfigurationProvider
import com.expediagroup.sdk.core.configuration.provider.RuntimeConfigurationProvider
import com.expediagroup.sdk.core.constant.Constant.EMPTY_STRING
import com.expediagroup.sdk.core.test.TestConstants.CLIENT_KEY_TEST_CREDENTIAL
import com.expediagroup.sdk.core.test.TestConstants.CLIENT_SECRET_TEST_CREDENTIAL
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class ConfigurationProviderQueueTest {
@Test
fun `test a provider queue with only a default provider`() {
val configurationProviderQueue = ConfigurationProviderQueue.from(listOf(ExpediaGroupConfigurationProvider))
assertEquals(ProvidedConfiguration(EMPTY_STRING, ExpediaGroupConfigurationProvider.name), configurationProviderQueue.firstWith { it.key })
assertEquals(ProvidedConfiguration(EMPTY_STRING, ExpediaGroupConfigurationProvider.name), configurationProviderQueue.firstWith { it.secret })
assertEquals(ProvidedConfiguration(ExpediaGroupConfigurationProvider.endpoint, ExpediaGroupConfigurationProvider.name), configurationProviderQueue.firstWith { it.endpoint })
assertEquals(ProvidedConfiguration(ExpediaGroupConfigurationProvider.authEndpoint, ExpediaGroupConfigurationProvider.name), configurationProviderQueue.firstWith { it.authEndpoint })
assertEquals(ProvidedConfiguration(ExpediaGroupConfigurationProvider.requestTimeout, ExpediaGroupConfigurationProvider.name), configurationProviderQueue.firstWith { it.requestTimeout })
}
@Test
fun `test a provider queue with at least a non-empty provider`() {
val runtimeConfigurationProvider =
RuntimeConfigurationProvider(
key = CLIENT_KEY_TEST_CREDENTIAL,
secret = CLIENT_SECRET_TEST_CREDENTIAL,
endpoint = ExpediaGroupConfigurationProvider.endpoint,
authEndpoint = ExpediaGroupConfigurationProvider.authEndpoint,
requestTimeout = ExpediaGroupConfigurationProvider.requestTimeout
)
val configurationProviderQueue =
ConfigurationProviderQueue.from(
listOf(runtimeConfigurationProvider)
)
assertEquals(runtimeConfigurationProvider, configurationProviderQueue.first())
assertEquals(runtimeConfigurationProvider, configurationProviderQueue.first { it.key != null })
assertEquals(runtimeConfigurationProvider, configurationProviderQueue.first { it.key != EMPTY_STRING })
assertEquals(ProvidedConfiguration(CLIENT_KEY_TEST_CREDENTIAL, runtimeConfigurationProvider.name), configurationProviderQueue.firstWith { it.key })
assertEquals(ProvidedConfiguration(CLIENT_SECRET_TEST_CREDENTIAL, runtimeConfigurationProvider.name), configurationProviderQueue.firstWith { it.secret })
assertEquals(ProvidedConfiguration(ExpediaGroupConfigurationProvider.endpoint, runtimeConfigurationProvider.name), configurationProviderQueue.firstWith { it.endpoint })
assertEquals(ProvidedConfiguration(ExpediaGroupConfigurationProvider.authEndpoint, runtimeConfigurationProvider.name), configurationProviderQueue.firstWith { it.authEndpoint })
assertEquals(ProvidedConfiguration(ExpediaGroupConfigurationProvider.requestTimeout, runtimeConfigurationProvider.name), configurationProviderQueue.firstWith { it.requestTimeout })
}
}
|
package com.example.orderservice.controller;
import com.example.basedomains.dto.Order;
import com.example.basedomains.dto.OrderEvent;
import com.example.orderservice.kafka.OrderKafkaProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
@RestController
@RequestMapping("/api/v1")
public class OrderController {
private OrderKafkaProducer orderKafkaProducer;
@Autowired
public OrderController(OrderKafkaProducer orderKafkaProducer){
this.orderKafkaProducer = orderKafkaProducer;
}
//http://localhost:8080/api/v1/orders
@PostMapping("/orders")
public String placeOrder(@RequestBody Order order){
order.setOrderId(UUID.randomUUID().toString());
OrderEvent orderEvent = new OrderEvent();
orderEvent.setStatus("PENDING");
orderEvent.setMessage("Order status is in pending state");
orderEvent.setOrder(order);
orderKafkaProducer.sendMessage(orderEvent);
return "Order placed successfully";
}
}
|
from Comparer import Comparer
from unittest import TestCase
from unittest import mock
import pytest
import io
class TestComparer(TestCase):
comparer = Comparer()
def test_compare_equal(self):
assert self.comparer.compare([100, 200], [99, 201]) == -1
def test_compare_max_a(self):
assert self.comparer.compare([1.9, 10, -1], [1, -1, -0.5]) == 0
def test_compare_empty(self):
assert self.comparer.compare([], [1]) == 1
def test_find_avg_empty(self):
assert self.comparer.find_avg([], [5, 15, 10]) == [0, 10]
def test_find_avg_type_error(self):
with pytest.raises(TypeError):
self.comparer.find_avg({1, 2, 3}, [5, 15])
def test_compare_type_error_a(self):
with pytest.raises(TypeError):
self.comparer.compare([1, 2, (3, 4)], [1, 2, 3, 4.5])
def test_compare_type_error_b(self):
with pytest.raises(TypeError):
self.comparer.compare([1, 2, 3, 10.999], [1, 2, 'a'])
def test_print_result_b(self):
with mock.patch('sys.stdout', new=io.StringIO()) as stdout:
self.comparer.print_compare_result([0, -100, 0.777], [1, 2, 100, 1000])
assert stdout.getvalue() == 'Второй список имеет большее среднее значение\n'
def test_print_result_eqquals(self):
with mock.patch('sys.stdout', new=io.StringIO()) as stdout:
self.comparer.print_compare_result([0], [])
assert stdout.getvalue() == 'Средние значения равны\n'
|
import swaggerUiExpress from "swagger-ui-express";
import swaggerJsDoc from "swagger-jsdoc";
import { swaggerOptions } from "../swagger-options";
import express, { type NextFunction, type Response, type Request, type ErrorRequestHandler } from "express";
import { mongoConnect } from "../domain/repositories/mongo-repository";
import { userRouter } from "./user.routes";
import { teamRoute } from "./team.routes";
import { matchRoute } from "./match.routes";
import { leagueRoute } from "./league.routes";
import { matchDayRoute } from "./matchDay.routes";
export const configureRoutes = (app: any): any => {
// Swagger
const specs = swaggerJsDoc(swaggerOptions);
app.use("/api-docs", swaggerUiExpress.serve, swaggerUiExpress.setup(specs));
// Middleware de conexión a Mongo
app.use(async (req: Request, res: Response, next: NextFunction) => {
await mongoConnect();
next();
});
// Rutas
const router = express.Router();
router.get("*", (req: Request, res: Response) => {
res.status(404).send("Lo sentimos :( No hemos encontrado la página solicitada.");
});
// Usamos las rutas
app.use("/user", userRouter);
app.use("/team", teamRoute);
app.use("/match", matchRoute);
app.use("/league", leagueRoute);
app.use("/matchDay", matchDayRoute);
app.use("/", router);
// Middleware de gestión de errores
app.use((err: ErrorRequestHandler, req: Request, res: Response, next: NextFunction) => {
console.log("*** INICIO DE ERROR ***");
console.log(`PETICIÓN FALLIDA: ${req.method} a la url ${req.originalUrl}`);
console.log(err);
console.log("*** FIN DE ERROR ***");
// Truco para quitar el tipo a una variable
const errorAsAny: any = err as unknown as any;
if (err?.name === "ValidationError") {
res.status(400).json(err);
} else if (errorAsAny.errmsg && errorAsAny.errmsg?.indexOf("duplicate key") !== -1) {
res.status(400).json({ error: errorAsAny.errmsg });
} else if (errorAsAny?.code === "ER_NO_DEFAULT_FOR_FIELD") {
res.status(400).json({ error: errorAsAny?.sqlMessage });
} else {
res.status(500).json(err);
}
});
return app;
};
|
<!doctype html>
<html lang="pl-PL">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kurs Javascript - Symbole</title>
<meta name="description" content="Kurs Javascript dla superbohaterów, artykuły, tutoriale, porady, zadania do wykonania" />
<link rel="canonical" href="https://kursjs.pl/kurs/es6/symbole.php" />
<link rel="stylesheet" href="./css.css" />
<link href="https://fonts.googleapis.com/css?family=IBM+Plex+Mono:400,700&display=swap&subset=latin-ext" rel="stylesheet">
<meta name="image" content="https://kursjs.pl/kursjs.png">
<meta name="twitter:card" content="product">
<meta name="twitter:site" content="@publisher_handle">
<meta name="twitter:title" content="Kurs Javascript">
<meta name="twitter:description" content="Kurs Javascript dla superbohaterów">
<meta name="twitter:creator" content="@kartofelek007">
<meta name="twitter:image" content="https://kursjs.pl/kursjs.png">
<meta property="og:title" content="Kurs Javascript">
<meta property="og:type" content="article">
<meta property="og:url" content="https://www.kursjs.com/">
<meta property="og:image" content="https://kursjs.pl/kursjs.png">
<meta property="og:description" content="Kurs Javascript dla superbohaterów">
<meta property="og:site_name" content="Kurs Javascript">
<link rel="apple-touch-icon" sizes="57x57" href="/favicons/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/favicons/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/favicons/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/favicons/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/favicons/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/favicons/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/favicons/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/favicons/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/favicons/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicons/android-chrome-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#FF6347">
<meta name="msapplication-TileImage" content="/mstile-144x144.png">
<script src="/js/jquery.min.js"></script>
</head>
<body>
<div class="page-container" id="pageContainer">
<div class="page-content-wrapper">
<main class="page-content" id="mainContent" data-text-for-print="Kurs Javascript dla superbohaterów">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<div class="rekl-cnt">
<ins
class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-6843603045703750"
data-ad-slot="4690777640"
data-ad-format="auto"
data-full-width-responsive="true"
></ins>
</div>
<div class="page-content-text">
<h1 class="page-title">Symbole</h1>
<p>
Jedną z nowości jakie przyniosło ES6 jest nowy typ prymitywny zwany <strong>symbolem</strong>.
Podobnie jak w przypadku innych prymitywów symbol możemy stworzyć za pomocą konstruktora,
w przeciwieństwie jednak do innych typów nie możemy tutaj stosować literałów:
</p>
<pre><code class="language-js">
const sym = Symbol();
console.log(typeof sym); //symbol
//dla każdego symbolu możemy przekazać własną nazwę
//która ułatwia debugowanie
const sym2 = Symbol('Moj symbol');
console.log(sym2); //Symbol(Moj symbol)
</code></pre>
<p>Główną cechą symboli jest to, że każdorazowo przyjmują one całkowicie nową wartość, którą określa dany symbol. Nawet jeżeli przekażemy im taki sam tekst opisowy, każdy nowo utworzony
symbol ma nową wartość, inną od innych symboli:</p>
<pre><code class="language-js">
//false bo oba symbole mają podobny tekst opisowy, ale ich "wartości" są całkowicie unikatowe
console.log(Symbol("foo") === Symbol("foo"))
</code></pre>
<p>W przypadku Symboli nie interesuje nas jaką konkretną wartość ma dany symbol, ale to, że
jego wartość jest zawsze unikatowa. Czyli w przeciwieństwie np. do Number odwołując się do zmiennej nie pobieramy konkretnej wartości, a tylko "coś unikatowego".</p>
<p>Do czego to się może przydać?<br>
<p>
Wyobraź sobie, że wraz z innymi tworzycie super zaawansowany silnik do gier. Pojedynczy obiekt
ma mnóstwo metod np. collision, moved itp. Ty w pewnym momencie chcesz dodać nową metodę, ale też chcesz mieć pewność, że nie nadpiszesz żadnej innej metody. Klasycznie mógłbyś wykorzystać do tego celu pętlę while, tak by generować unikatową nazwę dla twojej metody:</p>
<pre><code class="language-js">
let check = true;
let methodName = "moved";
const ob = {};
while (ob.hasOwnProperty(methodName)) {
methodName += randomLetter();
}
ob[methodName] = function() {
...
}
</code></pre>
<p>
W przypadku symboli zawsze będziesz miał unikatową wartość, a więc i twoją metodę:
</p>
<pre><code class="language-js">
const move = Symbol('my move method');
const ob = {};
ob[move] = function() {
...
}
//jedyna możliwość odwołania się do powyższej metody
//jest skorzystanie z symbolu, do którego mamy referencję w stałej move
ob[move](); //Test
</code></pre>
<pre><code class="language-js">
const myObj = {};
let sym1 = Symbol('moj'); //tworze nowy symbol
myObj[sym1] = "Ala";
console.log(myObj); //{Symbol(moj): "Ala"}
sym1 = Symbol(); //tworze nowy symbol pod tą samą nazwą
myObj[sym1] = "Monika";
console.log(myObj); //{Symbol(moj): "Ala", Symbol(): "Monika"}
const sym2 = Symbol('moj'); //podobny opis nic nie oznacza
myObj[sym2] = "Beata";
console.log(myObj); //{Symbol(moj): "Ala", Symbol(): "Monika", Symbol(moj): "Beata"}
</code></pre>
<p>Nawet jeżeli stworzymy nowy symbol o tej samej nazwie i wartości, będzie on zupełnie nowym symbolem. Dzięki temu wszystkie trzy właściwości są pod innymi kluczami.</p>
<p>Jeżeli teraz chcielibyśmy się do tych właściwości dostać moglibyśmy użyć zmiennych wskazujących na dany symbol. W powyższym przykładzie jednak zmienna sym została zmieniona, więc w żaden sposób nie wskazuje na pierwszy symbol. Możemy tutaj skorzystać z metody <strong>Object.getOwnPropertySymbols(ob)</strong>, która zwraca symbole użyte w danym obiekcie:</p>
<pre><code class="language-js">
const symb = Object.getOwnPropertySymbols(myObj);
console.log(symb.length); //3
console.log(symb[0]); //Symbol(moj)
console.log(myObj[symb[0]]) //Ala
</code></pre>
<!-- ### -->
<h2 class="subtitle" id="symbol-for">Metody dla symboli</h2>
<p>JavaScript udostępnia kilka metod dla symboli. Pierwszą z nich jest <strong>Symbol.for(nazwa)</strong>. Służy ona do tworzenia danych symboli w globalnym rejestrze. Wyobraź sobie globalną listę. Gdy na danej pozycji nie ma jeszcze stworzonego symbolu, wtedy użycie tej metody stworzy pod daną pozycją nowy symbol. Każde kolejne użycie tej metody z daną nazwą nie stworzy nowego symbolu, a tylko pobierze już stworzony symbol:</p>
<pre><code class="language-js">
Symbol.for("mySymbol name"); //tworzę nowy symbol
Symbol.for("other symbol"); //tworzę nowy symbol
console.log(Symbol.for("mySymbol name")); //pobieram wcześniej utworzony symbol
console.log(Symbol.for("mySymbol name2")); //tworzę nowy symbol
</code></pre>
<pre><code class="language-js">
const hidden = Symbol.for("name"); //tworzę nowy symbol
//odwołuję się do symbolu
console.log(hidden);
console.log(Symbol.for("name"));
</code></pre>
<p>Jeżeli znamy nazwę zmiennej do której przypisany został symbol, możemy za jej pomocą
pobrać klucz, który został wpisany przy tworzeniu symbolu. Wykorzystamy do tego metodę <strong>Symbol.keyFor()</strong></p>
<pre><code class="language-js">
const hidden = Symbol.for("my hidden message");
console.log(Symbol.keyFor(hidden)); //my hidden message
</code></pre>
</div><!-- e: page-content-text -->
<footer class="page-footer">
<p>
Wszelkie prawa zastrzeżone. Jeżeli chcesz używać jakiejś części tego kursu, skontaktuj się z <a href="/kurs/autor.php">autorem</a>.
Aha - i ta strona korzysta z <a href="/kurs/polityka-prywatnosci.php">ciasteczek</a>.
</p>
</footer>
<div class="rekl-cnt">
<ins
class="adsbygoogle" style="margin-top:40px; display:block"
data-ad-client="ca-pub-6843603045703750"
data-ad-slot="4690777640"
data-ad-format="auto"
data-full-width-responsive="true"
></ins>
</div>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</main><!-- e: page-content -->
</div><!-- e: page-content-wrapper -->
<aside id="page-sidebar-cnt" class="page-sidebar-cnt">
<div id="page-sidebar" class="page-sidebar">
<button aria-label="Pokaż/ukryj Menu" aria-expanded="false" aria-controls="page-sidebar" type="button" id="pageSidebarBurger" class="page-sidebar-burger">
<span></span>
</button>
<h2 class="visuallyhidden">
Menu
</h2>
<button class="sidebar-toggle-btn" title="Pokaż/schowaj menu" aria-hidden="true">
<strong>Pokaż/ukryj menu</strong>
<span></span>
<span></span>
<span></span>
</button>
<div class="page-sidebar-title">
<a href="/kurs/kontakt.html" title="Nawrzucaj autorowi" class="mail-to-author" id="mailToAuthor">Napisz do mnie</a>
<a href="#popupOptions" class="page-setup-link popupOpen" title="Ustawienia strony" id="showOptions">Ustawienia</a>
<a href="/index.html" aria-label="Strona główna" class="page-sidebar-title-link">Kurs Javascript</a>
</div>
<form aria-label="Wyszukiwarka" class="search-sidebar" action="/search.html" method="post">
<label for="search" class="search-sidebar-label">Szukaj</label>
<div class="search-sidebar-input-cnt">
<svg class="search-sidebar-input-icon" xmlns="http://www.w3.org/2000/svg" width="26" height="28" viewBox="0 0 26 28" aria-hidden="true">
<path d="M18 13c0-3.859-3.141-7-7-7s-7 3.141-7 7 3.141 7 7 7 7-3.141 7-7zm8 13c0 1.094-.906 2-2 2a1.96 1.96 0 0 1-1.406-.594l-5.359-5.344a10.971 10.971 0 0 1-6.234 1.937c-6.078 0-11-4.922-11-11s4.922-11 11-11 11 4.922 11 11c0 2.219-.672 4.406-1.937 6.234l5.359 5.359c.359.359.578.875.578 1.406z"></path>
</svg>
<input type="text" id="search" autocomplete="off" name="q" class="search-sidebar-input">
</div>
<button type="submit" class="search-sidebar-button">Szukaj</button>
</form>
<div class="page-sidebar-table-of-content">
<h2 class="visuallyhidden">Spis treści</h2>
<div class="page-sidebar-section">
<h3 class="page-sidebar-section-title noopen">
<a href="./index.html">Strona główna</a>
</h3>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">Słowem wstępu</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="./wstep.html">Wstęp</a>
</li>
<li >
<a href="./co-to-jest-javascript.html">Co to jest JavaScript i z czym go się je?</a>
</li>
<li >
<a href="./wymagania.html">Wymagania</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">Super podstawy</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="./debuger.html">Debuger</a>
</li>
<li >
<a href="./pierwszy-skrypt.html">Wstawiamy skrypty na naszą stronę</a>
</li>
<li >
<a href="./strict-mode.html">Strict mode</a>
</li>
<li >
<a href="./typy-danych.html">Typy danych i konwersja danych</a>
</li>
<li >
<a href="./zmienne.html">Zmienne</a>
</li>
<li >
<a href="./operatory.html">Operatory</a>
</li>
<li >
<a href="./math.html">Obiekt Math</a>
</li>
<li >
<a href="./string.html">String - teksty</a>
</li>
<li >
<a href="./instrukcje-warunkowe.html">Instrukcje warunkowe</a>
</li>
<li >
<a href="./petle.html">Pętle</a>
</li>
<li >
<a href="./funkcje.html">Funkcje</a>
</li>
<li >
<a href="./funkcje-tematy-dodatkowe.html">Funkcje - tematy dodatkowe</a>
</li>
<li >
<a href="./tablice.html">Tablice</a>
</li>
<li >
<a href="./tablice-iteracje.html">Tablice pętle</a>
</li>
<li >
<a href="./debugowanie.html">Debugowanie kodu</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">Obiekty</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="./obiekty.html">Obiekty i this</a>
</li>
<li >
<a href="./obiekty-jak-to-dziala.html">Jak to działa</a>
</li>
<li >
<a href="./obiekty-konstruktor.html">Konstruktor</a>
</li>
<li >
<a href="./obiekty-zaawansowane-this.html">Zaawansowane this</a>
</li>
<li >
<a href="./obiekty-dziedziczenie.html">Dziedziczenie w Javascript</a>
</li>
<li >
<a href="./obiekty-inne-sposoby-tworzenia.html">Inne sposoby tworzenia obiektów</a>
</li>
<li >
<a href="./obiekty-instanceof-hasownproperty.html">instanceof i hasOwnProperty</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">DOM i zdarzenia</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="./dom.html">Document Object Model</a>
</li>
<li >
<a href="./dom-wlasciwosci.html">Właściwości elementów</a>
</li>
<li >
<a href="./dom-relacje.html">Relacje między elementami</a>
</li>
<li >
<a href="./dom-tworzenie-i-usuwanie.html">Tworzenie i usuwanie elementów</a>
</li>
<li >
<a href="./style.html">Style w CSS</a>
</li>
<li >
<a href="./events.html">Zdarzenia</a>
</li>
<li >
<a href="./events-keys.html">Zdarzenia - klawisze</a>
</li>
<li >
<a href="./events-mouse.html">Zdarzenia - myszka</a>
</li>
<li >
<a href="./projekt-todo.html">Projekt TODO</a>
</li>
<li >
<a href="./slider.html">Tworzymy slider</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">Prawie podstawy</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="./grafika-na-stronie.html">Grafika na stronie</a>
</li>
<li >
<a href="./intervals.html">setTimeout i setInterval</a>
</li>
<li >
<a href="./match-media.html">Praca z RWD</a>
</li>
<li >
<a href="./okna-dialogowe.html">Okienka dialogowe</a>
</li>
<li >
<a href="./okna.html">Tworzenie nowych okien</a>
</li>
<li >
<a href="./date.html">Obiekt Date</a>
</li>
<li >
<a href="./date-calendar.html">Tworzymy kalendarz</a>
</li>
<li >
<a href="./cookie.html">Obiekt Cookie</a>
</li>
<li >
<a href="./storage.html">Storage</a>
</li>
<li >
<a href="./regular.html">Wyrażenia regularne</a>
</li>
<li >
<a href="./formularze.html">Formularze</a>
</li>
<li >
<a href="./formularze-walidacja.html">Formularze - walidacja</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section show has-active-element">
<h3 class="page-sidebar-section-title">
<a href="#">Ajax</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li class="active">
<a href="./ajax.html">AJAX, REST, JSON</a>
</li>
<li >
<a href="./xmlhttprequest.html">XMLHttpRequest</a>
</li>
<li >
<a href="./fetch.html">Fetch API</a>
</li>
<li >
<a href="./formularz-kontaktowy.html">Dynamiczny formularz kontaktowy</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">Nowy Javascript</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="./ecma-script-2015.html">ES6</a>
</li>
<li >
<a href="./webpack.html">Webpack</a>
</li>
./
<a href="./obiekty-w-es6.html">Obiekty w ES6</a>
</li>
<li >
<a href="./funkcja-strzalkowa.html">Funkcja strzałkowa</a>
</li>
<li >
<a href="./spread-rest.html">Spread i rest</a>
</li>
<li >
<a href="./template-strings.html">Template strings</a>
</li>
<li >
<a href="./destructuring.html">Dekompozycja</a>
</li>
<li >
<a href="./class.html">Klasy w ES6</a>
</li>
<li >
<a href="./promises.html">Promises</a>
</li>
<li >
<a href="./async-await.html">Async/Await</a>
</li>
<li >
<a href="./symbole.html">Symbole</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">jQuery</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="/kurs/jquery/jquery.html">jQuery</a>
</li>
<li >
<a href="/kurs/jquery/animacje-w-jquery.html">Animacje w jQuery</a>
</li>
<li >
<a href="/kurs/jquery/jquery-ajax.html">Ajax w jQuery</a>
</li>
<li >
<a href="/kurs/jquery/tabs.html">Taby w jQuery</a>
</li>
<li >
<a href="/kurs/jquery/plugin.html">Karuzela w jQuery</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">Canvas</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="/kurs/canvas/canvas.html">Canvas</a>
</li>
<li >
<a href="/kurs/canvas/canvas-images.html">Grafika w canvas</a>
</li>
<li >
<a href="/kurs/canvas/canvas-paint.html">Praktycznie : Paint w canvas</a>
</li>
<li >
<a href="/kurs/canvas/canvas-animacja.html">Animacja w canvas</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">Gry</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="/kurs/gry/hangman/hangman.html">Szubienica</a>
</li>
<li >
<a href="/kurs/gry/memory/memory.html">Memory</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section ">
<h3 class="page-sidebar-section-title">
<a href="#">Inne</a>
</h3>
<div class="page-sidebar-list-cnt">
<ul class="page-sidebar-list">
<li >
<a href="/kurs/dodatkowe-materialy.html">Dodatkowe materiały</a>
</li>
<li >
<a href="/kurs/faq.html">FAQ</a>
</li>
<li >
<a href="/kurs/polityka-prywatnosci.html">Polityka prywatności</a>
</li>
<li >
<a href="/kurs/autor.html">O autorze</a>
</li>
<li >
<a href="/kurs/kontakt.html">Kontakt</a>
</li>
</ul>
</div>
</div>
<div class="page-sidebar-section">
<a class="special-link" href="/kurs/autor.html#donate">Wesprzyj kurs</a>
</div>
</div>
</div>
</aside></div><!-- e: page-container -->
<div class="popup" id="popupOptions">
<div class="popup-inside">
<div class="popup-container-cnt">
<div class="popup-container">
<button class="popup-close">Zamknij</button>
<h2 class="popup-title">
Opcje
</h2>
<div class="popup-content">
<form class="form-options">
<div class="form-option">
<div class="form-row">
<div class="form-col">
<label for="optionsThemeSelect">Wybierz skórkę dla listingów</label>
<select id="optionsThemeSelect"></select>
</div>
</div>
<div class="form-row">
<pre><code class="language-js">
//tak będzie wyglądał kod
function test() {
for (let i=0; i<10; i++) {
console.log("Tekst numer ", 1);
}
}
test();
</code></pre>
</div>
<div class="form-row" id="themeLightModeRow">
<div class="form-col">
<label for="themeLightMode">
Tryb dzienny / nocny
</label>
<div class="light-mode-el">
<input type="checkbox" id="themeLightMode">
<span class="light-mode"></span>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script async defer src="https://www.googletagmanager.com/gtag/js?id=UA-38558970-5"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-38558970-5');
</script>
<script src="/js/ads.js"></script>
<script src="/js/script.min.js?v=0.13" defer></script>
</body>
</html>
|
import { Buffer } from "node:buffer";
import { getInput, info, setFailed, setOutput, setSecret } from "@actions/core";
import isBase64 from "is-base64";
import { getOctokit } from "@actions/github";
import { createAppAuth } from "@octokit/auth-app";
import { request } from "@octokit/request";
async function run(): Promise<void> {
try {
const appId = getInput("app_id", { required: true });
const privateKeyInput = getInput("private_key", { required: true });
const privateKey = isBase64(privateKeyInput)
? Buffer.from(privateKeyInput, "base64").toString("utf8")
: privateKeyInput;
const repository = getInput("repository");
const githubApiUrlInput = getInput("github_api_url");
const githubApiUrl = new URL(githubApiUrlInput);
const installationToken = await fetch({
appId,
privateKey,
githubApiUrl,
repository,
});
setSecret(installationToken);
setOutput("token", installationToken);
info("Token generated successfully!");
} catch (error) {
if (error instanceof Error) {
setFailed(error.message);
}
}
}
async function fetch({
appId,
privateKey,
githubApiUrl,
repository,
}: Readonly<{
appId: string;
privateKey: string;
githubApiUrl: URL;
repository: string;
}>): Promise<string> {
const app = createAppAuth({
appId,
privateKey,
request: request.defaults({
baseUrl: githubApiUrl
.toString()
// Remove optional trailing `/`.
.replace(/\/$/, ""),
}),
});
const authApp = await app({ type: "app" });
const octokit = getOctokit(authApp.token);
let installationId: number;
const [owner, repo] = repository.split("/");
if (!owner || !repo) {
throw new Error("Invalid repository name.");
}
try {
({
data: { id: installationId },
} = await octokit.rest.apps.getRepoInstallation({ owner, repo }));
} catch (error: unknown) {
throw new Error(
"Could not get repo installation. Is the app installed on this repo?",
{ cause: error },
);
}
try {
const { data: installation } =
await octokit.rest.apps.createInstallationAccessToken({
installation_id: installationId,
});
return installation.token;
} catch (error: unknown) {
throw new Error("Could not create installation access token.", {
cause: error,
});
}
}
run();
|
## Object 생성자 함수
new 연산자와 함께 Object 생성자 함수를 호출하면 빈 객체를 생성할 수 있습니다.
이후 빈 객체에 프로퍼티 및 메서드를 추가할 수 있습니다.
```jsx
// 빈 객체의 생성
const person = new Object();
// 프로퍼티 추가
person.name = 'Lee';
person.sayHello = function () {
console.log('Hi! My name is ' + this.name);
};
console.log(person); // {name: "Lee", sayHello: ƒ}
person.sayHello(); // Hi! My name is Lee
```
JavaScript는 Object 생성자 이외에도 String, Number, Boolean, Function, Array, Date, RegExp, Promise 등 빌트인 생성자 함수를 제공한다.
```jsx
// String 생성자 함수에 의한 String 객체 생성
const strObj = new String('Lee');
console.log(typeof strObj); // object
console.log(strObj); // String {"Lee"}
```
우리는 10장에서 객체 리터럴로 객체를 생성하는 방법을 배웠다. 특별한 이유가 없다면 객체 리터럴로 객체를 생성하는게 더 유용하다는게 저자의 의견이다.
## 생성자 함수
### 1) 객체 리터럴에 의한 객체 생성 방식의 문제점
객체 리터럴 방식은 간편하고 직관적이지만 하나의 객체만 생성할 수 있다.
```jsx
const circle1 = {
radius: 5,
getDiameter() {
return 2 * this.radius;
}
};
console.log(circle1.getDiameter()); // 10
const circle2 = {
radius: 10,
getDiameter() {
return 2 * this.radius;
}
};
console.log(circle2.getDiameter()); // 20
```
위 예제에서 getDiameter()는 프로퍼티 구조가 동일하지만 객체 리터럴 방식이므로 따로 기술해야 한다는 단점이 존재한다.
### 생성자 함수에 의한 객체 생성 방식의 장점
생성자 함수는 생성을 위한 템플릿(클래스) 처럼 생성자 함수를 사용하여 프로퍼티 구조가 동일한 객체의 생성을 편리하게 할 수 있다.
```jsx
// 생성자 함수
function Circle(radius) {
// 생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// 인스턴스의 생성
const circle1 = new Circle(5); // 반지름이 5인 Circle 객체를 생성
const circle2 = new Circle(10); // 반지름이 10인 Circle 객체를 생성
console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20
const circle3 = Circle(15);
// 함수로서의 Circle은 return이 없어 undefined가 반환됨
console.log(circle3); // undefined
// 일반 함수로 호출된 Circle 내의 this는 window 객체를 가리킴
cnosole.log(radius); // 15
```
위 예제처럼 Circle은 new 연산자와 함께 호출하면 생성자 함수로 동작하고 new 연산자가 없이 호출하면 일반 함수로 동작한다.
### 생성자 함수의 인스턴스 생성 과정
- 인스턴스 생성
- this를 통해 프로퍼티를 추가
- 생성된 인스턴스 초기화(인스턴스 프로퍼티 추가 및 할당)
- this를 통해 추가된 프로퍼티에 초기 값 할당 및 초기화
```jsx
// 생성자 함수
function Circle(radius) {
// 인스턴스 초기화
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// 인스턴스 생성
const circle1 = new Circle(5); // 반지름이 5인 Circle 객체를 생성
```
JavaScript는 암묵적으로 인스턴스를 생성하고 반환하므로 반환문이 따로 존재하지 않아도 된다.
1) 인스턴스 생성과 this 바인딩
- 인스턴스를 생성하면 암묵적으로 빈 객체가 생성됩니다.
- 이 빈객체는 this에 바인딩됩니다. (생성자 함수 내부의 this가 생성자 함수가 생성할 인스턴스를 가리키는 이유)
2) 인스턴스 초기화
- this에 바인딩되어있는 인스턴스를 개발자가 기술한 대로 초기화합니다.
3) 인스턴스 반환
- 생성자 함수의 처리가 끝나면 암묵적으로 바인딩된 this가 반환됩니다.
- 만약 return문이 적혀있다면 this가 아닌 return이 반환된다.
- 하지만 여기서 원시값의 반환은 무시된다.
```jsx
function Circle(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
// 3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다
// 3. 암묵적으로 this를 반환한다.
// 명시적으로 객체를 반환하면 암묵적인 this 반환이 무시된다.
return {};
// 3. 암묵적으로 this를 반환한다.
// 명시적으로 원시값을 반환하면 원시값 반환은 무시되고 암묵적으로 this가 반환된다.
return 100;
}
// 인스턴스 생성. Circle 생성자 함수는 명시적으로 반환한 객체를 반환한다.
const circle = new Circle(1);
console.log(circle); // Circle {radius: 1, getDiameter: ƒ}
```
### 내부 메서드 [[Call]]과 [[Construct]]
함수를 new 연산자와 함게 호출하거나 new 연산자가 없이 호출이 가능한 이유는, 일반 객체가 가지고 있는 내부 슬롯과 내부 메서드를 모두 가지고 있기 때문이다.
```jsx
// 함수는 객체다.
function foo() {}
// 함수는 객체이므로 프로퍼티를 소유할 수 있다.
foo.prop = 10;
// 함수는 객체이므로 메서드를 소유할 수 있다.
foo.method = function () {
console.log(this.prop);
};
foo.method(); // 10
```
함수는 객체이지만 일반 객체와 다르다. 함수는 일반 객체와 다르게 호출할 수 있다.
```jsx
function foo() {}
// 일반적인 함수로서 호출: [[Call]]이 호출된다.
foo();
// 생성자 함수로서 호출: [[Construct]]가 호출된다.
new foo();
```
모든 함수는 객체 내부 메서드 [[Call]]을 갖고 있으므로 호출 할 수 있지만 모든 함수가 [[Construct]]를 갖고있진 않다.
- constructor : 함수 선언문, 함수 표현식, 클래스
- non-constructor : 메서드, 화살표 함수
```jsx
// 일반 함수 정의: 함수 선언문, 함수 표현식
function foo() {}
const bar = function () {};
// 프로퍼티 x의 값으로 할당된 것은 일반 함수로 정의된 함수다. 이는 메서드로 인정하지 않는다.
const baz = {
x: function () {}
};
// 일반 함수로 정의된 함수만이 constructor이다.
new foo(); // -> foo {}
new bar(); // -> bar {}
new baz.x(); // -> x {}
// 화살표 함수 정의
const arrow = () => {};
new arrow(); // TypeError: arrow is not a constructor
// 메서드 정의: ES6의 메서드 축약 표현만을 메서드로 인정한다.
const obj = {
x() {}
};
new obj.x(); // TypeError: obj.x is not a constructor
```
### new 연산자
함수를 new 와 함께 사용하면 [[Call]]이 아닌 [[Constructor]]가 호출된다. 즉 new는 constructor인 함수 앞에 사용해야 에러가 발생하지 않는다.
일반 함수와 생성자 함수의 차이는 없다. 따라서 생성자 함수는 일반적으로 첫 문자를 대문자로 기술하는 파스칼 케이스로 명명하여 구분한다.
### new.target
파스칼 케이스로만 생성자 함수를 표시하면 실수가 발생할 수 있어 ES6에서는 new.target을 제공합니다.
하지만 IE에선 제공하지 않음을 주의해야 합니다.
- 생성자 함수로 호출 : new.target은 함수 자신을 가리킴
- 일반 함수로 호출 : new.target은 undefined
위 두가지의 속성을통해 실수시 에러를 방지할 수 있습니다.
```jsx
// 생성자 함수
function Circle(radius) {
// 이 함수가 new 연산자와 함께 호출되지 않았다면 new.target은 undefined다.
if (!new.target) {
// new 연산자와 함께 생성자 함수를 재귀 호출하여 생성된 인스턴스를 반환한다.
return new Circle(radius);
}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// new 연산자 없이 생성자 함수를 호출하여도 new.target을 통해 생성자 함수로서 호출된다.
const circle = Circle(5);
console.log(circle.getDiameter()); // 10
```
### 스코프 세이프 생성자 패턴
IE에서 써야한다면 스코프 세이프 생성자 패턴을 통해 에러를 막을 수 있다.
```jsx
// Scope-Safe Constructor Pattern
function Circle(radius) {
// 생성자 함수가 new 연산자와 함께 호출되면 함수의 선두에서 빈 객체를 생성하고
// this에 바인딩한다. 이때 this와 Circle은 프로토타입에 의해 연결된다.
// 이 함수가 new 연산자와 함께 호출되지 않았다면 이 시점의 this는 전역 객체 window를 가리킨다.
// 즉, this와 Circle은 프로토타입에 의해 연결되지 않는다.
if (!(this instanceof Circle)) {
// new 연산자와 함께 호출하여 생성된 인스턴스를 반환한다.
return new Circle(radius);
}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// new 연산자 없이 생성자 함수를 호출하여도 생성자 함수로서 호출된다.
const circle = Circle(5);
console.log(circle.getDiameter()); // 10
```
Object와 Function 생성자 함수는 new 연산자가 없어도 동일하게 동작한다.
```jsx
let obj = new Object();
console.log(obj); // {}
obj = Object();
console.log(obj); // {}
let f = new Function('x', 'return x ** x');
console.log(f); // ƒ anonymous(x) { return x ** x }
f = Function('x', 'return x ** x');
console.log(f); // ƒ anonymous(x) { return x ** x }
```
String, Number, Boolean은 new연산자가 없으면 동일하게 동작하지 않는다.
```jsx
const str = String(123);
console.log(str, typeof str); // 123 string
const str2 = new String(123);
console.log(str2, typeof str2); // String {'123'}, object
```
|
package br.com.erudio;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import br.com.erudio.exception.UnsuportedMathOperationException;
@RestController
public class MathController {
@RequestMapping(value="/sum/{numberOne}/{numberTwo}", method=RequestMethod.GET )
public Double sum(@PathVariable("numberOne")String numberOne,@PathVariable("numberTwo")String numberTwo) throws Exception {
if (!isNumeric(numberOne) || !isNumeric(numberTwo)){
throw new UnsuportedMathOperationException("Please set a numeric value!");
}
Double sum = convertToDouble(numberOne) + convertToDouble(numberTwo);
return sum;
}
@RequestMapping(value="/subtraction/{numberOne}/{numberTwo}", method=RequestMethod.GET )
public Double subtraction(@PathVariable("numberOne")String numberOne,@PathVariable("numberTwo")String numberTwo) throws Exception {
if (!isNumeric(numberOne) || !isNumeric(numberTwo)){
throw new UnsuportedMathOperationException("Please set a numeric value!");
}
Double subtraction = convertToDouble(numberOne) - convertToDouble(numberTwo);
return subtraction;
}
@RequestMapping(value="/multiplication/{numberOne}/{numberTwo}", method=RequestMethod.GET )
public Double multiplication(@PathVariable("numberOne")String numberOne,@PathVariable("numberTwo")String numberTwo) throws Exception {
if (!isNumeric(numberOne) || !isNumeric(numberTwo)){
throw new UnsuportedMathOperationException("Please set a numeric value!");
}
Double multiplication = convertToDouble(numberOne) * convertToDouble(numberTwo);
return multiplication;
}
@RequestMapping(value="/division/{numberOne}/{numberTwo}", method=RequestMethod.GET )
public Double division(@PathVariable("numberOne")String numberOne,@PathVariable("numberTwo")String numberTwo) throws Exception {
if (!isNumeric(numberOne) || !isNumeric(numberTwo)){
throw new UnsuportedMathOperationException("Please set a numeric value!");
}
Double division = convertToDouble(numberOne) / convertToDouble(numberTwo);
return division;
}
@RequestMapping(value="/mean/{numberOne}/{numberTwo}", method=RequestMethod.GET )
public Double mean(@PathVariable("numberOne")String numberOne,@PathVariable("numberTwo")String numberTwo) throws Exception {
if (!isNumeric(numberOne) || !isNumeric(numberTwo)){
throw new UnsuportedMathOperationException("Please set a numeric value!");
}
Double mean = (convertToDouble(numberOne) + convertToDouble(numberTwo))/2;
return mean;
}
@RequestMapping(value="/squareRoot/{number}", method=RequestMethod.GET )
public Double squareRoot(@PathVariable("number")String number) throws Exception {
if (!isNumeric(number)){
throw new UnsuportedMathOperationException("Please set a numeric value!");
}
Double squareRoot = (Double) Math.sqrt(convertToDouble(number));
return squareRoot;
}
private Double convertToDouble(String strnumber) {
if(strnumber == null)return 0D;
String number = strnumber.replaceAll(",",".");
if (isNumeric(number))return Double.parseDouble(number);
return 0D;
}
private boolean isNumeric(String strnumber) {
if(strnumber == null)return false;
String number = strnumber.replaceAll(",",".");
return number.matches("[-+]?[0-9]*\\.?[0-9]+");
}
}
|
package Task3
import scala.io.StdIn.readLine
object subTask1 {
def getReversedString(): Unit = {
println("Задание 1")
println("Введите строку")
val string = readLine()
val result = reverseString(string)
println(result)
}
private def reverseString(string: String): String = {
// Разделяю строку на слова. В качестве разделителей - пробелы
val words = string.trim.split("\\s+")
// Объединяю слова в обратном порядке (reverse)
// и добавляю между ними по одному пробелу (mkString)
val reversed = words.reverse.mkString(" ")
reversed
}
}
object subTask2 {
def getReversedString(): Unit = {
println("Задание 2")
println("Введите строку")
val string = readLine()
val words = string.trim.split("\\s+").toList
val result = reverseString(words, "")
println(result)
}
private def reverseString(words: List[String], accumulator: String): String = {
// accumulator - итоговая строка
// words - список строк (слов из начальной строки)
// рекурсивно вызываем reverseString,
// в качестве words - оставшиеся слова (tail),
// в качестве accumulator - добавляем перед accumulator голову списка
words match {
case Nil => accumulator
case head :: tail => reverseString(tail, head + " " + accumulator)
}
}
}
object subTask3 {
private var result: Float = 0
def getChipsWeight(withMethod: Boolean): Unit = {
println("Задание 3")
println("Введите вес картофеля")
val potatoWeight = readLine().toFloat
println("Введите долю воды в картофеле")
val waterInPotato = readLine().toFloat
println("Введите долю воды в чипсах")
val waterInChips = readLine().toFloat
if (!withMethod) {
println("Ручное каррирование")
val addWeight = curriedGetWeightOfChips(potatoWeight) _
val addWaterInPotato = addWeight(waterInPotato)
result = addWaterInPotato(waterInChips)
} else {
println("Каррирование с помощью функции curried")
// преобразование обычной функции в каррированную
val curriedCalculate = (calculateChipsWeight _).curried
val addWeight = curriedCalculate(potatoWeight)
val addWaterInPotato = addWeight(waterInPotato)
result = addWaterInPotato(waterInChips)
}
println(f"weight of chips = $result%.2f")
}
private def calculateChipsWeight(weight: Float, waterInPotato: Float, waterInChips: Float): Float = {
(weight * (1 - waterInPotato)) / (1 - waterInChips)
}
private def curriedGetWeightOfChips(weight: Float)(waterInPotato: Float)(waterInChips: Float): Float = {
(weight * (1 - waterInPotato)) / (1 - waterInChips)
}
}
object task3 extends App {
subTask1.getReversedString()
subTask2.getReversedString()
subTask3.getChipsWeight(false)
}
|
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template
*/
package controller.Users;
import jakarta.servlet.RequestDispatcher;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.net.URLEncoder;
import model.Client.ClientDAO;
import model.Users.UsersDAO;
/**
*
* @author dell
*/
public class CheckCodeForgotServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet CheckCodeForgotServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet CheckCodeForgotServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/CoffeeLand/server/Users/GetCodeForget.jsp").forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String code1 = request.getParameter("code");
String newpass = request.getParameter("newpass");
HttpSession session = request.getSession();
String storedCode = (String) session.getAttribute("storedCodeS");
if (code1.equals(storedCode)) {
String email = (String) session.getAttribute("email");
UsersDAO cd = new UsersDAO();
cd.updatePassword(email, newpass);
response.sendRedirect("/CoffeeLand/server/Users/login.jsp");
} else {
String notice = "Nhập code sai";
response.sendRedirect("/CoffeeLand/server/Users/GetCodeForget.jsp?notice=" + URLEncoder.encode(notice, "UTF-8"));
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
# 3DVC_Project
陈新 2022210877 计研三一
P.S. : The code works with pytorch 2.0 new feature `set_default_device`
Choose to solve `6D Object Pose Estimation`
Experiments carried on
> Windows11
>
> i9-9900
>
> Mem 32G-3200MHz
>
> RTX-2080Ti
## 0. Background
We are given the RGB/depth/label images of a certain rendering setting, to estimate the transformation matrix of the object model to the scene's world space.
We can easily get the PCD of the visiable part of the model in the world space of the scene.
Thus, if we don't consider the RGB image, the problem is simplified to the estimation of the transformation from point set $p$ to $q$.
$$
R, t = \text{argmax}_{R, t} ||Rp + t - q||
$$
## 1. ICP
### Method
Before ICP, we give a translation to the PCD so that the centers of gravity of two PCDs overlap.
For a particular match `(src -> gt)` , we have a initial setting `(R_init, t_init)`
So we set $src = R_{init} @ src + t_{init}$ as the initial state to get a better result.
For every iteration:
1. Calculate $x = R @ src + t$
2. Use K-d tree to query the nearest matching points. $y = src[match[x]]$
3. Calculate
$$
H = (y - \bar{y}) @ (x - \bar{x})^T \\
$$
Use SVD to solve
$$
H = U \Sigma V^T
$$
And we get
$$
R = U @ V^T \\
(\text{if } det(R) < 0, \text{flip the last row of } V^T) \\
t = \bar{y} - R @ \bar{x}
$$
4. Iterate util `0 < loss - loss_new < tolerance` or `loss_new < tolerance` . Note that we set `tolerance = 1e-8` here. Since we have a distance match, we use a simple $L_2$ loss here.
#### Initial pose
And I notice that the quality of ICP highly relies on the initial state `(R_init, t_init)`, so we first set $n\_seg ^ 3$ initial poses to cover more poses.
For example, when $n\_seg = 3$, we set Eurler angle $i, j, k$ as $0\degree, 120\degree, 240\degree$ separately, and combine them together to get 27 initial poses.
##### Branch-cut
This brute-force method may cost too much time, which leads me to think how to cut branches.
###### By geometric symmetry
Since we have geometric symmetry, so we can transform the object model in the object space to make use of it (we cannot transform the partial model in the image because the geometric symmetry is axis aligned with no rotation).
If an axis's (let's say, `x`) geometric symmetry is
1. `inf`, we set `n_seg_x = 1`
2. not mentioned, we set `n_seg_x = n_seg`
3. `k`, we set `n_seg_x =`
1. $\min(2, n\_seg), \text{if } k = 3, 4$
2. $1, \text{if } k \ge 5$
$\text{degree\_max } = n\_seg / k$
Additionally, if 2 axises have `inf` geometric symmetry, it means this object has `inf` geometric symmetry in the 3rd axis also.
We can share k-d trees for query when the matching targets are the same, but the initialization algorithm will transform the target to different poses. So we add a simple optimization: if the object doesn't have geometric symmetry in any axis, we share the same kd tree of visiable points in world coordinate and rotate the model groud truth, otherwise we rotate the model object and construct a kd tree for each initial pose.
###### By value
Since we have multiple initial poses, we will get several results.
If `loss_min / obj_model.oblique_axis < loss_tolerance`, we can assume that we've found the correct answer.
Here `obj_model.oblique_axis` represents the length of the oblique axis of the model's AABB. `loss_tolerance = 0.00011` according to our tests.
In this way, we cut many unnecessary branches.
### Experiments
We sample `n_sample_points = 10000` points on the object model surface (same for learning-based method)
`icp_tolerance = 1e-9`
`icp_max_iter = 500`
`loss_tolerance = 0.00011`
`n_seg = 3`
Success if rotation error < 5 degree and translation error < 1 cm.
We roughly get a correct rate of
1. $98.8\%$ `w/` multi-initial pose (and `w/` branch-cut, average $5.78$ of $3^3 = 27$ initial poses will be calculated)
2. $88.9\%$ `w/o` multi-initial pose
on the training/validate dataset.
Here are some examples:
<center>
<figure>
<img src="pictures/ICP - 0.png" width='450'/>
<img src="pictures/ICP - 1.png" width='450'/>
</figure>
</center>
Here are some failure cases:
<center>
<figure>
<img src="pictures/ICP - F - 0.png" width='300'/>
<img src="pictures/ICP - F - 1.png" width='300'/>
<img src="pictures/ICP - F - 2.png" width='300'/>
</figure>
</center>
The 1st failure case is caused by the number of the visiable points in the raw data. There are only tens of points so that the algorithm doesn't work.
The 2nd failure case is caused by the geometric symmetry. The iterative algorithm falls into local minimum.
The 3rd failure case is caused by our initialization method. We give it a translation before ICP so that we can make the gravity center of the 2 PCDs overlap, which makes the algorithm falls into local minimum.
### Possible improvements
We set multiple initial poses to compensate for the initial pose sensitivity of the ICP. Although we also cut branches, the cost of ICP itself is very high, which makes that of the whole pipeline very high too.
To avoid it, we can adopt some initialization algorithms like GO-ICP/...
## 2. Learning-based method
### Method
#### 1. Representation
We use a 6D representation as below, to make it continuous and unique for a rotation.
6D representation: $[a_1^T, a_2^T]$, where $a_1, a_2 \in R^{3\times1}$
Convert $x = [a_1^T, a_2^T]$ to a rotation matrix $R = [b_1, b_2, b_3]$ through the Gram-Schmidt process, where $b_1, b_2, b_3 \in R^{3\times1}$ with unit length,
$$
\begin{aligned}
b_1 &= \frac{a_1}{||a_1||} \\
b_2 &= \frac{a_2 - <a_2, a_1> b_1}{||a_2 - <a_2, a_1> b_1||} \\
b_3 &= b_1 \times b_2
\end{aligned}
$$
Convert a rotation matrix to 6D: $x = [b_1^T, b_2^T]$
#### 2. Loss
Chamfer Distance Loss(CD loss) are as below:
$$
L_{CD}(S_1, S_2) = \frac{1}{|S_1|} \sum_{x \in S_1} { \min_{y \in S_2} { ||x - y||^2_2 } } + \frac{1}{|S_2|} \sum_{y \in S_2} { \min_{x \in S_1} { ||y - x||^2_2 } }
$$
Since we only have a small part of the object point cloud, so we use a half-CD loss here:
$$
L_{CD\_half}(S_1, S_2) = \frac{1}{|S_1|} \sum_{x \in S_1} { \min_{y \in S_2} { ||x - y||^2_2 } }
$$
$S_1$ represents the partial PCD in the picture's world space, and $S_2$ represents the transformed whole object model PCD.
In this way, if we get a perfect match, the loss may come close to 0, otherwise it may get values far bigger than 0.
#### 3. Network design
We didn't use RGB information. Only geometric information is used. And we train 79 networks for 79 objects, which may improve the expressive ability of the network.
The network structures are as below:

1. Concat the pre-transformed `world_coord` and `model_coord` as input, to improve the network's ability of expression.
2. Use an MLP to get the features of each point. (1024-dimension features)
3. Use a max pooling layer to extract the feature of the whole PCD.
3. Use an MLP to get a 9D feature (6D pose representation $[a_1^T, a_2^T]$ and a 3D translate $t$)
Considering that neural networks are more expressive when the values are in the range of $[-1, 1]$, we give a translate ($t_0$) to both the object model and visiable world coordinate PCD, so that no matter how the object model rotate, it will be in the range of $[-1, 1]$. Adding the gravity center concerned translate $t_{mean}$ and the scene specified scale $S_0$, we get
$$
\begin{aligned}
s_0 (W + t_0) - t_{mean} &= s_0 R (M + t_0) + t \\
W + t_0 - \frac{1}{s_0} t_{mean} &= RM + R t_0 + \frac{1}{s_0} t \\
W &= RM + R t_0 -t_0 + \frac{1}{s_0} (t + t_{mean}) \\
\\
\text{Namely, } R' &= R, t' = R t_0 -t_0 + \frac{1}{s_0} (t + t_{mean})
\end{aligned}
$$
Then we use $L_{CD\_half}$ states above to calculate loss and backward.
### Experiment
Use `Adam` optimizer and `LambdaLR` (`lr_lambda = lr_scheduler_gamma ** (epoch / lr_scheduler_step_size )`)
`lr = 1e-4`
`lr_scheduler_step_size = 5`
`lr_scheduler_gamma = 0.9`
We separate training/validate set as the provided `splits`
Training for `10 epochs` because of time limit.
We get a correct rate of $27.4\%$ on the validate set.
Here are some examples:
<center>
<figure>
<img src="pictures/nn - 0.png" width="450"/>
</figure>
</center>
Here are some failure cases:
<center>
<figure>
<img src="pictures/nn - F - 0.png" width='300'/>
<img src="pictures/nn - F - 1.png" width='300'/>
<img src="pictures/nn - F - 2.png" width='300'/>
<img src="pictures/nn - F - 3.png" width='300'/>
<img src="pictures/nn - F - 4.png" width='300'/>
</figure>
</center>
Most of the failure cases are caused by local minimum.
### Possible improvements
1. We refered to `PointNet` and designed a similar network to extract features of the PCD. However, the structure of this network (only 1 max pooling layer in the points channel) limits the ability of feature extraction. So this network structure can only extract global features and is more suitable for tasks based on global features like classification.
1. A possible solution is to extract features by LOD like `PointNet++`. For every extraction, we enlarge the kernel size to extract features from adjacent points, and add and MLP between 2 levels.
2. If there is more time for this project, I may try PCD registration like `PCRNet` or `OMNet`. We believe these networks are more suitable for this problem.
2. We considered geometric symmetry in the ICP algorithm, but didn't consider it in the learning-based section, because of which the network will miss many correct answers. If we improve loss function by geometric symmetry, like a minimum of all possible transformation, the network will detect more potential correct answers I think.
2. We didn't use RGB information, which could be used for pixel-PCD matching. A `ResNet` for RGB feature extraction may provide some help.
## 3. Combination method
ICP algorithm is extremely accurate if we give it a good initial pose $(R_0, t_0)$ and it doesn't fall into local minimum.
But as is stated above in the ICP section, we set multiple initial poses, each (expect those skipped by branch-cut algorithm) may go through ICP algorithm, which is very expensive.
### Idea 1
We could use multiple initial poses and ICP to generate rough transformations $(R_0, t_0)$.
For example, adjusting `icp_tolerance` from `1e-8` to `1e-2`.
Apply the rough transform $(R_0, t_0)$ to the object model as input of the neural network (to solve the problems of initial poses sensitivity).
We can also apply the possible improvements mentioned in both sections above.
### Idea 2
We could first use a neural network to learn the pose estimation in the case of orientation range $[-180\degree, 180\degree]$
Then, based on the transformation $(R_0, t_0)$ predicted by the network, the 2 PCDs can be further aligned precisely in the second stage by using ICP algorithm.
### Experiments
We can record the speed and accuracy of experiment settings below:
Idea 1 and 2 can form a comparation themselves, to balance the speed and accuracy.
We can also do some ablation studies on the 2 ideas:
1. Idea 1:
1. Change the rough transformation generation algorithm, like different `icp_tolerance`, or no initialization
2. Compare it with purely network method
3. Compare it with idea 2
2. Idea 2:
1. Compare the initial poses quality generated with clear/noisy input by network
2. Compare it with purely ICP
3. Compare it with idea 1
|
const doTask = (name, time, cb) => {
console.log("Thực hiện công việc: " + name);
setTimeout(() => {
cb();
}, time);
}
const finish = () => {
console.log("Hoàn thành công việc");
}
// doTask("Rửa bát", 2000, finish);
// Th1: Các tác vụ có liên quan đến nhau
// Nhặt rau - Rửa rau - Luộc rau
console.log("Start");
doTask("Nhặt rau", 3000, () => {
doTask("Rửa rau", 2000, () => {
doTask("Luộc rau", 4000, finish);
});
});
console.log("End");
// Th2: Các tác vụ không liên quan đến nhau
// Ăn cơm - Lướt facebook - Check mail
// console.log("Start");
// doTask("Ăn cơm", 4000, () => {
// console.log("Ăn cơm xong");
// });
// doTask("Lướt facebook", 2000, () => {
// console.log("Lướt facebook xong");
// });
// doTask("Check mail", 3000, () => {
// console.log("Check mail xong");
// });
// console.log("End");
|
package com.farmmart.data.model.product;
import com.farmmart.data.model.message.ValidateErrorMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ResponseStatus
@ControllerAdvice
public class ProductRestEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<ValidateErrorMessage> productExceptionHandler(ProductNotFoundException productNotFoundException){
ValidateErrorMessage validateErrorMessage=new ValidateErrorMessage(HttpStatus.NOT_FOUND,productNotFoundException.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(validateErrorMessage);
}
}
|
package provider
import (
"context"
"encoding/json"
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/rs/zerolog"
"github.com/stretchr/testify/require"
"github.com/persistenceOne/oracle-feeder/oracle/types"
)
const (
lastPriceAtom = "34.69000000"
lastPriceOsmo = "41.35000000"
volume = "2396974.02000000"
)
func TestBinanceProvider_GetTickerPrices(t *testing.T) {
p, err := NewBinanceProvider(
context.TODO(),
zerolog.Nop(),
Endpoint{},
false,
types.CurrencyPair{Base: "ATOM", Quote: "USD"},
)
require.NoError(t, err)
t.Run("valid_request_single_ticker", func(t *testing.T) {
tickerMap := map[string]BinanceTicker{}
tickerMap["ATOMUSD"] = BinanceTicker{
Symbol: "ATOMUSD",
LastPrice: lastPriceAtom,
Volume: volume,
}
p.tickers = tickerMap
prices, err := p.GetTickerPrices(types.CurrencyPair{Base: "ATOM", Quote: "USD"})
require.NoError(t, err)
require.Len(t, prices, 1)
require.Equal(t, sdk.MustNewDecFromStr(lastPriceAtom), prices["ATOMUSD"].Price)
require.Equal(t, sdk.MustNewDecFromStr(volume), prices["ATOMUSD"].Volume)
})
t.Run("valid_request_multi_ticker", func(t *testing.T) {
tickerMap := map[string]BinanceTicker{}
tickerMap["ATOMUSD"] = BinanceTicker{
Symbol: "ATOMUSD",
LastPrice: lastPriceAtom,
Volume: volume,
}
tickerMap["OSMOUSD"] = BinanceTicker{
Symbol: "OSMOUSD",
LastPrice: lastPriceOsmo,
Volume: volume,
}
p.tickers = tickerMap
prices, err := p.GetTickerPrices(
types.CurrencyPair{Base: "ATOM", Quote: "USD"},
types.CurrencyPair{Base: "OSMO", Quote: "USD"},
)
require.NoError(t, err)
require.Len(t, prices, 2)
require.Equal(t, sdk.MustNewDecFromStr(lastPriceAtom), prices["ATOMUSD"].Price)
require.Equal(t, sdk.MustNewDecFromStr(volume), prices["ATOMUSD"].Volume)
require.Equal(t, sdk.MustNewDecFromStr(lastPriceOsmo), prices["OSMOUSD"].Price)
require.Equal(t, sdk.MustNewDecFromStr(volume), prices["OSMOUSD"].Volume)
})
t.Run("invalid_request_invalid_ticker", func(t *testing.T) {
prices, err := p.GetTickerPrices(types.CurrencyPair{Base: "FOO", Quote: "BAR"})
require.EqualError(t, err, "binance failed to get ticker price for FOOBAR")
require.Nil(t, prices)
})
}
func TestBinanceCurrencyPairToBinancePair(t *testing.T) {
cp := types.CurrencyPair{Base: "ATOM", Quote: "USD"}
binanceSymbol := currencyPairToBinanceTickerPair(cp)
require.Equal(t, binanceSymbol, "atomusd@ticker")
}
func TestBinanceProvider_getSubscriptionMsgs(t *testing.T) {
provider := &BinanceProvider{
subscribedPairs: map[string]types.CurrencyPair{},
}
cps := []types.CurrencyPair{
{Base: "ATOM", Quote: "USD"},
}
subMsgs := provider.getSubscriptionMsgs(cps...)
msg, _ := json.Marshal(subMsgs[0])
require.Equal(t, "{\"method\":\"SUBSCRIBE\",\"params\":[\"atomusd@ticker\"],\"id\":1}", string(msg))
msg, _ = json.Marshal(subMsgs[1])
require.Equal(t, "{\"method\":\"SUBSCRIBE\",\"params\":[\"atomusd@kline_1m\"],\"id\":1}", string(msg))
}
|
import { Request, Response } from 'express';
import expressAsyncHandler from 'express-async-handler';
import { body, param, query, validationResult } from 'express-validator';
import TwilioServices from '../../lib/twilio';
import logger from '../../lib/logger';
import userDao from '../../dao/users/userDao';
import { isAuthenticated } from '../../middleware/authMiddleware';
/**
* @api {post} /user/v1/:id/verify/code Send verification code
* @apiDescription Receive a verification email or sms to verify a user's email or phone number
* @apiPermission Authentication
* @apiVersion 1.0.0
* @apiName VerificationCode
* @apiGroup User
*
* @apiParam {String} id Users unique ID.
*
* @apiQuery {String} type Either email or phone.
*
* @apiBody {String} Phone The mobile phone to send verification code (only required if type = phone)
* @apiBody {String} Email The email to send verification code (only required if type = email)
*
* @apiSuccess {Object} User.
*
* @apiError UserDoesNotExist Cannot signin user that does not exist.
* @apiError InvalidVerificationCode Cannot verify incorrect code.
*/
export const userVerificationCodeController = [
// Requires user to be authenticated
isAuthenticated,
// Validate params
param('id', 'Id param must be a string').isString().escape(),
// Validate query params
query(
'type',
'Invalid value for query param type: type must be either phone or email'
)
.isString()
.isIn(['email', 'phone'])
.escape(),
// Sanitize and validate body params
body('phone', 'Enter valid phone')
.optional()
.isMobilePhone('any', { strictMode: true })
.escape(),
body('email', 'Enter valid email').optional().isEmail().escape(),
expressAsyncHandler(async function (req: Request, res: Response) {
// Find the validation errors from the request.
const errors = validationResult(req);
if (!errors.isEmpty()) {
logger.error(errors);
res.status(404).json(errors);
return;
}
// Check if user does not exist
const userId = req.params.id;
const user = await userDao.findUserById(userId);
if (!user) {
const err = new Error(
`User not found: User with id ${req.params.id} not found.`
);
logger.error(err.message);
res.status(404).json({ message: err.message });
return;
}
const type = req.query.type === 'email' ? 'email' : 'phone';
// If type is email, and email already verified, avoid
// sending verification code.
// Ensure that email exists if sending verification
// code to email.
const email = req.body.email;
if (type === 'email' && !email) {
const err = new Error('Invalid Request: Enter a valid email in body.');
logger.error(err.message);
res.status(400).json({ message: err.message });
return;
} else if (type === 'email' && email === user.email && user.emailVerified) {
const err = new Error('Invalid Request: Email already verified.');
logger.error(err.message);
res.status(400).json({ message: err.message });
return;
}
// We need to make sure that the email is not being used by another user
if (type === 'email') {
const existingEmailUser = await userDao.findUserByEmail(email);
if (
existingEmailUser &&
existingEmailUser.email === user.email &&
user.emailVerified
) {
const err = new Error('Invalid Request: Email already being used.');
logger.error(err.message);
res.status(400).json({ message: err.message });
return;
}
}
// Ensure that phone exists if sending verification
// code to phone.
const phone = req.body.phone;
if (type === 'phone' && !phone) {
const err = new Error(
'Invalid Request: Enter a valid phone number in body.'
);
logger.error(err.message);
res.status(400).json({ message: err.message });
return;
}
const address = type === 'email' ? email : phone;
// Send verification code to phone or email accordingly
await TwilioServices.sendVerificationCode(
address,
type === 'email' ? 'email' : 'sms'
)
.then(() => {
res
.status(200)
.send({ message: 'Sent verification code succesfully.' });
return;
})
.catch((err) => {
res
.status(500)
.json({ message: 'Failed: Verification code not sent.' });
logger.error(err);
return;
});
})
];
|
<div id="spent_time_curve_page">
<%
if @user.pref.others[:spent_time_period].nil?
period = 21
else
period = @user.pref.others[:spent_time_period].to_i
end
sql_period = period - 1
%>
<%# this is a comment: select display options %>
<h3 class="clearfix">
<%=l(:label_spent_time)%> (<%= l(:label_last_n_days, period) %>)
<div class="spent-time-options-container">
<span class="select-link-label"><%= l(:label_extended_spent_time_options) %></span>
<a href="#" data-period="7" class="select-link <%= 'current' if period == 7 %>">
1 <%= l(:label_extended_spent_time_week) %></a>
<a href="#" data-period="14" class="select-link <%= 'current' if period == 14 %>">
2 <%= l(:label_extended_spent_time_weeks) %></a>
<a href="#" data-period="21" class="select-link <%= 'current' if period == 21 %>">
3 <%= l(:label_extended_spent_time_weeks) %></a>
<a href="#" data-period="28" class="select-link <%= 'current' if period == 28 %>">
4 <%= l(:label_extended_spent_time_weeks) %></a>
<a href="#" data-period="35" class="select-link <%= 'current' if period == 35 %>">
5 <%= l(:label_extended_spent_time_weeks) %></a>
</div>
</h3>
<%# collecting data here %>
<%
entries = TimeEntry.joins(:activity, :project, {:issue => [:tracker, :status]})
.where("#{TimeEntry.table_name}.user_id = ? AND #{TimeEntry.table_name}.spent_on BETWEEN ? AND ?", @user.id, Date.today - sql_period, Date.today)
.order("#{TimeEntry.table_name}.spent_on DESC, #{Project.table_name}.name ASC, #{Tracker.table_name}.position ASC, #{Issue.table_name}.id ASC")
entries_by_day = entries.group_by(&:spent_on)
%>
<%# add total hour display %>
<div class="total-hours">
<p><%= l(:label_total) %>: <%= html_hours("%.2f" % entries.sum(:hours).to_f) %></p>
</div>
<% if entries.any? %>
<table class="list time-entries">
<thead><tr>
<th><%= l(:label_extended_spent_time_date) %></th>
<th><%= l(:field_hours) %></th>
<th></th>
</tr></thead>
<tbody>
<% entries_by_day.keys.sort.reverse.each do |day| %>
<tr class="odd">
<td><strong><%= day == Date.today ? l(:label_today).titleize : format_date(day) %></strong></td>
<td class="hours"><em><%= html_hours("%.2f" % entries_by_day[day].sum(&:hours).to_f) %></em></td>
<td></td>
</tr>
<% end -%>
</tbody>
</table>
<% end %>
</div>
|
import Transaction from '../../domain/Transaction';
import PaymentGateway from '../gateway/PaymentGateway';
import TransactionRepository from '../repository/TransactionRepository';
export default class ProcessPayment {
constructor(
readonly transactionRepository: TransactionRepository,
readonly paymentGateway: PaymentGateway,
) {}
async execute(input: Input): Promise<Output> {
console.log('processPayment', input);
const transaction = Transaction.create(input.rideId, input.amount);
const inputPaymentGateway = {
cardHolder: 'Cliente Exemplo',
creditCardNumber: '4012001037141112',
expDate: '05/2027',
cvv: '123',
amount: input.amount,
};
const outputPaymentGateway = await this.paymentGateway.createTransaction(inputPaymentGateway);
if (outputPaymentGateway.status === 'approved') {
transaction.approve();
} else {
transaction.reject();
}
await this.transactionRepository.save(transaction);
return {
transactionId: transaction.transactionId,
};
}
}
type Input = {
rideId: string;
amount: number;
};
type Output = {
transactionId: string;
};
|
import functools as ft
import operator as op
import pyspark.sql as sql
import pyspark.sql.functions as f
from .xlsx import SpreadsheetTemplateReader
from .mappings import FormatString, SplitFieldElements
from ..enums import ViSpreadsheetEnum, WorksTemplateEnum
def WorksTemplateReader(path: str) -> sql.DataFrame:
not_null_condition = ft.reduce(op.or_,
[f.col(str(field_name)).isNotNull()
for field_name in [WorksTemplateEnum.WorkTitle,
WorksTemplateEnum.WorkISWC,
WorksTemplateEnum.OtherWorkCode]])
base_mappings = [lambda df: df.withColumn(str(WorksTemplateEnum.WorkTitle),
FormatString(f.col(str(WorksTemplateEnum.WorkTitle)),
to_upper=False)),
lambda df: df.withColumn(str(WorksTemplateEnum.WorkSubTitle),
FormatString(f.col(str(WorksTemplateEnum.WorkSubTitle)),
to_upper=False)),
lambda df: df.withColumn(str(WorksTemplateEnum.WorkOtherTitles),
SplitFieldElements(f.col(str(WorksTemplateEnum.WorkOtherTitles)),
to_upper=False)),
lambda df: df.withColumn(str(WorksTemplateEnum.WorkISWC),
FormatString(f.col(str(WorksTemplateEnum.WorkISWC)),
to_upper=True,
strip_special_chars=True)),
lambda df: df.withColumn(str(WorksTemplateEnum.OtherWorkCode),
FormatString(f.col(str(WorksTemplateEnum.OtherWorkCode)))),
lambda df: df.withColumn(str(WorksTemplateEnum.WriterFirstName),
FormatString(f.col(str(WorksTemplateEnum.WriterFirstName)),
to_upper=True)),
lambda df: df.withColumn(str(WorksTemplateEnum.WriterMiddleName),
FormatString(f.col(str(WorksTemplateEnum.WriterMiddleName)),
to_upper=False)),
lambda df: df.withColumn(str(WorksTemplateEnum.WriterLastName),
FormatString(f.col(str(WorksTemplateEnum.WriterLastName)),
to_upper=False)),
lambda df: df.withColumn(str(WorksTemplateEnum.WriterFullName),
FormatString(f.col(str(WorksTemplateEnum.WriterFullName)),
to_upper=False)),
lambda df: df.withColumn(str(WorksTemplateEnum.WriterIPI),
f.lpad(FormatString(f.col(str(WorksTemplateEnum.WriterIPI))), 11, "0")),
lambda df: df.withColumn(str(WorksTemplateEnum.WriterPRSocieties),
SplitFieldElements(f.col(str(WorksTemplateEnum.WriterPRSocieties)),
to_upper=True)),
lambda df: df.withColumn(str(WorksTemplateEnum.WriterRole),
FormatString(f.col(str(WorksTemplateEnum.WriterRole)))),
lambda df: df.withColumn(str(WorksTemplateEnum.PublisherName),
FormatString(f.col(str(WorksTemplateEnum.PublisherName)),
to_upper=False)),
lambda df: df.withColumn(str(WorksTemplateEnum.PublisherIPI),
f.lpad(FormatString(f.col(str(WorksTemplateEnum.PublisherIPI))), 11, "0")),
lambda df: df.withColumn(str(WorksTemplateEnum.PublisherRole),
FormatString(f.col(str(WorksTemplateEnum.PublisherRole)))),
lambda df: df.withColumn(str(WorksTemplateEnum.RecordingISRC),
FormatString(f.col(str(WorksTemplateEnum.RecordingISRC)),
to_upper=True,
strip_special_chars=True)),
lambda df: df.withColumn(str(WorksTemplateEnum.OtherRecordingCode),
FormatString(f.col(str(WorksTemplateEnum.OtherRecordingCode))))]
return SpreadsheetTemplateReader(path,
spreadsheet=ViSpreadsheetEnum.WorksTemplate,
not_null_condition=not_null_condition,
base_mappings=base_mappings)
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.17;
import {Owned} from "solmate/auth/Owned.sol";
import {Constants} from "src/libraries/Constants.sol";
import {ERC20, SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";
/// @title LiquidTransferProxy
/// @notice This contract is used to transfer tokens to the Liquid Router.
contract LiquidTransferProxy is Owned {
using SafeTransferLib for ERC20;
/// @notice LiquidRouter contract address.
address public liquidRouter;
/// @notice New implementation address.
address public newLiquidRouter;
event ImplementationUpgraded(address indexed liquidRouter);
event NewImplementationQueued(address indexed liquidRouter);
constructor() Owned(msg.sender) {}
function initialize(address _liquidRouter) external onlyOwner {
if (liquidRouter != address(0)) revert Constants.ALREADY_INITIALIZED();
liquidRouter = _liquidRouter;
}
modifier onlyLiquidRouter() {
if (msg.sender != liquidRouter) revert Constants.NOT_ALLOWED();
_;
}
function transferFrom(address token, address from, address to, uint256 amount) external onlyLiquidRouter {
ERC20(token).safeTransferFrom(from, to, amount);
}
function queueImplementation(address _liquidRouter) external onlyOwner {
emit NewImplementationQueued(newLiquidRouter = _liquidRouter);
}
function upgradeImplementation() external onlyOwner {
if (newLiquidRouter == address(0)) revert Constants.NOT_ALLOWED();
emit ImplementationUpgraded(liquidRouter = newLiquidRouter);
newLiquidRouter = address(0);
}
}
|
class Task {
final int id;
final int userId;
final String title;
final String? description;
final List<String>? category;
final DateTime? deadline;
Task({
required this.id,
required this.userId,
required this.title,
this.category,
this.description,
this.deadline,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'userId': userId,
'title': title,
'description': description,
'category': category,
'deadline': deadline?.toIso8601String(),
};
}
factory Task.fromJson(Map<String, dynamic> json) {
return Task(
id: json['id'],
userId: json['userId'],
title: json['title'],
description: json['description'],
category: json['category'],
deadline: json['deadline'],
);
}
}
|
package APITests.week6;
import APITests.utilities.SpartanTestBase;
import io.restassured.response.*;
import org.junit.jupiter.api.*;
import java.util.*;
import static io.restassured.RestAssured.*;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
public class JSONtoJAVATest extends SpartanTestBase {
@DisplayName("GET one Spartan and deserialize to Map")
@Test
public void oneSpartanToMap(){
Response response = given().pathParam("id", 15)
.when().get("/api/spartans/{id}")
.then().statusCode(200).extract().response();
//get the json and convert it to the map
Map<String,Object> jsonMap = response.as(Map.class);//This can not convert the data by itself, requires dependency. Select and add one of the below-mentioned dependencies
//Get the body and map it to a Java object. For JSON responses this requires that you have either
//Jackson, or
//Gson==> I used this.
System.out.println(jsonMap.toString());
//after we got the map, we can use hamcrest or junit assertions to do assertion
String actualName = (String) jsonMap.get("name");
assertThat(actualName,is("Meta"));
}
@DisplayName("GET all spartans to JAVA data structure")
@Test
public void getAllSpartan(){
Response response = get("/api/spartans").then().statusCode(200).extract().response();
//we need to convert json to java which is deserialized
List<Map<String,Object>> jsonList = response.as(List.class);
System.out.println("jsonList.get(1).get(\"name\") = " + jsonList.get(2).get("name"));
Map<String,Object> spartan3 = jsonList.get(2);
System.out.println(spartan3);
}
}
|
import 'package:flutter/material.dart';
import '../../constants.dart';
import '../../model/course.dart';
class CourseSectionCard extends StatelessWidget {
const CourseSectionCard({Key? key, required this.course}) : super(key: key);
final Course course;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Container(
height: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(41),
gradient: course.background,
boxShadow: [
BoxShadow(
color: course.background.colors[0].withOpacity(0.3),
blurRadius: 30,
offset: const Offset(0, 20),
),
BoxShadow(
color: course.background.colors[1].withOpacity(0.3),
blurRadius: 30,
offset: const Offset(0, 20),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(41),
child: Padding(
padding: const EdgeInsets.only(left: 32),
child: Stack(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Image.asset(
'asset/illustrations/${course.illustration}',
fit: BoxFit.cover,
)
],
),
Row(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
course.courseSubtitle,
style: kCardSubtitleStyle,
),
const SizedBox(height: 6),
Text(
course.courseSubtitle,
style: kCardTitleStyle,
),
],
),
),
const Spacer()
],
),
],
),
),
),
),
);
}
}
|
import React from "react";
// @ts-ignore
import styled from "styled-components/native";
const ButtonLabel = styled.Text`
color: black;
`;
const ActionButton = styled.TouchableOpacity<{ width?: number }>`
background-color: white;
justify-content: center;
align-items: center;
padding: 4px;
width: ${({ width }) => width ? `${width}px` : '100%'};
border-radius: 4px;
`;
interface ICustomButton {
label: string;
onPress?: () => void;
width?: number;
}
const CustomButton: React.FC<ICustomButton> = ({label, onPress, width}) => (
<ActionButton onPress={onPress} width={width}>
<ButtonLabel>{label}</ButtonLabel>
</ActionButton>
)
export default CustomButton;
|
// Copyright 2024 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !skip_msgtrace_tests
// +build !skip_msgtrace_tests
package server
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/klauspost/compress/s2"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nats.go"
"github.com/nats-io/nkeys"
)
func init() {
msgTraceRunInTests = true
}
func TestMsgTraceConnName(t *testing.T) {
c := &client{kind: ROUTER, route: &route{remoteName: "somename"}}
c.opts.Name = "someid"
// If route.remoteName is set, it will take precedence.
val := getConnName(c)
require_Equal[string](t, val, "somename")
// When not set, we revert to c.opts.Name
c.route.remoteName = _EMPTY_
val = getConnName(c)
require_Equal[string](t, val, "someid")
// Now same for GW.
c.route = nil
c.gw = &gateway{remoteName: "somename"}
c.kind = GATEWAY
val = getConnName(c)
require_Equal[string](t, val, "somename")
// Revert to c.opts.Name
c.gw.remoteName = _EMPTY_
val = getConnName(c)
require_Equal[string](t, val, "someid")
// For LeafNode now
c.gw = nil
c.leaf = &leaf{remoteServer: "somename"}
c.kind = LEAF
val = getConnName(c)
require_Equal[string](t, val, "somename")
// But if not set...
c.leaf.remoteServer = _EMPTY_
val = getConnName(c)
require_Equal[string](t, val, "someid")
c.leaf = nil
c.kind = CLIENT
val = getConnName(c)
require_Equal[string](t, val, "someid")
}
func TestMsgTraceGenHeaderMap(t *testing.T) {
for _, test := range []struct {
name string
header []byte
expected map[string][]string
external bool
}{
{"missing header line", []byte("Nats-Trace-Dest: val\r\n"), nil, false},
{"no trace header present", []byte(hdrLine + "Header1: val1\r\nHeader2: val2\r\n"), nil, false},
{"trace header with some prefix", []byte(hdrLine + "Some-Prefix-" + MsgTraceDest + ": some value\r\n"), nil, false},
{"trace header with some suffix", []byte(hdrLine + MsgTraceDest + "-Some-Suffix: some value\r\n"), nil, false},
{"trace header with space before colon", []byte(hdrLine + MsgTraceDest + " : some value\r\n"), nil, false},
{"trace header with missing cr_lf for value", []byte(hdrLine + MsgTraceDest + " : bogus"), nil, false},
{"external trace header with some prefix", []byte(hdrLine + "Some-Prefix-" + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\n"), nil, false},
{"external trace header with some suffix", []byte(hdrLine + traceParentHdr + "-Some-Suffix: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\n"), nil, false},
{"external header with space before colon", []byte(hdrLine + traceParentHdr + " : 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\n"), nil, false},
{"external header with missing cr_lf for value", []byte(hdrLine + traceParentHdr + " : 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"), nil, false},
{"trace header first", []byte(hdrLine + MsgTraceDest + ": some.dest\r\nSome-Header: some value\r\n"),
map[string][]string{"Some-Header": {"some value"}, MsgTraceDest: {"some.dest"}}, false},
{"trace header last", []byte(hdrLine + "Some-Header: some value\r\n" + MsgTraceDest + ": some.dest\r\n"),
map[string][]string{"Some-Header": {"some value"}, MsgTraceDest: {"some.dest"}}, false},
{"trace header multiple values", []byte(hdrLine + MsgTraceDest + ": some.dest\r\nSome-Header: some value\r\n" + MsgTraceDest + ": some.dest.2"),
map[string][]string{"Some-Header": {"some value"}, MsgTraceDest: {"some.dest", "some.dest.2"}}, false},
{"trace header and some empty key", []byte(hdrLine + MsgTraceDest + ": some.dest\r\n: bogus\r\nSome-Header: some value\r\n"),
map[string][]string{"Some-Header": {"some value"}, MsgTraceDest: {"some.dest"}}, false},
{"trace header and some header missing cr_lf for value", []byte(hdrLine + MsgTraceDest + ": some.dest\r\nSome-Header: bogus"),
map[string][]string{MsgTraceDest: {"some.dest"}}, false},
{"trace header and external after", []byte(hdrLine + MsgTraceDest + ": some.dest\r\n" + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\nSome-Header: some value\r\n"),
map[string][]string{"Some-Header": {"some value"}, MsgTraceDest: {"some.dest"}, traceParentHdr: {"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"}}, false},
{"trace header and external before", []byte(hdrLine + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\n" + MsgTraceDest + ": some.dest\r\nSome-Header: some value\r\n"),
map[string][]string{"Some-Header": {"some value"}, MsgTraceDest: {"some.dest"}, traceParentHdr: {"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"}}, false},
{"external malformed", []byte(hdrLine + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-01\r\n"), nil, false},
{"external first and sampling", []byte(hdrLine + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\nSome-Header: some value\r\n"),
map[string][]string{"Some-Header": {"some value"}, traceParentHdr: {"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"}}, true},
{"external middle and sampling", []byte(hdrLine + "Some-Header: some value1\r\n" + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\nSome-Header: some value2\r\n"),
map[string][]string{"Some-Header": {"some value1", "some value2"}, traceParentHdr: {"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"}}, true},
{"external last and sampling", []byte(hdrLine + "Some-Header: some value\r\n" + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\n"),
map[string][]string{"Some-Header": {"some value"}, traceParentHdr: {"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"}}, true},
{"external sampling with not just 01", []byte(hdrLine + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-27\r\nSome-Header: some value\r\n"),
map[string][]string{"Some-Header": {"some value"}, traceParentHdr: {"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-27"}}, true},
{"external with different case and sampling", []byte(hdrLine + "TrAcEpArEnT: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\nSome-Header: some value\r\n"),
map[string][]string{"Some-Header": {"some value"}, traceParentHdr: {"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"}}, true},
{"external first and not sampling", []byte(hdrLine + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00\r\nSome-Header: some value\r\n"), nil, false},
{"external middle and not sampling", []byte(hdrLine + "Some-Header: some value1\r\n" + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00\r\nSome-Header: some value2\r\n"), nil, false},
{"external last and not sampling", []byte(hdrLine + "Some-Header: some value\r\n" + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00\r\n"), nil, false},
{"external not sampling with not just 00", []byte(hdrLine + traceParentHdr + ": 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-22\r\nSome-Header: some value\r\n"), nil, false},
} {
t.Run(test.name, func(t *testing.T) {
m, ext := genHeaderMapIfTraceHeadersPresent(test.header)
if test.external != ext {
t.Fatalf("Expected external to be %v, got %v", test.external, ext)
}
if len(test.expected) != len(m) {
t.Fatalf("Expected map to be of size %v, got %v", len(test.expected), len(m))
}
// If external, we should find traceParentHdr
if test.external {
if _, ok := m[traceParentHdr]; !ok {
t.Fatalf("Expected traceparent header to be present, it was not: %+v", m)
}
// Header should have been rewritten, so we should find it in original header.
if !bytes.Contains(test.header, []byte(traceParentHdr)) {
t.Fatalf("Header should have been rewritten to have the traceparent in lower case: %s", test.header)
}
}
for k, vv := range m {
evv, ok := test.expected[k]
if !ok {
t.Fatalf("Did not find header %q in resulting map: %+v", k, m)
}
for i, v := range vv {
if evv[i] != v {
t.Fatalf("Expected value %v of key %q to be %q, got %q", i, k, evv[i], v)
}
}
}
})
}
}
func TestMsgTraceBasic(t *testing.T) {
conf := createConfFile(t, []byte(`
listen: 127.0.0.1:-1
mappings = {
foo: bar
}
`))
s, _ := RunServerWithConfig(conf)
defer s.Shutdown()
nc := natsConnect(t, s.ClientURL())
defer nc.Close()
cid, err := nc.GetClientID()
require_NoError(t, err)
traceSub := natsSubSync(t, nc, "my.trace.subj")
natsFlush(t, nc)
// Send trace message to a dummy subject to check that resulting trace's
// SubjectMapping and Egress are nil.
msg := nats.NewMsg("dummy")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
msg.Header.Set(MsgTraceOnly, "true")
msg.Data = []byte("hello!")
err = nc.PublishMsg(msg)
require_NoError(t, err)
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
// We don't remove the headers, so we will find the tracing header there.
require_True(t, e.Request.Header != nil)
require_Equal[int](t, len(e.Request.Header), 2)
// The message size is 6 + whatever size for the 2 trace headers.
// Let's just make sure that size is > 20...
require_True(t, e.Request.MsgSize > 20)
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
require_True(t, ingress.Timestamp != time.Time{})
require_Equal[uint64](t, ingress.CID, cid)
require_Equal[string](t, ingress.Name, _EMPTY_)
require_Equal[string](t, ingress.Account, globalAccountName)
require_Equal[string](t, ingress.Subject, "dummy")
require_Equal[string](t, ingress.Error, _EMPTY_)
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.StreamExports() == nil)
require_True(t, e.ServiceImports() == nil)
require_True(t, e.JetStream() == nil)
require_True(t, e.Egresses() == nil)
// Now setup subscriptions that generate interest on the subject.
nc2 := natsConnect(t, s.ClientURL(), nats.Name("sub1And2"))
defer nc2.Close()
sub1 := natsSubSync(t, nc2, "bar")
sub2 := natsSubSync(t, nc2, "bar")
natsFlush(t, nc2)
nc2CID, _ := nc2.GetClientID()
nc3 := natsConnect(t, s.ClientURL())
defer nc3.Close()
sub3 := natsSubSync(t, nc3, "*")
natsFlush(t, nc3)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg = nats.NewMsg("foo")
msg.Header.Set("Some-App-Header", "some value")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello!")
err = nc.PublishMsg(msg)
require_NoError(t, err)
checkAppMsg := func(sub *nats.Subscription, expected bool) {
if expected {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "hello!")
// We don't remove message trace header, so we should have
// 2 headers (the app + trace destination)
require_True(t, len(appMsg.Header) == 2)
require_Equal[string](t, appMsg.Header.Get("Some-App-Header"), "some value")
require_Equal[string](t, appMsg.Header.Get(MsgTraceDest), traceSub.Subject)
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got %s", msg.Data)
}
}
for _, sub := range []*nats.Subscription{sub1, sub2, sub3} {
checkAppMsg(sub, test.deliverMsg)
}
traceMsg = natsNexMsg(t, traceSub, time.Second)
e = MsgTraceEvent{}
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
require_True(t, e.Request.Header != nil)
// We should have the app header and the trace header(s) too.
expected := 2
if !test.deliverMsg {
// The "trace-only" header is added.
expected++
}
require_Equal[int](t, len(e.Request.Header), expected)
require_Equal[string](t, e.Request.Header["Some-App-Header"][0], "some value")
// The message size is 6 + whatever size for the 2 trace headers.
// Let's just make sure that size is > 20...
require_True(t, e.Request.MsgSize > 20)
ingress := e.Ingress()
require_True(t, ingress.Kind == CLIENT)
require_True(t, ingress.Timestamp != time.Time{})
require_Equal[string](t, ingress.Account, globalAccountName)
require_Equal[string](t, ingress.Subject, "foo")
sm := e.SubjectMapping()
require_True(t, sm != nil)
require_True(t, sm.Timestamp != time.Time{})
require_Equal[string](t, sm.MappedTo, "bar")
egress := e.Egresses()
require_Equal[int](t, len(egress), 3)
var sub1And2 int
for _, eg := range egress {
// All Egress should be clients
require_True(t, eg.Kind == CLIENT)
require_True(t, eg.Timestamp != time.Time{})
// For nc2CID, we should have two egress
if eg.CID == nc2CID {
// Check name
require_Equal[string](t, eg.Name, "sub1And2")
require_Equal[string](t, eg.Subscription, "bar")
sub1And2++
} else {
// No name set
require_Equal[string](t, eg.Name, _EMPTY_)
require_Equal[string](t, eg.Subscription, "*")
}
}
require_Equal[int](t, sub1And2, 2)
})
}
}
func TestMsgTraceIngressMaxPayloadError(t *testing.T) {
o := DefaultOptions()
o.MaxPayload = 1024
s := RunServer(o)
defer s.Shutdown()
nc := natsConnect(t, s.ClientURL())
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
natsSub(t, nc, "foo", func(_ *nats.Msg) {})
natsFlush(t, nc)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
nc2, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", o.Port))
require_NoError(t, err)
defer nc2.Close()
nc2.Write([]byte("CONNECT {\"protocol\":1,\"headers\":true,\"no_responders\":true}\r\n"))
var traceOnlyHdr string
if !test.deliverMsg {
traceOnlyHdr = fmt.Sprintf("%s:true\r\n", MsgTraceOnly)
}
hdr := fmt.Sprintf("%s%s:%s\r\n%s\r\n", hdrLine, MsgTraceDest, traceSub.Subject, traceOnlyHdr)
hPub := fmt.Sprintf("HPUB foo %d 2048\r\n%sAAAAAAAAAAAAAAAAAA...", len(hdr), hdr)
nc2.Write([]byte(hPub))
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
require_True(t, e.Request.Header == nil)
require_True(t, e.Ingress() != nil)
require_Contains(t, e.Ingress().Error, ErrMaxPayload.Error())
require_True(t, e.Egresses() == nil)
})
}
}
func TestMsgTraceIngressErrors(t *testing.T) {
conf := createConfFile(t, []byte(`
port: -1
accounts {
A {
users: [
{
user: a
password: pwd
permissions {
subscribe: ["my.trace.subj", "foo"]
publish {
allow: ["foo", "bar.>"]
deny: ["bar.baz"]
}
}
}
]
}
}
`))
s, _ := RunServerWithConfig(conf)
defer s.Shutdown()
nc := natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
natsSub(t, nc, "foo", func(_ *nats.Msg) {})
natsFlush(t, nc)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
nc2 := natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"))
defer nc2.Close()
sendMsg := func(subj, reply, errTxt string) {
msg := nats.NewMsg(subj)
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Reply = reply
msg.Data = []byte("hello")
nc2.PublishMsg(msg)
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
require_True(t, e.Request.Header != nil)
require_Contains(t, e.Ingress().Error, errTxt)
require_True(t, e.Egresses() == nil)
}
// Send to a subject that causes permission violation
sendMsg("bar.baz", _EMPTY_, "Permissions Violation for Publish to")
// Send to a subject that is reserved for GW replies
sendMsg(gwReplyPrefix+"foo", _EMPTY_, "Permissions Violation for Publish to")
// Send with a Reply that is reserved
sendMsg("foo", replyPrefix+"bar", "Permissions Violation for Publish with Reply of")
})
}
}
func TestMsgTraceEgressErrors(t *testing.T) {
conf := createConfFile(t, []byte(`
port: -1
accounts {
A {
users: [
{
user: a
password: pwd
permissions {
subscribe: {
allow: ["my.trace.subj", "foo", "bar.>"]
deny: "bar.bat"
}
publish {
allow: ["foo", "bar.>"]
deny: ["bar.baz"]
}
}
}
]
}
}
`))
s, _ := RunServerWithConfig(conf)
defer s.Shutdown()
nc := natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
natsFlush(t, nc)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
sendMsg := func(pubc *nats.Conn, subj, errTxt string) {
t.Helper()
msg := nats.NewMsg(subj)
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello")
pubc.PublishMsg(msg)
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
require_Contains(t, egress[0].Error, errTxt)
}
// Test no-echo.
nc2 := natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"), nats.NoEcho())
defer nc2.Close()
natsSubSync(t, nc2, "foo")
sendMsg(nc2, "foo", errMsgTraceNoEcho)
nc2.Close()
// Test deny sub.
nc2 = natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"))
defer nc2.Close()
natsSubSync(t, nc2, "bar.>")
sendMsg(nc2, "bar.bat", errMsgTraceSubDeny)
nc2.Close()
// Test sub closed
nc2 = natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"))
defer nc2.Close()
natsSubSync(t, nc2, "bar.>")
natsFlush(t, nc2)
// Aritifially change the closed status of the subscription
cid, err := nc2.GetClientID()
require_NoError(t, err)
c := s.GetClient(cid)
c.mu.Lock()
for _, sub := range c.subs {
if string(sub.subject) == "bar.>" {
sub.close()
}
}
c.mu.Unlock()
sendMsg(nc2, "bar.bar", errMsgTraceSubClosed)
nc2.Close()
// The following applies only when doing delivery.
if test.deliverMsg {
// Test auto-unsub exceeded
nc2 = natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"))
defer nc2.Close()
sub := natsSubSync(t, nc2, "bar.>")
err := sub.AutoUnsubscribe(10)
require_NoError(t, err)
natsFlush(t, nc2)
// Modify sub.nm to be already over the 10 limit
cid, err := nc2.GetClientID()
require_NoError(t, err)
c := s.GetClient(cid)
c.mu.Lock()
for _, sub := range c.subs {
if string(sub.subject) == "bar.>" {
sub.nm = 20
}
}
c.mu.Unlock()
sendMsg(nc2, "bar.bar", errMsgTraceAutoSubExceeded)
nc2.Close()
// Test client closed
nc2 = natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"))
defer nc2.Close()
natsSubSync(t, nc2, "bar.>")
cid, err = nc2.GetClientID()
require_NoError(t, err)
c = s.GetClient(cid)
c.mu.Lock()
c.out.stc = make(chan struct{})
c.mu.Unlock()
msg := nats.NewMsg("bar.bar")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello")
nc2.PublishMsg(msg)
time.Sleep(10 * time.Millisecond)
cid, err = nc2.GetClientID()
require_NoError(t, err)
c = s.GetClient(cid)
c.mu.Lock()
c.flags.set(closeConnection)
c.mu.Unlock()
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
require_Contains(t, egress[0].Error, errMsgTraceClientClosed)
c.mu.Lock()
c.flags.clear(closeConnection)
c.mu.Unlock()
nc2.Close()
}
})
}
}
func TestMsgTraceWithQueueSub(t *testing.T) {
o := DefaultOptions()
s := RunServer(o)
defer s.Shutdown()
nc := natsConnect(t, s.ClientURL())
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
natsFlush(t, nc)
nc2 := natsConnect(t, s.ClientURL(), nats.Name("sub1"))
defer nc2.Close()
sub1 := natsQueueSubSync(t, nc2, "foo", "bar")
natsFlush(t, nc2)
nc3 := natsConnect(t, s.ClientURL(), nats.Name("sub2"))
defer nc3.Close()
sub2 := natsQueueSubSync(t, nc3, "foo", "bar")
sub3 := natsQueueSubSync(t, nc3, "*", "baz")
natsFlush(t, nc3)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
if !test.deliverMsg {
msg.Data = []byte("hello1")
} else {
msg.Data = []byte("hello2")
}
err := nc.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
// Only one should have got the message...
msg1, err1 := sub1.NextMsg(100 * time.Millisecond)
msg2, err2 := sub2.NextMsg(100 * time.Millisecond)
if err1 == nil && err2 == nil {
t.Fatalf("Only one message should have been received")
}
var val string
if msg1 != nil {
val = string(msg1.Data)
} else {
val = string(msg2.Data)
}
require_Equal[string](t, val, "hello2")
// Queue baz should also have received the message
msg := natsNexMsg(t, sub3, time.Second)
require_Equal[string](t, string(msg.Data), "hello2")
}
// Check that no (more) messages are received.
for _, sub := range []*nats.Subscription{sub1, sub2, sub3} {
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Expected no message, got %s", msg.Data)
}
}
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, ingress.Subject, "foo")
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
var qbar, qbaz int
for _, eg := range egress {
switch eg.Queue {
case "bar":
require_Equal[string](t, eg.Subscription, "foo")
qbar++
case "baz":
require_Equal[string](t, eg.Subscription, "*")
qbaz++
default:
t.Fatalf("Wrong queue name: %q", eg.Queue)
}
}
require_Equal[int](t, qbar, 1)
require_Equal[int](t, qbaz, 1)
})
}
}
func TestMsgTraceWithRoutes(t *testing.T) {
tmpl := `
port: -1
accounts {
A { users: [{user:A, password: pwd}] }
B { users: [{user:B, password: pwd}] }
}
cluster {
name: "local"
port: -1
accounts: ["A"]
%s
}
`
conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, _EMPTY_)))
s1, o1 := RunServerWithConfig(conf1)
defer s1.Shutdown()
conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
s2, _ := RunServerWithConfig(conf2)
defer s2.Shutdown()
checkClusterFormed(t, s1, s2)
checkDummy := func(user string) {
nc := natsConnect(t, s1.ClientURL(), nats.UserInfo(user, "pwd"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
natsFlush(t, nc)
// Send trace message to a dummy subject to check that resulting trace
// is as expected.
msg := nats.NewMsg("dummy")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
msg.Header.Set(MsgTraceOnly, "true")
msg.Data = []byte("hello!")
err := nc.PublishMsg(msg)
require_NoError(t, err)
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s1.Name())
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
// "user" is same than account name in this test.
require_Equal[string](t, ingress.Account, user)
require_Equal[string](t, ingress.Subject, "dummy")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.Egresses() == nil)
// We should also not get an event from the remote server.
if msg, err := traceSub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Expected no message, got %s", msg.Data)
}
}
checkDummy("A")
checkDummy("B")
for _, test := range []struct {
name string
acc string
}{
{"pinned account", "A"},
{"reg account", "B"},
} {
t.Run(test.name, func(t *testing.T) {
acc := test.acc
// Now create subscriptions on both s1 and s2
nc2 := natsConnect(t, s2.ClientURL(), nats.UserInfo(acc, "pwd"), nats.Name("sub2"))
defer nc2.Close()
sub2 := natsQueueSubSync(t, nc2, "foo.*", "my_queue")
nc3 := natsConnect(t, s2.ClientURL(), nats.UserInfo(acc, "pwd"), nats.Name("sub3"))
defer nc3.Close()
sub3 := natsQueueSubSync(t, nc3, "*.*", "my_queue_2")
checkSubInterest(t, s1, acc, "foo.bar", time.Second)
nc1 := natsConnect(t, s1.ClientURL(), nats.UserInfo(acc, "pwd"), nats.Name("sub1"))
defer nc1.Close()
sub1 := natsSubSync(t, nc1, "*.bar")
nct := natsConnect(t, s1.ClientURL(), nats.UserInfo(acc, "pwd"), nats.Name("tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, "my.trace.subj")
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo.bar")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello!")
err := nct.PublishMsg(msg)
require_NoError(t, err)
checkAppMsg := func(sub *nats.Subscription, expected bool) {
if expected {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "hello!")
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got %s", msg.Data)
}
}
for _, sub := range []*nats.Subscription{sub1, sub2, sub3} {
checkAppMsg(sub, test.deliverMsg)
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, s1.Name())
require_Equal[string](t, ingress.Account, acc)
require_Equal[string](t, ingress.Subject, "foo.bar")
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
if eg.Kind == CLIENT {
require_Equal[string](t, eg.Name, "sub1")
require_Equal[string](t, eg.Subscription, "*.bar")
require_Equal[string](t, eg.Queue, _EMPTY_)
} else {
require_True(t, eg.Kind == ROUTER)
require_Equal[string](t, eg.Name, s2.Name())
require_Equal[string](t, eg.Subscription, _EMPTY_)
require_Equal[string](t, eg.Queue, _EMPTY_)
}
}
case ROUTER:
require_Equal[string](t, e.Server.Name, s2.Name())
require_Equal[string](t, ingress.Account, acc)
require_Equal[string](t, ingress.Subject, "foo.bar")
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
var gotSub2, gotSub3 int
for _, eg := range egress {
require_True(t, eg.Kind == CLIENT)
switch eg.Name {
case "sub2":
require_Equal[string](t, eg.Subscription, "foo.*")
require_Equal[string](t, eg.Queue, "my_queue")
gotSub2++
case "sub3":
require_Equal[string](t, eg.Subscription, "*.*")
require_Equal[string](t, eg.Queue, "my_queue_2")
gotSub3++
default:
t.Fatalf("Unexpected egress name: %+v", eg)
}
}
require_Equal[int](t, gotSub2, 1)
require_Equal[int](t, gotSub3, 1)
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
// We should get 2 events. Order is not guaranteed.
check()
check()
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
})
}
})
}
}
func TestMsgTraceWithRouteToOldServer(t *testing.T) {
msgTraceCheckSupport = true
defer func() { msgTraceCheckSupport = false }()
tmpl := `
port: -1
cluster {
name: "local"
port: -1
pool_size: -1
%s
}
`
conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, _EMPTY_)))
s1, o1 := RunServerWithConfig(conf1)
defer s1.Shutdown()
conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
o2 := LoadConfig(conf2)
// Make this server behave like an older server
o2.overrideProto = setServerProtoForTest(MsgTraceProto - 1)
s2 := RunServer(o2)
defer s2.Shutdown()
checkClusterFormed(t, s1, s2)
// Now create subscriptions on both s1 and s2
nc2 := natsConnect(t, s2.ClientURL(), nats.Name("sub2"))
defer nc2.Close()
sub2 := natsSubSync(t, nc2, "foo")
checkSubInterest(t, s1, globalAccountName, "foo", time.Second)
nc1 := natsConnect(t, s1.ClientURL(), nats.Name("sub1"))
defer nc1.Close()
sub1 := natsSubSync(t, nc1, "foo")
nct := natsConnect(t, s1.ClientURL(), nats.Name("tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, "my.trace.subj")
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello!")
err := nct.PublishMsg(msg)
require_NoError(t, err)
checkAppMsg := func(sub *nats.Subscription, expected bool) {
if expected {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "hello!")
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got %s", msg.Data)
}
}
// Even if a server does not support tracing, as long as the header
// TraceOnly is not set, the message should be forwarded to the remote.
for _, sub := range []*nats.Subscription{sub1, sub2} {
checkAppMsg(sub, test.deliverMsg)
}
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, e.Server.Name, s1.Name())
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, ci := range egress {
switch ci.Kind {
case CLIENT:
require_Equal[string](t, ci.Name, "sub1")
case ROUTER:
require_Equal[string](t, ci.Name, s2.Name())
if test.deliverMsg {
require_Contains(t, ci.Error, errMsgTraceNoSupport)
} else {
require_Contains(t, ci.Error, errMsgTraceOnlyNoSupport)
}
default:
t.Fatalf("Unexpected egress: %+v", ci)
}
}
// We should not get a second trace
if msg, err := traceSub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect other trace, got %s", msg.Data)
}
})
}
}
func TestMsgTraceWithLeafNode(t *testing.T) {
for _, mainTest := range []struct {
name string
fromHub bool
leafUseLocalAcc bool
}{
{"from hub", true, false},
{"from leaf", false, false},
{"from hub with local account", true, true},
{"from leaf with local account", false, true},
} {
t.Run(mainTest.name, func(t *testing.T) {
confHub := createConfFile(t, []byte(`
port: -1
server_name: "A"
accounts {
A { users: [{user: "a", password: "pwd"}]}
B { users: [{user: "b", password: "pwd"}]}
}
leafnodes {
port: -1
}
`))
hub, ohub := RunServerWithConfig(confHub)
defer hub.Shutdown()
var accs string
var lacc string
if mainTest.leafUseLocalAcc {
accs = `accounts { B { users: [{user: "b", password: "pwd"}]} }`
lacc = `account: B`
}
confLeaf := createConfFile(t, []byte(fmt.Sprintf(`
port: -1
server_name: "B"
%s
leafnodes {
remotes [
{
url: "nats://a:pwd@127.0.0.1:%d"
%s
}
]
}
`, accs, ohub.LeafNode.Port, lacc)))
leaf, _ := RunServerWithConfig(confLeaf)
defer leaf.Shutdown()
checkLeafNodeConnected(t, hub)
checkLeafNodeConnected(t, leaf)
var s1, s2 *Server
if mainTest.fromHub {
s1, s2 = hub, leaf
} else {
s1, s2 = leaf, hub
}
// Now create subscriptions on both s1 and s2
opts := []nats.Option{nats.Name("sub2")}
var user string
// If fromHub, then it means that s2 is the leaf.
if mainTest.fromHub {
if mainTest.leafUseLocalAcc {
user = "b"
}
} else {
// s2 is the hub, always connect with user "a'"
user = "a"
}
if user != _EMPTY_ {
opts = append(opts, nats.UserInfo(user, "pwd"))
}
nc2 := natsConnect(t, s2.ClientURL(), opts...)
defer nc2.Close()
sub2 := natsSubSync(t, nc2, "foo")
if mainTest.fromHub {
checkSubInterest(t, s1, "A", "foo", time.Second)
} else if mainTest.leafUseLocalAcc {
checkSubInterest(t, s1, "B", "foo", time.Second)
} else {
checkSubInterest(t, s1, globalAccountName, "foo", time.Second)
}
user = _EMPTY_
opts = []nats.Option{nats.Name("sub1")}
if mainTest.fromHub {
// s1 is the hub, so we need user "a"
user = "a"
} else if mainTest.leafUseLocalAcc {
// s1 is the leaf, we need user "b" if leafUseLocalAcc
user = "b"
}
if user != _EMPTY_ {
opts = append(opts, nats.UserInfo(user, "pwd"))
}
nc1 := natsConnect(t, s1.ClientURL(), opts...)
defer nc1.Close()
sub1 := natsSubSync(t, nc1, "foo")
opts = []nats.Option{nats.Name("tracer")}
if user != _EMPTY_ {
opts = append(opts, nats.UserInfo(user, "pwd"))
}
nct := natsConnect(t, s1.ClientURL(), opts...)
defer nct.Close()
traceSub := natsSubSync(t, nct, "my.trace.subj")
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello!")
err := nct.PublishMsg(msg)
require_NoError(t, err)
checkAppMsg := func(sub *nats.Subscription, expected bool) {
if expected {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "hello!")
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got %s", msg.Data)
}
}
for _, sub := range []*nats.Subscription{sub1, sub2} {
checkAppMsg(sub, test.deliverMsg)
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, s1.Name())
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
switch eg.Kind {
case CLIENT:
require_Equal[string](t, eg.Name, "sub1")
case LEAF:
require_Equal[string](t, eg.Name, s2.Name())
require_Equal[string](t, eg.Error, _EMPTY_)
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
case LEAF:
require_Equal[string](t, e.Server.Name, s2.Name())
require_True(t, ingress.Kind == LEAF)
require_Equal(t, ingress.Name, s1.Name())
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == CLIENT)
require_Equal[string](t, eg.Name, "sub2")
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
check()
check()
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
})
}
})
}
}
func TestMsgTraceWithLeafNodeToOldServer(t *testing.T) {
msgTraceCheckSupport = true
defer func() { msgTraceCheckSupport = false }()
for _, mainTest := range []struct {
name string
fromHub bool
}{
{"from hub", true},
{"from leaf", false},
} {
t.Run(mainTest.name, func(t *testing.T) {
confHub := createConfFile(t, []byte(`
port: -1
server_name: "A"
leafnodes {
port: -1
}
`))
ohub := LoadConfig(confHub)
if !mainTest.fromHub {
// Make this server behave like an older server
ohub.overrideProto = setServerProtoForTest(MsgTraceProto - 1)
}
hub := RunServer(ohub)
defer hub.Shutdown()
confLeaf := createConfFile(t, []byte(fmt.Sprintf(`
port: -1
server_name: "B"
leafnodes {
remotes [{url: "nats://127.0.0.1:%d"}]
}
`, ohub.LeafNode.Port)))
oleaf := LoadConfig(confLeaf)
if mainTest.fromHub {
// Make this server behave like an older server
oleaf.overrideProto = setServerProtoForTest(MsgTraceProto - 1)
}
leaf := RunServer(oleaf)
defer leaf.Shutdown()
checkLeafNodeConnected(t, hub)
checkLeafNodeConnected(t, leaf)
var s1, s2 *Server
if mainTest.fromHub {
s1, s2 = hub, leaf
} else {
s1, s2 = leaf, hub
}
// Now create subscriptions on both s1 and s2
nc2 := natsConnect(t, s2.ClientURL(), nats.Name("sub2"))
defer nc2.Close()
sub2 := natsSubSync(t, nc2, "foo")
checkSubInterest(t, s1, globalAccountName, "foo", time.Second)
nc1 := natsConnect(t, s1.ClientURL(), nats.Name("sub1"))
defer nc1.Close()
sub1 := natsSubSync(t, nc1, "foo")
nct := natsConnect(t, s1.ClientURL(), nats.Name("tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, "my.trace.subj")
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello!")
err := nct.PublishMsg(msg)
require_NoError(t, err)
checkAppMsg := func(sub *nats.Subscription, expected bool) {
if expected {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "hello!")
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got %s", msg.Data)
}
}
// Even if a server does not support tracing, as long as the header
// TraceOnly is not set, the message should be forwarded to the remote.
for _, sub := range []*nats.Subscription{sub1, sub2} {
checkAppMsg(sub, test.deliverMsg)
}
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, e.Server.Name, s1.Name())
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, ci := range egress {
switch ci.Kind {
case CLIENT:
require_Equal[string](t, ci.Name, "sub1")
case LEAF:
require_Equal[string](t, ci.Name, s2.Name())
if test.deliverMsg {
require_Contains(t, ci.Error, errMsgTraceNoSupport)
} else {
require_Contains(t, ci.Error, errMsgTraceOnlyNoSupport)
}
default:
t.Fatalf("Unexpected egress: %+v", ci)
}
}
// We should not get a second trace
if msg, err := traceSub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect other trace, got %s", msg.Data)
}
})
}
})
}
}
func TestMsgTraceWithLeafNodeDaisyChain(t *testing.T) {
confHub := createConfFile(t, []byte(`
port: -1
server_name: "A"
accounts {
A { users: [{user: "a", password: "pwd"}]}
}
leafnodes {
port: -1
}
`))
hub, ohub := RunServerWithConfig(confHub)
defer hub.Shutdown()
confLeaf1 := createConfFile(t, []byte(fmt.Sprintf(`
port: -1
server_name: "B"
accounts {
B { users: [{user: "b", password: "pwd"}]}
}
leafnodes {
port: -1
remotes [{url: "nats://a:pwd@127.0.0.1:%d", account: B}]
}
`, ohub.LeafNode.Port)))
leaf1, oleaf1 := RunServerWithConfig(confLeaf1)
defer leaf1.Shutdown()
confLeaf2 := createConfFile(t, []byte(fmt.Sprintf(`
port: -1
server_name: "C"
accounts {
C { users: [{user: "c", password: "pwd"}]}
}
leafnodes {
remotes [{url: "nats://b:pwd@127.0.0.1:%d", account: C}]
}
`, oleaf1.LeafNode.Port)))
leaf2, _ := RunServerWithConfig(confLeaf2)
defer leaf2.Shutdown()
checkLeafNodeConnected(t, hub)
checkLeafNodeConnectedCount(t, leaf1, 2)
checkLeafNodeConnected(t, leaf2)
nct := natsConnect(t, hub.ClientURL(), nats.UserInfo("a", "pwd"), nats.Name("Tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, "my.trace.subj")
natsFlush(t, nct)
// Make sure that subject interest travels down to leaf2
checkSubInterest(t, leaf2, "C", traceSub.Subject, time.Second)
nc1 := natsConnect(t, leaf1.ClientURL(), nats.UserInfo("b", "pwd"), nats.Name("sub1"))
defer nc1.Close()
nc2 := natsConnect(t, leaf2.ClientURL(), nats.UserInfo("c", "pwd"), nats.Name("sub2"))
defer nc2.Close()
sub2 := natsQueueSubSync(t, nc2, "foo.bar", "my_queue")
natsFlush(t, nc2)
// Check the subject interest makes it to leaf1
checkSubInterest(t, leaf1, "B", "foo.bar", time.Second)
// Now create the sub on leaf1
sub1 := natsSubSync(t, nc1, "foo.*")
natsFlush(t, nc1)
// Check that subject interest registered on "hub"
checkSubInterest(t, hub, "A", "foo.bar", time.Second)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo.bar")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello!")
err := nct.PublishMsg(msg)
require_NoError(t, err)
checkAppMsg := func(sub *nats.Subscription, expected bool) {
if expected {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "hello!")
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got %s", msg.Data)
}
}
for _, sub := range []*nats.Subscription{sub1, sub2} {
checkAppMsg(sub, test.deliverMsg)
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, hub.Name())
require_Equal[string](t, ingress.Name, "Tracer")
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "foo.bar")
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == LEAF)
require_Equal[string](t, eg.Name, leaf1.Name())
require_Equal[string](t, eg.Account, _EMPTY_)
require_Equal[string](t, eg.Subscription, _EMPTY_)
case LEAF:
switch e.Server.Name {
case leaf1.Name():
require_Equal(t, ingress.Name, hub.Name())
require_Equal(t, ingress.Account, "B")
require_Equal[string](t, ingress.Subject, "foo.bar")
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
switch eg.Kind {
case CLIENT:
require_Equal[string](t, eg.Name, "sub1")
require_Equal[string](t, eg.Subscription, "foo.*")
require_Equal[string](t, eg.Queue, _EMPTY_)
case LEAF:
require_Equal[string](t, eg.Name, leaf2.Name())
require_Equal[string](t, eg.Account, _EMPTY_)
require_Equal[string](t, eg.Subscription, _EMPTY_)
require_Equal[string](t, eg.Queue, _EMPTY_)
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
case leaf2.Name():
require_Equal(t, ingress.Name, leaf1.Name())
require_Equal(t, ingress.Account, "C")
require_Equal[string](t, ingress.Subject, "foo.bar")
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == CLIENT)
require_Equal[string](t, eg.Name, "sub2")
require_Equal[string](t, eg.Subscription, "foo.bar")
require_Equal[string](t, eg.Queue, "my_queue")
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
check()
check()
check()
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
})
}
}
func TestMsgTraceWithGateways(t *testing.T) {
o2 := testDefaultOptionsForGateway("B")
o2.NoSystemAccount = false
s2 := runGatewayServer(o2)
defer s2.Shutdown()
o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
o1.NoSystemAccount = false
s1 := runGatewayServer(o1)
defer s1.Shutdown()
waitForOutboundGateways(t, s1, 1, time.Second)
waitForInboundGateways(t, s2, 1, time.Second)
waitForOutboundGateways(t, s2, 1, time.Second)
nc2 := natsConnect(t, s2.ClientURL(), nats.Name("sub2"))
defer nc2.Close()
sub2 := natsQueueSubSync(t, nc2, "foo.*", "my_queue")
nc3 := natsConnect(t, s2.ClientURL(), nats.Name("sub3"))
defer nc3.Close()
sub3 := natsQueueSubSync(t, nc3, "*.*", "my_queue_2")
nc1 := natsConnect(t, s1.ClientURL(), nats.Name("sub1"))
defer nc1.Close()
sub1 := natsSubSync(t, nc1, "*.bar")
nct := natsConnect(t, s1.ClientURL(), nats.Name("tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, "my.trace.subj")
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo.bar")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello!")
err := nct.PublishMsg(msg)
require_NoError(t, err)
checkAppMsg := func(sub *nats.Subscription, expected bool) {
if expected {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "hello!")
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got %s", msg.Data)
}
}
for _, sub := range []*nats.Subscription{sub1, sub2, sub3} {
checkAppMsg(sub, test.deliverMsg)
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, s1.Name())
require_Equal[string](t, ingress.Account, globalAccountName)
require_Equal[string](t, ingress.Subject, "foo.bar")
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
switch eg.Kind {
case CLIENT:
require_Equal[string](t, eg.Name, "sub1")
require_Equal[string](t, eg.Subscription, "*.bar")
require_Equal[string](t, eg.Queue, _EMPTY_)
case GATEWAY:
require_Equal[string](t, eg.Name, s2.Name())
require_Equal[string](t, eg.Error, _EMPTY_)
require_Equal[string](t, eg.Subscription, _EMPTY_)
require_Equal[string](t, eg.Queue, _EMPTY_)
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
case GATEWAY:
require_Equal[string](t, e.Server.Name, s2.Name())
require_Equal[string](t, ingress.Account, globalAccountName)
require_Equal[string](t, ingress.Subject, "foo.bar")
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
var gotSub2, gotSub3 int
for _, eg := range egress {
require_True(t, eg.Kind == CLIENT)
switch eg.Name {
case "sub2":
require_Equal[string](t, eg.Subscription, "foo.*")
require_Equal[string](t, eg.Queue, "my_queue")
gotSub2++
case "sub3":
require_Equal[string](t, eg.Subscription, "*.*")
require_Equal[string](t, eg.Queue, "my_queue_2")
gotSub3++
default:
t.Fatalf("Unexpected egress name: %+v", eg)
}
}
require_Equal[int](t, gotSub2, 1)
require_Equal[int](t, gotSub3, 1)
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
// We should get 2 events
check()
check()
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
})
}
}
func TestMsgTraceWithGatewayToOldServer(t *testing.T) {
msgTraceCheckSupport = true
defer func() { msgTraceCheckSupport = false }()
o2 := testDefaultOptionsForGateway("B")
o2.NoSystemAccount = false
// Make this server behave like an older server
o2.overrideProto = setServerProtoForTest(MsgTraceProto - 1)
s2 := runGatewayServer(o2)
defer s2.Shutdown()
o1 := testGatewayOptionsFromToWithServers(t, "A", "B", s2)
o1.NoSystemAccount = false
s1 := runGatewayServer(o1)
defer s1.Shutdown()
waitForOutboundGateways(t, s1, 1, time.Second)
waitForInboundGateways(t, s2, 1, time.Second)
waitForOutboundGateways(t, s2, 1, time.Second)
nc2 := natsConnect(t, s2.ClientURL(), nats.Name("sub2"))
defer nc2.Close()
sub2 := natsSubSync(t, nc2, "foo")
nc1 := natsConnect(t, s1.ClientURL(), nats.Name("sub1"))
defer nc1.Close()
sub1 := natsSubSync(t, nc1, "foo")
nct := natsConnect(t, s1.ClientURL(), nats.Name("tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, "my.trace.subj")
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello!")
err := nct.PublishMsg(msg)
require_NoError(t, err)
checkAppMsg := func(sub *nats.Subscription, expected bool) {
if expected {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "hello!")
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got %s", msg.Data)
}
}
// Even if a server does not support tracing, as long as the header
// TraceOnly is not set, the message should be forwarded to the remote.
for _, sub := range []*nats.Subscription{sub1, sub2} {
checkAppMsg(sub, test.deliverMsg)
}
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, s1.Name())
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, ci := range egress {
switch ci.Kind {
case CLIENT:
require_Equal[string](t, ci.Name, "sub1")
case GATEWAY:
require_Equal[string](t, ci.Name, s2.Name())
if test.deliverMsg {
require_Contains(t, ci.Error, errMsgTraceNoSupport)
} else {
require_Contains(t, ci.Error, errMsgTraceOnlyNoSupport)
}
default:
t.Fatalf("Unexpected egress: %+v", ci)
}
}
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
// We should not get a second trace
if msg, err := traceSub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect other trace, got %s", msg.Data)
}
})
}
}
func TestMsgTraceServiceImport(t *testing.T) {
tmpl := `
listen: 127.0.0.1:-1
accounts {
A {
users: [{user: a, password: pwd}]
exports: [ { service: ">", allow_trace: %v} ]
mappings = {
bar: bozo
}
}
B {
users: [{user: b, password: pwd}]
imports: [ { service: {account: "A", subject:">"} } ]
exports: [ { service: ">", allow_trace: %v} ]
}
C {
users: [{user: c, password: pwd}]
exports: [ { service: ">", allow_trace: %v } ]
}
D {
users: [{user: d, password: pwd}]
imports: [
{ service: {account: "B", subject:"bar"}, to: baz }
{ service: {account: "C", subject:">"} }
]
mappings = {
bat: baz
}
}
}
`
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, false, false, false)))
s, _ := RunServerWithConfig(conf)
defer s.Shutdown()
nc := natsConnect(t, s.ClientURL(), nats.UserInfo("d", "pwd"), nats.Name("Requestor"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
sub := natsSubSync(t, nc, "my.service.response.inbox")
nc2 := natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"), nats.Name("ServiceA"))
defer nc2.Close()
recv := int32(0)
natsQueueSub(t, nc2, "*", "my_queue", func(m *nats.Msg) {
atomic.AddInt32(&recv, 1)
m.Respond(m.Data)
})
natsFlush(t, nc2)
nc3 := natsConnect(t, s.ClientURL(), nats.UserInfo("c", "pwd"), nats.Name("ServiceC"))
defer nc3.Close()
natsSub(t, nc3, "baz", func(m *nats.Msg) {
atomic.AddInt32(&recv, 1)
m.Respond(m.Data)
})
natsFlush(t, nc3)
for mainIter, mainTest := range []struct {
name string
allow bool
}{
{"not allowed", false},
{"allowed", true},
{"not allowed again", false},
} {
atomic.StoreInt32(&recv, 0)
t.Run(mainTest.name, func(t *testing.T) {
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("bat")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
if !test.deliverMsg {
msg.Data = []byte("request1")
} else {
msg.Data = []byte("request2")
}
msg.Reply = sub.Subject
err := nc.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
for i := 0; i < 2; i++ {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "request2")
}
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); msg != nil || err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got msg=%v err=%v", msg, err)
}
if !test.deliverMsg {
// Just to make sure that message was not delivered to service
// responders, wait a bit and check the recv value.
time.Sleep(50 * time.Millisecond)
if n := atomic.LoadInt32(&recv); n != 0 {
t.Fatalf("Expected no message to be received, but service callback fired %d times", n)
}
}
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, ingress.Account, "D")
require_Equal[string](t, ingress.Subject, "bat")
sm := e.SubjectMapping()
require_True(t, sm != nil)
require_Equal[string](t, sm.MappedTo, "baz")
simps := e.ServiceImports()
require_True(t, simps != nil)
var expectedServices int
if mainTest.allow {
expectedServices = 3
} else {
expectedServices = 2
}
require_Equal[int](t, len(simps), expectedServices)
for _, si := range simps {
require_True(t, si.Timestamp != time.Time{})
switch si.Account {
case "C":
require_Equal[string](t, si.From, "baz")
require_Equal[string](t, si.To, "baz")
case "B":
require_Equal[string](t, si.From, "baz")
require_Equal[string](t, si.To, "bar")
case "A":
if !mainTest.allow {
t.Fatalf("Without allow_trace, we should not see service for account A")
}
require_Equal[string](t, si.From, "bar")
require_Equal[string](t, si.To, "bozo")
default:
t.Fatalf("Unexpected account name: %s", si.Account)
}
}
egress := e.Egresses()
if !mainTest.allow {
require_Equal[int](t, len(egress), 0)
} else {
require_Equal[int](t, len(egress), 2)
var gotA, gotC bool
for _, eg := range egress {
// All Egress should be clients
require_True(t, eg.Kind == CLIENT)
// We should have one for ServiceA and one for ServiceC
if eg.Name == "ServiceA" {
require_Equal[string](t, eg.Account, "A")
require_Equal[string](t, eg.Subscription, "*")
require_Equal[string](t, eg.Queue, "my_queue")
gotA = true
} else if eg.Name == "ServiceC" {
require_Equal[string](t, eg.Account, "C")
require_Equal[string](t, eg.Queue, _EMPTY_)
gotC = true
}
}
if !gotA {
t.Fatalf("Did not get Egress for serviceA: %+v", egress)
}
if !gotC {
t.Fatalf("Did not get Egress for serviceC: %+v", egress)
}
}
// Make sure we properly remove the responses.
checkResp := func(an string) {
acc, err := s.lookupAccount(an)
require_NoError(t, err)
checkFor(t, time.Second, 15*time.Millisecond, func() error {
if n := acc.NumPendingAllResponses(); n != 0 {
return fmt.Errorf("Still %d responses pending for account %q on server %s", n, acc, s)
}
return nil
})
}
for _, acc := range []string{"A", "B", "C", "D"} {
checkResp(acc)
}
})
}
switch mainIter {
case 0:
reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, true, true, true))
case 1:
reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, false, false, false))
}
})
}
}
func TestMsgTraceServiceImportWithSuperCluster(t *testing.T) {
for _, mainTest := range []struct {
name string
allowStr string
allow bool
}{
{"allowed", "true", true},
{"not allowed", "false", false},
} {
t.Run(mainTest.name, func(t *testing.T) {
tmpl := `
listen: 127.0.0.1:-1
server_name: %s
jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
cluster {
name: %s
listen: 127.0.0.1:%d
routes = [%s]
}
accounts {
A {
users: [{user: a, password: pwd}]
exports: [ { service: ">", allow_trace: ` + mainTest.allowStr + ` } ]
mappings = {
bar: bozo
}
trace_dest: "a.trace.subj"
}
B {
users: [{user: b, password: pwd}]
imports: [ { service: {account: "A", subject:">"} } ]
exports: [ { service: ">" , allow_trace: ` + mainTest.allowStr + ` } ]
trace_dest: "b.trace.subj"
}
C {
users: [{user: c, password: pwd}]
exports: [ { service: ">" , allow_trace: ` + mainTest.allowStr + ` } ]
trace_dest: "c.trace.subj"
}
D {
users: [{user: d, password: pwd}]
imports: [
{ service: {account: "B", subject:"bar"}, to: baz }
{ service: {account: "C", subject:">"} }
]
mappings = {
bat: baz
}
trace_dest: "d.trace.subj"
}
$SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
}
`
sc := createJetStreamSuperClusterWithTemplate(t, tmpl, 3, 2)
defer sc.shutdown()
sfornc := sc.clusters[0].servers[0]
nc := natsConnect(t, sfornc.ClientURL(), nats.UserInfo("d", "pwd"), nats.Name("Requestor"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
sub := natsSubSync(t, nc, "my.service.response.inbox")
sfornc2 := sc.clusters[0].servers[1]
nc2 := natsConnect(t, sfornc2.ClientURL(), nats.UserInfo("a", "pwd"), nats.Name("ServiceA"))
defer nc2.Close()
subSvcA := natsQueueSubSync(t, nc2, "*", "my_queue")
natsFlush(t, nc2)
sfornc3 := sc.clusters[1].servers[0]
nc3 := natsConnect(t, sfornc3.ClientURL(), nats.UserInfo("c", "pwd"), nats.Name("ServiceC"))
defer nc3.Close()
subSvcC := natsSubSync(t, nc3, "baz")
natsFlush(t, nc3)
// Create a subscription for each account trace destination to make
// sure that we are not sending it there.
var accSubs []*nats.Subscription
for _, user := range []string{"a", "b", "c", "d"} {
nc := natsConnect(t, sfornc.ClientURL(), nats.UserInfo(user, "pwd"))
defer nc.Close()
accSubs = append(accSubs, natsSubSync(t, nc, user+".trace.subj"))
}
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("bat")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
// We add the traceParentHdr header to make sure that it is
// deactivated in addition to the Nats-Trace-Dest header too
// when needed.
traceParentHdrVal := "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
msg.Header.Set(traceParentHdr, traceParentHdrVal)
if !test.deliverMsg {
msg.Data = []byte("request1")
} else {
msg.Data = []byte("request2")
}
msg.Reply = sub.Subject
err := nc.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
processSvc := func(sub *nats.Subscription) {
t.Helper()
appMsg := natsNexMsg(t, sub, time.Second)
// This test causes a message to be routed to the
// service responders. When not allowing, we need
// to make sure that the trace header has been
// disabled. Not receiving the trace event from
// the remote is not enough to verify since the
// trace would not reach the origin server because
// the origin account header will not be present.
if mainTest.allow {
if hv := appMsg.Header.Get(MsgTraceDest); hv != traceSub.Subject {
t.Fatalf("Expecting header with %q, but got %q", traceSub.Subject, hv)
}
if hv := appMsg.Header.Get(traceParentHdr); hv != traceParentHdrVal {
t.Fatalf("Expecting header with %q, but got %q", traceParentHdrVal, hv)
}
} else {
if hv := appMsg.Header.Get(MsgTraceDest); hv != _EMPTY_ {
t.Fatalf("Expecting no header, but header was present with value: %q", hv)
}
if hv := appMsg.Header.Get(traceParentHdr); hv != _EMPTY_ {
t.Fatalf("Expecting no header, but header was present with value: %q", hv)
}
// We don't really need to check that, but we
// should see the header with the first letter
// being an `X`.
hnb := []byte(MsgTraceDest)
hnb[0] = 'X'
hn := string(hnb)
if hv := appMsg.Header.Get(hn); hv != traceSub.Subject {
t.Fatalf("Expected header %q to be %q, got %q", hn, traceSub.Subject, hv)
}
hnb = []byte(traceParentHdr)
hnb[0] = 'X'
hn = string(hnb)
if hv := appMsg.Header.Get(hn); hv != traceParentHdrVal {
t.Fatalf("Expected header %q to be %q, got %q", hn, traceParentHdrVal, hv)
}
}
appMsg.Respond(appMsg.Data)
}
processSvc(subSvcA)
processSvc(subSvcC)
for i := 0; i < 2; i++ {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "request2")
}
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); msg != nil || err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got msg=%v err=%v", msg, err)
}
if !test.deliverMsg {
// Just to make sure that message was not delivered to service
// responders, wait a bit and check the recv value.
time.Sleep(50 * time.Millisecond)
for _, sub := range []*nats.Subscription{subSvcA, subSvcC} {
if msg, err := sub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Expected no message to be received, but service subscription got %s", msg.Data)
}
}
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, sfornc.Name())
require_Equal[string](t, ingress.Account, "D")
require_Equal[string](t, ingress.Subject, "bat")
sm := e.SubjectMapping()
require_True(t, sm != nil)
require_Equal[string](t, sm.MappedTo, "baz")
simps := e.ServiceImports()
require_True(t, simps != nil)
var expectedServices int
if mainTest.allow {
expectedServices = 3
} else {
expectedServices = 2
}
require_Equal[int](t, len(simps), expectedServices)
for _, si := range simps {
switch si.Account {
case "C":
require_Equal[string](t, si.From, "baz")
require_Equal[string](t, si.To, "baz")
case "B":
require_Equal[string](t, si.From, "baz")
require_Equal[string](t, si.To, "bar")
case "A":
if !mainTest.allow {
t.Fatalf("Without allow_trace, we should not see service for account A")
}
require_Equal[string](t, si.From, "bar")
require_Equal[string](t, si.To, "bozo")
default:
t.Fatalf("Unexpected account name: %s", si.Account)
}
}
egress := e.Egresses()
if !mainTest.allow {
require_Equal[int](t, len(egress), 0)
} else {
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
switch eg.Kind {
case ROUTER:
require_Equal[string](t, eg.Name, sfornc2.Name())
require_Equal[string](t, eg.Account, _EMPTY_)
case GATEWAY:
require_Equal[string](t, eg.Name, sfornc3.Name())
require_Equal[string](t, eg.Account, _EMPTY_)
}
}
}
case ROUTER:
require_Equal[string](t, e.Server.Name, sfornc2.Name())
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "bozo")
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == CLIENT)
require_Equal[string](t, eg.Name, "ServiceA")
require_Equal[string](t, eg.Account, _EMPTY_)
require_Equal[string](t, eg.Subscription, "*")
require_Equal[string](t, eg.Queue, "my_queue")
case GATEWAY:
require_Equal[string](t, e.Server.Name, sfornc3.Name())
require_Equal[string](t, ingress.Account, "C")
require_Equal[string](t, ingress.Subject, "baz")
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == CLIENT)
require_Equal[string](t, eg.Name, "ServiceC")
require_Equal[string](t, eg.Account, _EMPTY_)
require_Equal[string](t, eg.Subscription, "baz")
require_Equal[string](t, eg.Queue, _EMPTY_)
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
// We should receive 3 events when allowed, a single when not.
check()
if mainTest.allow {
check()
check()
}
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
// Make sure that we never receive on any of the account
// trace destination's sub.
for _, sub := range accSubs {
if tm, err := sub.NextMsg(100 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message on account's trace sub, got %s", tm.Data)
}
}
// Make sure we properly remove the responses.
checkResp := func(an string) {
for _, s := range []*Server{sfornc, sfornc2, sfornc3} {
acc, err := s.lookupAccount(an)
require_NoError(t, err)
checkFor(t, time.Second, 15*time.Millisecond, func() error {
if n := acc.NumPendingAllResponses(); n != 0 {
return fmt.Errorf("Still %d responses pending for account %q on server %s", n, acc, s)
}
return nil
})
}
}
for _, acc := range []string{"A", "B", "C", "D"} {
checkResp(acc)
}
})
}
})
}
}
func TestMsgTraceServiceImportWithLeafNodeHub(t *testing.T) {
confHub := createConfFile(t, []byte(`
listen: 127.0.0.1:-1
server_name: "S1"
accounts {
A {
users: [{user: a, password: pwd}]
exports: [ { service: ">", allow_trace: true } ]
mappings = {
bar: bozo
}
}
B {
users: [{user: b, password: pwd}]
imports: [ { service: {account: "A", subject:">"} } ]
exports: [ { service: ">", allow_trace: true } ]
}
C {
users: [{user: c, password: pwd}]
exports: [ { service: ">", allow_trace: true } ]
}
D {
users: [{user: d, password: pwd}]
imports: [
{ service: {account: "B", subject:"bar"}, to: baz }
{ service: {account: "C", subject:">"} }
]
mappings = {
bat: baz
}
}
$SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
}
leafnodes {
port: -1
}
`))
hub, ohub := RunServerWithConfig(confHub)
defer hub.Shutdown()
confLeaf := createConfFile(t, []byte(fmt.Sprintf(`
listen: 127.0.0.1:-1
server_name: "S2"
leafnodes {
remotes [{url: "nats://d:pwd@127.0.0.1:%d"}]
}
`, ohub.LeafNode.Port)))
leaf, _ := RunServerWithConfig(confLeaf)
defer leaf.Shutdown()
checkLeafNodeConnectedCount(t, hub, 1)
checkLeafNodeConnectedCount(t, leaf, 1)
nc2 := natsConnect(t, hub.ClientURL(), nats.UserInfo("a", "pwd"), nats.Name("ServiceA"))
defer nc2.Close()
recv := int32(0)
natsQueueSub(t, nc2, "*", "my_queue", func(m *nats.Msg) {
atomic.AddInt32(&recv, 1)
m.Respond(m.Data)
})
natsFlush(t, nc2)
nc3 := natsConnect(t, hub.ClientURL(), nats.UserInfo("c", "pwd"), nats.Name("ServiceC"))
defer nc3.Close()
natsSub(t, nc3, "baz", func(m *nats.Msg) {
atomic.AddInt32(&recv, 1)
m.Respond(m.Data)
})
natsFlush(t, nc3)
nc := natsConnect(t, leaf.ClientURL(), nats.Name("Requestor"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
sub := natsSubSync(t, nc, "my.service.response.inbox")
checkSubInterest(t, leaf, globalAccountName, "bat", time.Second)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("bat")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
if !test.deliverMsg {
msg.Data = []byte("request1")
} else {
msg.Data = []byte("request2")
}
msg.Reply = sub.Subject
err := nc.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
for i := 0; i < 2; i++ {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "request2")
}
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); msg != nil || err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got msg=%v err=%v", msg, err)
}
if !test.deliverMsg {
// Just to make sure that message was not delivered to service
// responders, wait a bit and check the recv value.
time.Sleep(50 * time.Millisecond)
if n := atomic.LoadInt32(&recv); n != 0 {
t.Fatalf("Expected no message to be received, but service callback fired %d times", n)
}
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, "S2")
require_Equal[string](t, ingress.Account, globalAccountName)
require_Equal[string](t, ingress.Subject, "bat")
require_True(t, e.SubjectMapping() == nil)
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == LEAF)
require_Equal[string](t, eg.Name, "S1")
require_Equal[string](t, eg.Account, _EMPTY_)
case LEAF:
require_Equal[string](t, e.Server.Name, hub.Name())
require_Equal[string](t, ingress.Name, leaf.Name())
require_Equal[string](t, ingress.Account, "D")
require_Equal[string](t, ingress.Subject, "bat")
sm := e.SubjectMapping()
require_True(t, sm != nil)
require_Equal[string](t, sm.MappedTo, "baz")
simps := e.ServiceImports()
require_True(t, simps != nil)
require_Equal[int](t, len(simps), 3)
for _, si := range simps {
switch si.Account {
case "C":
require_Equal[string](t, si.From, "baz")
require_Equal[string](t, si.To, "baz")
case "B":
require_Equal[string](t, si.From, "baz")
require_Equal[string](t, si.To, "bar")
case "A":
require_Equal[string](t, si.From, "bar")
require_Equal[string](t, si.To, "bozo")
default:
t.Fatalf("Unexpected account name: %s", si.Account)
}
}
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
require_True(t, eg.Kind == CLIENT)
switch eg.Account {
case "C":
require_Equal[string](t, eg.Name, "ServiceC")
require_Equal[string](t, eg.Subscription, "baz")
require_Equal[string](t, eg.Queue, _EMPTY_)
case "A":
require_Equal[string](t, eg.Name, "ServiceA")
require_Equal[string](t, eg.Subscription, "*")
require_Equal[string](t, eg.Queue, "my_queue")
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
// We should receive 2 events.
check()
check()
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
// Make sure we properly remove the responses.
checkResp := func(an string) {
acc, err := hub.lookupAccount(an)
require_NoError(t, err)
checkFor(t, time.Second, 15*time.Millisecond, func() error {
if n := acc.NumPendingAllResponses(); n != 0 {
return fmt.Errorf("Still %d responses for account %q pending on %s", n, an, hub)
}
return nil
})
}
for _, acc := range []string{"A", "B", "C", "D"} {
checkResp(acc)
}
})
}
}
func TestMsgTraceServiceImportWithLeafNodeLeaf(t *testing.T) {
confHub := createConfFile(t, []byte(`
listen: 127.0.0.1:-1
server_name: "S1"
accounts {
A {
users: [{user: a, password: pwd}]
exports: [ { service: "bar", allow_trace: true } ]
}
B {
users: [{user: b, password: pwd}]
imports: [{ service: {account: "A", subject:"bar"}, to: baz }]
}
$SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
}
leafnodes {
port: -1
}
`))
hub, ohub := RunServerWithConfig(confHub)
defer hub.Shutdown()
confLeaf := createConfFile(t, []byte(fmt.Sprintf(`
listen: 127.0.0.1:-1
server_name: "S2"
accounts {
A {
users: [{user: a, password: pwd}]
exports: [ { service: "bar"} ]
}
B { users: [{user: b, password: pwd}] }
$SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
}
leafnodes {
remotes [
{
url: "nats://a:pwd@127.0.0.1:%d"
account: A
}
{
url: "nats://b:pwd@127.0.0.1:%d"
account: B
}
]
}
`, ohub.LeafNode.Port, ohub.LeafNode.Port)))
leaf, _ := RunServerWithConfig(confLeaf)
defer leaf.Shutdown()
checkLeafNodeConnectedCount(t, hub, 2)
checkLeafNodeConnectedCount(t, leaf, 2)
nc2 := natsConnect(t, leaf.ClientURL(), nats.UserInfo("a", "pwd"), nats.Name("ServiceA"))
defer nc2.Close()
recv := int32(0)
natsQueueSub(t, nc2, "*", "my_queue", func(m *nats.Msg) {
atomic.AddInt32(&recv, 1)
m.Respond(m.Data)
})
natsFlush(t, nc2)
nc := natsConnect(t, hub.ClientURL(), nats.UserInfo("b", "pwd"), nats.Name("Requestor"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
sub := natsSubSync(t, nc, "my.service.response.inbox")
// Check that hub has a subscription interest on "baz"
checkSubInterest(t, hub, "A", "baz", time.Second)
// And check that the leaf has the sub interest on the trace subject
checkSubInterest(t, leaf, "B", traceSub.Subject, time.Second)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("baz")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
if !test.deliverMsg {
msg.Data = []byte("request1")
} else {
msg.Data = []byte("request2")
}
msg.Reply = sub.Subject
err := nc.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
appMsg := natsNexMsg(t, sub, time.Second)
require_Equal[string](t, string(appMsg.Data), "request2")
}
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); msg != nil || err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got msg=%v err=%v", msg, err)
}
if !test.deliverMsg {
// Just to make sure that message was not delivered to service
// responders, wait a bit and check the recv value.
time.Sleep(50 * time.Millisecond)
if n := atomic.LoadInt32(&recv); n != 0 {
t.Fatalf("Expected no message to be received, but service callback fired %d times", n)
}
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, "S1")
require_Equal[string](t, ingress.Name, "Requestor")
require_Equal[string](t, ingress.Account, "B")
require_Equal[string](t, ingress.Subject, "baz")
require_True(t, e.SubjectMapping() == nil)
simps := e.ServiceImports()
require_True(t, simps != nil)
require_Equal[int](t, len(simps), 1)
si := simps[0]
require_Equal[string](t, si.Account, "A")
require_Equal[string](t, si.From, "baz")
require_Equal[string](t, si.To, "bar")
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == LEAF)
require_Equal[string](t, eg.Name, "S2")
require_Equal[string](t, eg.Account, "A")
require_Equal[string](t, eg.Subscription, _EMPTY_)
case LEAF:
require_Equal[string](t, e.Server.Name, leaf.Name())
require_Equal[string](t, ingress.Name, hub.Name())
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "bar")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.ServiceImports() == nil)
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == CLIENT)
require_Equal[string](t, eg.Name, "ServiceA")
require_Equal[string](t, eg.Subscription, "*")
require_Equal[string](t, eg.Queue, "my_queue")
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
// We should receive 2 events.
check()
check()
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
// Make sure we properly remove the responses.
checkResp := func(an string) {
acc, err := leaf.lookupAccount(an)
require_NoError(t, err)
checkFor(t, time.Second, 15*time.Millisecond, func() error {
if n := acc.NumPendingAllResponses(); n != 0 {
return fmt.Errorf("Still %d responses for account %q pending on %s", n, an, leaf)
}
return nil
})
}
for _, acc := range []string{"A", "B"} {
checkResp(acc)
}
})
}
}
func TestMsgTraceStreamExport(t *testing.T) {
tmpl := `
listen: 127.0.0.1:-1
accounts {
A {
users: [{user: a, password: pwd}]
exports: [
{ stream: "info.*.*.>"}
]
}
B {
users: [{user: b, password: pwd}]
imports: [ { stream: {account: "A", subject:"info.*.*.>"}, to: "B.info.$2.$1.>", allow_trace: %v } ]
}
C {
users: [{user: c, password: pwd}]
imports: [ { stream: {account: "A", subject:"info.*.*.>"}, to: "C.info.$1.$2.>", allow_trace: %v } ]
}
}
`
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, false, false)))
s, _ := RunServerWithConfig(conf)
defer s.Shutdown()
nc := natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"), nats.Name("Tracer"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
nc2 := natsConnect(t, s.ClientURL(), nats.UserInfo("b", "pwd"), nats.Name("sub1"))
defer nc2.Close()
sub1 := natsSubSync(t, nc2, "B.info.*.*.>")
natsFlush(t, nc2)
nc3 := natsConnect(t, s.ClientURL(), nats.UserInfo("c", "pwd"), nats.Name("sub2"))
defer nc3.Close()
sub2 := natsQueueSubSync(t, nc3, "C.info.>", "my_queue")
natsFlush(t, nc3)
for mainIter, mainTest := range []struct {
name string
allow bool
}{
{"not allowed", false},
{"allowed", true},
{"not allowed again", false},
} {
t.Run(mainTest.name, func(t *testing.T) {
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("info.11.22.bar")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello")
err := nc.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
appMsg := natsNexMsg(t, sub1, time.Second)
require_Equal[string](t, appMsg.Subject, "B.info.22.11.bar")
appMsg = natsNexMsg(t, sub2, time.Second)
require_Equal[string](t, appMsg.Subject, "C.info.11.22.bar")
}
// Check that no (more) messages are received.
for _, sub := range []*nats.Subscription{sub1, sub2} {
if msg, err := sub.NextMsg(100 * time.Millisecond); msg != nil || err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got msg=%v err=%v", msg, err)
}
}
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "info.11.22.bar")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.ServiceImports() == nil)
stexps := e.StreamExports()
require_True(t, stexps != nil)
require_Equal[int](t, len(stexps), 2)
for _, se := range stexps {
require_True(t, se.Timestamp != time.Time{})
switch se.Account {
case "B":
require_Equal[string](t, se.To, "B.info.22.11.bar")
case "C":
require_Equal[string](t, se.To, "C.info.11.22.bar")
default:
t.Fatalf("Unexpected stream export: %+v", se)
}
}
egress := e.Egresses()
if mainTest.allow {
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
require_True(t, eg.Kind == CLIENT)
switch eg.Account {
case "B":
require_Equal[string](t, eg.Name, "sub1")
require_Equal[string](t, eg.Subscription, "info.*.*.>")
require_Equal[string](t, eg.Queue, _EMPTY_)
case "C":
require_Equal[string](t, eg.Name, "sub2")
require_Equal[string](t, eg.Subscription, "info.*.*.>")
require_Equal[string](t, eg.Queue, "my_queue")
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
} else {
require_Equal[int](t, len(egress), 0)
}
})
}
switch mainIter {
case 0:
reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, true, true))
case 1:
reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, false, false))
}
})
}
}
func TestMsgTraceStreamExportWithSuperCluster(t *testing.T) {
for _, mainTest := range []struct {
name string
allowStr string
allow bool
}{
{"allowed", "true", true},
{"not allowed", "false", false},
} {
t.Run(mainTest.name, func(t *testing.T) {
tmpl := `
listen: 127.0.0.1:-1
server_name: %s
jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
cluster {
name: %s
listen: 127.0.0.1:%d
routes = [%s]
}
accounts {
A {
users: [{user: a, password: pwd}]
exports: [
{ stream: "info.*.*.>"}
]
}
B {
users: [{user: b, password: pwd}]
imports: [ { stream: {account: "A", subject:"info.*.*.>"}, to: "B.info.$2.$1.>", allow_trace: ` + mainTest.allowStr + ` } ]
}
C {
users: [{user: c, password: pwd}]
imports: [ { stream: {account: "A", subject:"info.*.*.>"}, to: "C.info.$1.$2.>", allow_trace: ` + mainTest.allowStr + ` } ]
}
$SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
}
`
sc := createJetStreamSuperClusterWithTemplate(t, tmpl, 2, 2)
defer sc.shutdown()
sfornc := sc.clusters[0].servers[0]
nc := natsConnect(t, sfornc.ClientURL(), nats.UserInfo("a", "pwd"), nats.Name("Tracer"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
sfornc2 := sc.clusters[0].servers[1]
nc2 := natsConnect(t, sfornc2.ClientURL(), nats.UserInfo("b", "pwd"), nats.Name("sub1"))
defer nc2.Close()
sub1 := natsSubSync(t, nc2, "B.info.*.*.>")
natsFlush(t, nc2)
checkSubInterest(t, sfornc2, "A", traceSub.Subject, time.Second)
sfornc3 := sc.clusters[1].servers[0]
nc3 := natsConnect(t, sfornc3.ClientURL(), nats.UserInfo("c", "pwd"), nats.Name("sub2"))
defer nc3.Close()
sub2 := natsQueueSubSync(t, nc3, "C.info.>", "my_queue")
natsFlush(t, nc3)
checkSubInterest(t, sfornc, "A", "info.1.2.3.4", time.Second)
for _, s := range sc.clusters[0].servers {
checkForRegisteredQSubInterest(t, s, "C2", "A", "info.1.2.3", 1, time.Second)
}
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("info.11.22.bar")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello")
err := nc.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
appMsg := natsNexMsg(t, sub1, time.Second)
require_Equal[string](t, appMsg.Subject, "B.info.22.11.bar")
appMsg = natsNexMsg(t, sub2, time.Second)
require_Equal[string](t, appMsg.Subject, "C.info.11.22.bar")
}
// Check that no (more) messages are received.
for _, sub := range []*nats.Subscription{sub1, sub2} {
if msg, err := sub.NextMsg(100 * time.Millisecond); msg != nil || err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got msg=%v err=%v", msg, err)
}
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, sfornc.Name())
require_Equal[string](t, ingress.Name, "Tracer")
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "info.11.22.bar")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.ServiceImports() == nil)
require_True(t, e.StreamExports() == nil)
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
switch eg.Kind {
case ROUTER:
require_Equal[string](t, eg.Name, sfornc2.Name())
require_Equal[string](t, eg.Account, _EMPTY_)
case GATEWAY:
require_Equal[string](t, eg.Name, sfornc3.Name())
require_Equal[string](t, eg.Account, _EMPTY_)
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
case ROUTER:
require_Equal[string](t, e.Server.Name, sfornc2.Name())
require_Equal[string](t, ingress.Name, sfornc.Name())
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "info.11.22.bar")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.ServiceImports() == nil)
stexps := e.StreamExports()
require_True(t, stexps != nil)
require_Equal[int](t, len(stexps), 1)
se := stexps[0]
require_Equal[string](t, se.Account, "B")
require_Equal[string](t, se.To, "B.info.22.11.bar")
egress := e.Egresses()
if mainTest.allow {
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == CLIENT)
require_Equal[string](t, eg.Name, "sub1")
require_Equal[string](t, eg.Subscription, "info.*.*.>")
require_Equal[string](t, eg.Queue, _EMPTY_)
} else {
require_Equal[int](t, len(egress), 0)
}
case GATEWAY:
require_Equal[string](t, e.Server.Name, sfornc3.Name())
require_Equal[string](t, ingress.Name, sfornc.Name())
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "info.11.22.bar")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.ServiceImports() == nil)
stexps := e.StreamExports()
require_True(t, stexps != nil)
require_Equal[int](t, len(stexps), 1)
se := stexps[0]
require_Equal[string](t, se.Account, "C")
require_Equal[string](t, se.To, "C.info.11.22.bar")
egress := e.Egresses()
if mainTest.allow {
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == CLIENT)
require_Equal[string](t, eg.Name, "sub2")
require_Equal[string](t, eg.Subscription, "info.*.*.>")
require_Equal[string](t, eg.Queue, "my_queue")
} else {
require_Equal[int](t, len(egress), 0)
}
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
// We expect 3 events
check()
check()
check()
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
})
}
})
}
}
func TestMsgTraceStreamExportWithLeafNode_Hub(t *testing.T) {
confHub := createConfFile(t, []byte(`
listen: 127.0.0.1:-1
server_name: "S1"
accounts {
A {
users: [{user: a, password: pwd}]
exports: [
{ stream: "info.*.*.>"}
]
}
B {
users: [{user: b, password: pwd}]
imports: [ { stream: {account: "A", subject:"info.*.*.>"}, to: "B.info.$2.$1.>", allow_trace: true } ]
}
C {
users: [{user: c, password: pwd}]
imports: [ { stream: {account: "A", subject:"info.*.*.>"}, to: "C.info.$1.$2.>", allow_trace: true } ]
}
}
leafnodes {
port: -1
}
`))
hub, ohub := RunServerWithConfig(confHub)
defer hub.Shutdown()
confLeaf := createConfFile(t, []byte(fmt.Sprintf(`
listen: 127.0.0.1:-1
server_name: "S2"
accounts {
LEAF { users: [{user: leaf, password: pwd}] }
}
leafnodes {
remotes [
{ url: "nats://a:pwd@127.0.0.1:%d", account: "LEAF" }
]
}
`, ohub.LeafNode.Port)))
leaf, _ := RunServerWithConfig(confLeaf)
defer leaf.Shutdown()
checkLeafNodeConnectedCount(t, hub, 1)
checkLeafNodeConnectedCount(t, leaf, 1)
nc := natsConnect(t, leaf.ClientURL(), nats.UserInfo("leaf", "pwd"), nats.Name("Tracer"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
checkSubInterest(t, hub, "A", traceSub.Subject, time.Second)
nc2 := natsConnect(t, hub.ClientURL(), nats.UserInfo("b", "pwd"), nats.Name("sub1"))
defer nc2.Close()
sub1 := natsSubSync(t, nc2, "B.info.*.*.>")
natsFlush(t, nc2)
nc3 := natsConnect(t, hub.ClientURL(), nats.UserInfo("c", "pwd"), nats.Name("sub2"))
defer nc3.Close()
sub2 := natsQueueSubSync(t, nc3, "C.info.>", "my_queue")
natsFlush(t, nc3)
acc, err := leaf.LookupAccount("LEAF")
require_NoError(t, err)
checkFor(t, time.Second, 50*time.Millisecond, func() error {
acc.mu.RLock()
sl := acc.sl
acc.mu.RUnlock()
r := sl.Match("info.1.2.3")
ok := len(r.psubs) > 0
if ok && (len(r.qsubs) == 0 || len(r.qsubs[0]) == 0) {
ok = false
}
if !ok {
return fmt.Errorf("Subscription interest not yet propagated")
}
return nil
})
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("info.11.22.bar")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello")
err := nc.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
appMsg := natsNexMsg(t, sub1, time.Second)
require_Equal[string](t, appMsg.Subject, "B.info.22.11.bar")
appMsg = natsNexMsg(t, sub2, time.Second)
require_Equal[string](t, appMsg.Subject, "C.info.11.22.bar")
}
// Check that no (more) messages are received.
for _, sub := range []*nats.Subscription{sub1, sub2} {
if msg, err := sub.NextMsg(100 * time.Millisecond); msg != nil || err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got msg=%v err=%v", msg, err)
}
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, leaf.Name())
require_Equal[string](t, ingress.Name, "Tracer")
require_Equal[string](t, ingress.Account, "LEAF")
require_Equal[string](t, ingress.Subject, "info.11.22.bar")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.ServiceImports() == nil)
require_True(t, e.StreamExports() == nil)
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == LEAF)
require_Equal[string](t, eg.Name, hub.Name())
require_Equal[string](t, eg.Account, _EMPTY_)
require_Equal[string](t, eg.Subscription, _EMPTY_)
require_Equal[string](t, eg.Queue, _EMPTY_)
case LEAF:
require_Equal[string](t, e.Server.Name, hub.Name())
require_Equal[string](t, ingress.Name, leaf.Name())
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "info.11.22.bar")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.ServiceImports() == nil)
stexps := e.StreamExports()
require_True(t, stexps != nil)
require_Equal[int](t, len(stexps), 2)
for _, se := range stexps {
switch se.Account {
case "B":
require_Equal[string](t, se.To, "B.info.22.11.bar")
case "C":
require_Equal[string](t, se.To, "C.info.11.22.bar")
default:
t.Fatalf("Unexpected stream export: %+v", se)
}
}
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
require_True(t, eg.Kind == CLIENT)
switch eg.Account {
case "B":
require_Equal[string](t, eg.Name, "sub1")
require_Equal[string](t, eg.Subscription, "info.*.*.>")
require_Equal[string](t, eg.Queue, _EMPTY_)
case "C":
require_Equal[string](t, eg.Name, "sub2")
require_Equal[string](t, eg.Subscription, "info.*.*.>")
require_Equal[string](t, eg.Queue, "my_queue")
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
// We expect 2 events
check()
check()
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
})
}
}
func TestMsgTraceStreamExportWithLeafNode_Leaf(t *testing.T) {
confHub := createConfFile(t, []byte(`
listen: 127.0.0.1:-1
server_name: "S1"
accounts {
HUB { users: [{user: hub, password: pwd}] }
}
leafnodes {
port: -1
}
`))
hub, ohub := RunServerWithConfig(confHub)
defer hub.Shutdown()
confLeaf := createConfFile(t, []byte(fmt.Sprintf(`
listen: 127.0.0.1:-1
server_name: "S2"
accounts {
A {
users: [{user: a, password: pwd}]
exports: [
{ stream: "info.*.*.>"}
]
}
B {
users: [{user: b, password: pwd}]
imports: [ { stream: {account: "A", subject:"info.*.*.>"}, to: "B.info.$2.$1.>", allow_trace: true } ]
}
C {
users: [{user: c, password: pwd}]
imports: [ { stream: {account: "A", subject:"info.*.*.>"}, to: "C.info.$1.$2.>", allow_trace: true } ]
}
}
leafnodes {
remotes [
{ url: "nats://hub:pwd@127.0.0.1:%d", account: "A" }
]
}
`, ohub.LeafNode.Port)))
leaf, _ := RunServerWithConfig(confLeaf)
defer leaf.Shutdown()
checkLeafNodeConnectedCount(t, hub, 1)
checkLeafNodeConnectedCount(t, leaf, 1)
nc := natsConnect(t, hub.ClientURL(), nats.UserInfo("hub", "pwd"), nats.Name("Tracer"))
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
checkSubInterest(t, leaf, "A", traceSub.Subject, time.Second)
nc2 := natsConnect(t, leaf.ClientURL(), nats.UserInfo("b", "pwd"), nats.Name("sub1"))
defer nc2.Close()
sub1 := natsSubSync(t, nc2, "B.info.*.*.>")
natsFlush(t, nc2)
nc3 := natsConnect(t, leaf.ClientURL(), nats.UserInfo("c", "pwd"), nats.Name("sub2"))
defer nc3.Close()
sub2 := natsQueueSubSync(t, nc3, "C.info.>", "my_queue")
natsFlush(t, nc3)
acc, err := hub.LookupAccount("HUB")
require_NoError(t, err)
checkFor(t, time.Second, 50*time.Millisecond, func() error {
acc.mu.RLock()
sl := acc.sl
acc.mu.RUnlock()
r := sl.Match("info.1.2.3")
ok := len(r.psubs) > 0
if ok && (len(r.qsubs) == 0 || len(r.qsubs[0]) == 0) {
ok = false
}
if !ok {
return fmt.Errorf("Subscription interest not yet propagated")
}
return nil
})
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("info.11.22.bar")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = []byte("hello")
err := nc.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
appMsg := natsNexMsg(t, sub1, time.Second)
require_Equal[string](t, appMsg.Subject, "B.info.22.11.bar")
appMsg = natsNexMsg(t, sub2, time.Second)
require_Equal[string](t, appMsg.Subject, "C.info.11.22.bar")
}
// Check that no (more) messages are received.
for _, sub := range []*nats.Subscription{sub1, sub2} {
if msg, err := sub.NextMsg(100 * time.Millisecond); msg != nil || err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got msg=%v err=%v", msg, err)
}
}
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, hub.Name())
require_Equal[string](t, ingress.Name, "Tracer")
require_Equal[string](t, ingress.Account, "HUB")
require_Equal[string](t, ingress.Subject, "info.11.22.bar")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.ServiceImports() == nil)
require_True(t, e.StreamExports() == nil)
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
eg := egress[0]
require_True(t, eg.Kind == LEAF)
require_Equal[string](t, eg.Name, leaf.Name())
require_Equal[string](t, eg.Account, _EMPTY_)
require_Equal[string](t, eg.Subscription, _EMPTY_)
require_Equal[string](t, eg.Queue, _EMPTY_)
case LEAF:
require_Equal[string](t, e.Server.Name, leaf.Name())
require_Equal[string](t, ingress.Name, hub.Name())
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "info.11.22.bar")
require_True(t, e.SubjectMapping() == nil)
require_True(t, e.ServiceImports() == nil)
stexps := e.StreamExports()
require_True(t, stexps != nil)
require_Equal[int](t, len(stexps), 2)
for _, se := range stexps {
switch se.Account {
case "B":
require_Equal[string](t, se.To, "B.info.22.11.bar")
case "C":
require_Equal[string](t, se.To, "C.info.11.22.bar")
default:
t.Fatalf("Unexpected stream export: %+v", se)
}
}
egress := e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
require_True(t, eg.Kind == CLIENT)
switch eg.Account {
case "B":
require_Equal[string](t, eg.Name, "sub1")
require_Equal[string](t, eg.Subscription, "info.*.*.>")
require_Equal[string](t, eg.Queue, _EMPTY_)
case "C":
require_Equal[string](t, eg.Name, "sub2")
require_Equal[string](t, eg.Subscription, "info.*.*.>")
require_Equal[string](t, eg.Queue, "my_queue")
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
// We expect 2 events
check()
check()
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
})
}
}
func TestMsgTraceJetStream(t *testing.T) {
opts := DefaultTestOptions
opts.Port = -1
opts.JetStream = true
opts.JetStreamMaxMemory = 270
opts.StoreDir = t.TempDir()
s := RunServer(&opts)
defer s.Shutdown()
nc, js := jsClientConnect(t, s)
defer nc.Close()
cfg := &nats.StreamConfig{
Name: "TEST",
Storage: nats.MemoryStorage,
Subjects: []string{"foo"},
Replicas: 1,
AllowRollup: true,
SubjectTransform: &nats.SubjectTransformConfig{
Source: "foo",
Destination: "bar",
},
}
_, err := js.AddStream(cfg)
require_NoError(t, err)
nct := natsConnect(t, s.ClientURL(), nats.Name("Tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, "my.trace.subj")
natsFlush(t, nct)
msg := nats.NewMsg("foo")
msg.Header.Set(JSMsgId, "MyId")
msg.Data = make([]byte, 50)
_, err = js.PublishMsg(msg)
require_NoError(t, err)
checkStream := func(t *testing.T, expected int) {
t.Helper()
checkFor(t, time.Second, 15*time.Millisecond, func() error {
si, err := js.StreamInfo("TEST")
if err != nil {
return err
}
if n := si.State.Msgs; int(n) != expected {
return fmt.Errorf("Expected %d messages, got %v", expected, n)
}
return nil
})
}
checkStream(t, 1)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
msg.Data = make([]byte, 50)
err = nct.PublishMsg(msg)
require_NoError(t, err)
// Wait a bit and check if message should be in the stream or not.
time.Sleep(50 * time.Millisecond)
if test.deliverMsg {
checkStream(t, 2)
} else {
checkStream(t, 1)
}
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, ingress.Name, "Tracer")
require_Equal[int](t, len(e.Egresses()), 0)
js := e.JetStream()
require_True(t, js != nil)
require_True(t, js.Timestamp != time.Time{})
require_Equal[string](t, js.Stream, "TEST")
require_Equal[string](t, js.Subject, "bar")
require_False(t, js.NoInterest)
require_Equal[string](t, js.Error, _EMPTY_)
})
}
jst, err := nct.JetStream()
require_NoError(t, err)
mset, err := s.globalAccount().lookupStream("TEST")
require_NoError(t, err)
// Now we will not ask for delivery and use headers that will fail checks
// and make sure that message is not added, that the stream's clfs is not
// increased, and that the JS trace shows the error.
newMsg := func() *nats.Msg {
msg = nats.NewMsg("foo")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
msg.Header.Set(MsgTraceOnly, "true")
msg.Data = []byte("hello")
return msg
}
msgCount := 2
for _, test := range []struct {
name string
headerName string
headerVal string
expectedErr string
special int
}{
{"unexpected stream name", JSExpectedStream, "WRONG", "expected stream does not match", 0},
{"duplicate id", JSMsgId, "MyId", "duplicate", 0},
{"last seq by subject mismatch", JSExpectedLastSubjSeq, "10", "last sequence by subject mismatch", 0},
{"last seq mismatch", JSExpectedLastSeq, "10", "last sequence mismatch", 0},
{"last msgid mismatch", JSExpectedLastMsgId, "MyId3", "last msgid mismatch", 0},
{"invalid rollup command", JSMsgRollup, "wrong", "rollup value invalid: \"wrong\"", 0},
{"rollup not permitted", JSMsgRollup, JSMsgRollupSubject, "rollup not permitted", 1},
{"max msg size", _EMPTY_, _EMPTY_, ErrMaxPayload.Error(), 2},
{"normal message ok", _EMPTY_, _EMPTY_, _EMPTY_, 3},
{"insufficient resources", _EMPTY_, _EMPTY_, NewJSInsufficientResourcesError().Error(), 0},
{"stream sealed", _EMPTY_, _EMPTY_, NewJSStreamSealedError().Error(), 4},
} {
t.Run(test.name, func(t *testing.T) {
msg = newMsg()
if test.headerName != _EMPTY_ {
msg.Header.Set(test.headerName, test.headerVal)
}
switch test.special {
case 1:
// Update stream to prevent rollups, and set a max size.
cfg.AllowRollup = false
cfg.MaxMsgSize = 100
_, err = js.UpdateStream(cfg)
require_NoError(t, err)
case 2:
msg.Data = make([]byte, 200)
case 3:
pa, err := jst.Publish("foo", make([]byte, 100))
require_NoError(t, err)
msgCount++
checkStream(t, msgCount)
require_Equal[uint64](t, pa.Sequence, 3)
return
case 4:
cfg.Sealed = true
_, err = js.UpdateStream(cfg)
require_NoError(t, err)
default:
}
jst.PublishMsg(msg)
// Message count should not have increased and stay at 2.
checkStream(t, msgCount)
// Check that clfs does not increase
mset.mu.RLock()
clfs := mset.getCLFS()
mset.mu.RUnlock()
if clfs != 0 {
t.Fatalf("Stream's clfs was expected to be 0, is %d", clfs)
}
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, ingress.Name, "Tracer")
require_Equal[int](t, len(e.Egresses()), 0)
js := e.JetStream()
require_True(t, js != nil)
require_Equal[string](t, js.Stream, "TEST")
require_Equal[string](t, js.Subject, _EMPTY_)
require_False(t, js.NoInterest)
if et := js.Error; !strings.Contains(et, test.expectedErr) {
t.Fatalf("Expected JS error to contain %q, got %q", test.expectedErr, et)
}
})
}
// Create a stream with interest retention policy
_, err = js.AddStream(&nats.StreamConfig{
Name: "NO_INTEREST",
Subjects: []string{"baz"},
Retention: nats.InterestPolicy,
})
require_NoError(t, err)
msg = nats.NewMsg("baz")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
msg.Header.Set(MsgTraceOnly, "true")
msg.Data = []byte("hello")
err = nct.PublishMsg(msg)
require_NoError(t, err)
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
require_Equal[string](t, e.Server.Name, s.Name())
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, ingress.Name, "Tracer")
require_Equal[int](t, len(e.Egresses()), 0)
ejs := e.JetStream()
require_True(t, js != nil)
require_Equal[string](t, ejs.Stream, "NO_INTEREST")
require_Equal[string](t, ejs.Subject, "baz")
require_True(t, ejs.NoInterest)
require_Equal[string](t, ejs.Error, _EMPTY_)
}
func TestMsgTraceJetStreamWithSuperCluster(t *testing.T) {
sc := createJetStreamSuperCluster(t, 3, 2)
defer sc.shutdown()
traceDest := "my.trace.subj"
// Hack to set the trace destination for the global account in order
// to make sure that the traceParentHdr header is disabled when a message
// is stored in JetStream, which will prevent emitting a trace
// when such message is retrieved and traverses a route.
// Without the account destination set, the trace would not be
// triggered, but that does not mean that we would have been
// doing the right thing of disabling the header.
for _, cl := range sc.clusters {
for _, s := range cl.servers {
acc, err := s.LookupAccount(globalAccountName)
require_NoError(t, err)
acc.setTraceDest(traceDest)
}
}
c1 := sc.clusters[0]
c2 := sc.clusters[1]
nc, js := jsClientConnect(t, c1.randomServer())
defer nc.Close()
checkStream := func(t *testing.T, stream string, expected int) {
t.Helper()
checkFor(t, time.Second, 15*time.Millisecond, func() error {
si, err := js.StreamInfo(stream)
if err != nil {
return err
}
if n := si.State.Msgs; int(n) != expected {
return fmt.Errorf("Expected %d messages for stream %q, got %v", expected, stream, n)
}
return nil
})
}
for mainIter, mainTest := range []struct {
name string
stream string
}{
{"from stream leader", "TEST1"},
{"from non stream leader", "TEST2"},
{"from other cluster", "TEST3"},
} {
t.Run(mainTest.name, func(t *testing.T) {
cfg := &nats.StreamConfig{
Name: mainTest.stream,
Replicas: 3,
AllowRollup: true,
}
_, err := js.AddStream(cfg)
require_NoError(t, err)
sc.waitOnStreamLeader(globalAccountName, mainTest.stream)
// The streams are created from c1 cluster.
slSrv := c1.streamLeader(globalAccountName, mainTest.stream)
// Store some messages
payload := make([]byte, 50)
for i := 0; i < 5; i++ {
_, err = js.Publish(mainTest.stream, payload)
require_NoError(t, err)
}
// We will connect the app that sends the trace message to a server
// that is either the stream leader, a random server in c1, or
// a server in c2 (to go through a GW).
var s *Server
switch mainIter {
case 0:
s = slSrv
case 1:
s = c1.randomNonStreamLeader(globalAccountName, mainTest.stream)
case 2:
s = c2.randomServer()
}
nct := natsConnect(t, s.ClientURL(), nats.Name("Tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, traceDest)
natsFlush(t, nct)
for _, test := range []struct {
name string
deliverMsg bool
}{
{"just trace", false},
{"deliver msg", true},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg(mainTest.stream)
msg.Header.Set(MsgTraceDest, traceSub.Subject)
if !test.deliverMsg {
msg.Header.Set(MsgTraceOnly, "true")
}
// We add the traceParentHdr header to make sure that it
// is deactivated in addition to the Nats-Trace-Dest
// header too when needed.
msg.Header.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
msg.Header.Set(JSMsgId, "MyId")
msg.Data = payload
err = nct.PublishMsg(msg)
require_NoError(t, err)
if test.deliverMsg {
checkStream(t, mainTest.stream, 6)
} else {
checkStream(t, mainTest.stream, 5)
}
var (
clientOK bool
gatewayOK bool
routeOK bool
)
check := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
checkJS := func() {
t.Helper()
js := e.JetStream()
require_True(t, js != nil)
require_Equal[string](t, js.Stream, mainTest.stream)
require_Equal[string](t, js.Subject, mainTest.stream)
require_False(t, js.NoInterest)
require_Equal[string](t, js.Error, _EMPTY_)
}
ingress := e.Ingress()
require_True(t, ingress != nil)
switch mainIter {
case 0:
require_Equal[string](t, e.Server.Name, s.Name())
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, ingress.Name, "Tracer")
require_Equal[int](t, len(e.Egresses()), 0)
checkJS()
case 1:
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, s.Name())
require_Equal[string](t, ingress.Name, "Tracer")
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
ci := egress[0]
require_True(t, ci.Kind == ROUTER)
require_Equal[string](t, ci.Name, slSrv.Name())
case ROUTER:
require_Equal[string](t, e.Server.Name, slSrv.Name())
require_Equal[int](t, len(e.Egresses()), 0)
checkJS()
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
case 2:
switch ingress.Kind {
case CLIENT:
require_Equal[string](t, e.Server.Name, s.Name())
require_Equal[string](t, ingress.Name, "Tracer")
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
ci := egress[0]
require_True(t, ci.Kind == GATEWAY)
// It could have gone to any server in the C1 cluster.
// If it is not the stream leader, it should be
// routed to it.
clientOK = true
case GATEWAY:
require_Equal[string](t, ingress.Name, s.Name())
// If the server that emitted this event is the
// stream leader, then we should have the stream,
// otherwise, it should be routed.
if e.Server.Name == slSrv.Name() {
require_Equal[int](t, len(e.Egresses()), 0)
checkJS()
// Set this so that we know that we don't expect
// to have the route receive it.
routeOK = true
} else {
egress := e.Egresses()
require_Equal[int](t, len(egress), 1)
ci := egress[0]
require_True(t, ci.Kind == ROUTER)
require_Equal[string](t, ci.Name, slSrv.Name())
}
gatewayOK = true
case ROUTER:
require_Equal[string](t, e.Server.Name, slSrv.Name())
require_Equal[int](t, len(e.Egresses()), 0)
checkJS()
routeOK = true
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
}
check()
if mainIter > 0 {
// There will be at least 2 events
check()
// For the last test, there may be a 3rd.
if mainIter == 2 && !(clientOK && gatewayOK && routeOK) {
check()
}
}
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
})
}
jst, err := nct.JetStream()
require_NoError(t, err)
newMsg := func() *nats.Msg {
msg := nats.NewMsg(mainTest.stream)
msg.Header.Set(MsgTraceDest, traceSub.Subject)
msg.Header.Set(MsgTraceOnly, "true")
msg.Header.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
msg.Data = []byte("hello")
return msg
}
msgCount := 6
for _, subtest := range []struct {
name string
headerName string
headerVal string
expectedErr string
special int
}{
{"unexpected stream name", JSExpectedStream, "WRONG", "expected stream does not match", 0},
{"duplicate id", JSMsgId, "MyId", "duplicate", 0},
{"last seq by subject mismatch", JSExpectedLastSubjSeq, "3", "last sequence by subject mismatch", 0},
{"last seq mismatch", JSExpectedLastSeq, "10", "last sequence mismatch", 0},
{"last msgid mismatch", JSExpectedLastMsgId, "MyId3", "last msgid mismatch", 0},
{"invalid rollup command", JSMsgRollup, "wrong", "rollup value invalid: \"wrong\"", 0},
{"rollup not permitted", JSMsgRollup, JSMsgRollupSubject, "rollup not permitted", 1},
{"max msg size", _EMPTY_, _EMPTY_, ErrMaxPayload.Error(), 2},
{"new message ok", _EMPTY_, _EMPTY_, _EMPTY_, 3},
{"stream sealed", _EMPTY_, _EMPTY_, NewJSStreamSealedError().Error(), 4},
} {
t.Run(subtest.name, func(t *testing.T) {
msg := newMsg()
if subtest.headerName != _EMPTY_ {
msg.Header.Set(subtest.headerName, subtest.headerVal)
}
switch subtest.special {
case 1:
// Update stream to prevent rollups, and set a max size.
cfg.AllowRollup = false
cfg.MaxMsgSize = 100
_, err = js.UpdateStream(cfg)
require_NoError(t, err)
case 2:
msg.Data = make([]byte, 200)
case 3:
pa, err := jst.Publish(mainTest.stream, []byte("hello"))
require_NoError(t, err)
msgCount++
checkStream(t, mainTest.stream, msgCount)
require_Equal[uint64](t, pa.Sequence, 7)
return
case 4:
cfg.Sealed = true
_, err = js.UpdateStream(cfg)
require_NoError(t, err)
default:
}
jst.PublishMsg(msg)
checkStream(t, mainTest.stream, msgCount)
var (
clientOK bool
gatewayOK bool
routeOK bool
)
checkJSTrace := func() {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
checkJS := func() {
t.Helper()
js := e.JetStream()
require_True(t, e.JetStream() != nil)
require_Equal[string](t, js.Stream, mainTest.stream)
require_Equal[string](t, js.Subject, _EMPTY_)
require_False(t, js.NoInterest)
if et := js.Error; !strings.Contains(et, subtest.expectedErr) {
t.Fatalf("Expected JS error to contain %q, got %q", subtest.expectedErr, et)
}
}
ingress := e.Ingress()
require_True(t, ingress != nil)
// We will focus only on the trace message that
// includes the JetStream event.
switch mainIter {
case 0:
require_Equal[string](t, e.Server.Name, s.Name())
require_True(t, ingress.Kind == CLIENT)
require_Equal[string](t, ingress.Name, "Tracer")
require_Equal[int](t, len(e.Egresses()), 0)
checkJS()
case 1:
if ingress.Kind == ROUTER {
require_Equal[string](t, e.Server.Name, slSrv.Name())
require_Equal[int](t, len(e.Egresses()), 0)
require_True(t, e.JetStream() != nil)
checkJS()
}
case 2:
switch ingress.Kind {
case CLIENT:
clientOK = true
case GATEWAY:
require_Equal[string](t, ingress.Name, s.Name())
// If the server that emitted this event is the
// stream leader, then we should have the stream,
// otherwise, it should be routed.
if e.Server.Name == slSrv.Name() {
require_Equal[int](t, len(e.Egresses()), 0)
checkJS()
// We don't expect the route event
routeOK = true
}
gatewayOK = true
case ROUTER:
require_Equal[string](t, e.Server.Name, slSrv.Name())
require_Equal[int](t, len(e.Egresses()), 0)
checkJS()
routeOK = true
}
}
}
checkJSTrace()
if mainIter > 0 {
// There will be at least 2 events
checkJSTrace()
// For the last test, there may be a 3rd.
if mainIter == 2 && !(clientOK && gatewayOK && routeOK) {
checkJSTrace()
}
}
})
}
})
}
// Now cause a step-down, and verify count is as expected.
for _, stream := range []string{"TEST1", "TEST2", "TEST3"} {
_, err := nc.Request(fmt.Sprintf(JSApiStreamLeaderStepDownT, stream), nil, time.Second)
require_NoError(t, err)
sc.waitOnStreamLeader(globalAccountName, stream)
checkStream(t, stream, 7)
}
s := c1.randomNonStreamLeader(globalAccountName, "TEST1")
// Try to get a message that will come from a route and make sure that
// this does not trigger a trace message, that is, that headers have
// been properly removed so that they don't trigger it.
nct := natsConnect(t, s.ClientURL(), nats.Name("Tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, traceDest)
natsFlush(t, nct)
jct, err := nct.JetStream()
require_NoError(t, err)
sub, err := jct.SubscribeSync("TEST1")
require_NoError(t, err)
for i := 0; i < 7; i++ {
jmsg, err := sub.NextMsg(time.Second)
require_NoError(t, err)
require_Equal[string](t, jmsg.Header.Get(MsgTraceDest), _EMPTY_)
}
msg, err := traceSub.NextMsg(250 * time.Millisecond)
if err != nats.ErrTimeout {
if msg != nil {
t.Fatalf("Expected timeout, got msg headers=%+v data=%s", msg.Header, msg.Data)
}
t.Fatalf("Expected timeout, got err=%v", err)
}
}
func TestMsgTraceWithCompression(t *testing.T) {
o := DefaultOptions()
s := RunServer(o)
defer s.Shutdown()
nc := natsConnect(t, s.ClientURL())
defer nc.Close()
traceSub := natsSubSync(t, nc, "my.trace.subj")
natsFlush(t, nc)
for _, test := range []struct {
compressAlgo string
expectedHdr string
unsupported bool
}{
{"gzip", "gzip", false},
{"snappy", "snappy", false},
{"s2", "snappy", false},
{"bad one", "identity", true},
} {
t.Run(test.compressAlgo, func(t *testing.T) {
msg := nats.NewMsg("foo")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
msg.Header.Set(acceptEncodingHeader, test.compressAlgo)
msg.Data = []byte("hello!")
err := nc.PublishMsg(msg)
require_NoError(t, err)
traceMsg := natsNexMsg(t, traceSub, time.Second)
data := traceMsg.Data
eh := traceMsg.Header.Get(contentEncodingHeader)
require_Equal[string](t, eh, test.expectedHdr)
if test.unsupported {
// We should be able to unmarshal directly
} else {
switch test.expectedHdr {
case "gzip":
zr, err := gzip.NewReader(bytes.NewReader(data))
require_NoError(t, err)
data, err = io.ReadAll(zr)
if err != nil && err != io.ErrUnexpectedEOF {
t.Fatalf("Unexpected error: %v", err)
}
err = zr.Close()
require_NoError(t, err)
case "snappy":
sr := s2.NewReader(bytes.NewReader(data))
data, err = io.ReadAll(sr)
if err != nil && err != io.ErrUnexpectedEOF {
t.Fatalf("Unexpected error: %v", err)
}
}
}
var e MsgTraceEvent
err = json.Unmarshal(data, &e)
require_NoError(t, err)
ingress := e.Ingress()
require_True(t, ingress != nil)
require_Equal[string](t, e.Server.Name, s.Name())
require_Equal[string](t, ingress.Subject, "foo")
})
}
}
func TestMsgTraceHops(t *testing.T) {
// Will have a test with following toplogy
//
// = C1 cluster = = C2 cluster =
// = C1-S1 <-> C1-S2 = = C2-S1 =
// ^ ^ ^
// | Leafnode | | Leafnode
// | | |
// = C3 cluster = = C4 cluster =
// = C3-S1 <-> C3-S2 = = C4-S1 =
// ^
// | Leafnode
// |-------|
// = C5 cluster =
// = C5-S1 <-> C5-S2 =
//
// And a subscription on "foo" attached to all servers, and the subscription
// on the trace subject attached to c1-s1 (and where the trace message will
// be sent from).
//
commonTmpl := `
port: -1
server_name: "%s-%s"
accounts {
A { users: [{user:"a", pass: "pwd"}] }
$SYS { users: [{user:"admin", pass: "s3cr3t!"}] }
}
system_account: "$SYS"
cluster {
port: -1
name: "%s"
%s
}
`
genCommon := func(cname, sname string, routePort int) string {
var routes string
if routePort > 0 {
routes = fmt.Sprintf(`routes: ["nats://127.0.0.1:%d"]`, routePort)
}
return fmt.Sprintf(commonTmpl, cname, sname, cname, routes)
}
c1s1conf := createConfFile(t, []byte(fmt.Sprintf(`
%s
gateway {
port: -1
name: "C1"
}
leafnodes {
port: -1
}
`, genCommon("C1", "S1", 0))))
c1s1, oc1s1 := RunServerWithConfig(c1s1conf)
defer c1s1.Shutdown()
c1s2conf := createConfFile(t, []byte(fmt.Sprintf(`
%s
gateway {
port: -1
name: "C1"
}
leafnodes {
port: -1
}
`, genCommon("C1", "S2", oc1s1.Cluster.Port))))
c1s2, oc1s2 := RunServerWithConfig(c1s2conf)
defer c1s2.Shutdown()
checkClusterFormed(t, c1s1, c1s2)
c2s1conf := createConfFile(t, []byte(fmt.Sprintf(`
%s
gateway {
port: -1
name: "C2"
gateways [
{
name: "C1"
url: "nats://a:pwd@127.0.0.1:%d"
}
]
}
leafnodes {
port: -1
}
`, genCommon("C2", "S1", 0), oc1s1.Gateway.Port)))
c2s1, oc2s1 := RunServerWithConfig(c2s1conf)
defer c2s1.Shutdown()
c4s1conf := createConfFile(t, []byte(fmt.Sprintf(`
%s
leafnodes {
remotes [{url: "nats://a:pwd@127.0.0.1:%d", account: "A"}]
}
`, genCommon("C4", "S1", 0), oc2s1.LeafNode.Port)))
c4s1, _ := RunServerWithConfig(c4s1conf)
defer c4s1.Shutdown()
for _, s := range []*Server{c1s1, c1s2, c2s1} {
waitForOutboundGateways(t, s, 1, time.Second)
}
waitForInboundGateways(t, c2s1, 2, time.Second)
c3s1conf := createConfFile(t, []byte(fmt.Sprintf(`
%s
leafnodes {
port: -1
remotes [{url: "nats://a:pwd@127.0.0.1:%d", account: "A"}]
}
`, genCommon("C3", "S1", 0), oc1s1.LeafNode.Port)))
c3s1, oc3s1 := RunServerWithConfig(c3s1conf)
defer c3s1.Shutdown()
c3s2conf := createConfFile(t, []byte(fmt.Sprintf(`
%s
leafnodes {
port: -1
remotes [{url: "nats://a:pwd@127.0.0.1:%d", account: "A"}]
}
system_account: "$SYS"
`, genCommon("C3", "S2", oc3s1.Cluster.Port), oc1s2.LeafNode.Port)))
c3s2, oc3s2 := RunServerWithConfig(c3s2conf)
defer c3s2.Shutdown()
checkClusterFormed(t, c3s1, c3s2)
checkLeafNodeConnected(t, c1s1)
checkLeafNodeConnected(t, c1s2)
checkLeafNodeConnected(t, c3s1)
checkLeafNodeConnected(t, c3s2)
c5s1conf := createConfFile(t, []byte(fmt.Sprintf(`
%s
leafnodes {
remotes [{url: "nats://a:pwd@127.0.0.1:%d", account: "A"}]
}
`, genCommon("C5", "S1", 0), oc3s2.LeafNode.Port)))
c5s1, oc5s1 := RunServerWithConfig(c5s1conf)
defer c5s1.Shutdown()
c5s2conf := createConfFile(t, []byte(fmt.Sprintf(`
%s
leafnodes {
remotes [{url: "nats://a:pwd@127.0.0.1:%d", account: "A"}]
}
`, genCommon("C5", "S2", oc5s1.Cluster.Port), oc3s2.LeafNode.Port)))
c5s2, _ := RunServerWithConfig(c5s2conf)
defer c5s2.Shutdown()
checkLeafNodeConnected(t, c5s1)
checkLeafNodeConnected(t, c5s2)
checkLeafNodeConnectedCount(t, c3s2, 3)
nct := natsConnect(t, c1s1.ClientURL(), nats.UserInfo("a", "pwd"), nats.Name("Tracer"))
defer nct.Close()
traceSub := natsSubSync(t, nct, "my.trace.subj")
natsFlush(t, nct)
allServers := []*Server{c1s1, c1s2, c2s1, c3s1, c3s2, c4s1, c5s1, c5s2}
// Check that the subscription interest on the trace subject reaches all servers.
for _, s := range allServers {
if s == c2s1 {
// Gateway needs to be checked differently.
checkGWInterestOnlyModeInterestOn(t, c2s1, "C1", "A", traceSub.Subject)
continue
}
checkSubInterest(t, s, "A", traceSub.Subject, time.Second)
}
var subs []*nats.Subscription
// Now create a subscription on "foo" on all servers (do in reverse order).
for i := len(allServers) - 1; i >= 0; i-- {
s := allServers[i]
nc := natsConnect(t, s.ClientURL(), nats.UserInfo("a", "pwd"), nats.Name(fmt.Sprintf("sub%d", i+1)))
defer nc.Close()
subs = append(subs, natsSubSync(t, nc, "foo"))
natsFlush(t, nc)
}
// Check sub interest on "foo" on all servers.
for _, s := range allServers {
checkSubInterest(t, s, "A", "foo", time.Second)
}
// Now send a trace message from c1s1
msg := nats.NewMsg("foo")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
msg.Data = []byte("hello!")
err := nct.PublishMsg(msg)
require_NoError(t, err)
// Check that all subscriptions received the message
for i, sub := range subs {
appMsg, err := sub.NextMsg(time.Second)
if err != nil {
t.Fatalf("Error getting app message for server %q", allServers[i])
}
require_Equal[string](t, string(appMsg.Data), "hello!")
// Check that no (more) messages are received.
if msg, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Did not expect application message, got %s", msg.Data)
}
}
events := make(map[string]*MsgTraceEvent, 8)
// We expect 8 events
for i := 0; i < 8; i++ {
traceMsg := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
json.Unmarshal(traceMsg.Data, &e)
var hop string
if hopVals := e.Request.Header[MsgTraceHop]; len(hopVals) > 0 {
hop = hopVals[0]
}
events[hop] = &e
}
// Make sure we are not receiving more traces
if tm, err := traceSub.NextMsg(250 * time.Millisecond); err == nil {
t.Fatalf("Should not have received trace message: %s", tm.Data)
}
checkIngress := func(e *MsgTraceEvent, kind int, name, hop string) *MsgTraceIngress {
t.Helper()
ingress := e.Ingress()
require_True(t, ingress != nil)
require_True(t, ingress.Kind == kind)
require_Equal[string](t, ingress.Account, "A")
require_Equal[string](t, ingress.Subject, "foo")
require_Equal[string](t, ingress.Name, name)
var hhop string
if hopVals := e.Request.Header[MsgTraceHop]; len(hopVals) > 0 {
hhop = hopVals[0]
}
require_Equal[string](t, hhop, hop)
return ingress
}
checkEgressClient := func(eg *MsgTraceEgress, name string) {
t.Helper()
require_True(t, eg.Kind == CLIENT)
require_Equal[string](t, eg.Name, name)
require_Equal[string](t, eg.Hop, _EMPTY_)
require_Equal[string](t, eg.Subscription, "foo")
require_Equal[string](t, eg.Queue, _EMPTY_)
}
// First, we should have an event without a "hop" header, that is the
// ingress from the client.
e, ok := events[_EMPTY_]
require_True(t, ok)
checkIngress(e, CLIENT, "Tracer", _EMPTY_)
require_Equal[int](t, e.Hops, 3)
egress := e.Egresses()
require_Equal[int](t, len(egress), 4)
var (
leafC3S1Hop string
leafC3S2Hop string
leafC4S1Hop string
leafC5S1Hop string
leafC5S2Hop string
routeC1S2Hop string
gwC2S1Hop string
)
for _, eg := range egress {
switch eg.Kind {
case CLIENT:
checkEgressClient(eg, "sub1")
case ROUTER:
require_Equal[string](t, eg.Name, c1s2.Name())
routeC1S2Hop = eg.Hop
case LEAF:
require_Equal[string](t, eg.Name, c3s1.Name())
leafC3S1Hop = eg.Hop
case GATEWAY:
require_Equal[string](t, eg.Name, c2s1.Name())
gwC2S1Hop = eg.Hop
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
// All "hop" ids should be not empty and different from each other
require_True(t, leafC3S1Hop != _EMPTY_ && routeC1S2Hop != _EMPTY_ && gwC2S1Hop != _EMPTY_)
require_True(t, leafC3S1Hop != routeC1S2Hop && leafC3S1Hop != gwC2S1Hop && routeC1S2Hop != gwC2S1Hop)
// Now check the routed server in C1 (c1s2)
e, ok = events[routeC1S2Hop]
require_True(t, ok)
checkIngress(e, ROUTER, c1s1.Name(), routeC1S2Hop)
require_Equal[int](t, e.Hops, 1)
egress = e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
switch eg.Kind {
case CLIENT:
checkEgressClient(eg, "sub2")
case LEAF:
require_Equal[string](t, eg.Name, c3s2.Name())
require_Equal[string](t, eg.Hop, routeC1S2Hop+".1")
leafC3S2Hop = eg.Hop
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
require_True(t, leafC3S2Hop != _EMPTY_)
// Let's check the gateway server
e, ok = events[gwC2S1Hop]
require_True(t, ok)
checkIngress(e, GATEWAY, c1s1.Name(), gwC2S1Hop)
require_Equal[int](t, e.Hops, 1)
egress = e.Egresses()
require_Equal[int](t, len(egress), 2)
for _, eg := range egress {
switch eg.Kind {
case CLIENT:
checkEgressClient(eg, "sub3")
case LEAF:
require_Equal[string](t, eg.Name, c4s1.Name())
require_Equal[string](t, eg.Hop, gwC2S1Hop+".1")
leafC4S1Hop = eg.Hop
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
require_True(t, leafC4S1Hop != _EMPTY_)
// Let's check the C3 cluster, starting at C3-S1
e, ok = events[leafC3S1Hop]
require_True(t, ok)
checkIngress(e, LEAF, c1s1.Name(), leafC3S1Hop)
require_Equal[int](t, e.Hops, 0)
egress = e.Egresses()
require_Equal[int](t, len(egress), 1)
checkEgressClient(egress[0], "sub4")
// Now C3-S2
e, ok = events[leafC3S2Hop]
require_True(t, ok)
checkIngress(e, LEAF, c1s2.Name(), leafC3S2Hop)
require_Equal[int](t, e.Hops, 2)
egress = e.Egresses()
require_Equal[int](t, len(egress), 3)
for _, eg := range egress {
switch eg.Kind {
case CLIENT:
checkEgressClient(eg, "sub5")
case LEAF:
require_True(t, eg.Name == c5s1.Name() || eg.Name == c5s2.Name())
require_True(t, eg.Hop == leafC3S2Hop+".1" || eg.Hop == leafC3S2Hop+".2")
if eg.Name == c5s1.Name() {
leafC5S1Hop = eg.Hop
} else {
leafC5S2Hop = eg.Hop
}
default:
t.Fatalf("Unexpected egress: %+v", eg)
}
}
// The leafC5SxHop must be different and not empty
require_True(t, leafC5S1Hop != _EMPTY_ && leafC5S1Hop != leafC5S2Hop && leafC5S2Hop != _EMPTY_)
// Check the C4 cluster
e, ok = events[leafC4S1Hop]
require_True(t, ok)
checkIngress(e, LEAF, c2s1.Name(), leafC4S1Hop)
require_Equal[int](t, e.Hops, 0)
egress = e.Egresses()
require_Equal[int](t, len(egress), 1)
checkEgressClient(egress[0], "sub6")
// Finally, the C5 cluster, starting with C5-S1
e, ok = events[leafC5S1Hop]
require_True(t, ok)
checkIngress(e, LEAF, c3s2.Name(), leafC5S1Hop)
require_Equal[int](t, e.Hops, 0)
egress = e.Egresses()
require_Equal[int](t, len(egress), 1)
checkEgressClient(egress[0], "sub7")
// Then C5-S2
e, ok = events[leafC5S2Hop]
require_True(t, ok)
checkIngress(e, LEAF, c3s2.Name(), leafC5S2Hop)
require_Equal[int](t, e.Hops, 0)
egress = e.Egresses()
require_Equal[int](t, len(egress), 1)
checkEgressClient(egress[0], "sub8")
}
func TestMsgTraceTriggeredByExternalHeader(t *testing.T) {
tmpl := `
port: -1
server_name: "%s"
accounts {
A {
users: [{user:A, password: pwd}]
trace_dest: "acc.trace.dest"
}
B {
users: [{user:B, password: pwd}]
%s
}
}
cluster {
name: "local"
port: -1
%s
}
`
conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", _EMPTY_, _EMPTY_)))
s1, o1 := RunServerWithConfig(conf1)
defer s1.Shutdown()
conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B", _EMPTY_, fmt.Sprintf(`routes: ["nats://127.0.0.1:%d"]`, o1.Cluster.Port))))
s2, _ := RunServerWithConfig(conf2)
defer s2.Shutdown()
checkClusterFormed(t, s1, s2)
nc2 := natsConnect(t, s2.ClientURL(), nats.UserInfo("A", "pwd"))
defer nc2.Close()
appSub := natsSubSync(t, nc2, "foo")
natsFlush(t, nc2)
checkSubInterest(t, s1, "A", "foo", time.Second)
nc1 := natsConnect(t, s1.ClientURL(), nats.UserInfo("A", "pwd"))
defer nc1.Close()
traceSub := natsSubSync(t, nc1, "trace.dest")
accTraceSub := natsSubSync(t, nc1, "acc.trace.dest")
natsFlush(t, nc1)
checkSubInterest(t, s1, "A", traceSub.Subject, time.Second)
checkSubInterest(t, s1, "A", accTraceSub.Subject, time.Second)
var msgCount int
for _, test := range []struct {
name string
setHeaders func(h nats.Header)
traceTriggered bool
traceOnly bool
expectedAccSub bool
}{
// Tests with external header only (no Nats-Trace-Dest). In this case, the
// trace is triggered based on sampling (last token is `-01`). The presence
// of Nats-Trace-Only has no effect and message should always be delivered
// to the application.
{"only external header sampling",
func(h nats.Header) {
h.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
},
true,
false,
true},
{"only external header with different case and sampling",
func(h nats.Header) {
h.Set("TraceParent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
},
true,
false,
true},
{"only external header sampling but not simply 01",
func(h nats.Header) {
h.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-25")
},
true,
false,
true},
{"only external header no sampling",
func(h nats.Header) {
h.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00")
},
false,
false,
false},
{"external header sampling and trace only",
func(h nats.Header) {
h.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
h.Set(MsgTraceOnly, "true")
},
true,
false,
true},
{"external header no sampling and trace only",
func(h nats.Header) {
h.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00")
h.Set(MsgTraceOnly, "true")
},
false,
false,
false},
// Tests where Nats-Trace-Dest is present, so ignore external header and
// always deliver to the Nats-Trace-Dest, not the account.
{"trace dest and external header sampling",
func(h nats.Header) {
h.Set(MsgTraceDest, traceSub.Subject)
h.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
},
true,
false,
false},
{"trace dest and external header no sampling",
func(h nats.Header) {
h.Set(MsgTraceDest, traceSub.Subject)
h.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00")
},
true,
false,
false},
{"trace dest with trace only and external header sampling",
func(h nats.Header) {
h.Set(MsgTraceDest, traceSub.Subject)
h.Set(MsgTraceOnly, "true")
h.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
},
true,
true,
false},
{"trace dest with trace only and external header no sampling",
func(h nats.Header) {
h.Set(MsgTraceDest, traceSub.Subject)
h.Set(MsgTraceOnly, "true")
h.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00")
},
true,
true,
false},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo")
test.setHeaders(msg.Header)
msgCount++
msgPayload := fmt.Sprintf("msg%d", msgCount)
msg.Data = []byte(msgPayload)
err := nc1.PublishMsg(msg)
require_NoError(t, err)
if !test.traceOnly {
appMsg := natsNexMsg(t, appSub, time.Second)
require_Equal[string](t, string(appMsg.Data), msgPayload)
}
// Make sure we don't receive more (or not if trace only)
if appMsg, err := appSub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Expected no app message, got %q", appMsg.Data)
}
checkTrace := func(sub *nats.Subscription) {
// We should receive 2 traces, 1 per server.
for i := 0; i < 2; i++ {
tm := natsNexMsg(t, sub, time.Second)
var e MsgTraceEvent
err := json.Unmarshal(tm.Data, &e)
require_NoError(t, err)
}
}
if test.traceTriggered {
if test.expectedAccSub {
checkTrace(accTraceSub)
} else {
checkTrace(traceSub)
}
}
// Make sure no trace is received in the other trace sub
// or no trace received at all.
for _, sub := range []*nats.Subscription{accTraceSub, traceSub} {
if tm, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Expected no trace for the trace sub on %q, got %q", sub.Subject, tm.Data)
}
}
})
}
nc1.Close()
nc2.Close()
// Now replace connections and subs for account "B"
nc2 = natsConnect(t, s2.ClientURL(), nats.UserInfo("B", "pwd"))
defer nc2.Close()
appSub = natsSubSync(t, nc2, "foo")
natsFlush(t, nc2)
checkSubInterest(t, s1, "B", "foo", time.Second)
nc1 = natsConnect(t, s1.ClientURL(), nats.UserInfo("B", "pwd"))
defer nc1.Close()
traceSub = natsSubSync(t, nc1, "trace.dest")
accTraceSub = natsSubSync(t, nc1, "acc.trace.dest")
natsFlush(t, nc1)
checkSubInterest(t, s1, "B", traceSub.Subject, time.Second)
checkSubInterest(t, s1, "B", accTraceSub.Subject, time.Second)
for _, test := range []struct {
name string
reload bool
}{
{"external header but no account destination", true},
{"external header with account destination added through config reload", false},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo")
msg.Header.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
msg.Data = []byte("hello")
err := nc1.PublishMsg(msg)
require_NoError(t, err)
// Application should receive the message
appMsg := natsNexMsg(t, appSub, time.Second)
require_Equal[string](t, string(appMsg.Data), "hello")
// Only once...
if appMsg, err := appSub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Expected no app message, got %q", appMsg.Data)
}
if !test.reload {
// We should receive the traces (1 per server) on the account destination
for i := 0; i < 2; i++ {
tm := natsNexMsg(t, accTraceSub, time.Second)
var e MsgTraceEvent
err := json.Unmarshal(tm.Data, &e)
require_NoError(t, err)
}
}
// No (or no more) trace message should be received.
for _, sub := range []*nats.Subscription{accTraceSub, traceSub} {
if tm, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
t.Fatalf("Expected no trace for the trace sub on %q, got %q", sub.Subject, tm.Data)
}
}
// Do the config reload and we will repeat the test and now
// we should receive the trace message into the account
// destination trace.
if test.reload {
reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", `trace_dest: "acc.trace.dest"`, _EMPTY_))
reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", `trace_dest: "acc.trace.dest"`, fmt.Sprintf(`routes: ["nats://127.0.0.1:%d"]`, o1.Cluster.Port)))
}
})
}
}
func TestMsgTraceAccountTraceDestJWTUpdate(t *testing.T) {
// create system account
sysKp, _ := nkeys.CreateAccount()
sysPub, _ := sysKp.PublicKey()
sysCreds := newUser(t, sysKp)
// create account A
akp, _ := nkeys.CreateAccount()
aPub, _ := akp.PublicKey()
claim := jwt.NewAccountClaims(aPub)
aJwt, err := claim.Encode(oKp)
require_NoError(t, err)
dir := t.TempDir()
conf := createConfFile(t, []byte(fmt.Sprintf(`
listen: -1
operator: %s
resolver: {
type: full
dir: '%s'
}
system_account: %s
`, ojwt, dir, sysPub)))
s, _ := RunServerWithConfig(conf)
defer s.Shutdown()
updateJwt(t, s.ClientURL(), sysCreds, aJwt, 1)
nc := natsConnect(t, s.ClientURL(), createUserCreds(t, nil, akp))
defer nc.Close()
sub := natsSubSync(t, nc, "acc.trace.dest")
natsFlush(t, nc)
for i, test := range []struct {
name string
traceTriggered bool
}{
{"no acc dest", false},
{"adding trace dest", true},
{"removing trace dest", false},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("foo")
msg.Header.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
msg.Data = []byte("hello")
err = nc.PublishMsg(msg)
require_NoError(t, err)
if test.traceTriggered {
tm := natsNexMsg(t, sub, time.Second)
var e MsgTraceEvent
err = json.Unmarshal(tm.Data, &e)
require_NoError(t, err)
// Simple check
require_Equal[string](t, e.Server.Name, s.Name())
}
// No (more) trace message expected.
tm, err := sub.NextMsg(250 * time.Millisecond)
if err != nats.ErrTimeout {
t.Fatalf("Expected no trace message, got %s", tm.Data)
}
if i < 2 {
if i == 0 {
claim.Trace = &jwt.MsgTrace{Destination: "acc.trace.dest"}
} else {
claim.Trace = nil
}
aJwt, err = claim.Encode(oKp)
require_NoError(t, err)
updateJwt(t, s.ClientURL(), sysCreds, aJwt, 1)
}
})
}
}
func TestMsgTraceServiceJWTUpdate(t *testing.T) {
// create system account
sysKp, _ := nkeys.CreateAccount()
sysPub, _ := sysKp.PublicKey()
sysCreds := newUser(t, sysKp)
// create account A
akp, _ := nkeys.CreateAccount()
aPub, _ := akp.PublicKey()
aClaim := jwt.NewAccountClaims(aPub)
serviceExport := &jwt.Export{Subject: "req", Type: jwt.Service}
aClaim.Exports.Add(serviceExport)
aJwt, err := aClaim.Encode(oKp)
require_NoError(t, err)
// create account B
bkp, _ := nkeys.CreateAccount()
bPub, _ := bkp.PublicKey()
bClaim := jwt.NewAccountClaims(bPub)
serviceImport := &jwt.Import{Account: aPub, Subject: "req", Type: jwt.Service}
bClaim.Imports.Add(serviceImport)
bJwt, err := bClaim.Encode(oKp)
require_NoError(t, err)
dir := t.TempDir()
conf := createConfFile(t, []byte(fmt.Sprintf(`
listen: -1
operator: %s
resolver: {
type: full
dir: '%s'
}
system_account: %s
`, ojwt, dir, sysPub)))
s, _ := RunServerWithConfig(conf)
defer s.Shutdown()
updateJwt(t, s.ClientURL(), sysCreds, aJwt, 1)
updateJwt(t, s.ClientURL(), sysCreds, bJwt, 1)
ncA := natsConnect(t, s.ClientURL(), createUserCreds(t, nil, akp), nats.Name("Service"))
defer ncA.Close()
natsSub(t, ncA, "req", func(m *nats.Msg) {
m.Respond([]byte("resp"))
})
natsFlush(t, ncA)
ncB := natsConnect(t, s.ClientURL(), createUserCreds(t, nil, bkp))
defer ncB.Close()
sub := natsSubSync(t, ncB, "trace.dest")
natsFlush(t, ncB)
for i, test := range []struct {
name string
allowTrace bool
}{
{"trace not allowed", false},
{"trace allowed", true},
{"trace not allowed again", false},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("req")
msg.Header.Set(MsgTraceDest, sub.Subject)
msg.Data = []byte("request")
reply, err := ncB.RequestMsg(msg, time.Second)
require_NoError(t, err)
require_Equal[string](t, string(reply.Data), "resp")
tm := natsNexMsg(t, sub, time.Second)
var e MsgTraceEvent
err = json.Unmarshal(tm.Data, &e)
require_NoError(t, err)
require_Equal[string](t, e.Server.Name, s.Name())
require_Equal[string](t, e.Ingress().Account, bPub)
sis := e.ServiceImports()
require_Equal[int](t, len(sis), 1)
si := sis[0]
require_Equal[string](t, si.Account, aPub)
egresses := e.Egresses()
if !test.allowTrace {
require_Equal[int](t, len(egresses), 0)
} else {
require_Equal[int](t, len(egresses), 1)
eg := egresses[0]
require_Equal[string](t, eg.Name, "Service")
require_Equal[string](t, eg.Account, aPub)
require_Equal[string](t, eg.Subscription, "req")
}
// No (more) trace message expected.
tm, err = sub.NextMsg(250 * time.Millisecond)
if err != nats.ErrTimeout {
t.Fatalf("Expected no trace message, got %s", tm.Data)
}
if i < 2 {
// Set AllowTrace to true at the first iteration, then
// false at the second.
aClaim.Exports[0].AllowTrace = (i == 0)
aJwt, err = aClaim.Encode(oKp)
require_NoError(t, err)
updateJwt(t, s.ClientURL(), sysCreds, aJwt, 1)
}
})
}
}
func TestMsgTraceStreamJWTUpdate(t *testing.T) {
// create system account
sysKp, _ := nkeys.CreateAccount()
sysPub, _ := sysKp.PublicKey()
sysCreds := newUser(t, sysKp)
// create account A
akp, _ := nkeys.CreateAccount()
aPub, _ := akp.PublicKey()
aClaim := jwt.NewAccountClaims(aPub)
streamExport := &jwt.Export{Subject: "info", Type: jwt.Stream}
aClaim.Exports.Add(streamExport)
aJwt, err := aClaim.Encode(oKp)
require_NoError(t, err)
// create account B
bkp, _ := nkeys.CreateAccount()
bPub, _ := bkp.PublicKey()
bClaim := jwt.NewAccountClaims(bPub)
streamImport := &jwt.Import{Account: aPub, Subject: "info", To: "b", Type: jwt.Stream}
bClaim.Imports.Add(streamImport)
bJwt, err := bClaim.Encode(oKp)
require_NoError(t, err)
dir := t.TempDir()
conf := createConfFile(t, []byte(fmt.Sprintf(`
listen: -1
operator: %s
resolver: {
type: full
dir: '%s'
}
system_account: %s
`, ojwt, dir, sysPub)))
s, _ := RunServerWithConfig(conf)
defer s.Shutdown()
updateJwt(t, s.ClientURL(), sysCreds, aJwt, 1)
updateJwt(t, s.ClientURL(), sysCreds, bJwt, 1)
ncA := natsConnect(t, s.ClientURL(), createUserCreds(t, nil, akp))
defer ncA.Close()
traceSub := natsSubSync(t, ncA, "trace.dest")
natsFlush(t, ncA)
ncB := natsConnect(t, s.ClientURL(), createUserCreds(t, nil, bkp), nats.Name("BInfo"))
defer ncB.Close()
appSub := natsSubSync(t, ncB, "b.info")
natsFlush(t, ncB)
for i, test := range []struct {
name string
allowTrace bool
}{
{"trace not allowed", false},
{"trace allowed", true},
{"trace not allowed again", false},
} {
t.Run(test.name, func(t *testing.T) {
msg := nats.NewMsg("info")
msg.Header.Set(MsgTraceDest, traceSub.Subject)
msg.Data = []byte("some info")
err = ncA.PublishMsg(msg)
require_NoError(t, err)
appMsg := natsNexMsg(t, appSub, time.Second)
require_Equal[string](t, string(appMsg.Data), "some info")
tm := natsNexMsg(t, traceSub, time.Second)
var e MsgTraceEvent
err = json.Unmarshal(tm.Data, &e)
require_NoError(t, err)
require_Equal[string](t, e.Server.Name, s.Name())
ses := e.StreamExports()
require_Equal[int](t, len(ses), 1)
se := ses[0]
require_Equal[string](t, se.Account, bPub)
require_Equal[string](t, se.To, "b.info")
egresses := e.Egresses()
if !test.allowTrace {
require_Equal[int](t, len(egresses), 0)
} else {
require_Equal[int](t, len(egresses), 1)
eg := egresses[0]
require_Equal[string](t, eg.Name, "BInfo")
require_Equal[string](t, eg.Account, bPub)
require_Equal[string](t, eg.Subscription, "info")
}
// No (more) trace message expected.
tm, err = traceSub.NextMsg(250 * time.Millisecond)
if err != nats.ErrTimeout {
t.Fatalf("Expected no trace message, got %s", tm.Data)
}
if i < 2 {
// Set AllowTrace to true at the first iteration, then
// false at the second.
bClaim.Imports[0].AllowTrace = (i == 0)
bJwt, err = bClaim.Encode(oKp)
require_NoError(t, err)
updateJwt(t, s.ClientURL(), sysCreds, bJwt, 1)
}
})
}
}
func TestMsgTraceParseAccountDestWithSampling(t *testing.T) {
tmpl := `
port: -1
accounts {
A {
users: [{user: a, password: pwd}]
%s
}
}
`
for _, test := range []struct {
name string
samplingStr string
want int
}{
{"trace sampling no dest", `msg_trace: {sampling: 50}`, 0},
{"trace dest only", `msg_trace: {dest: foo}`, 100},
{"trace dest with number only", `msg_trace: {dest: foo, sampling: 20}`, 20},
{"trace dest with percentage", `msg_trace: {dest: foo, sampling: 50%}`, 50},
} {
t.Run(test.name, func(t *testing.T) {
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, test.samplingStr)))
o := LoadConfig(conf)
_, sampling := o.Accounts[0].getTraceDestAndSampling()
require_Equal[int](t, test.want, sampling)
})
}
}
func TestMsgTraceAccountDestWithSampling(t *testing.T) {
tmpl := `
port: -1
server_name: %s
accounts {
A {
users: [{user: a, password:pwd}]
msg_trace: {dest: "acc.dest"%s}
}
}
cluster {
port: -1
%s
}
`
conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", _EMPTY_, _EMPTY_)))
s1, o1 := RunServerWithConfig(conf1)
defer s1.Shutdown()
routes := fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port)
conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B", _EMPTY_, routes)))
s2, _ := RunServerWithConfig(conf2)
defer s2.Shutdown()
checkClusterFormed(t, s1, s2)
nc2 := natsConnect(t, s2.ClientURL(), nats.UserInfo("a", "pwd"))
defer nc2.Close()
natsSub(t, nc2, "foo", func(_ *nats.Msg) {})
natsFlush(t, nc2)
nc1 := natsConnect(t, s1.ClientURL(), nats.UserInfo("a", "pwd"))
defer nc1.Close()
sub := natsSubSync(t, nc1, "acc.dest")
natsFlush(t, nc1)
checkSubInterest(t, s1, "A", "foo", time.Second)
checkSubInterest(t, s2, "A", "acc.dest", time.Second)
for iter, test := range []struct {
name string
samplingStr string
sampling int
}{
// Sampling is considered 100% if not specified or <=0 or >= 100.
// To disable sampling, the account destination should not be specified.
{"no sampling specified", _EMPTY_, 100},
{"sampling specified", ", sampling: \"25%\"", 25},
{"no sampling again", _EMPTY_, 100},
} {
t.Run(test.name, func(t *testing.T) {
if iter > 0 {
reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", test.samplingStr, _EMPTY_))
reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", test.samplingStr, routes))
}
msg := nats.NewMsg("foo")
msg.Header.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
total := 400
for i := 0; i < total; i++ {
err := nc1.PublishMsg(msg)
require_NoError(t, err)
}
// Wait a bit to make sure that we received all traces that should
// have been received.
time.Sleep(500 * time.Millisecond)
n, _, err := sub.Pending()
require_NoError(t, err)
fromClient := 0
fromRoute := 0
for i := 0; i < n; i++ {
msg = natsNexMsg(t, sub, time.Second)
var e MsgTraceEvent
err = json.Unmarshal(msg.Data, &e)
require_NoError(t, err)
ingress := e.Ingress()
require_True(t, ingress != nil)
switch ingress.Kind {
case CLIENT:
fromClient++
case ROUTER:
fromRoute++
default:
t.Fatalf("Unexpected ingress: %+v", ingress)
}
}
// There should be as many messages coming from the origin server
// and the routed server. This checks that if sampling is not 100%
// then when a message is routed, the header is properly deactivated.
require_Equal[int](t, fromClient, fromRoute)
// Now check that if sampling was 100%, we have the total number
// of published messages.
if test.sampling == 100 {
require_Equal[int](t, fromClient, total)
} else {
// Otherwise, we should have no more (but let's be conservative)
// than the sampling number.
require_LessThan[int](t, fromClient, int(float64(test.sampling*total/100)*1.35))
}
})
}
}
func TestMsgTraceAccDestWithSamplingJWTUpdate(t *testing.T) {
// create system account
sysKp, _ := nkeys.CreateAccount()
sysPub, _ := sysKp.PublicKey()
sysCreds := newUser(t, sysKp)
// create account A
akp, _ := nkeys.CreateAccount()
aPub, _ := akp.PublicKey()
claim := jwt.NewAccountClaims(aPub)
claim.Trace = &jwt.MsgTrace{Destination: "acc.trace.dest"}
aJwt, err := claim.Encode(oKp)
require_NoError(t, err)
dir := t.TempDir()
conf := createConfFile(t, []byte(fmt.Sprintf(`
listen: -1
operator: %s
resolver: {
type: full
dir: '%s'
}
system_account: %s
`, ojwt, dir, sysPub)))
s, _ := RunServerWithConfig(conf)
defer s.Shutdown()
updateJwt(t, s.ClientURL(), sysCreds, aJwt, 1)
nc := natsConnect(t, s.ClientURL(), createUserCreds(t, nil, akp))
defer nc.Close()
sub := natsSubSync(t, nc, "acc.trace.dest")
natsFlush(t, nc)
for iter, test := range []struct {
name string
sampling int
}{
{"no sampling specified", 100},
{"sampling", 25},
{"set back sampling to 0", 100},
} {
t.Run(test.name, func(t *testing.T) {
if iter > 0 {
claim.Trace = &jwt.MsgTrace{Destination: "acc.trace.dest", Sampling: test.sampling}
aJwt, err = claim.Encode(oKp)
require_NoError(t, err)
updateJwt(t, s.ClientURL(), sysCreds, aJwt, 1)
}
msg := nats.NewMsg("foo")
msg.Header.Set(traceParentHdr, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
msg.Data = []byte("hello")
total := 400
for i := 0; i < total; i++ {
err := nc.PublishMsg(msg)
require_NoError(t, err)
}
// Wait a bit to make sure that we received all traces that should
// have been received.
time.Sleep(500 * time.Millisecond)
n, _, err := sub.Pending()
require_NoError(t, err)
for i := 0; i < n; i++ {
msg = natsNexMsg(t, sub, time.Second)
var e MsgTraceEvent
err = json.Unmarshal(msg.Data, &e)
require_NoError(t, err)
}
// Now check that if sampling was 100%, we have the total number
// of published messages.
if test.sampling == 100 {
require_Equal[int](t, n, total)
} else {
// Otherwise, we should have no more (but let's be conservative)
// than the sampling number.
require_LessThan[int](t, n, int(float64(test.sampling*total/100)*1.35))
}
})
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta
name="viewport"
content="width=device-width,minimum-scale=1,initial-scale=1"
/>
<title>Login</title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" href="/css/base.css" />
</head>
<body>
<div class="auth">
<h1>Login</h1>
<form>
<p>
<label for="email">Email:</label> <input type="text" name="email" />
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" />
</p>
<button class="login">Login</button>
</form>
<div id="message"></div>
</div>
<script src="/js/base.js"></script>
<script>
const loginBtn = document.querySelector("button.login");
loginBtn.addEventListener("click", login);
function login(e) {
const messageDiv = document.getElementById("message");
messageDiv.innerText = "";
e.preventDefault();
const email = document.querySelector("input[name=email]").value;
const password = document.querySelector("input[name=password]").value;
fetch(`${EXPRESS_ENDPOINT}/auth/login`, {
method: "POST",
body: JSON.stringify({ email, password }),
headers: { "Content-Type": "application/json" },
})
.then((response) => {
console.log("response", response);
if (response.ok) {
return response.json();
} else {
return Promise.reject("Invalid login.");
}
})
.then((data) => {
console.log(data);
localStorage.setItem("jwt_token", data.token);
window.location = "/index.html";
})
.catch((err) => {
console.warn(err);
messageDiv.innerText = err;
});
}
</script>
</body>
</html>
|
import { BrowserRouter, Routes, Route } from "react-router-dom";
import styled from "styled-components";
import ResetCss from "../styles/resetCss";
import GlobalStyle from "../styles/globalStyles";
import UserProvider from "../contexts/UserContext.jsx";
import DataProvider from "../contexts/DataContext.jsx";
import Home from "./Home.jsx";
import Login from "./Login.jsx";
import SignUp from "./SignUp.jsx";
import Product from "./Product.jsx";
import Cart from "./Cart.jsx";
import Checkout from "./Checkout.jsx"
export default function App() {
return (
<>
<ResetCss />
<GlobalStyle />
<Container>
<UserProvider>
<DataProvider>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/cadastro" element={<SignUp />} />
<Route path="/produto" element={<Product />} />
<Route path="/carrinho" element={<Cart />} />
<Route path="/confirmacao" element={<Checkout />} />
</Routes>
</BrowserRouter>
</DataProvider>
</UserProvider>
</Container>
</>
);
}
const Container = styled.div`
height: 100vh;
width: 100%;
`;
|
## Popover
### Uso básico
Similar a un Tooltip, Popover está construido con `Vue-popper`. Así que para atributos duplicados, por favor refiérase a la documentación de Tooltip.
:::demo Lx atributo `trigger` es usado para definir como el popover se dispara: `hover`, `click`, `focus` o `manual`. En cuanto al elemento desencadenante, puedes escribirlo de dos maneras diferentes: usando el `#reference`[named slot](https://vuejs.org/v2/guide/components.html#Named-Slots), o usando la directiva `v-popover` y poniendo el `ref` de Popover.
```html
<template>
<lx-popover
placement="top-start"
title="Title"
:width="200"
trigger="hover"
content="this is content, this is content, this is content"
>
<template #reference>
<lx-button>Hover to activate</lx-button>
</template>
</lx-popover>
<lx-popover
placement="bottom"
title="Title"
:width="200"
trigger="click"
content="this is content, this is content, this is content"
>
<template #reference>
<lx-button>Click to activate</lx-button>
</template>
</lx-popover>
<lx-popover
ref="popover"
placement="right"
title="Title"
:width="200"
trigger="focus"
content="this is content, this is content, this is content"
>
<template #reference>
<lx-button>Focus to activate</lx-button>
</template>
</lx-popover>
<lx-popover
placement="bottom"
title="Title"
:width="200"
trigger="manual"
content="this is content, this is content, this is content"
v-model:visible="visible"
>
<template #reference>
<lx-button @click="visible = !visible">Manual to activate</lx-button>
</template>
</lx-popover>
</template>
<script>
export default {
data() {
return {
visible: false
};
}
};
</script>
<!--
<setup>
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
return {
visible: ref(false),
};
},
});
</setup>
-->
```
:::
### Información anidada
Otros componentes pueden anidarse dentro de popover. A continuación un ejemplo de una tabla anidada.
:::demo Reemplaza el atributo `content` con un `slot`.
```html
<lx-popover
placement="right"
:width="400"
trigger="click"
>
<template #reference>
<lx-button>Click to activate</lx-button>
</template>
<lx-table :data="gridData">
<lx-table-column width="150" property="date" label="date"></lx-table-column>
<lx-table-column width="100" property="name" label="name"></lx-table-column>
<lx-table-column width="300" property="address" label="address"></lx-table-column>
</lx-table>
</lx-popover>
<script>
export default {
data() {
return {
gridData: [{
date: '2016-05-02',
name: 'Jack',
address: 'New York City'
}, {
date: '2016-05-04',
name: 'Jack',
address: 'New York City'
}, {
date: '2016-05-01',
name: 'Jack',
address: 'New York City'
}, {
date: '2016-05-03',
name: 'Jack',
address: 'New York City'
}]
};
}
};
</script>
<!--
<setup>
import { defineComponent, reactive, toRefs } from 'vue';
export default defineComponent({
setup() {
const state = reactive({
gridData: [
{
date: '2016-05-02',
name: 'Jack',
address: 'New York City',
},
{
date: '2016-05-04',
name: 'Jack',
address: 'New York City',
},
{
date: '2016-05-01',
name: 'Jack',
address: 'New York City',
},
{
date: '2016-05-03',
name: 'Jack',
address: 'New York City',
},
],
});
return {
...toRefs(state),
};
},
});
</setup>
-->
```
:::
### Operación anidada
Por supuesto, puedes anidar otras operaciones. Es más ligero que utilizar un `dialog`.
:::demo
```html
<lx-popover
placement="top"
:width="160"
v-model:visible="visible"
>
<p>Are you sure to delete this?</p>
<div style="text-align: right; margin: 0">
<lx-button size="mini" type="text" @click="visible = false">cancel</lx-button>
<lx-button type="primary" size="mini" @click="visible = false">confirm</lx-button>
</div>
<template #reference>
<lx-button @click="visible = true">Delete</lx-button>
</template>
</lx-popover>
<script>
export default {
data() {
return {
visible: false
};
}
};
</script>
<!--
<setup>
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
return {
visible: ref(false),
};
},
});
</setup>
-->
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------------- | ---------------------------------------- | -------------- | ---------------------------------------- | ---------------------------------------- |
| trigger | cómo se dispara el popover | string | click/focus/hover/manual | click |
| title | título del popover | string | — | — |
| content | contenido del popover, puede ser sustituido por un `slot` | string | — | — |
| width | ancho del popover | string, number | — | Min width 150px |
| placement | posición del popover en la pantalla | string | top/top-start/top-end/bottom/bottom-start/bottom-end/left/left-start/left-end/right/right-start/right-end | bottom |
| disabled | si el popover está deshabilitado | boolean | — | false |
| visible / v-model:visible | si el popover está visible | Boolean | — | false |
| offset | popover offset | number | — | 0 |
| transition | animación de transición del popover | string | — | lx-fade-in-linear |
| show-arrow | si una flecha del tooltip es mostrada o no. Para más información, por favor refiérase a [Vue-popper](https://github.com/element-component/vue-popper) | boolean | — | true |
| popper-options | parámetros para [popper.js](https://popper.js.org/documentation.html) | object | por favor, refiérase a [popper.js](https://popper.js.org/documentation.html) | `{ boundariesElement: 'body', gpuAcceleration: false }` |
| popper-class | clase propia para popover | string | — | — |
| show-after | retraso de la apariencia, en milisegundos | number | — | 0 |
| hide-after | retraso en el cierre, en milisegundos | number | — | 0 |
| auto-close | tiempo a esperar en milisegundos para esconder el Tooltip | number | — | 0 |
| tabindex | [tabindex](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex) de Popover | number | — | — |
### Slot
| Nombre | Descripción |
| --------- | ------------------------------------ |
| — | texto contenido en popover |
| reference | elemento HTML que dispara el popover |
### Eventos
| Nombre del evento | Descripción | Parámetros |
| ----------------- | --------------------------------------- | ---------- |
| show | se dispara cuando se muestra el popover | — |
| after-enter | se dispara cuando la transición de entrada termina | — |
| hide | se dispara cuando se oculta el popover | — |
| after-leave | se dispara cuando la transición de salida termina | — |
|
<!DOCTYPE html>
<html style="font-size: 16px;" xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<meta name="keywords" content="Organi">
<meta name="description" content="">
<title>job application management</title>
<link rel="stylesheet" href="/nicepage.css" media="screen">
<link rel="stylesheet" href="/product-details.css" media="screen">
<script class="u-script" type="text/javascript" src="/jquery.js" defer=""></script>
<script class="u-script" type="text/javascript" src="/nicepage.js" defer=""></script>
<meta name="generator" content="Nicepage 5.5.0, nicepage.com">
<link id="u-theme-google-font" rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i|Open+Sans:300,300i,400,400i,500,500i,600,600i,700,700i,800,800i">
<link id="u-page-google-font" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lobster:400">
<script type="application/ld+json">{
"@context": "http://schema.org",
"@type": "Organization",
"name": ""
}</script>
<meta name="theme-color" content="#478ac9">
<meta property="og:title" content="usermanagement">
<meta property="og:type" content="website">
<meta data-intl-tel-input-cdn-path="intlTelInput/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body class="u-body u-xl-mode" data-style="shopping-cart-template-1" data-posts="">
<!--HEADER-->
<th:block th:include="~{fragments/header}"></th:block>
<!-- HEADER END-->
<section class="u-clearfix u-section-1">
<div class="u-clearfix u-sheet u-sheet-1">
<div class="product-details" th:object="${product}">
<form th:action="@{/item/save}" method="post">
<input type="hidden" th:field="*{id}">
<h1 th:text="${product.name}"></h1>
<input type="hidden" th:field="*{name}">
<img th:src="${product.imageUrl}" alt="Product Image">
<input type="hidden" th:field="*{imageUrl}">
<p th:field="*{description}" th:text="${product.description}"></p>
<input type="hidden" th:field="*{description}">
<p th:field="*{priceBGN}" th:text="${#numbers.formatDecimal(product.priceBGN,1,2)} + 'лв'"></p>
<input type="hidden" th:field="*{priceBGN}">
<label for="quantity">Количество:</label>
<input th:field="*{quantity}" type="number" id="quantity" name="quantity" min="1">
<th:block th:if="${quantityError != null}">
<p style="text-align: center" class="alert alert-danger" th:text="${quantityError}"></p>
</th:block>
<button id="add-to-cart" type="submit">Добави в количката</button>
</form>
</div>
</div>
</section>
<!--FOOTER-->
<th:block th:include="~{fragments/footer}"></th:block>
</body>
</html>
|
import 'package:flutter/material.dart';
import '../constants.dart';
import '../custom_widgets/bullet.dart';
import 'package:app/models/models.dart';
import 'package:provider/provider.dart';
class ChoixSexe extends StatefulWidget {
ChoixSexe({Key? key}) : super(key: key);
static MaterialPage page() {
return MaterialPage(
name: "/choixSexe",
key: ValueKey("/choixSexe"),
child: ChoixSexe(),
);
}
@override
State<ChoixSexe> createState() => _ChoixSexeState();
}
class _ChoixSexeState extends State<ChoixSexe> {
String sexe = '';
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
final appStateManager = Provider.of<AppStateManager>(context, listen: false);
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
const SizedBox(
height: 16,
),
Image.asset(
'assets/icons/um6p.png',
scale: 10,
),
const Spacer(
flex: 2,
),
Bullet(
"Quel est votre sexe ?",
style: const TextStyle(
fontSize: 28,
),
),
const Spacer(
flex: 2,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
CustomButton(
value: "femelle",
groupValue: sexe,
onTap: () {
sexe = "femelle";
setState(() {});
},
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset(
'assets/icons/female.png',
scale: 10,
),
const Text("Femelle"),
],
),
),
CustomButton(
value: "male",
onTap: () {
sexe = "male";
setState(() {});
},
groupValue: sexe,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset(
'assets/icons/male.png',
scale: 20,
),
const Text("Male"),
],
),
),
],
),
const Spacer(
flex: 1,
),
Padding(
padding: const EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset(
'assets/icons/new LOGO.png',
scale: 8,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: kPrimaryColor,
),
onPressed: () {
user.sexe = sexe;
appStateManager.setIndex(5);
},
child: Text("Suivant"),
),
],
),
)
],
),
),
);
}
}
class CustomButton extends StatefulWidget {
final Widget child;
void Function()? onTap;
String value;
String groupValue;
CustomButton(
{Key? key,
required this.child,
this.onTap,
required this.value,
required this.groupValue})
: super(key: key);
@override
_CustomButtonState createState() => _CustomButtonState();
}
class _CustomButtonState extends State<CustomButton> {
BorderSide borderSide = const BorderSide(
width: 2,
style: BorderStyle.solid,
color: kPrimaryColor,
);
@override
Widget build(BuildContext context) {
return InkWell(
onTap: widget.onTap,
child: Container(
decoration: BoxDecoration(
border: (widget.value == widget.groupValue) ? Border.fromBorderSide(borderSide) : null,
),
padding: const EdgeInsets.all(8),
height: 150,
width: 80,
child: widget.child,
),
);
}
}
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, LSTM, GRU, Dropout, SimpleRNN
import seaborn as sns
import keras
data = pd.read_csv('pressure_dataset_2.csv', sep=';', decimal=',')[:-1]
# print(data)
# mean_gas = np.mean(data['Дебит газа'])
# for num, i in enumerate(data['Дебит газа']):
# data['Дебит газа'][num] = np.abs(i - mean_gas)
# print(data)
for num, i in enumerate(data['Время сбора данных']):
t = i.split(':')
t = [int(i) for i in t]
time_of_measurement_in_seconds = t[0] * 3600 + t[1] * 60 + t[2]
data['Время сбора данных'][num] = time_of_measurement_in_seconds
plt.plot(data['Время сбора данных'], data['Давление'])
plt.xlabel('Время измерения')
plt.ylabel('Давление, атм')
print(data)
for num, _ in enumerate(data['Давление']):
t = []
n = 1 # скользящее среднее по n точкам
shift = (n - 1) // 2
for i in range(n):
index = num - shift + i
if index >= len(data['Давление']):
t.append(data['Давление'][index % len(data['Давление'])])
elif index >= 0:
t.append(data['Давление'][index])
else:
t.append(data['Давление'][len(data['Давление']) + index])
data['Давление'][num] = np.sum(t) / n
x = data.values
scaler = MinMaxScaler()
x_scaled = scaler.fit_transform(x)
data = pd.DataFrame(x_scaled)
# data[1] == Y
# Y is being predicted, based on X (in this case oil based on years)
# data[2] == X
X = data.loc[:, 2]
Y = data.loc[:, 1]
# print(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, shuffle=False)
model = Sequential()
model.add(Dense(64, input_shape=(14, 1)))
model.add(GRU(300))
# model.add(GRU(300))
model.add(Dense(1))
epochs = 10
learning_rate = 0.001
decay_rate = learning_rate / epochs
model.compile(loss='mse', optimizer=keras.optimizers.Adam(learning_rate=learning_rate, decay=decay_rate))
estimation_object = model.fit(X_train, Y_train, epochs=epochs, batch_size=32, verbose=1,
validation_split=0.25)
predict = model.predict(X_test)
predicted = predict.flatten()
original = Y_test.values
plt.figure(2)
plt.plot(predicted, color='blue', label='Predicted data')
plt.plot(original, color='red', label='Original data')
plt.legend(loc='best')
plt.title('Actual and predicted')
name_of_fig = f'plots/epochs_{str(epochs)}.png'
plt.savefig(name_of_fig)
model.summary()
predicted_and_original_difference = []
for i, j in enumerate(original):
predicted_and_original_difference.append(abs(predicted[i] - j))
print(np.mean(predicted_and_original_difference))
loss = []
for i in estimation_object.history['loss']:
loss.append(i)
plt.figure(3)
plt.plot(loss)
plt.xlabel('MSE')
plt.show()
|
import { useMutation, useQueryClient } from 'react-query'
import { createAnecdote } from '../requests'
import { useMessageDispatch } from '../MessageContext'
const AnecdoteForm = () => {
const dispatch = useMessageDispatch()
const queryClient = useQueryClient()
const newAnecdoteMutation = useMutation(createAnecdote, {
onSuccess: () => {
queryClient.invalidateQueries('anecdotes')
}
})
const onCreate = (event) => {
event.preventDefault()
const content = event.target.anecdote.value
if (content.length < 5) {
dispatch({type: 'SHORT'})
} else {
event.target.anecdote.value = ''
newAnecdoteMutation.mutate({ content, 'votes': 0 })
dispatch({type: 'CREATE', name: content})
}
}
return (
<div>
<h3>create new</h3>
<form onSubmit={onCreate}>
<input name='anecdote' />
<button type="submit">create</button>
</form>
</div>
)
}
export default AnecdoteForm
|
% op_average_subSpecs_s.m
% Jamie Near, McGill University 2014, modified by Ralf Mekle, Charite Berlin 2021.
%
% USAGE:
% out=op_average_subSpecs_s(in);
%
% DESCRIPTION:
% Combine the subspecs in a scan by adding the subspecs together and then
% dividing by the number of subspecs.
%
% INPUTS:
% in = input data in matlab structure format.
%
% OUTPUTS:
% out = Output following averaging.
function out = op_average_subSpecs_s(in)
%if in.flags.averaged || in.subspecs<2
if in.subspecs<2
%DO NOTHING
disp('WARNING: No subSpecs found (in.subspecs < 2). Returning input without modification!');
return;
end
if in.dims.subSpecs==0
%DO NOTHING
disp('WARNING: No subSpecs found (in.dims.subSpecs = 0). Returning input without modification!');
out=in;
return;
else
% add the spectra along the subSpecs dimension;
fids=sum(in.fids,in.dims.subSpecs);
fids=squeeze(fids);
fids=fids/in.sz(in.dims.subSpecs); %divide by number of subSpecs;
%re-calculate Specs using fftveraged
specs=fftshift(ifft(fids,[],in.dims.t),in.dims.t);
%change the dims variables.
if in.dims.t>in.dims.subSpecs
dims.t=in.dims.t-1;
else
dims.t=in.dims.t;
end
if in.dims.coils>in.dims.subSpecs
dims.coils=in.dims.coils-1;
else
dims.coils=in.dims.coils;
end
dims.subSpecs=0;
if in.dims.averages>in.dims.subSpecs
dims.averages=in.dims.averages-1;
else
dims.averages=in.dims.averages;
end
if in.dims.extras>in.dims.subSpecs
dims.extras=in.dims.extras-1;
else
dims.extras=in.dims.extras;
end
%re-calculate the sz variable
sz=size(fids);
%FILLING IN DATA STRUCTURE
out=in;
out.fids=fids;
out.specs=specs;
out.sz=sz;
out.dims=dims;
out.subspecs=1;
out.averages=in.averages/in.subspecs; % Assuming that in.averages is multiple of
% in.subspecs
%FILLING IN THE FLAGS
out.flags=in.flags;
out.flags.writtentostruct=1;
out.flags.isISIS=0; % No more ISIS data available after averaging
end
|
<!--
- @copyright Copyright (c) 2018 Team Popcorn <teampopcornberlin@gmail.com>
-
- @author Team Popcorn <teampopcornberlin@gmail.com>
-
- @license GNU AGPL version 3 or any later version
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-->
<template>
<div class="addressbook-shares">
<Multiselect
id="users-groups-search"
:options="usersOrGroups"
:searchable="true"
:internal-search="false"
:max-height="600"
:show-no-results="true"
:placeholder="placeholder"
:class="{ 'showContent': inputGiven, 'icon-loading': isLoading }"
:user-select="true"
open-direction="bottom"
track-by="user"
label="user"
@search-change="findSharee"
@input="shareAddressbook" />
<!-- list of user or groups addressbook is shared with -->
<ul v-if="addressbook.shares.length > 0" class="addressbook-shares__list">
<address-book-sharee v-for="sharee in addressbook.shares"
:key="sharee.uri"
:sharee="sharee"
:addressbook="addressbook" />
</ul>
</div>
</template>
<script>
import Multiselect from '@nextcloud/vue/dist/Components/Multiselect'
import client from '../../../services/cdav'
import addressBookSharee from './SettingsAddressbookSharee'
import debounce from 'debounce'
export default {
name: 'SettingsAddressbookShare',
components: {
Multiselect,
addressBookSharee,
},
props: {
addressbook: {
type: Object,
default() {
return {}
},
},
},
data() {
return {
isLoading: false,
inputGiven: false,
usersOrGroups: [],
}
},
computed: {
placeholder() {
return t('contacts', 'Share with users or groups')
},
noResult() {
return t('contacts', 'No users or groups')
},
},
mounted() {
// This ensures that the multiselect input is in focus as soon as the user clicks share
document.getElementById('users-groups-search').focus()
},
methods: {
/**
* Share addressbook
*
* @param {object} data destructuring object
* @param {string} data.user the userId
* @param {string} data.displayName the displayName
* @param {string} data.uri the sharing principalScheme uri
* @param {boolean} data.isGroup is this a group ?
*/
shareAddressbook({ user, displayName, uri, isGroup }) {
const addressbook = this.addressbook
uri = decodeURI(uri)
user = decodeURI(user)
this.$store.dispatch('shareAddressbook', { addressbook, user, displayName, uri, isGroup })
},
/**
* Use the cdav client call to find matches to the query from the existing Users & Groups
*
* @param {string} query
*/
findSharee: debounce(async function(query) {
this.isLoading = true
this.usersOrGroups = []
if (query.length > 0) {
const results = await client.principalPropertySearchByDisplayname(query)
this.usersOrGroups = results.reduce((list, result) => {
if (['GROUP', 'INDIVIDUAL'].indexOf(result.calendarUserType) > -1
&& !this.addressbook.shares.some((share) => share.uri === result.principalScheme)) {
const isGroup = result.calendarUserType === 'GROUP'
list.push({
user: result[isGroup ? 'groupId' : 'userId'],
displayName: result.displayname,
icon: isGroup ? 'icon-group' : 'icon-user',
uri: result.principalScheme,
isGroup,
})
}
return list
}, [])
this.isLoading = false
this.inputGiven = true
} else {
this.inputGiven = false
this.isLoading = false
}
}, 500),
},
}
</script>
|
# OCP(Open Close Principle)
<span style="font-familly:Papyrus;font-size:2em;">개방-폐쇄 원칙</span>
<br/>
Open / Closed 는 "소프트웨어는의 모듈 및 클래스는 확장을 위해 열려 있어야하며 수정을 위해 닫혀 있어야 한다."
<br/>
여기서" 확장을 위한 개방"은 새로운 요구사항이 생성될 때만 새로운 기능이 추가 될 수 있도록 모듈 및 클래스를 설계해야 한다는 뜻이며 "수정을 위해 닫힘"은 클래스를 이미 개발하였고 단위테스팅도 하여 확인이 끝난 클래스가 있다. 그런 클래스는 새로운 버그를 찾을 때까지 변경하여서는 안된다. 말했듯이 확장에 대해서는 열려있어야 한다; 우리는 상속을 사용 할 수 있다.
예를 들어보자.
아래는 Rectangle class이며 Height와 Wight 의 속성을 갖는다.
```
public class Rectangle{
public double Height {get;set;}
public double Wight {get;set; }
}
```
우리는 사각형의 총 면적을 계산하는 어플리케이션이 필요하다. 그래서 우리는 앞에서 SRP를 배웠기 때문에 Rectagle 안에 계산을 넣을 필요가 없다. 그래서 아래와 같이 면적을 구하는 Class 를 만들었다.
```
public class AreaCalculator
{
public double TotalArea(Rectangle[] arrRectangles)
{
double area;
foreach(var objRectangle in arrRectangles)
{
area += objRectangle.Height * objRectangle.Width;
}
return area;
}
}
```
우리는 SRP 위반없이 계산하는 App를 만들수 있었고 현재까지 다른 이슈는 없었다. 그러나 사각형이 아닌 원의 면적을 구하는 기능도 확장하려고 한다면? 우리는 원의 면적을 구하는 방식은 다르기 때문에 이슈가 생길 것이다. 그것은 큰 문제가 아니다. 우리는 TotalArea method 를 변경하여 구할수 있을 것이다. loop 에서 객체 유형을 확인하고 계산하면 된다.
```
public class Rectangle{
public double Height {get;set;}
public double Wight {get;set; }
}
public class Circle{
public double Radius {get;set;}
}
public class AreaCalculator
{
public double TotalArea(object[] arrObjects)
{
double area = 0;
Rectangle objRectangle;
Circle objCircle;
foreach(var obj in arrObjects)
{
if(obj is Rectangle)
{
area += obj.Height * obj.Width;
}
else
{
objCircle = (Circle)obj;
area += objCircle.Radius * objCircle.Radius * Math.PI;
}
}
return area;
}
}
```
위의 코드는 Circle 면적을 구하는 코드를 추가했다. 삼각형 면적도 요청을 받아 추가할 수 있다. TotalArea method 에 있는 "if" 문 을 사용한다면 말이다. 그러나 새로운 도형이 나올때마다 우리는 TotalArea method를 수정해야한다. 그래서 AreaCalculator Class는 수정에 닫혀있지 못하다. 그렇다면 어떻게 이 상황을 피할 수 있을까? 일반적으로 우리는 구체적인 클래스 보다 인터페이스나 추상화 클래스 를 이용할 수 있을 것이다. 이러한 인터페이스들은 일단 개발되면 변할 수 있으므로 이에 의존하는 클래스는 변하지 않는 추상화에 의존 할 수 있다.
인터페이스를 구현하는 새 클래스를 만들어 기능을 추가할 수 있다. 아래는 수정된 예시이다.
```
public abstract class Shape
{
public abstract double Area();
}
public class Rectangle : Shape
{
public double Height {get;set;}
public double Width {get;set;}
public override double Area()
{
return Height * Width;
}
}
public class Circle : Shape
{
public double Radius {get;set;}
public override double Area()
{
return Radius * Radius * Math.PI;
}
}
public class AreaCalculator
{
public double TotalArea(Shape[] arrShapes)
{
double area = 0;
foreach(var objShape in arrShapes)
{
area += objShape.Area();
}
return area;
}
}
```
위의 코드는 SRP 와 OCP 를 따르고 있다. "Shape" 라는 추상클래스에서 파생하여 새로운 도형이 추가될 때마다 AreaCalculator 를 변경 할 필요가 없다.
[<- Go to Home](../SUMMARY.md)
|
### 解题思路
1.定义一个 class MyTreeNode 继承 TreeNode,添加一个root字段表示当前节点的根节点
2.遍历一次二叉树,取出所有叶子节点 List<MyTreeNode> yz;
3.逆向比较叶子节点,输出结果
### 代码
```csharp
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public class MyTreeNode : TreeNode
{
// 当前节点的根节点
public MyTreeNode root;
public MyTreeNode(int x)
: base(x) { }
}
public string SmallestFromLeaf(TreeNode root)
{
StringBuilder result = new StringBuilder();
List<MyTreeNode> yz = new List<MyTreeNode>();
getYz(new MyTreeNode(root.val)
{
left = root.left,
right = root.right,
root = null,
}, yz);
appenChar(result, yz);
return result.ToString();
}
private void appenChar(StringBuilder result, List<MyTreeNode> yz)
{
if (yz.Count == 0)
return;
List<MyTreeNode> minis = new List<MyTreeNode>();
int mini = yz[0].val;
minis.Add(yz[0]);
for (int i = 1; i < yz.Count(); i++)
{
var item = yz[i];
if (item.val < mini)
{
minis.Clear();
mini = item.val;
minis.Add(item);
}
else if (item.val == mini)
{
minis.Add(item);
}
}
result.Append((char)('a' + mini));
if (minis.Any(x => x.root == null))
return;
appenChar(result, minis.Select(x => x.root).ToList());
}
private void getYz(MyTreeNode root, List<MyTreeNode> yz)
{
if (root.left == null && root.right == null)
{
yz.Add(root);
}
else
{
if (root.left != null)
{
getYz(new MyTreeNode(root.left.val)
{
left = root.left.left,
right = root.left.right,
root = root,
}, yz);
}
if (root.right != null)
{
getYz(new MyTreeNode(root.right.val)
{
left = root.right.left,
right = root.right.right,
root = root,
}, yz);
}
}
}
}
```
|
package com.spring.advanced.trace.template;
import com.spring.advanced.trace.template.code.AbstractTemplate;
import com.spring.advanced.trace.template.code.SubClassLogic1;
import com.spring.advanced.trace.template.code.SubClassLogic2;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
@Slf4j
public class TemplateMethodTest {
/**
* @memo 템플릿 패턴의 필요성
* 현재 logic1과 2는 log.info("비즈니스 로직1 실행"); 부분을 제외하고 모든 부분이 동일
* 변하는 부분과 변하지 않는 부분을 분리할 필요 o
* <p> AbstractTemplate을 사용해서 변하지 않는 부분(공통로직)을 추상적으로 만들고
* 해당 로직을 사용하고 싶은 하위 클래스에서 재정의하게 분리.
* <p> 만약 log.info("resultTime={}", result); 부분을 result가 아닌 총 시간 이렇게 변경하게 될 경우 2번 변경 일어남.
* 반면 AbstractTemplate을 사용하게 되면 1번만 변경하면 됨.
**/
@Test
void templateMethodV0() {
logic1();
logic2();
}
private void logic1() {
long startTime = System.currentTimeMillis();
log.info("비즈니스 로직1 실행");
long endTime = System.currentTimeMillis();
long result = endTime - startTime;
log.info("resultTime={}", result);
}
private void logic2() {
long startTime = System.currentTimeMillis();
log.info("비즈니스 로직2 실행");
long endTime = System.currentTimeMillis();
long result = endTime - startTime;
log.info("resultTime={}", result);
}
@Test
void templateMethodV1() {
AbstractTemplate template1 = new SubClassLogic1();
template1.execute();
AbstractTemplate template2 = new SubClassLogic2();
template2.execute();
}
/*
템플릿 메서드 패턴을 익명 내부 클래스로 구현.
앞서 만든 템플릿 메서드 패턴의 경우 클래스를 굳이 만들어줘야 함.
익명 내부 클래스를 사용하게 될 경우 불필요한 클래스를 만들 필요 x
*/
@Test
void templateMethodV2(){
AbstractTemplate template1 = new AbstractTemplate(){
@Override
protected void call() {
log.info("비즈니스 로직1 실행");
}
};
log.info("클래스 이름1={}", template1.getClass());
template1.execute();
AbstractTemplate template2 = new AbstractTemplate(){
@Override
protected void call() {
log.info("비즈니스 로직2 실행");
}
};
log.info("클래스 이름2={}", template2.getClass());
template2.execute();
}
}
|
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tag;
class TagController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$tags = Tag::all();
return view('admin.tags.index',compact('tags'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$colors = [
'green'=>'Green',
'blue'=>'Blue',
'yellow'=>'Yellow',
'red'=>'Red',
'purple'=>'Purple',
'orange'=>'Orange',
'indigo'=>'Indigo',
];
return view('admin.tags.create',compact('colors'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'slug' => 'required|unique:tags',
'color' => 'required'
]);
$tag = Tag::create($request->all());
return redirect()->route('admin.tags.edit',compact('tag'))->with('info','Tag created successfully');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Tag $tag)
{
return view('admin.tags.show',compact('tag'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Tag $tag)
{
// return $tag;
$colors = [
'green'=>'Green',
'blue'=>'Blue',
'yellow'=>'Yellow',
'red'=>'Red',
'purple'=>'Purple',
'orange'=>'Orange',
'indigo'=>'Indigo',
];
return view('admin.tags.edit',compact('tag'),compact('colors'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Tag $tag)
{
$request->validate([
'name' => 'required',
'slug' => "required|unique:tags,slug,$tag->id",
'color' => 'required'
]);
$tag->update($request->all());
return redirect()->route('admin.tags.edit',$tag)->with('info','Tag edited successfully');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Tag $tag)
{
$tag->delete();
return redirect()->route('admin.tags.index')->with('info','Tag deleted successfully');
}
}
|
import 'package:get/get.dart';
import 'package:nearby_me/core/data_state.dart';
import 'package:nearby_me/models/stores_model.dart';
import 'package:nearby_me/services/remote/api_services.dart';
class HomeController extends GetxController {
final ApiServices _apiServices = ApiServices();
final Rx<String> _searchQuery = Rx<String>('');
String get searchQuery => _searchQuery.value;
bool isLoading = false;
List<StoresModel> storesList = [];
_fetchStoresList(String location) async {
isLoading = true;
update();
await _apiServices.getStoresList(location).then((DataState dataState) {
if (dataState is SuccessfulDataState) {
storesList = dataState.data;
isLoading = false;
update();
}
if (dataState is FailureDataState) {
storesList = [];
isLoading = false;
update();
}
});
}
searchApi(String query) {
_fetchStoresList(query);
}
updateQuery(String query) {
_searchQuery.value = query;
}
@override
void onInit() {
debounce(
_searchQuery,
searchApi,
time: const Duration(seconds: 2),
);
super.onInit();
}
}
|
import { expect } from "chai";
import { ethers } from "hardhat";
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import {
LenderPool,
RedeemPool,
Reward,
RewardManager,
Strategy,
Token,
Verification,
} from "../typechain";
import { aUSDTAddress, USDTAddress } from "./constants/constants.helpers";
import { constants } from "ethers";
describe("Contract Deployment", function () {
let accounts: SignerWithAddress[];
let addresses: string[];
let stableToken: any;
let tStableToken: Token;
let tradeToken: Token;
let aStable: any;
let redeemPool: RedeemPool;
let stableReward: Reward;
let tradeReward: Reward;
let rewardManager: RewardManager;
let verification: Verification;
let lenderPool: LenderPool;
let strategy: Strategy;
before(async () => {
accounts = await ethers.getSigners();
addresses = accounts.map((account: SignerWithAddress) => account.address);
});
it("should deploy trade, stable and tStable Token", async () => {
const Token = await ethers.getContractFactory("Token");
stableToken = await ethers.getContractAt(
"IERC20",
USDTAddress,
accounts[0]
);
tStableToken = await Token.deploy("Tether derivative", "TUSDT", 6);
tradeToken = await Token.deploy("PolyTrade", "poly", 6);
expect(
await ethers.provider.getCode(stableToken.address)
).to.be.length.above(10);
expect(
await ethers.provider.getCode(tStableToken.address)
).to.be.length.above(10);
expect(
await ethers.provider.getCode(tradeToken.address)
).to.be.length.above(10);
});
it("should deploy Redeem Pool", async () => {
const RedeemPool = await ethers.getContractFactory("RedeemPool");
redeemPool = await RedeemPool.deploy(
stableToken.address,
tStableToken.address
);
expect(
await ethers.provider.getCode(redeemPool.address)
).to.be.length.above(10);
});
it("should deploy stable and trade Reward", async () => {
const Reward = await ethers.getContractFactory("Reward");
stableReward = await Reward.deploy(stableToken.address);
tradeReward = await Reward.deploy(tradeToken.address);
expect(
await ethers.provider.getCode(stableReward.address)
).to.be.length.above(10);
expect(
await ethers.provider.getCode(tradeReward.address)
).to.be.length.above(10);
});
it("should deploy Reward Manager", async () => {
const RewardManager = await ethers.getContractFactory("RewardManager");
rewardManager = await RewardManager.deploy(
stableReward.address,
tradeReward.address,
ethers.constants.AddressZero
);
expect(
await ethers.provider.getCode(rewardManager.address)
).to.be.length.above(10);
});
it("should deploy Lender Pool", async () => {
const LenderPool = await ethers.getContractFactory("LenderPool");
lenderPool = await LenderPool.deploy(
stableToken.address,
tStableToken.address,
redeemPool.address,
constants.AddressZero,
rewardManager.address
);
expect(
await ethers.provider.getCode(lenderPool.address)
).to.be.length.above(10);
});
it("Should set lenderPool on RewardManager", async () => {
await rewardManager["startRewardManager(address)"](lenderPool.address);
});
it("should deploy Verification", async () => {
const Verification = await ethers.getContractFactory("Verification");
verification = await Verification.deploy(lenderPool.address);
expect(
await ethers.provider.getCode(verification.address)
).to.be.length.above(10);
});
it("should deploy Strategy", async () => {
aStable = await ethers.getContractAt("IERC20", aUSDTAddress, accounts[0]);
const Strategy = await ethers.getContractFactory("Strategy");
strategy = await Strategy.deploy(
"0x8dFf5E27EA6b7AC08EbFdf9eB090F32ee9a30fcf",
stableToken.address,
aStable.address
);
await strategy.deployed();
expect(await ethers.provider.getCode(strategy.address)).to.be.length.above(
10
);
});
it("should assign roles in stableReward and tradeReward", async () => {
await stableReward.grantRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("REWARD_MANAGER")),
rewardManager.address
);
await stableReward.grantRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("OWNER")),
addresses[1]
);
await tradeReward.grantRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("REWARD_MANAGER")),
rewardManager.address
);
await tradeReward.grantRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("OWNER")),
addresses[1]
);
expect(
await stableReward.hasRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("REWARD_MANAGER")),
rewardManager.address
)
);
expect(
await stableReward.hasRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("OWNER")),
addresses[1]
)
);
expect(
await tradeReward.hasRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("REWARD_MANAGER")),
rewardManager.address
)
);
expect(
await tradeReward.hasRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("OWNER")),
addresses[1]
)
);
});
it("should assign roles in RewardManager", async () => {
await rewardManager.grantRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("LENDER_POOL")),
lenderPool.address
);
expect(
await rewardManager.hasRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("LENDER_POOL")),
lenderPool.address
)
);
});
it("should assign roles in RewardManager", async () => {
await strategy.grantRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("LENDER_POOL")),
lenderPool.address
);
expect(
await strategy.hasRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("LENDER_POOL")),
lenderPool.address
)
);
});
it("should assign roles in Redeem Pool", async () => {
await redeemPool.grantRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("LENDER_POOL")),
lenderPool.address
);
await redeemPool.grantRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("OWNER")),
addresses[1]
);
expect(
await redeemPool.hasRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("LENDER_POOL")),
lenderPool.address
)
);
expect(
await redeemPool.hasRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("OWNER")),
addresses[1]
)
);
});
it("should assign roles in tStableToken", async function () {
await tStableToken.grantRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("MINTER_ROLE")),
lenderPool.address
);
expect(
await tStableToken.hasRole(
ethers.utils.keccak256(ethers.utils.toUtf8Bytes("MINTER_ROLE")),
lenderPool.address
)
);
});
});
|
import requests
import fitz # PyMuPDF
from crewai_tools import BaseTool
class PDFReaderTool(BaseTool):
name: str = "PDFReaderTool"
description: str = "Fetches and reads a PDF from a given URL, extracting readable text."
def _run(self, pdf_url: str) -> str:
try:
# Fetch the PDF from the URL
response = requests.get(pdf_url)
response.raise_for_status()
# Load the PDF into PyMuPDF
pdf_document = fitz.open("pdf", response.content)
# Extract text from the PDF
text = ""
for page_num in range(len(pdf_document)):
page = pdf_document.load_page(page_num)
text += page.get_text()
return text
except requests.exceptions.RequestException as e:
return f"Failed to fetch PDF: {e}"
except Exception as e:
return f"An error occurred while processing the PDF: {e}"
# Example usage
"""
if __name__ == "__main__":
tool = PDFReaderTool()
pdf_url = "http://www.example.com/sample.pdf"
result = tool._run(pdf_url)
print(result)
"""
|
using AssignUsersToAccessPackages.Models;
using AssignUsersToAccessPackages.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Graph;
using Microsoft.Identity.Web;
namespace AssignUsersToAccessPackages.Pages;
[AuthorizeForScopes(ScopeKeySection = "MicrosoftGraph:Scopes")]
public class IndexModel(ILogger<IndexModel> logger, GraphServiceClient graphServiceClient, ManagementService managementService) : PageModel
{
private readonly GraphServiceClient _graphServiceClient = graphServiceClient;
private readonly ManagementService _managementService = managementService;
private readonly ILogger<IndexModel> _logger = logger;
public string? DisplayName { get; set; }
public List<DataModel> Users { get; set; } = [];
public List<DataModel> AccessPackages { get; set; } = [];
[BindProperty]
public List<string> SelectedUsers { get; set; } = [];
[BindProperty]
public List<string> SelectedAccesses { get; set; } = [];
public async Task OnGet()
{
var user = await _graphServiceClient.Me.GetAsync();
DisplayName = user?.DisplayName;
Users = await _managementService.GetUsers();
AccessPackages = await _managementService.GetAccessPackages();
}
public async Task OnPost()
{
if (SelectedUsers.Count > 0 && SelectedAccesses.Count > 0)
{
await _managementService.Assign(SelectedUsers, SelectedAccesses);
}
await OnGet();
}
}
|
* Question:
Exercise 2.38: Describe the differences in type deduction between
decltype and auto. Give an example of an expression where auto and
decltype will deduce the same type and an example where they will deduce
differing types.
* Answer:
auto will losing the top level information of type, decltype will not. decltype will keep the reference type and const.
For example:
#+begin_src cpp
const int ci = 0, &cri = ci;
auto a = ci; // a is an int
decltype(ci) b = 100; // b is an const int
auto c = cri; // c is an int
decltype(cri) d = ci // d is a reference to const int
#+end_src
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CanActivateAuthGuard } from './login/can-activate.service';
import { ForgotPasswordComponent } from './login/forgot-password/forgot-password.component';
import { LoginComponent } from './login/login.component';
import { ListingComponent } from './listing/listing.component';
import { DetailsComponent } from './listing/details/details.component';
const routes: Routes = [
{ path: '', component: ListingComponent, canActivate: [CanActivateAuthGuard], canActivateChild: [CanActivateAuthGuard]},
{ path: 'forgot', component: ForgotPasswordComponent },
{ path: 'login', component: LoginComponent },
{ path: '**', redirectTo: '/' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import React, { Component, useContext } from "react";
import { BookContext } from "../contexts/BookContext";
import { ThemeContext } from "../contexts/ThemeContext";
// class BookList extends Component {
// static contextType = ThemeContext
// render () {
// const {isLightTrue, light, dark} = this.context
// const theme = isLightTrue ? light : dark
// return (
// <div className="book-list">
// <ul style={{background: theme.bg, color: theme.syntax}}>
// <li style={{background: theme.ui}}>Rich Dad Poor Dad</li>
// <li style={{background: theme.ui}}>Eat that frog</li>
// <li style={{background: theme.ui}}>Pyjama Profit</li>
// </ul>
// </div>
// )
// }
// }
const BookList = () => {
const {books} = useContext(BookContext)
const {isLightTrue,light,dark} = useContext(ThemeContext)
const theme = isLightTrue ? light:dark
return (
<div className="book=list">
<ul style={{background: theme.bg, color: theme.sytax}}>
{books.map(book => {
return (<li style={{background: theme.ui}} key={book.id}>{book.title}</li>)
})}
</ul>
</div>
)
}
export default BookList
|
## Part 1
## Data Science R programming Week 2 assisgnment
## pollutantmean function takes the mean of measurements of
## the selected pollutant from selected monitors (ids)
pollutantmean <- function (directory, pollutant, id = 1:332) {
## 'directory' is a character vector of length l indicating
## the location of the CSV files
## 'pollutant' is a character vector of length l indicating
## the name of the pollutant for which we calculate the mean -
## either "sulfate" or "nitrate"
## 'id' is an integer vector indicating the monitor ID numbers
## to be used
## Return the mean of the pollutant across all monitors listed
## in the 'id' vector (ignoring the NA values)
## NOTE: Do not round the result!
## initialize the final dataset from which the mean is calculated
y_total <- matrix (0, nrow = 0, ncol=3)
x <- c()
## create a character vector of csv files to read
for (l in 1:length(id)) {
x[l] <- paste(getwd(), "/", directory, "/", id[l], ".csv", sep="")
y <- read.csv(x[l])
## concatenate the csv file for each id
y_total <- rbind(y_total, y)
}
## calculate the mean of the final dataset
mean (y_total[,pollutant], na.rm = TRUE)
}
|
document.addEventListener("DOMContentLoaded", function () {
// Sélectionnez les éléments du DOM
const budgetForm = document.getElementById("budget-form");
const statutFilter = document.getElementById("statut-filter");
const jeuxTableBody = document.querySelector("#jeux-table tbody");
// Fonction pour charger et afficher les données des jeux vidéo
function chargerDonneesJeux() {
fetch("espaceprod.php")
.then(response => response.json()) // Traitement JSON ici
.then(data => {
// Nettoyez le contenu du tableau
jeuxTableBody.innerHTML = "";
// Filtrage des données en fonction du statut sélectionné
const statutFiltre = statutFilter.value;
const jeuxFiltres = statutFiltre === "Tous" ? data : data.filter(jeu => jeu.statut === statutFiltre);
// Remplissez le tableau avec les données filtrées
jeuxFiltres.forEach(jeu => {
const row = document.createElement("tr");
const titreCell = document.createElement("td");
const budgetCell = document.createElement("td");
titreCell.textContent = jeu.titre;
budgetCell.textContent = jeu.budget;
row.appendChild(titreCell);
row.appendChild(budgetCell);
jeuxTableBody.appendChild(row);
});
})
.catch(error => {
console.error("Erreur lors du chargement des données : " + error);
});
}
// Ajoutez un gestionnaire d'événements au formulaire de modification du budget
budgetForm.addEventListener("submit", function (e) {
e.preventDefault(); // Empêche le formulaire de se soumettre normalement
// Récupérez les données du formulaire
const formData = new FormData(budgetForm);
// Envoyez les données du formulaire au serveur via une requête AJAX
fetch("espaceprod.php", {
method: "POST",
body: formData,
})
.then(response => response.text())
.then(data => {
alert(data); // Affichez la réponse du serveur dans une alerte
// Actualisez la vue globale des jeux vidéo après la modification
chargerDonneesJeux();
})
.catch(error => {
console.error("Erreur lors de la modification : " + error);
});
});
// Ajoutez un gestionnaire d'événements au changement de filtre de statut
statutFilter.addEventListener("change", chargerDonneesJeux);
// Chargez les données des jeux vidéo lors du chargement de la page
chargerDonneesJeux();
});
// Sélectionnez le formulaire
const budgetForm = document.getElementById("budget-form");
// Ajoutez un gestionnaire d'événements au formulaire pour l'envoi
budgetForm.addEventListener("submit", function (e) {
e.preventDefault(); // Empêche le formulaire de se soumettre normalement
// Récupérez les données du formulaire
const formData = new FormData(budgetForm);
// Envoyez les données du formulaire au script PHP via une requête AJAX
fetch("espaceprod.php", {
method: "POST",
body: formData
})
.then(response => response.text())
.then(data => {
// Traitez la réponse du serveur ici, par exemple, mettez à jour l'interface utilisateur
alert("Modification réussie !");
})
.catch(error => {
console.error("Erreur lors de la modification : " + error);
});
});
|
import React, { useEffect } from "react";
import { createContext, useContext, useState } from "react";
import { onAuthStateChanged } from "firebase/auth";
import { auth } from '../config/firebase';
export const UserContext = createContext(false);
const userContextProvider = ({ children }) => {
const [user, setUser] = useState(false);
useEffect(() => {
const unsuscribe = onAuthStateChanged(auth, (user)=>{
setUser(user);
})
return unsuscribe;
}, []);
if(user === false) return (<p>Loading app...</p>)
return (
<div>
<UserContext.Provider value={{ user }}>{children}</UserContext.Provider>
</div>
);
};
export default userContextProvider;
export const useUserContext = () => useContext(UserContext);
|
#pragma once
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <iostream>
#include <unordered_set>
#include "BeastAttribute.hpp"
/**
* @brief declaration of WebSocket
*/
class WebSocket;
/**
* @brief type adapter
*/
template<typename T> struct Type2Type { typedef T OriginalType; };
/**
* @brief class Shared_state
* @details class appears to be a container for maintaining the shared state of WebSocket sessions.
* It stores the document root path and keeps track of active WebSocket sessions.
*/
class Shared_state
{
std::string _doc_root;
std::unordered_set<Type2Type<WebSocket>::OriginalType*> _sessions;
public:
/**
* @brief definition of constructor
*/
explicit Shared_state(std::string doc)
: _doc_root(std::move(doc)) {}
/**
* @brief getter for current root
*/
const std::string& doc_root() const noexcept
{
return _doc_root;
}
/**
* @brief method for takes a reference to a WebSocket object session
* and adds it to the set of WebSocket sessions _sessions using the insert function
*/
void join(WebSocket& session);
/**
* @brief method for takes a reference to a WebSocket object session
* and removes it from the set of WebSocket sessions _sessions using the erase function
*/
void leave(WebSocket& session);
/**
* @brief method then iterates over each pointer session in the _sessions
* @details set and calls the send function on each session, passing the ss shared pointer as an argument.
* This function is responsible for sending a message to all WebSocket sessions in the shared state.
*/
void send(std::string message);
};
/**
* @brief class WebSocket
* @details Is used to establish and maintain a WebSocket connection
* between a client and a server.
*/
class WebSocket : public std::enable_shared_from_this<WebSocket>
{
boost::beast::flat_buffer _buffer;
boost::beast::websocket::stream<tcp::socket> _ws;
std::shared_ptr<Type2Type<Shared_state>::OriginalType> _state;
std::vector<std::shared_ptr<const std::string>> _queue;
/**
* @brief method called in case of an error
* and passing the error code and error description.
*/
void fail(error_code ec, const char* what);
/**
* @brief method is called after accepting a WebSocket connection
* @details If ec contains an error, the function calls the fail function with the corresponding error message.
* If the connection acceptance is successful, the function calls the join shared state _state function
* to add the current WebSocket object to the list of active connections.
* The function then asynchronously reads data from the socket _ws
* into the _buffer and passes control to the onRead function.
*/
void onAccept(error_code ec);
/**
* @brief method is called after reading data from a WebSocket
* @details If ec contains an error, the function calls the fail function with the corresponding error message.
* If the data read is successful, the function sends the data to the shared _state using the
* send function, passing the data from the _buffer. The function then clears the _buffer using the consume
* function and asynchronously continues reading data from the socket into the _buffer
* and passes control to the onRead function.
*/
void onRead(error_code ec, std::size_t bytes_transferred);
/**
* @brief method is called after successful writing of data to the WebSocket
* @details If ec contains an error, the function calls the fail function with the corresponding error message.
* If the data write was successful, the function removes the first element from the _queue
* because the data was successfully sent. The function then checks whether the _queue queue is empty.
* If the queue is not empty, the function asynchronously writes data from _queue.front() to the _ws socket
* and passes control to the onWrite function.
*/
void onWrite(error_code ec, std::size_t bytes_transferred);
public:
/**
* @brief definition of constructor
*/
WebSocket(tcp::socket socket, const std::shared_ptr<Shared_state>& state)
: _ws(std::move(socket)), _state(state) {}
/**
* @brief class destructor that calls the leave generic _state function
* when the WebSocket object is destroyed
*/
virtual ~WebSocket() { _state->leave(*this); }
/**
* @brief method that performs HTTP request processing
* and WebSocket connection establishment
*/
template<typename Body, typename Allocator>
void run(boost::beast::http::request<Body
, boost::beast::http::basic_fields<Allocator>> req);
/**
* @brief method for sending a message over WebSocket
* @details It takes a std::shared_ptr on a constant std::string
* object that represents the message to send.
* The function adds the message to the _queue queue.
*/
void send(const std::shared_ptr<const std::string>& ss);
/**
* @brief getter for current queue
*/
std::vector<std::shared_ptr<const std::string>> queue() const { return _queue; }
};
template<class Body, class Allocator>
void WebSocket::run(boost::beast::http::request<Body,
boost::beast::http::basic_fields<Allocator>> req)
{
_ws.async_accept(
req,
std::bind(
&WebSocket::onAccept,
shared_from_this(),
std::placeholders::_1));
}
void Shared_state::join(WebSocket& session)
{
_sessions.insert(&session);
}
void Shared_state::leave(WebSocket& session)
{
_sessions.erase(&session);
}
void Shared_state::send(std::string message)
{
const auto ss = std::make_shared<const std::string>(std::move(message));
for (auto* session : _sessions)
session->send(ss);
}
void WebSocket::fail(error_code ec, const char* what)
{
if (ec == asio::error::operation_aborted ||
ec == boost::beast::websocket::error::closed)
return;
std::cerr << what << ": " << "\n";
}
void WebSocket::onAccept(error_code ec)
{
if (ec)
return fail(ec, ec.message().c_str());
_state->join(*this);
_ws.async_read(_buffer,
[sp = shared_from_this()](
error_code ec, std::size_t bytes)
{
sp->onRead(ec, bytes);
});
}
void WebSocket::onRead(error_code ec, std::size_t bytes_transferred)
{
if (ec)
return fail(ec, ec.message().c_str());
_state->send(boost::beast::buffers_to_string(_buffer.data()));
_buffer.consume(_buffer.size());
_ws.async_read(
_buffer,
[sp = shared_from_this()](
error_code ec, std::size_t bytes)
{
sp->onRead(ec, bytes);
});
}
void WebSocket::onWrite(error_code ec, std::size_t bytes_transferred)
{
if (ec)
return fail(ec, ec.message().c_str());
_queue.erase(_queue.begin());
if (!_queue.empty())
_ws.async_write(
asio::buffer(*_queue.front()),
[sp = shared_from_this()](
error_code ec, std::size_t bytes)
{
sp->onWrite(ec, bytes);
});
}
void WebSocket::send(const std::shared_ptr<const std::string>& ss)
{
_queue.push_back(ss);
if (_queue.size() > 1)
return;
_ws.async_write(
asio::buffer(*_queue.front()),
[sp = shared_from_this()](
error_code ec, std::size_t bytes)
{
sp->onWrite(ec, bytes);
});
}
|
//best
class Solution {
public:
int equalPairs(vector<vector<int>>& grid) {
map<vector<int> , int> mp;
int ans = 0;
for(int i=0;i<grid.size();i++){
vector<int> v;
for(int j=0;j<grid.size();j++)
v.push_back(grid[i][j]);
mp[v]++;
}
for(int j=0;j<grid.size();j++){
vector<int> v;
for(int i=0;i<grid.size();i++)
v.push_back(grid[i][j]);
if(mp[v] > 0)
ans += mp[v];
}
return ans;
}
};
//self
class Solution {
public:
vector<vector<int>> trans(vector<vector<int>>& grid){
vector<vector<int>> tgrid(grid.size(),vector<int>(grid.size(),0));
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[0].size();j++){
tgrid[i][j]=grid[j][i];
}
}
return tgrid;
}
int equalPairs(vector<vector<int>>& grid) {
vector<vector<int>> Tgrid=trans(grid);
int count=0;
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid.size();j++){
if(grid[i]==Tgrid[j])
{
count++;
}
}
}
return count;
}
};
|
<template>
<div class="tw-flex tw-flex-col">
<div class="tw-shadow tw-bg-white tw-p-4 tw-flex tw-justify-between tw-mb-7">
<div class="tw-font-bold tw-text-gray-700 tw-text-lg tw-py-1">Visitors List</div>
</div>
<div class="tw-flex-grow">
<div class="tw-shadow tw-bg-white tw-p-4">
<ec-table :rows="visitors" :columns="columns">
<template v-slot:cell-client="slotProps">
<div class="tw-text-xs">
{{ sessionInfo(slotProps.row.session_id)?.init_name || slotProps.row.init_ip }}
</div>
</template>
<template v-slot:cell-location="slotProps"> {{ slotProps.row.init_location }}</template>
<template v-slot:cell-referrer="slotProps"> {{ slotProps.row.referrer }}</template>
<template v-slot:cell-url="slotProps">
<div>
<a
:href="$_.last(slotProps.row.visits).url"
target="_blank"
class="text-blue-5 tw-font-medium tw-whitespace-pre-wrap"
>{{ $_.last(slotProps.row.visits).title }}</a
>
</div>
</template>
<template v-slot:cell-activity="slotProps">
<div class="tw-flex tw-items-center tw-gap-2">
<!--{{ $_.last(slotProps.row.visits).visiting }}-->
<q-icon
name="fa fa-circle"
size="8px"
:color="$_.last(slotProps.row.visits).visiting ? 'green-8' : 'grey-6'"
/>
<div
class="tw-font-medium"
:class="{
'text-green-8': $_.last(slotProps.row.visits).visiting,
'text-grey-8': !$_.last(slotProps.row.visits).visiting,
}"
>
{{ $_.last(slotProps.row.visits).visiting ? "Visiting" : "Not Visiting" }}
</div>
</div>
</template>
<!--<template v-slot:cell-stay_time="slotProps">-->
<!-- <div class="">-->
<!-- <!– <pre>{{ slotProps.row }}</pre> –>-->
<!-- {{ $helpers.diffAsMinute($_.last(slotProps.row.visits).first_visit_time) }}-->
<!-- </div>-->
<!--</template>-->
</ec-table>
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { mapGetters } from "vuex";
import EcTable from "components/common/table/EcTable.vue";
import SocketSession from "src/store/models/SocketSession";
const columns = [
{
name: "client",
align: "left",
label: "Client",
},
{
name: "location",
align: "left",
label: "Location",
},
{
name: "url",
align: "left",
label: "Currently On",
},
{
name: "referrer",
align: "left",
label: "Referrer",
},
{
name: "activity",
align: "left",
label: "Activity",
},
// {
// name: "stay_time",
// label: "Time On Site",
// },
];
export default defineComponent({
components: {
EcTable,
},
data(): any {
return {
visitorInterval: "",
};
},
setup() {
return {
columns,
};
},
computed: {
...mapGetters({
visitors: "visitor/visitors",
}),
},
methods: {
sessionInfo(sesId: any) {
return SocketSession.find(sesId) || {};
},
},
mounted() {
this.visitorInterval = setInterval(() => {
this.$forceUpdate();
}, 10000);
},
beforeUnmount() {
clearInterval(this.visitorInterval);
},
});
</script>
|
#include "Application.h"
Application::Application(
std::string title,
int width,
int height,
int fps_limit
) : window_{ sf::VideoMode(width, height), title, sf::Style::Titlebar | sf::Style::Close },
event_{sf::Event()} {
window_.setFramerateLimit(fps_limit);
}
void Application::update() {
update_events();
update_mouse_position();
for (std::shared_ptr<Object> object : p_objects_) {
object->update();
}
}
void Application::render() {
window_.clear(Colors::WHITE);
for (std::shared_ptr<Object> object : p_objects_) {
object->render(window_);
}
window_.display();
}
void Application::update_events() {
// Event polling.
while (window_.pollEvent(event_)) {
if (p_event_handler_) p_event_handler_(event_);
switch (event_.type) {
// Process window closing.
case sf::Event::Closed:
window_.close();
break;
// Process pressed keys.
case sf::Event::KeyPressed:
switch (event_.key.code) {
case sf::Keyboard::Escape:
window_.close();
break;
}
// Process mouse button click.
case sf::Event::MouseButtonPressed: {
if (event_.mouseButton.button == sf::Mouse::Left) {
for (std::shared_ptr<Object> object : p_clickable_objects_) {
auto bounds = object->get_global_bounds();
auto leftUpper = bounds.first;
auto rightBottom = bounds.second;
if (mouse_position_.x >= leftUpper.x &&
mouse_position_.x <= rightBottom.x &&
mouse_position_.y >= leftUpper.y &&
mouse_position_.y <= rightBottom.y &&
object->get_click_handler()) {
object->get_click_handler()->on_mouse_pressed();
break;
}
}
}
break;
}
}
}
}
void Application::update_mouse_position() {
mouse_position_ = sf::Mouse::getPosition(window_);
}
void Application::start() {
while (is_running()) {
update();
render();
}
}
const bool Application::is_running() const {
return window_.isOpen();
}
void Application::add_object(std::shared_ptr<Object> object) {
p_objects_.push_back(object);
if (object->is_clickable()) {
p_clickable_objects_.push_back(object);
}
}
void Application::add_objects(const std::vector<std::shared_ptr<Object>>& objects) {
for (std::shared_ptr<Object> object : objects) {
add_object(object);
}
}
void Application::add_event_handler(EventHandler p_event_handler) {
p_event_handler_ = p_event_handler;
}
void Application::set_icon(const sf::Image& icon) {
window_.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());
}
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.red {
color: red;
}
.green {
color: green;
}
.blue {
color: blue;
}
</style>
</head>
<body>
<div><span id="hours" class="red">hh</span>:<span id="minutes" class="green">mm</span>:<span id="seconds" class="blue">ss</span></div>
<div>
<button id="start" type="button">Start</button>
<button id="stop" type="button">Stop</button>
</div>
<script>
const updateTime = () => {
let hours = document.querySelector('#hours')
let minutes = document.querySelector('#minutes')
let seconds = document.querySelector('#seconds')
hours.innerHTML = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
minutes.innerHTML = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
seconds.innerHTML = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
}
let timerId
const startClock = () => {
timerId = setInterval(updateTime, 1000)
updateTime()
}
const stopClock = () => {
clearInterval(timerId)
}
const buttonStart = document.querySelector('#start')
const buttonStop = document.querySelector('#stop')
buttonStart.addEventListener('click', startClock)
buttonStop.addEventListener('click', stopClock)
</script>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.