text
stringlengths 184
4.48M
|
---|
public class Member {
// Attributes
private int memberID; // member id
private String name; // member name
private String surname; // member surname
private double height; // member height
private double weight; // member weight
// Constructor method
public Member(int memberID, String name, String surname, double height, double weight){
this.memberID=memberID;
this.name=name;
this.surname=surname;
this.height=height;
this.weight=weight;
}
// Get / Set method
public int getMemberID() { return memberID; }
public void setMemberID(int MemberID) { this.memberID = MemberID; }
public String getName() { return name; }
public void setName(String Name) { this.name = Name; }
public String getSurname() { return surname; }
public void setSurname(String Surname) { this.surname = Surname; }
public double getHeight() { return height; }
public void setHeight(double Height) { this.height = Height; }
public double getWeight() { return weight; }
public void setWeight(double Weight) { this.weight = Weight; }
// Display method
public void display() {
System.out.println("Id:" + this.getMemberID() + " Name:" + this.getName() + " Surname:" + this.getSurname() + " Weight:" + this.getWeight() + " Height:" + this.getHeight());
}
// BMI method
public double getBMI() {
double BMI = weight / (height * height);
return BMI;
}
// Weight status method
public void weightStatus() {
if (getBMI() < 18.5) {
System.out.println("Underweight");
}
else if (getBMI() <= 24.9) {
System.out.println("Normal");
}
else if (getBMI() <= 29.9) {
System.out.println("Overweight");
}
else if (getBMI() <= 34.9) {
System.out.println("Obese");
}
else {
System.out.println("Extremely obese");
}
}
}
|
import React from "react";
import PropTypes from "prop-types";
import { Label } from "../Label";
import { Input } from "../Input";
import { HelpText } from "../HelpText";
import type { InputProps } from "../Input";
import { Box } from "../../primitives/Box";
export interface FormInputProps
extends Omit<
InputProps,
"aria-describedby" | "aria-label" | "aria-labelledby" | "id"
> {
/** The `id` of the input. */
id: string;
/** The text to be used for Label. */
label: NonNullable<React.ReactNode>;
/** The text to be used for HelpText. */
helpText?: React.ReactNode;
}
/** Combined Label, Input, and HelpText used for Inputs in forms. */
const FormInput = React.forwardRef<HTMLInputElement, FormInputProps>(
(
{
disabled,
hasError,
helpText,
id,
label,
required,
type = "text",
value,
...props
},
ref
) => {
return (
<Box.div>
<Label disabled={disabled} htmlFor={id} required={required}>
{label}
</Label>
<Input
aria-describedby={helpText ? `${id}-help-text` : undefined}
disabled={disabled}
hasError={hasError}
id={id}
ref={ref}
required={required}
type={type}
value={value}
{...props}
/>
{helpText ? (
<HelpText hasError={hasError} id={`${id}-help-text`}>
{helpText}
</HelpText>
) : (
<Box.div h="1rem" marginTop="space20" />
)}
</Box.div>
);
}
);
FormInput.displayName = "FormInput";
FormInput.propTypes = {
disabled: PropTypes.bool,
helpText: PropTypes.node,
id: PropTypes.string.isRequired,
label: PropTypes.node.isRequired,
name: PropTypes.string,
placeholder: PropTypes.string,
readOnly: PropTypes.bool,
required: PropTypes.bool,
};
export { FormInput };
|
import { ApplicationType } from '../../src/sources/types/index.js';
import {
IHackerOneProgram,
IHackerOneProgramScopeEntry,
parseOutOfScope,
parseProgram,
parseScope,
} from '../../src/sources/hackerone/hackerOneProgramParser.js';
describe('parseProgram', () => {
it('parses program', () => {
const program: IHackerOneProgram = {
id: 'test',
name: 'test',
url: 'https://bugcrowd.com/foo',
offers_bounties: true,
submission_state: 'open',
targets: {
in_scope: [
{
asset_type: 'OTHER',
asset_identifier:
'lrswitch-access-2.kulnet.kuleuven.be',
instruction: '',
},
],
out_of_scope: [
{
asset_type: 'OTHER',
asset_identifier: 'ad.nl',
instruction: '',
},
],
},
};
const parsedProgram = parseProgram(program);
const expectedProgram = {
organization: {
id: 'test',
bounty: true,
name: 'test',
programURL: 'https://bugcrowd.com/foo',
},
domains: [
{
domainId: 'ad.nl',
organizationId: 'test',
forceManualReview: false,
isInScope: false,
},
{
domainId: 'kuleuven.be',
organizationId: 'test',
forceManualReview: true,
},
],
subdomains: [
{
subdomainId: 'lrswitch-access-2.kulnet.kuleuven.be',
root: 'kuleuven.be',
organizationId: 'test',
},
],
ipRanges: [],
endpoints: [],
applications: [],
sourceCodeRepositories: [],
};
expect(parsedProgram).toMatchObject(expectedProgram);
});
});
describe('parseScope - type URL', () => {
it('parses instruction for domains and subdomains', () => {
const casinoDescription =
'unibet.me, maria.casino, stly.eu share the same platform, we will only reward the initial report for any bug, as one fix will solve the bug on all three domains.';
const semleDescription =
'Our main domain for Semmle and LGTM services. All subdomains under semmle.com are in-scope **except**:\n* dev.semmle.com\n* git.semmle.com\n* jira.semmle.com\n* wiki.semmle.com';
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'maria.casino',
asset_type: 'URL',
instruction: casinoDescription,
},
{
asset_identifier: 'semmle.com',
asset_type: 'URL',
instruction: semleDescription,
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [
{
domainId: 'maria.casino',
forceManualReview: false,
isInScope: true,
organizationId: 'test',
description: casinoDescription,
},
{
forceManualReview: true,
domainId: 'unibet.me',
organizationId: 'test',
description: casinoDescription,
},
{
domainId: 'stly.eu',
forceManualReview: true,
organizationId: 'test',
description: casinoDescription,
},
{
domainId: 'semmle.com',
organizationId: 'test',
description: semleDescription,
},
],
subdomains: [
{
subdomainId: 'dev.semmle.com',
root: 'semmle.com',
organizationId: 'test',
},
{
subdomainId: 'git.semmle.com',
root: 'semmle.com',
organizationId: 'test',
},
{
subdomainId: 'jira.semmle.com',
root: 'semmle.com',
organizationId: 'test',
},
{
subdomainId: 'wiki.semmle.com',
root: 'semmle.com',
organizationId: 'test',
},
],
applications: [],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
});
describe('parseScope - type OTHER_IPA', () => {
it('parses instruction as other application', () => {
const description =
'Sign up on Microsoft AppCenter and download the special app for BugBounty testing:\nhttps://install.appcenter.ms/orgs/innogames-gmbh/apps/elvenar-bugbounty-ios/distribution_groups/bugbounty';
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.innogames.enterprise.elvenar',
asset_type: 'OTHER_IPA',
instruction: description,
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
ipRanges: [],
endpoints: [],
applications: [
{
url:
'https://install.appcenter.ms/orgs/innogames-gmbh/apps/elvenar-bugbounty-ios/distribution_groups/bugbounty',
name: 'com.innogames.enterprise.elvenar',
type: ApplicationType.mobileUnknown,
organizationId: 'test',
description,
},
],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses asset_identifier as app name without url', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.mi.global.shop',
asset_type: 'OTHER_IPA',
instruction: '',
},
{
asset_identifier: 'com.foo.boo',
asset_type: 'OTHER_IPA',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
ipRanges: [],
endpoints: [],
applications: [
{
name: 'com.mi.global.shop',
type: ApplicationType.mobileUnknown,
},
{
name: 'com.foo.boo',
type: ApplicationType.mobileUnknown,
},
],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
});
describe('parseScope - type OTHER', () => {
it('parses instruction as mobile applications from description for apple', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'AOL (misc)',
asset_type: 'OTHER',
instruction:
'* [7News iOS](https://itunes.apple.com/au/app/7news/id439828000?mt=8)\\n* [7News Android](https://play.google.com/store/apps/details?id=com.seven.news&hl=en_US)',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [
{
url:
'https://itunes.apple.com/au/app/7news/id439828000?mt=8',
type: ApplicationType.iosMobile,
},
{
url:
'https://play.google.com/store/apps/details?id=com.seven.news&hl=en_US',
type: ApplicationType.androidMobile,
},
],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses instruction as mobile applications from description for google', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier:
'Wallet App (Android): https://play.google.com/store/apps/details?id=piuk.blockchain.android ',
asset_type: 'OTHER',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [
{
url:
'https://play.google.com/store/apps/details?id=piuk.blockchain.android',
type: ApplicationType.androidMobile,
},
],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses instruction as domains and subdomains from description', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'AOL (misc)',
asset_type: 'OTHER',
instruction:
'## In Scope\\n* *.aol.com\\n\\n## Notes\\nOnly use this asset when nothing else can be reasonably selected.\\n\\nBugs with AOL that are not listed in scope of our other AOL-related assets can still be submitted to this asset and **_*might*_** be eligible for award, at the sole discretion of the Verizon Media Bug Bounty team.\\n\\n## Out of Scope\\n* *nat.aol.com\\n* *.ipt.aol.com\\n',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [
{
domainId: 'aol.com',
organizationId: 'test',
description:
'## In Scope\\n* *.aol.com\\n\\n## Notes\\nOnly use this asset when nothing else can be reasonably selected.\\n\\nBugs with AOL that are not listed in scope of our other AOL-related assets can still be submitted to this asset and **_*might*_** be eligible for award, at the sole discretion of the Verizon Media Bug Bounty team.\\n\\n## Out of Scope\\n* *nat.aol.com\\n* *.ipt.aol.com\\n',
forceManualReview: true,
},
],
subdomains: [
{
subdomainId: 'nat.aol.com',
organizationId: 'test',
root: 'aol.com',
},
{
subdomainId: 'ipt.aol.com',
organizationId: 'test',
root: 'aol.com',
},
],
applications: [],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses instruction as source code from description', () => {
const instruction =
'###Review the Code\n* [Source Code](https://github.com/arkime/arkime)\n* Submit a PR to fix/update the code - [fork](https://help.github.com/en/articles/fork-a-repo) the codebase then submit a [PR](https://help.github.com/en/articles/creating-a-pull-request-from-a-fork)\n* Visit our web page at https://arkime.com/ for pre-bulit rpm/deb and instructions for running yourself.\n\n##Out of Scope\n* Known unauthenticated endpoints such as `parliament.json` & `eshealth.json`\n* UI based bugs on `parliament`\n* demo.arkime.com\n* *.molo.ch (old website)\n';
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'OTHER',
asset_type: 'OTHER',
instruction,
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [
{
domainId: 'arkime.com',
organizationId: 'test',
description: instruction,
forceManualReview: true,
},
{
domainId: 'molo.ch',
organizationId: 'test',
forceManualReview: true,
description: instruction,
},
],
subdomains: [
{
subdomainId: 'demo.arkime.com',
organizationId: 'test',
root: 'arkime.com',
},
],
applications: [],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [
{
url: 'https://github.com/arkime/arkime',
type: 'github',
},
],
};
expect(result).toMatchObject(expectedResult);
});
});
describe('parseScope - type CIDR', () => {
it('does not parse type CIDR with invalid IP', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'asdasd21312',
asset_type: 'CIDR',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses type CIDR as ipv4 range', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: '54.175.255.192/27',
asset_type: 'CIDR',
instruction: '',
},
{
asset_identifier: '140.95.0.0/16',
asset_type: 'CIDR',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [],
ipRanges: [
{
ipRange: '54.175.255.192/27',
organizationId: 'test',
type: 'ipv4',
},
{
ipRange: '140.95.0.0/16',
organizationId: 'test',
type: 'ipv4',
},
],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses type CIDR as ipv6 range', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: '2604:a880:400:d1::aad:8001',
asset_type: 'CIDR',
instruction: '',
},
{
asset_identifier: '2a01:7e00::f03c:91ff:fec6:27a3',
asset_type: 'CIDR',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [],
ipRanges: [
{
ipRange: '2604:a880:400:d1::aad:8001',
organizationId: 'test',
type: 'ipv6',
},
{
ipRange: '2a01:7e00::f03c:91ff:fec6:27a3',
organizationId: 'test',
type: 'ipv6',
},
],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
});
describe('parseScope - type APPLE_STORE_APP_ID', () => {
it('parses instruction as app url', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.defi.wallet',
asset_type: 'APPLE_STORE_APP_ID',
instruction:
'https://apps.apple.com/app/crypto-com-wallet/id1512048310',
},
{
asset_identifier: 'com.monaco.mobile',
asset_type: 'APPLE_STORE_APP_ID',
instruction:
'Get the app here - https://itunes.apple.com/us/app/monaco-card/id1262148500?ls=1&mt=8\n\nYou won’t need test accounts for this as it will be public facing sites for now.\n\nGet the MCO Cryptocurrency Card app for iOS in the link above this app should allow you to create an account and start using the Monaco services.',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [
{
type: ApplicationType.iosMobile,
url:
'https://apps.apple.com/app/crypto-com-wallet/id1512048310',
},
{
type: ApplicationType.iosMobile,
url:
'https://itunes.apple.com/us/app/monaco-card/id1262148500?ls=1&mt=8',
},
],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses asset_identifier as app url', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.defi.wallet',
asset_type: 'APPLE_STORE_APP_ID',
instruction: '',
},
{
asset_identifier: 'com.monaco.mobile',
asset_type: 'APPLE_STORE_APP_ID',
instruction:
'won’t need test accounts for this as it will be public facing sites for now.\n\nGet the MCO Cryptocurrency Card app for iOS in the link above this app should allow you to create an account and start using the Monaco services.',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [
{
type: ApplicationType.iosMobile,
url: 'https://apps.apple.com/app/com.defi.wallet',
},
{
type: ApplicationType.iosMobile,
url: 'https://apps.apple.com/app/com.monaco.mobile',
},
],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
});
describe('parseScope - type GOOGLE_PLAY_APP_ID', () => {
it('parses instruction as app url', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.defi.wallet',
asset_type: 'GOOGLE_PLAY_APP_ID',
instruction:
'https://play.google.com/store/apps/details?id=com.defi.wallet',
},
{
asset_identifier: 'app.zenly.locator',
asset_type: 'GOOGLE_PLAY_APP_ID',
instruction:
'https://play.google.com/store/apps/details?id=app.zenly.locator&hl=en_US',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [
{
type: ApplicationType.androidMobile,
url:
'https://play.google.com/store/apps/details?id=com.defi.wallet',
},
{
type: ApplicationType.androidMobile,
url:
'https://play.google.com/store/apps/details?id=app.zenly.locator&hl=en_US',
},
],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses asset_identifier as app url', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.defi.wallet',
asset_type: 'GOOGLE_PLAY_APP_ID',
instruction: '',
},
{
asset_identifier: 'app.zenly.locator',
asset_type: 'GOOGLE_PLAY_APP_ID',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [
{
type: ApplicationType.androidMobile,
url:
'https://play.google.com/store/apps/details?id=com.defi.wallet',
},
{
type: ApplicationType.androidMobile,
url:
'https://play.google.com/store/apps/details?id=app.zenly.locator',
},
],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
});
describe('parseScope - type DOWNLOADABLE_EXECUTABLES', () => {
it('parses instruction as app url', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'Basecamp.app',
asset_type: 'DOWNLOADABLE_EXECUTABLES',
instruction:
'Basecamp for Mac: https://basecamp.com/via#basecamp-for-your-mac-or-pc',
},
{
asset_identifier: 'HEY.app',
asset_type: 'DOWNLOADABLE_EXECUTABLES',
instruction: 'HEY for macOS: https://hey.com/apps/',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [
{
domainId: 'basecamp.com',
forceManualReview: true,
description:
'Basecamp for Mac: https://basecamp.com/via#basecamp-for-your-mac-or-pc',
organizationId: 'test',
},
{
domainId: 'hey.com',
description: 'HEY for macOS: https://hey.com/apps/',
forceManualReview: true,
organizationId: 'test',
},
],
subdomains: [],
ipRanges: [],
endpoints: [
{
path: '/via',
subdomainId: 'basecamp.com',
organizationId: 'test',
},
{
path: '/apps/',
subdomainId: 'hey.com',
organizationId: 'test',
},
],
applications: [
{
type: ApplicationType.executable,
url: 'https://basecamp.com/via#basecamp-for-your-mac-or-pc',
name: 'Basecamp.app',
},
{
type: ApplicationType.executable,
url: 'https://hey.com/apps/',
name: 'HEY.app',
},
],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses asset_identifier as app name without url', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'After Effects',
asset_type: 'DOWNLOADABLE_EXECUTABLES',
instruction: '',
},
{
asset_identifier: 'Animate',
asset_type: 'DOWNLOADABLE_EXECUTABLES',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
ipRanges: [],
endpoints: [],
applications: [
{
type: 'executable',
name: 'After Effects',
},
{
type: 'executable',
name: 'Animate',
},
],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
});
describe('parseScope - type WINDOWS_APP_STORE_APP_ID', () => {
it('parses instruction for application URLs', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: '9pp8m6lpfkgf',
asset_type: 'WINDOWS_APP_STORE_APP_ID',
instruction:
"It's the standalone edge extension\nhttps://www.microsoft.com/en-us/store/p/dashlane-password-manager/9pp8m6lpfkgf",
},
{
asset_identifier: 'HEY.exe',
asset_type: 'WINDOWS_APP_STORE_APP_ID',
instruction:
'HEY for Windows: https://www.microsoft.com/en-us/p/hey-mail/9pf08ljw7gw2',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
ipRanges: [],
endpoints: [],
applications: [
{
type: ApplicationType.windowsAppStore,
url:
'https://www.microsoft.com/en-us/store/p/dashlane-password-manager/9pp8m6lpfkgf',
},
{
type: ApplicationType.windowsAppStore,
url:
'https://www.microsoft.com/en-us/p/hey-mail/9pf08ljw7gw2',
},
],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses asset_identifier as app name', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'After Effects',
asset_type: 'WINDOWS_APP_STORE_APP_ID',
instruction: '',
},
{
asset_identifier: 'Animate',
asset_type: 'WINDOWS_APP_STORE_APP_ID',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
ipRanges: [],
endpoints: [],
applications: [
{
type: ApplicationType.windowsAppStore,
name: 'After Effects',
url: 'After Effects',
},
{
type: ApplicationType.windowsAppStore,
url: 'Animate',
name: 'Animate',
},
],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
});
describe('parseScope - type OTHER_APK', () => {
it('parses instruction for application urls', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.unibet.casino',
asset_type: 'OTHER_APK',
instruction:
'Unibet Casino - Slots & Games\n\nhttps://cdn.unicdn.net/apk/UnibetCasino.apk',
},
{
asset_identifier: 'com.mi.global.shop',
asset_type: 'OTHER_APK',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
ipRanges: [],
endpoints: [],
applications: [
{
type: ApplicationType.mobileUnknown,
name: 'com.unibet.casino',
url: 'https://cdn.unicdn.net/apk/UnibetCasino.apk',
},
{
type: ApplicationType.mobileUnknown,
name: 'com.mi.global.shop',
},
],
parameters: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses asset_identifier as app name', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.mi.global.shop',
asset_type: 'OTHER_APK',
instruction: '',
},
{
asset_identifier: 'com.foo.boo',
asset_type: 'OTHER_APK',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
ipRanges: [],
endpoints: [],
applications: [
{
name: 'com.mi.global.shop',
type: ApplicationType.mobileUnknown,
},
{
name: 'com.foo.boo',
type: ApplicationType.mobileUnknown,
},
],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses instruction as other application from description', () => {
const description =
'Sign up on Microsoft AppCenter and download the special app for BugBounty testing:\nhttps://install.appcenter.ms/orgs/innogames-gmbh/apps/elvenar-bugbounty-android/distribution_groups/bugbounty';
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.innogames.enterprise.elvenar',
asset_type: 'OTHER_APK',
instruction: description,
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
applications: [
{
url:
'https://install.appcenter.ms/orgs/innogames-gmbh/apps/elvenar-bugbounty-android/distribution_groups/bugbounty',
type: ApplicationType.mobileUnknown,
description,
organizationId: 'test',
},
],
ipRanges: [],
endpoints: [],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses asset_identifier as app name without url', () => {
const scopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'com.mi.global.shop',
asset_type: 'OTHER_APK',
instruction: '',
},
{
asset_identifier: 'com.foo.boo',
asset_type: 'OTHER_APK',
instruction: '',
},
];
const result = parseScope('test', scopeEntries);
const expectedResult = {
domains: [],
subdomains: [],
ipRanges: [],
endpoints: [],
applications: [
{
name: 'com.mi.global.shop',
type: ApplicationType.mobileUnknown,
},
{
name: 'com.foo.boo',
type: ApplicationType.mobileUnknown,
},
],
sourceCodeRepositories: [],
};
expect(result).toMatchObject(expectedResult);
});
});
describe('parseOutOfScope', () => {
it('parses instruction for domains and subdomains', () => {
const description =
'If you would like to report a vulnerability to **Verizon** for one of their other companies, please visit [this link]\n(https://www.verizon.com/info/reportsecurityvulnerability). These include, among others:\n* MapQuest\n* MovilData \n* Skyward\n* XO\n* Yahoo Small Business\n\nAlong with these Verizon Corporate domains:\n* *.verizonwireless.com\n* *.verizon.com\n* *.verizon.net\n* *.vzw.com\n* *.myvzw.com\n* *.verizonbusiness.com';
const outOfScopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'Verizon (parent)',
asset_type: 'OTHER',
instruction: description,
},
];
const result = parseOutOfScope('test', outOfScopeEntries);
const expectedResult = {
domains: [
{
domainId: 'verizon.com',
organizationId: 'test',
description,
forceManualReview: true,
},
{
domainId: 'verizonwireless.com',
organizationId: 'test',
isInScope: false,
description,
forceManualReview: true,
},
{
domainId: 'verizon.net',
organizationId: 'test',
isInScope: false,
description,
forceManualReview: true,
},
{
domainId: 'vzw.com',
organizationId: 'test',
isInScope: false,
description,
forceManualReview: true,
},
{
domainId: 'myvzw.com',
organizationId: 'test',
isInScope: false,
description,
forceManualReview: true,
},
{
domainId: 'verizonbusiness.com',
organizationId: 'test',
isInScope: false,
description,
forceManualReview: true,
},
],
subdomains: [
{
subdomainId: 'www.verizon.com',
root: 'verizon.com',
organizationId: 'test',
},
],
endpoints: [
{
path: '/info/reportsecurityvulnerability',
subdomainId: 'verizon.com',
organizationId: 'test',
},
{
path: '/info/reportsecurityvulnerability',
subdomainId: 'www.verizon.com',
organizationId: 'test',
},
],
parameters: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses asset_identifier for domain', () => {
const outOfScopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: '*.rubyonrails.org',
asset_type: 'URL',
instruction: '',
},
];
const result = parseOutOfScope('test', outOfScopeEntries);
const expectedResult = {
domains: [
{
domainId: 'rubyonrails.org',
organizationId: 'test',
isInScope: false,
forceManualReview: false,
},
],
subdomains: [],
endpoints: [],
};
expect(result).toMatchObject(expectedResult);
});
it('parses asset_identifier and instruction for domain and subdomain', () => {
const description =
'\nAirportrentalcars.com is current *not* in scope. Please do not test it. \n';
const outOfScopeEntries: IHackerOneProgramScopeEntry[] = [
{
asset_identifier: 'www.airportrentalcars.com',
asset_type: 'URL',
instruction: description,
},
];
const result = parseOutOfScope('test', outOfScopeEntries);
const expectedResult = {
domains: [
{
domainId: 'airportrentalcars.com',
organizationId: 'test',
isInScope: false,
description,
},
],
subdomains: [
{
subdomainId: 'www.airportrentalcars.com',
root: 'airportrentalcars.com',
organizationId: 'test',
},
],
endpoints: [],
};
expect(result).toMatchObject(expectedResult);
});
});
|
import * as fs from 'fs'
import { type AddressInfo } from 'net'
import * as path from 'path'
import t from 'tap'
import { createFastify } from './createFastify'
import { request, requestJSON } from './request'
import FormData = require('form-data')
const filePath = path.join(__dirname, '../package.json')
t.plan(1)
t.test('addHooks', function (t) {
t.plan(4)
t.test('single file', async function (t) {
t.plan(5)
const fastify = await createFastify(t, { addHooks: true })
const form = new FormData()
form.append('foo', 'bar')
form.append('file', fs.createReadStream(filePath))
const response = await request(`http://localhost:${(fastify.server.address() as AddressInfo).port}`, form)
t.equal(response.status, 200)
const json = await response.json()
t.equal(json.body.foo, 'bar')
t.equal(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/.test(json.body.file), true)
t.ok(json.files.file)
t.equal(json.files.file.filename, 'package.json')
})
t.test('multiple fields', async function (t) {
t.plan(4)
const fastify = await createFastify(t, { addHooks: true })
const form = new FormData()
form.append('foo', 'bar')
form.append('foo', 'baz')
form.append('file', fs.createReadStream(filePath))
const response = await request(`http://localhost:${(fastify.server.address() as AddressInfo).port}`, form)
t.equal(response.status, 200)
const json = await response.json()
t.same(json.body.foo, ['bar', 'baz'])
t.ok(json.files.file)
t.equal(json.files.file.filename, 'package.json')
})
t.test('multiple files', async function (t) {
t.plan(6)
const fastify = await createFastify(t, { addHooks: true, busboy: {} })
const form = new FormData()
form.append('foo', 'bar')
form.append('file', fs.createReadStream(filePath))
form.append('file', fs.createReadStream(filePath))
const response = await request(`http://localhost:${(fastify.server.address() as AddressInfo).port}`, form)
t.equal(response.status, 200)
const json = await response.json()
t.equal(json.body.foo, 'bar')
t.equal(Array.isArray(json.body.file), true)
t.ok(json.files.file)
t.equal(json.files.file[0].filename, 'package.json')
t.equal(json.files.file[1].filename, 'package.json')
})
t.test('non-multipart', async function (t) {
t.plan(3)
const fastify = await createFastify(t, { addHooks: true, removeFilesFromBody: true })
const response = await requestJSON(`http://localhost:${(fastify.server.address() as AddressInfo).port}`, {
foo: 'bar'
} as any)
t.equal(response.status, 200)
const json = await response.json()
t.equal(json.body.foo, 'bar')
t.equal(json.files, null)
})
})
|
/* eslint-disable react/prop-types */
import "./CurrentWeather.css";
const CurrentWeather = ({ data, unit }) => {
if (!data) {
return <p>No Data Available</p>;
}
if (data?.message) {
return (
<>
<p className="errorMessage">{data?.message}</p>
</>
);
}
const windDirection = getWindDirection(data?.wind?.deg);
return (
<div className="currentWeather">
<div className="container">
<div className="left">
<div className="temp">
<h1>
{Math.ceil(data?.main?.temp)}{" "}
<span> {unit === "metric" ? "° C" : "° F"}</span>
</h1>
<img
src={`http://openweathermap.org/img/w/${data?.weather?.[0]?.icon}.png`}
alt=""
/>
</div>
<h1 className="place">{data?.name}</h1>
<div className="time">
<p>
L : {Math.ceil(data?.main?.temp_min)}° H :{" "}
{Math.ceil(data?.main?.temp_max)}°
</p>
</div>
</div>
<div className="right">
<table>
<tbody>
<tr>
<td>Humidity</td>
<td>{data?.main?.humidity}%</td>
<td></td>
</tr>
<tr>
<td>Wind</td>
<td>
{`${windDirection} ${data?.wind?.speed}`}
<span id="speed"> {unit === "metric" ? "m/s" : "mph"}</span>
</td>
</tr>
<tr>
<td colSpan="2">{data?.weather?.[0]?.description}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
);
};
export default CurrentWeather;
const getWindDirection = (degrees) => {
const directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
const index = Math.round((degrees % 360) / 45);
return directions[index % 8];
};
|
import { useState, useEffect } from 'react';
/**
* Create a new React state and subscribed to localStorage updates
*
* @param {string} itemKey
* @param {string} initialValue
* @returns {[string, React.Dispatch<React.SetStateAction<string>>]}
*/
export const useLocalStoredState = (itemKey, initialValue = '') => {
const [value, setValue] = useState(localStorage.getItem(itemKey) || initialValue);
useEffect(() => {
localStorage.setItem(itemKey, value);
}, [value]);
return [value, setValue];
};
|
from collections import deque
class PathFinding:
"""Class creating instances of pathfinding behaviors Essentially how the enemy tracks player."""
def __init__(self, game):
"""Initialises attributes used in pathfinding methods."""
self.game = game
self.map = game.map.mini_map
self.ways = [-1, 0], [0, -1], [1, 0], [0, 1], [-1, -1], [1, -1], [1, 1], [-1, 1]
self.graph = {}
self.get_graph()
def get_path(self, start, goal):
"""Provides path from enemy to player."""
self.visited = self.bfs(start, goal, self.graph)
path = [goal]
step = self.visited.get(goal, start)
while step and step != start:
path.append(step)
step = self.visited[step]
return path[-1]
def bfs(self, start, goal, graph):
"""Classic algorithm for calculating all possible moves."""
queue = deque([start])
visited = {start: None}
while queue:
cur_node = queue.popleft()
if cur_node == goal:
break
next_nodes = graph[cur_node]
for next_node in next_nodes:
# Checks adjacent tile for enemy object to not clip enemies into 1 image.
if next_node not in visited and next_node not in self.game.object_handler.npc_positions:
queue.append(next_node)
visited[next_node] = cur_node
return visited
def get_next_nodes(self, x, y):
"""Returns values of next_node."""
return [(x + dx, y + dy) for dx, dy in self.ways if (x + dx, y + dy) not in self.game.map.world_map]
def get_graph(self):
"""Creates a graph of adjacent tiles."""
for y, row in enumerate(self.map):
for x, col in enumerate(row):
if not col:
self.graph[(x, y)] = self.graph.get((x, y), []) + self.get_next_nodes(x, y)
|
import { useEffect, useState } from "react";
import Avatar from "@mui/material/Avatar";
import Button from "@mui/material/Button";
import CssBaseline from "@mui/material/CssBaseline";
import TextField from "@mui/material/TextField";
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Container from "@mui/material/Container";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import NavBar from "../components/NavBar";
import { Link, useNavigate } from "react-router-dom";
import LockOpenIcon from "@mui/icons-material/LockOpen";
import { GoogleLogin } from "@react-oauth/google";
import jwtDecode from "jwt-decode";
const theme = createTheme();
interface TokenGoogle {
family_name: string;
given_name: string;
email: string;
}
export default function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [tokenGoogle, setTokenGoogle] = useState<string | undefined>("");
const [familyName, setFamilyName] = useState<string>("");
const [firstName, setFirstName] = useState<string>("");
const [googleEmail, setGoogleEmail] = useState<string>("");
const navigate = useNavigate();
const checkGoogleAccount = async () => {
const res = await fetch("http://localhost:8080/user/google_account", {
method: "POST",
body: JSON.stringify({
email: googleEmail,
firstname: firstName,
lastname: familyName,
}),
headers: {
"Content-Type": "application/json",
charset: "utf-8",
Authorization: `${tokenGoogle}`,
},
});
await res.json();
if (res.status === 200) {
onLogWithGoogleAccount(googleEmail, tokenGoogle);
}
else if(res.status === 201){
setTimeout(() => {
onLogWithGoogleAccount(googleEmail,tokenGoogle);
},2000)
}
};
useEffect(() => {
if (
familyName !== undefined &&
firstName !== undefined &&
googleEmail !== undefined &&
familyName !== "" &&
firstName !== "" &&
googleEmail !== "" &&
tokenGoogle !== undefined &&
tokenGoogle !== ""
) {
checkGoogleAccount();
}
});
const onChangeMail = (e: React.ChangeEvent<HTMLInputElement>) => {
setEmail(e.target.value);
};
const onChangePassword = (e: React.ChangeEvent<HTMLInputElement>) => {
setPassword(e.target.value);
};
const onLogWithGoogleAccount = async (email: string, password: string | undefined) => {
const res = await fetch("http://localhost:8080/authentification", {
method: "POST",
body: JSON.stringify({
email: email,
password: password,
}),
headers: {
"Content-Type": "application/json",
},
});
if (res.ok) {
const json = await res.json();
localStorage.setItem("tokenUser", json[0]);
localStorage.setItem("email", json[1]);
navigate("/");
}
};
const onLog = async () => {
const res = await fetch("http://localhost:8080/authentification", {
method: "POST",
body: JSON.stringify({
email: email,
password: password,
}),
headers: {
"Content-Type": "application/json",
},
});
if (res.ok) {
const json = await res.json();
console.log(json);
localStorage.setItem("tokenUser", json[0]);
localStorage.setItem("email", json[1]);
navigate("/");
}
};
return (
<>
<NavBar links={["Home", "Register"]} />
<ThemeProvider theme={theme}>
<Container component="main" maxWidth="xs">
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<Avatar sx={{ m: 1, bgcolor: "#ff5943" }}>
<LockOpenIcon />
</Avatar>
<Typography component="h1" variant="h5">
Login
</Typography>
<Box sx={{ mt: 3 }}>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
onChange={onChangeMail}
fullWidth
id="email"
label="Email"
name="email"
autoComplete="email"
/>
</Grid>
<Grid item xs={12}>
<TextField
onChange={onChangePassword}
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="new-password"
/>
</Grid>
<Grid item xs={12}></Grid>
</Grid>
<Button
onClick={onLog}
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Login
</Button>
<GoogleLogin
onSuccess={(credentialResponse) => {
setTokenGoogle(credentialResponse.credential);
setFamilyName(
jwtDecode<TokenGoogle>(
credentialResponse.credential as string
).family_name
);
setGoogleEmail(
jwtDecode<TokenGoogle>(
JSON.stringify(credentialResponse.credential)
).email
);
setFirstName(
jwtDecode<TokenGoogle>(
credentialResponse.credential as string
).given_name
);
}}
onError={() => {
console.log("Login Failed");
}}
/>
<Grid container justifyContent="flex-end">
<Grid item>
<Link style={{ textDecoration: "none" }} to={"/register"}>
You don't have an account? Sign up
</Link>
</Grid>
</Grid>
</Box>
</Box>
</Container>
</ThemeProvider>
</>
);
}
|
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
HttpCode,
HttpStatus,
} from '@nestjs/common';
import { ProductsService } from './products.service';
import {
CreateProductDto,
GetProductListDto,
ProductDto,
UpdateProductDto,
} from './dto';
import {
ApiTags,
ApiOperation,
ApiNoContentResponse,
ApiOkResponse,
ApiBadRequestResponse,
ApiNotFoundResponse,
} from '@nestjs/swagger';
@ApiTags('products')
@Controller('products')
export class ProductsController {
constructor(private readonly productsService: ProductsService) {}
@Post()
@ApiOperation({ summary: 'The product has been created' })
@ApiOkResponse({ type: ProductDto })
@ApiBadRequestResponse({ description: 'Validation errors' })
async create(
@Body() createProductDto: CreateProductDto,
): Promise<ProductDto> {
return this.productsService.create(createProductDto);
}
@Get()
@ApiOperation({ summary: 'Get a list of products' })
@ApiOkResponse({ type: GetProductListDto })
@ApiBadRequestResponse({ description: 'Validation errors' })
async findAll(): Promise<GetProductListDto[]> {
return this.productsService.findAll();
}
@Get(':id')
@ApiOperation({ summary: 'Get product details' })
@ApiOkResponse({ type: ProductDto })
@ApiNotFoundResponse({ description: 'Product was not found in database' })
@ApiBadRequestResponse({ description: 'Validation errors' })
async findOne(@Param('id') id: string): Promise<ProductDto> {
return this.productsService.findOne(id);
}
@Patch(':id')
@ApiOperation({ summary: 'Update a product' })
@ApiOkResponse({ type: ProductDto })
@ApiNotFoundResponse({ description: 'Product was not found in database' })
@ApiBadRequestResponse({ description: 'Validation errors' })
async update(
@Param('id') id: string,
@Body() updateProductDto: UpdateProductDto,
): Promise<ProductDto> {
return this.productsService.update(id, updateProductDto);
}
@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Delete a product' })
@ApiNoContentResponse({ description: 'Product was deleted' })
@ApiNotFoundResponse({ description: 'Product was not found in database' })
@ApiBadRequestResponse({ description: 'Validation errors' })
async remove(@Param('id') id: string): Promise<void> {
await this.productsService.remove(id);
}
}
|
import { RedirectParams } from './utils';
class Popup {
private window: Window | null;
private id: string;
constructor(public url: string, state: string) {
this.id = state;
}
public open(): void {
const windowFeatures = getWindowFeatures();
this.window = window.open(this.url, '_blank', windowFeatures);
}
public getWindowResponse(
modifier: (p: RedirectParams) => Promise<RedirectParams>
): Promise<RedirectParams> {
return new Promise((resolve, reject) => {
let safeClose = false;
const closedMonitor = setInterval(() => {
if (!safeClose && this.window?.closed) {
reject('popup closed by user');
}
}, 500);
const handler = async (event: MessageEvent) => {
if (!event?.data?.status) {
return;
}
const { status, error = null, params } = this.getParams(event.data);
safeClose = true;
clearInterval(closedMonitor);
this.clear(handler);
if (params.state && params.state !== this.id) {
return reject(`state mismatch`);
}
if (status === 'success' && !error) {
const modifiedParams = await modifier(params);
return resolve(modifiedParams);
} else {
return reject(`${error}: ${params.error_description}`);
}
};
window.addEventListener('message', handler, false);
});
}
private getParams(data: MessageEvent['data']) {
const {
status,
params,
}: { error: string | null; status: string; params: RedirectParams } = data;
return { status, error: params.error, params };
}
private clear(handler: (ev: MessageEvent) => void): void {
window.removeEventListener('message', handler);
this.window?.close();
}
}
const popupFeatures: { [key: string]: number } = {
titlebar: 0,
toolbar: 0,
status: 0,
menubar: 0,
resizable: 0,
height: 700,
width: 1200,
};
const getWindowFeatures = (): string => {
const f: string[] = [];
for (const feature in popupFeatures) {
f.push(`${feature}=${popupFeatures[feature]}`);
}
return f.join(',');
};
export default Popup;
|
package com.diandong.domain.po;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 菜品营养信息PO实体类
*
* @author YuLiu
* @date 2022-05-11
*/
@TableName("wis_dishes_nutrition")
@Data
@ApiModel("菜品营养信息PO实体类")
@Accessors(chain = true)
public class DishesNutritionPO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 编号
*/
@TableId(value = "id", type = IdType.AUTO)
@ApiModelProperty(value = "编号")
private Long id;
/**
* 食堂id
*/
@TableField(value = "canteen_id")
@ApiModelProperty(value = "食堂id")
private Long canteenId;
/**
* 菜品id
*/
@TableField(value = "dishes_id")
@ApiModelProperty(value = "菜品id")
private Long dishesId;
/**
* 菜品名称
*/
@TableField(value = "dishes_name")
@ApiModelProperty(value = "菜品名称")
private String dishesName;
/**
* 营养信息id
*/
@TableField(value = "nutrition_id")
@ApiModelProperty(value = "营养信息id")
private Long nutritionId;
/**
* 营养信息名称
*/
@TableField(value = "nutrition_name")
@ApiModelProperty(value = "营养信息名称")
private String nutritionName;
/**
* 数量
*/
@TableField(value = "number")
@ApiModelProperty(value = "数量")
private Double number;
/**
* 数据状态
*/
@TableField(value = "del_flag")
@ApiModelProperty(value = "数据状态")
private Integer delFlag;
/**
* 创建人id
*/
@TableField(value = "create_by", fill = FieldFill.INSERT)
@ApiModelProperty(value = "创建人id")
private Long createBy;
/**
* 创建日期 默认为当前时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
@ApiModelProperty(value = "创建日期 默认为当前时间")
private LocalDateTime createTime;
/**
* 更新者id
*/
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新者id")
private Long updateBy;
/**
* 更新人时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value = "更新人时间")
private LocalDateTime updateTime;
}
|
import mongoose from "mongoose";
import { User } from "../models/user.model";
import ApiError from "../utils/Apierror";
import { asynchandler } from "../utils/ascynchandler";
import APiresponse from "../utils/ApiResponse";
import { uploadOnCloudinary } from "../utils/cloudinary";
import { Video } from "../models/video.model";
const getallVideoes = asynchandler(async (req, res) => {
const { page = 1, limit = 10, query, sortyBy, sortType, userId } = req.query;
if (!userId) {
throw new ApiError(404, "user id is required");
}
const user = await User.findById(userId);
if (!user) {
throw new ApiError(404, "user not found");
}
// Aggregate pipeline to fetch videos owned by the user
const getvideoes = await User.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId(userId)
}
},
{
$lookup: {
from: "videos",
localField: "_id",
foreignField: "owner",
as: "videos"
}
}
]);
const videos = getvideoes.length > 0 ? getvideoes[0].videos : [];
const paginatedVideos = videos.slice((page - 1) * limit, page * limit);
return res.status(200).json(new APiresponse(200, paginatedVideos, "videoes fetched successfully"));
});
export const publishvideoes = asynchandler(async (req, res) => {
const { title, description } = req.body;
if (!(title && description)) {
throw new ApiError(400, "Title and description are required");
}
const videolocalPath = req.files?.video[0]?.path;
const thumbnailLocalpath = req.files?.thumbnail[0]?.path;
if (!(videolocalPath && thumbnailLocalpath)) {
throw new ApiError(400, "Video and thumbnail are required");
}
// Upload video and thumbnail to Cloudinary
const videoUpload = await uploadOnCloudinary(videolocalPath);
const thumbnailUpload = await uploadOnCloudinary(thumbnailLocalpath);
if (!(videoUpload && thumbnailUpload)) {
throw new ApiError(500, "Something happened while uploading to Cloudinary");
}
const videodata = await Video.create({
videoFile: videoUpload.url,
thumbnail: thumbnailUpload.url,
title: title,
description: description,
duration: videoUpload.duration,
views: 0,
isPublished: true,
owner: req?.user?._id
});
if (!videodata) {
throw new ApiError(500, "Something went wrong while creating video data");
}
return res.status(200).json(new APiresponse(200, videodata, "Video published"));
});
export const getvideoById = asynchandler(async (req, res) => {
const { videoId } = req.params
if (!videoId) {
throw new ApiError(400, "Video ID is required");
}
const video = await Video.findById(videoId);
if (!video) {
throw new ApiError(404, "Video not found");
}
res.status(200).json({
success: true,
data: video,
message: "Video found"
});
})
export const updateVideo = asynchandler(async (req, res) => {
const { videoId } = req.params
const { updatedtitle, updateddescription } = req.body;
// Check if videoId is provided
if (!videoId) {
throw new ApiError(400, "Video ID is required");
}
if (!req.files || !req.files.video || !req.files.thumbnail) {
throw new ApiError(400, "Updated video file and thumbnail are required");
}
const videoFile = req.files.video[0].path;
const thumbnail = req.files.thumbnail[0].path;
const updatedvideofile = await uploadOnCloudinary(videoFile)
const updatedthumbnail = await uploadOnCloudinary(thumbnail)
if (!(updateVideo && updatedthumbnail)) throw new ApiError(404, "something went wrong while uploading on cloudinary")
const updatedVideo = await Video.findByIdAndUpdate(
videoId,
{
$set: {
title: updatedtitle,
description: updateddescription,
videoFile: updatedvideofile.url,
thumbnail: updatedthumbnail.url
}
},
{ new: true }
);
if (!updatedVideo) {
throw new ApiError(404, "Video not found");
}
res.status(200).json({
success: true,
data: updatedVideo,
message: "Video updated successfully"
});
})
export const deletevideo = asynchandler(async (req, res) => {
const { videoId } = req.params;
if (!videoId) {
throw new ApiError(404, "Video ID is required");
}
const video = await Video.findById(videoId);
if (!video || video.owner.toString() !== req.user._id.toString()) {
throw new ApiError(404, "Video not found or you are not authorized to delete this video");
}
const deletedVideo = await Video.findByIdAndDelete(videoId);
if (!deletedVideo) {
throw new ApiError(404, "Something went wrong while deleting the video");
}
res.status(200).json(new APiresponse(200, deletedVideo, "Deleted successfully"));
});
export default getallVideoes;
|
import React from 'react';
import styled from "styled-components";
import SearchIcon from '@mui/icons-material/Search';
import Badge from "@mui/material/Badge";
import Avatar from '@mui/material/Avatar';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import {mobile} from "../responsive";
import {Link} from "react-router-dom";
import {useDispatch, useSelector} from "react-redux";
import {logout} from "../redux/userRedux";
const Container = styled.div`
height: 60px;
${mobile({height: "50px"})}
`
const Wrapper = styled.div`
padding: 10px 20px;
display: flex;
justify-content: space-between;
align-items: center;
${mobile({padding: "10px 0"})}
`
//Left Side --------------------------------------------------------------------------------------------------------------------------------------------------
const Left = styled.div`
flex: 1;
display: flex;
align-items: center;
`
const Langauge = styled.span`
font-size: 14px;
cursor: pointer;
${mobile({display: "none"})}
`
const SearchContainer = styled.div`
border: 0.5px solid lightgray;
display: flex;
align-items: center;
margin-left: 25px;
padding: 5px;
`
const Input = styled.input`
border: none;
${mobile({width: "50px"})}
`
//Center---------------------------------------------------------------------------------------------------------------
const Center = styled.div`
flex: 1;
text-align: center;
`
const Logo = styled.h1`
font-weight: bold;
${mobile({fontSize: "24px"})}
`
//Right Side------------------------------------------------------------------------------------------------------------
const Right = styled.div`
flex: 1;
display: flex;
justify-content: flex-end;
align-items: center;
${mobile({justifyContent: "center", flex: 2})}
`
const MenuItem = styled.div`
font-size: 14px;
cursor: pointer;
margin-left: 25px;
${mobile({fontSize: "12px", marginLeft: "10px"})}
`
const Navbar = () => {
const quantity = useSelector(state => state.cart.quantity);
const user = useSelector(state => state.user.currentUser);
const dispatch = useDispatch();
const logoutHandler =()=>{
console.log("logout");
dispatch(logout());
}
console.log(quantity);
return (
<Container>
<Wrapper>
<Left>
<Langauge>EN</Langauge>
<SearchContainer>
<Input placeholder={"Search"}></Input>
<SearchIcon style={{color: "gray", fontSize: "16px"}}></SearchIcon>
</SearchContainer>
</Left>
<Center>
<Link to={"/"}>
<Logo>Closet Essentials.</Logo>
</Link>
</Center>
<Right>
<MenuItem hidden={!user}>
<Avatar>{user && user.username.charAt(0)}</Avatar>
</MenuItem>
<Link to={"/register"}>
<MenuItem hidden={user}>REGISTER</MenuItem>
</Link>
<Link to={"/login"}>
<MenuItem hidden={user}>SIGN IN</MenuItem>
</Link>
<Link to={'/cart'}> <MenuItem>
<Badge badgeContent={quantity} color="primary">
<ShoppingCartIcon></ShoppingCartIcon>
</Badge>
</MenuItem>
</Link>
<MenuItem onClick={logoutHandler} hidden={!user}>
LOGOUT
</MenuItem>
</Right>
</Wrapper>
</Container>
);
};
export default Navbar;
|
import { expect, describe, it, beforeAll } from "vitest";
import { fakeAdminModel } from "../../_mocks/fake-admin.model";
import { AdminRepository } from "../admin.repository";
import { fakeAdmin } from "../../_mocks/fake-admin";
import { fakeUserModel } from "../../../user/_mocks/fake-user.model";
import { fakeUser } from "../../../user/_mocks/fake-user";
import { UserRepository } from "../../../user/repository/user.repository";
import { IAdminRepository } from "../admin.repository.interface";
let adminRepository: IAdminRepository;
const userRepository = new UserRepository(fakeUserModel);
describe("AdminRepository", () => {
beforeAll(() => {
adminRepository = new AdminRepository(fakeAdminModel, fakeUserModel);
});
describe("findAdminByEmail", () => {
it("Should return an admin when admin's email is found.", async () => {
try {
const admin = await adminRepository.findAdminByEmail(fakeAdmin.email);
expect(admin).toEqual(fakeAdmin);
} catch (error) {
console.error(error);
}
});
it("Should have called the findOne method from admin's model.", async () => {
try {
await adminRepository.findAdminByEmail(fakeAdmin.email);
expect(fakeAdminModel.findOne).toHaveBeenCalled();
} catch (error) {
console.error(error);
}
});
});
describe("sendJewelsToUser", () => {
it("Should send an jewels amount to an user.", async () => {
try {
const userId = fakeUser._id;
const amount = fakeUser.jewelsAmount;
await adminRepository.sendJewelsToUser(userId, amount);
const updatedUser: any = await userRepository.getUserById(userId);
expect(updatedUser.jewelsAmount).toBe(amount);
} catch (error) {
console.error(error);
}
});
it("Should have called the findById method from user's model.", async () => {
try {
await userRepository.getUserById(fakeUser._id);
expect(fakeUserModel.findById).toHaveBeenCalled();
} catch (error) {
console.error(error);
}
});
});
});
|
import "express-async-errors"
import express from "express"
import { handlerError } from "./error"
import userRouter from "./routes/user.routes"
import productRouter from "./routes/product.routes"
import cartRouter from "./routes/cart.routes"
import cors from "cors"
import helmet from "helmet"
import swaggerUi from "swagger-ui-express"
import { swaggerSpec } from "./utils/swaggerConfig"
const app = express()
app.use(helmet())
app.use(cors())
app.use(express.json())
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec))
app.use("/users", userRouter)
app.use("/products", productRouter)
app.use("/carts", cartRouter)
app.use(handlerError)
export default app
|
# Move photo files
Organize your jumbled photo files by date.
```
/Multimedia
/Camera\ Uploads ... source folder
...
/Photo/ ... destination
/2024-01/
...
```
The shooting date is obtained from EXIF.<br>
That's why I'm using the Pillow library.
## Table of Contents <!-- omit in toc -->
- [Move photo files](#move-photo-files)
- [Environment](#environment)
- [Create a container](#create-a-container)
- [Clone repository](#clone-repository)
- [Configuration Python](#configuration-python)
- [Use python3 in debian package](#use-python3-in-debian-package)
- [Use venv](#use-venv)
- [Test Run](#test-run)
- [File movement settings](#file-movement-settings)
- [Scheduling](#scheduling)
## Environment
- QTS 5.1.5.2679(2024-02-29) on TS-231K
- Container Station 3.0.6.833(2024/02/06)
- Docker version 20.10.27-qnap1, build 662936b
- debian:bookworm-slim (bookworm-20240311-slim, 12.5-slim, 12-slim)
## Create a container
Create a container using Container Station:
1. Creating a container
- image: `debian:bookworm-slim`
2. Container settings
- Advanced Settings
- \> Storage
- \> Add Volume (Bind path to mounted host)
- Host: /Multimedia
- Container: /mnt/Multimedia
- Mode: RW
- \> Environment variable
- TZ=Asia/Tokyo
3. Create container
- wait until running
## Clone repository
Enter the Docker container you just ran and start a console session:
```shell
docker exec -it <container-id> bash
```
First update apt. All commands after this are for root user:
```shell
apt update
```
And I don't have git.
```shell
apt install -y git
```
Once you have git installed, you can finally clone it.
```shell
mkdir -p /home/qnap
cd /home/qnap
git clone https://github.com/suzu-devworks/qnap-configurations.git
```
## Configuration Python
### Use python3 in debian package
All you need in python3 are the following three packages:
```shell
apt install -y python3 python3-pillow
```
Check the python path settings in `move_photo_files.sh`
```shell
python=/usr/bin/python3
```
> container size is 281MB.
### Use venv
All you need in python3 are the following three packages:
```shell
apt install -y python3 python3-venv python3-pip
# dependencies for pillow
apt install -y libjpeg62-turbo-dev
```
I used venv, but the packaged python might be faster.
```shell
python3 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
pip install pdm
```
Restore package.
```shell
pdm install
```
Check the python path settings in `move_photo_files.sh`
```shell
root_dir=$(cd $(dirname ${0})/../ && pwd)
python=${root_dir}/.venv/bin/python
```
> container size is 581MB.
## Test Run
I'll try running it anyway.
```shell
bin/move_photo_files.sh
```
The folder will be created (I'll do something about it eventually) but the files will not be moved and only a notification will be sent.
## File movement settings
File movement has been disabled in the python code, so enable it.
In `move_photo_files.py` and `move_other_image_files.py`
```py
def move_file(source: Path, dest: Path):
"""Moves source photo file to destination path.
Args
source: Source image file path
dest: Destination directory path
"""
dest.mkdir(mode=0o777, parents=True, exist_ok=True)
try:
# shutil.copy2(str(source), str(dest))
# shutil.move(str(source), str(dest)) # <- This one
logger.debug("move: {} -> {}".format(source, dest))
except shutil.Error as e:
logger.warning(repr(e))
```
## Scheduling
This configuration is done in docker host.
Even if you set it with `crontab -e`, it seems to disappear.
```shell
sudo vi /etc/config/crontab
```
For example, to start at 15:05 and 20:05 every day:
```crontab
5 15,20 * * * docker exec debian-1 sh -c "/home/qnap/qnap-configurations/bin/move_photo_files.sh > /dev/pts/0 2>&1" > /dev/null 2>&1
```
Redirects to the console device `/dev/pts/0` to output to the container log.
Restarting crond
```shell
sudo crontab /etc/config/crontab
sudo /etc/init.d/crond.sh restart
```
Check the settings
```shell
sudo crontab -l
```
|
describe Installer do
subject { described_class.new program: program, script_path: script_path }
let(:leeway) { RUBY_VERSION < '3.2.0' ? 0 : 3 }
let(:program) { 'completely-test' }
let(:script_path) { 'completions.bash' }
let(:targets) { subject.target_directories.map { |dir| "#{dir}/#{program}" } }
let(:install_command) do
%W[sudo cp #{subject.script_path} #{subject.target_path}]
end
let(:uninstall_command) do
%w[sudo rm -f] + targets
end
describe '#target_directories' do
it 'returns an array of potential completion directories' do
expect(subject.target_directories).to be_an Array
expect(subject.target_directories.size).to eq 3
end
end
describe '#target_path' do
it 'returns the first matching path' do
expect(subject.target_path)
.to eq '/usr/share/bash-completion/completions/completely-test'
end
end
describe '#install_command' do
it 'returns a copy command as an array' do
expect(subject.install_command)
.to eq %w[sudo cp completions.bash /usr/share/bash-completion/completions/completely-test]
end
context 'when the user is root' do
it 'returns the command without sudo' do
allow(subject).to receive(:root_user?).and_return true
expect(subject.install_command)
.to eq %w[cp completions.bash /usr/share/bash-completion/completions/completely-test]
end
end
end
describe '#install_command_string' do
it 'returns the install command as a string' do
expect(subject.install_command_string).to eq subject.install_command.join(' ')
end
end
describe '#uninstall_command' do
it 'returns an rm command as an array' do
expect(subject.uninstall_command).to eq %w[sudo rm -f] + targets
end
context 'when the user is root' do
it 'returns the command without sudo' do
allow(subject).to receive(:root_user?).and_return true
expect(subject.uninstall_command).to eq %w[rm -f] + targets
end
end
end
describe '#uninstall_command_string' do
it 'returns the uninstall command as a string' do
expect(subject.uninstall_command_string).to eq subject.uninstall_command.join(' ')
end
end
describe '#install' do
let(:existing_file) { 'spec/fixtures/existing-file.txt' }
let(:missing_file) { 'tmp/missing-file' }
before do
allow(subject).to receive(:script_path).and_return existing_file
allow(subject).to receive(:target_path).and_return missing_file
end
context 'when the completions_path cannot be found' do
it 'raises an error' do
allow(subject).to receive(:completions_path).and_return nil
expect { subject.install }.to raise_approval('installer/install-no-dir')
.diff(leeway)
end
end
context 'when the script cannot be found' do
it 'raises an error' do
allow(subject).to receive(:script_path).and_return missing_file
expect { subject.install }.to raise_approval('installer/install-no-script')
.diff(leeway)
end
end
context 'when the target exists' do
it 'raises an error' do
allow(subject).to receive(:target_path).and_return existing_file
expect { subject.install }.to raise_approval('installer/install-target-exists')
.diff(leeway)
end
end
context 'when the target exists but force=true' do
it 'proceeds to install' do
allow(subject).to receive(:target_path).and_return existing_file
expect(subject).to receive(:system).with(*install_command)
subject.install force: true
end
end
context 'when the target does not exist' do
it 'proceeds to install' do
allow(subject).to receive(:target_path).and_return missing_file
expect(subject).to receive(:system).with(*install_command)
subject.install
end
end
end
describe '#uninstall' do
it 'removes the completions script' do
expect(subject).to receive(:system).with(*uninstall_command)
subject.uninstall
end
end
end
|
import React, { useEffect } from 'react'
import { shallowEqual, useSelector } from 'react-redux';
import { useBlogCtx } from '../../features/context/providers/Blog/BlogProvider';
import Card from '../../components/Blog/Card';
import { Link } from 'react-router-dom';
export default function Blog() {
const { getBlogs } = useBlogCtx();
const { blogs } = useSelector((state) => ({
blogs: state.blogStore.blogs,
loading: state.blogStore.loading,
}), shallowEqual);
useEffect(() => {
getBlogs();
}, [])
return (
<div className='w-full flex flex-col justify-center items-center min-h-screen gap-4'>
<h1 className='text-2xl font-bold'>Blogs</h1>
{
blogs.length > 0 ?
<div className='grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-5 my-8'>
{
blogs.map(blog => <Card key={blog.id} id={blog.id} title={blog.title} body={blog.body} />)
}
</div> :
<p className='font-semibold text-center'>No blogs to show</p>
}
<div className='flex justify-center items-center space-x-2'>
<Link to='/add' className='bg-blue-600 px-5 py-1 font-semibold text-white'>
Add Blog
</Link>
<Link to='/favorites' className='bg-blue-600 px-5 py-1 font-semibold text-white'>
My Favorites
</Link>
</div>
</div>
)
}
|
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder
import streamlit as st
# Charger les données
data = pd.read_csv('Expresso_churn_dataset (1).csv')
# Exploration de base
st.write("Affichage des premières lignes du DataFrame :")
st.write(data.head())
st.write("Informations générales sur le DataFrame :")
st.write(data.info())
st.write("Description statistique du DataFrame :")
st.write(data.describe())
# Gérer les valeurs manquantes
data = data.dropna()
# Supprimer les doublons
data = data.drop_duplicates()
data = data.drop('MRG', axis=1)
data = data.drop('user_id', axis=1)
# Encodage des variables catégorielles
data_encoded = pd.get_dummies(data, columns=['REGION', 'TENURE', 'TOP_PACK'])
features = data_encoded.drop('CHURN', axis=1)
target = data_encoded['CHURN']
# Divisez les données en ensembles d'entraînement et de test
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
# Initialisez un modèle,
model = RandomForestClassifier()
# Entraînez le modèle
model.fit(X_train, y_train)
# Faites des prédictions sur l'ensemble de test
y_pred = model.predict(X_test)
# Évaluez les performances du modèle
accuracy = accuracy_score(y_test, y_pred)
st.write(f"Accuracy: {accuracy}")
# Fonction pour prédire une nouvelle observation
def predict(input_data):
input_data_encoded = pd.get_dummies(pd.DataFrame(input_data), columns=['REGION', 'TENURE', 'TOP_PACK'])
prediction = model.predict(input_data_encoded)[0]
return prediction
# Titre de l'application
st.title("Votre Application de Prédiction")
# Ajouter des champs de saisie pour les fonctionnalités
feature1 = st.slider("Feature 1", min_value=0, max_value=100)
feature2 = st.slider("Feature 2", min_value=0, max_value=100)
feature_cat = st.selectbox("Feature Catégorielle", options=["num1", "num2", "num3"])
# Bouton de validation
if st.button("Faire une prédiction"):
# Créer un dictionnaire avec les valeurs d'entrée
input_data = {'feature1': feature1, 'feature2': feature2, 'REGION_FATICK': 0, 'REGION_DAKAR': 0, 'REGION_LOUGA': 0, 'REGION_SAINT-LOUIS': 0, 'TENURE_D-12': 0, 'TENURE_D-6': 0, 'TENURE_D-7': 0, 'TENURE_D-8': 0, 'TENURE_D-9': 0, 'TENURE_D-11': 0, 'TENURE_D-10': 0, 'TENURE_D-5': 0, 'TENURE_D-4': 0, 'TENURE_D-3': 0, 'TENURE_D-2': 0, 'TENURE_D-1': 0, 'MRG_REGULAR': 0, 'MRG_YES': 0, 'MRG_SUSPENDED': 0, 'TOP_PACK_Data:2997': 0, 'TOP_PACK_ONNET_OTHER': 0, 'TOP_PACK_ON_NET': 0, 'TOP_PACK_OFF_NET': 0, 'TOP_PACK_Data:799': 0, 'TOP_PACK_Internet:490': 0, 'TOP_PACK_SUPERMAGIK_100F': 0, 'TOP_PACK_Jokko_Daily': 0, 'TOP_PACK_SUPERMAGIK_1000F': 0, 'TOP_PACK_Jokko_Weekly': 0, 'TOP_PACK_NEON_400F': 0, 'TOP_PACK_NEON_1000F': 0, 'TOP_PACK_SUPERMAGIK_5000F': 0, 'TOP_PACK_Jokko_Monthly': 0}
if feature_cat == "num1":
input_data['REGION_FATICK'] = 1
elif feature_cat == "num2":
input_data['REGION_DAKAR'] = 1
elif feature_cat == "num3":
input_data['REGION_LOUGA'] = 1
else:
input_data['REGION_SAINT-LOUIS'] = 1
# Faire une prédiction
prediction = predict(input_data)
# Afficher la prédiction
st.success(f"La prédiction est: {prediction}")
|
## DESCRIPTION
## Double Integral in Polar Coordinates
## ENDDESCRIPTION
## KEYWORDS('Multiple Integral', 'Polar Coordinates')
## Tagged by nhamblet
## DBsubject('Calculus')
## DBchapter('Multiple Integrals')
## DBsection('Double Integrals in Polar Coordinates')
## Date('6/2/2000')
## Author('Joseph Neisendorfer')
## Institution('University of Rochester')
## TitleText1('Calculus: Early Transcendentals')
## EditionText1('6')
## AuthorText1('Stewart')
## Section1('15.4')
## Problem1('')
DOCUMENT();
loadMacros(
"PG.pl",
"PGbasicmacros.pl",
"PGchoicemacros.pl",
"PGanswermacros.pl",
"PGauxiliaryFunctions.pl"
);
TEXT(beginproblem());
$showPartialCorrectAnswers = 1;
$a = random(1, 10);
$PI = arccos(-1);
$ans = $a ** 2 *(sqrt(3)/2 - $PI / 6);
BEGIN_TEXT
$PAR
Using polar coordinates, evaluate the integral which gives the area which lies
in the first quadrant below the line \(y=$a\) and between the circles
\( x^2 + y^2 = \{ 4*$a**2 \} \) and
\(x^2 - \{2*$a\}x + y^2 = 0 \).
$PAR
\{ ans_rule(50) \}
END_TEXT
ANS(num_cmp($ans));
ENDDOCUMENT();
|
// Copyright 2021 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import SwiftUI
public struct BraveButtonSize {
public var font: Font
public var padding: EdgeInsets
public init(font: Font, padding: EdgeInsets) {
self.font = font
self.padding = padding
}
public static let small: Self = .init(
font: Font.caption.weight(.semibold),
padding: .init(top: 6, leading: 12, bottom: 6, trailing: 12)
)
public static let normal: Self = .init(
font: Font.callout.weight(.semibold),
padding: .init(top: 8, leading: 14, bottom: 8, trailing: 14)
)
public static let large: Self = .init(
font: Font.body.weight(.semibold),
padding: .init(top: 10, leading: 20, bottom: 10, trailing: 20)
)
}
public struct BraveFilledButtonStyle: ButtonStyle {
@Environment(\.isEnabled) private var isEnabled
public var size: BraveButtonSize
public init(size: BraveButtonSize) {
self.size = size
}
public func makeBody(configuration: Configuration) -> some View {
configuration.label
.opacity(configuration.isPressed ? 0.7 : 1.0)
.font(size.font)
.foregroundColor(.white)
.padding(size.padding)
.background(
Group {
if isEnabled {
Color(.braveBlurpleTint).opacity(configuration.isPressed ? 0.7 : 1.0)
} else {
Color(.braveDisabled)
}
}
)
.clipShape(Capsule())
.contentShape(Capsule())
.animation(.linear(duration: 0.15), value: isEnabled)
}
}
public struct BraveOutlineButtonStyle: ButtonStyle {
@Environment(\.isEnabled) private var isEnabled
public var size: BraveButtonSize
public init(size: BraveButtonSize) {
self.size = size
}
public func makeBody(configuration: Configuration) -> some View {
configuration.label
.opacity(configuration.isPressed ? 0.7 : 1.0)
.font(size.font)
.foregroundColor(isEnabled ? Color(.braveLabel) : Color(.braveDisabled))
.padding(size.padding)
.background(
Group {
if isEnabled {
Color(.secondaryButtonTint).opacity(configuration.isPressed ? 0.7 : 1.0)
} else {
Color(.braveDisabled)
}
}
.clipShape(Capsule().inset(by: 0.5).stroke())
)
.clipShape(Capsule())
.contentShape(Capsule())
.animation(.linear(duration: 0.15), value: isEnabled)
}
}
#if DEBUG
struct BraveButtonStyle_Previews: PreviewProvider {
static let defaultSizes: [BraveButtonSize] = [
.small, .normal, .large,
]
static var previews: some View {
Group {
HStack {
ForEach([false, true], id: \.self) { disabled in
VStack {
ForEach(defaultSizes.indices) { index in
Button(action: {}) {
Text(verbatim: "Button text")
}
.buttonStyle(BraveFilledButtonStyle(size: defaultSizes[index]))
.disabled(disabled)
}
}
.padding()
}
}
HStack {
ForEach([false, true], id: \.self) { disabled in
VStack {
ForEach(defaultSizes.indices) { index in
Button(action: {}) {
Text(verbatim: "Button text")
}
.buttonStyle(BraveOutlineButtonStyle(size: defaultSizes[index]))
.disabled(disabled)
}
}
.padding()
}
}
}
.previewLayout(.sizeThatFits)
}
}
#endif
|
// for, while => ~동안: 반복문
// i라는 변수는 0부터 시작할거야
// i라는 변수가 10에 도달하기 전까지 계속할거야
// i라는 변수는 한 사이클이 돌고 나면 1을 더할거야
// for (let i = 0; i < 10; i++) {
// console.log(i);
// }
// 배열과 for문은 짝꿍이다.
// const arr = ["one", "two", "three", "four", "five"];
// for (let i = 0; i < arr.length; i++) {
// console.log(i);
// console.log(arr[i]);
// }
// for (let i = 0; i <= 10; i++) {
// if (i >= 2) {
// if (i % 2 === 0) {
// console.log(i + "는 2의 배수입니다!!");
// }
// }
// }
//for ~ in문
// 객체의 속성을 출력하는 문법
let person = {
name: "John",
age: 30,
gender: "male",
};
//person['key']
for (let key in person) {
console.log(key + ": " + person[key]);
}
|
# -*- coding: utf-8 -*-
"""
@Time : 2023/8/28
@Author : mashenquan
@File : openai.py
@Desc : mashenquan, 2023/8/28. Separate the `CostManager` class to support user-level cost accounting.
"""
import re
from typing import NamedTuple
from pydantic import BaseModel
from metagpt.logs import logger
from metagpt.utils.token_counter import FIREWORKS_GRADE_TOKEN_COSTS, TOKEN_COSTS
class Costs(NamedTuple):
total_prompt_tokens: int
total_completion_tokens: int
total_cost: float
total_budget: float
class CostManager(BaseModel):
"""Calculate the overhead of using the interface."""
total_prompt_tokens: int = 0
total_completion_tokens: int = 0
total_budget: float = 0
max_budget: float = 10.0
total_cost: float = 0
token_costs: dict[str, dict[str, float]] = TOKEN_COSTS # different model's token cost
def update_cost(self, prompt_tokens, completion_tokens, model):
"""
Update the total cost, prompt tokens, and completion tokens.
Args:
prompt_tokens (int): The number of tokens used in the prompt.
completion_tokens (int): The number of tokens used in the completion.
model (str): The model used for the API call.
"""
if prompt_tokens + completion_tokens == 0 or not model:
return
self.total_prompt_tokens += prompt_tokens
self.total_completion_tokens += completion_tokens
if model not in self.token_costs:
logger.warning(f"Model {model} not found in TOKEN_COSTS.")
return
cost = (
prompt_tokens * self.token_costs[model]["prompt"]
+ completion_tokens * self.token_costs[model]["completion"]
) / 1000
self.total_cost += cost
logger.info(
f"Total running cost: ${self.total_cost:.3f} | Max budget: ${self.max_budget:.3f} | "
f"Current cost: ${cost:.3f}, prompt_tokens: {prompt_tokens}, completion_tokens: {completion_tokens}"
)
def get_total_prompt_tokens(self):
"""
Get the total number of prompt tokens.
Returns:
int: The total number of prompt tokens.
"""
return self.total_prompt_tokens
def get_total_completion_tokens(self):
"""
Get the total number of completion tokens.
Returns:
int: The total number of completion tokens.
"""
return self.total_completion_tokens
def get_total_cost(self):
"""
Get the total cost of API calls.
Returns:
float: The total cost of API calls.
"""
return self.total_cost
def get_costs(self) -> Costs:
"""Get all costs"""
return Costs(self.total_prompt_tokens, self.total_completion_tokens, self.total_cost, self.total_budget)
class TokenCostManager(CostManager):
"""open llm model is self-host, it's free and without cost"""
def update_cost(self, prompt_tokens, completion_tokens, model):
"""
Update the total cost, prompt tokens, and completion tokens.
Args:
prompt_tokens (int): The number of tokens used in the prompt.
completion_tokens (int): The number of tokens used in the completion.
model (str): The model used for the API call.
"""
self.total_prompt_tokens += prompt_tokens
self.total_completion_tokens += completion_tokens
logger.info(f"prompt_tokens: {prompt_tokens}, completion_tokens: {completion_tokens}")
class FireworksCostManager(CostManager):
def model_grade_token_costs(self, model: str) -> dict[str, float]:
def _get_model_size(model: str) -> float:
size = re.findall(".*-([0-9.]+)b", model)
size = float(size[0]) if len(size) > 0 else -1
return size
if "mixtral-8x7b" in model:
token_costs = FIREWORKS_GRADE_TOKEN_COSTS["mixtral-8x7b"]
else:
model_size = _get_model_size(model)
if 0 < model_size <= 16:
token_costs = FIREWORKS_GRADE_TOKEN_COSTS["16"]
elif 16 < model_size <= 80:
token_costs = FIREWORKS_GRADE_TOKEN_COSTS["80"]
else:
token_costs = FIREWORKS_GRADE_TOKEN_COSTS["-1"]
return token_costs
def update_cost(self, prompt_tokens: int, completion_tokens: int, model: str):
"""
Refs to `https://app.fireworks.ai/pricing` **Developer pricing**
Update the total cost, prompt tokens, and completion tokens.
Args:
prompt_tokens (int): The number of tokens used in the prompt.
completion_tokens (int): The number of tokens used in the completion.
model (str): The model used for the API call.
"""
self.total_prompt_tokens += prompt_tokens
self.total_completion_tokens += completion_tokens
token_costs = self.model_grade_token_costs(model)
cost = (prompt_tokens * token_costs["prompt"] + completion_tokens * token_costs["completion"]) / 1000000
self.total_cost += cost
logger.info(
f"Total running cost: ${self.total_cost:.4f}"
f"Current cost: ${cost:.4f}, prompt_tokens: {prompt_tokens}, completion_tokens: {completion_tokens}"
)
|
import { Link, useParams } from 'react-router-dom'
import { FaArrowLeft } from 'react-icons/fa'
import axios from 'axios'
import { useEffect, useState, useCallback } from 'react'
import { FaYoutube } from 'react-icons/fa'
const url = `https://www.themealdb.com/api/json/v1/1/lookup.php?i=`
const SingleRecipe = () => {
const { recipeID } = useParams()
const [recipe, setRecipe] = useState({})
const [showMoreInfo, setShowMoreInfo] = useState(false)
const [error, setError] = useState('')
const getRecipe = async () => {
try {
const response = await axios(`${url}${recipeID}`)
const specificRecipe = response.data.meals[0]
if (specificRecipe) {
const {
strArea: area,
strCategory: category,
strMeal: name,
strMealThumb: image,
strInstructions: instructions,
strTags: tags,
strYoutube: youtube,
strIngredient1,
strIngredient2,
strIngredient3,
strIngredient4,
strIngredient5,
strIngredient6,
strIngredient7,
strMeasure1,
strMeasure2,
strMeasure3,
strMeasure4,
strMeasure5,
strMeasure6,
strMeasure7,
} = specificRecipe
const ingredients = [
{
ingredient: strIngredient1,
measure: strMeasure1,
},
{
ingredient: strIngredient2,
measure: strMeasure2,
},
{
ingredient: strIngredient3,
measure: strMeasure3,
},
{
ingredient: strIngredient4,
measure: strMeasure4,
},
{
ingredient: strIngredient5,
measure: strMeasure5,
},
{
ingredient: strIngredient6,
measure: strMeasure6,
},
{
ingredient: strIngredient7,
measure: strMeasure7,
},
]
const newRecipe = {
name,
area,
category,
image,
instructions,
tags,
youtube,
ingredients,
}
setRecipe(newRecipe)
} else {
setRecipe(null)
}
} catch (error) {
console.log(error.response)
setError(error.response)
}
}
useEffect(() => {
getRecipe()
}, [recipeID])
const {
name,
area,
category,
image,
instructions,
tags,
youtube,
ingredients,
} = recipe
if (error === undefined) {
return (
<section className='section-container no-recipe'>
<div className='section-center '>
<h3>no recipe to display</h3>
<Link to='/recipes' className='btn'>
back to recipe page
</Link>
</div>
</section>
)
}
return (
<section className='single-recipe'>
<div className='section-center single-recipe-center'>
<Link to='/recipes' className='back-forward'>
<FaArrowLeft />
back
</Link>
<article className='recipe-header'>
<div className='recipe-content'>
<img src={image} alt={name} className='img' />
<h5 className='name'>{name}</h5>
<p className='category'>
<span>{category}</span>
<span>{area}</span>
</p>
</div>
<div className='instructions'>
<h5>instructions</h5>
<p>
{instructions
? showMoreInfo
? instructions
: instructions.slice(0, 200)
: null}
<button onClick={() => setShowMoreInfo(!showMoreInfo)}>
{showMoreInfo ? 'show less' : 'show more'}
</button>
</p>
<Link to={youtube} className='prepare' target='_blank'>
To know the ingredients and how to prepare
<FaYoutube />
</Link>
<div className='tags'>
{tags &&
tags.split(',').map((tag, index) => {
return <span key={index}>{tag}</span> || null
})}
</div>
</div>
</article>
<article className='recipe-ingredients'>
<h5>ingredients</h5>
<div className='ingredients-container'>
{ingredients &&
ingredients.map((item, index) => {
const { ingredient, measure } = item
return (
item && (
<p key={index}>
<span>{ingredient}</span>
<span>{measure}</span>
</p>
)
)
})}
</div>
</article>
</div>
</section>
)
}
export default SingleRecipe
/* */
|
import { createSlice, PayloadAction, Middleware } from "@reduxjs/toolkit";
import type { RootState } from "@/store/store";
import { v4 as uuidv4 } from "uuid";
export interface ITasksState {
id?: string;
name: string;
description?: string;
active?: boolean;
createdAt?: string;
updatedAt?: string;
}
const initialState: ITasksState[] = JSON.parse(
localStorage.getItem("tasks") || "[]"
);
export const tasksSlice = createSlice({
name: "tasks",
initialState,
reducers: {
addTask: (
state,
action: PayloadAction<
Omit<ITasksState, "active" | "id" | "createdAt" | "updatedAt">
>
) => {
const now = new Date().toISOString();
state.push({
...action.payload,
id: uuidv4(),
active: false,
createdAt: now,
updatedAt: now,
});
},
editTask: (
state,
action: PayloadAction<
Omit<ITasksState, "active" | "createdAt" | "updatedAt">
>
) => {
state.forEach((task) => {
if (task.id === action.payload.id) {
task.name = action.payload.name;
task.description = action.payload.description;
task.updatedAt = new Date().toISOString();
}
});
},
activeTask: (state, action: PayloadAction<string>) => {
state.forEach((task) => {
if (task.id === action.payload) {
task.active = !task.active;
task.updatedAt = new Date().toISOString();
}
});
},
deleteTask: (state, action: PayloadAction<string>) => {
return state.filter((task) => task.id !== action.payload);
},
resetTasks: () => {
return [];
},
},
});
export const { addTask, resetTasks, deleteTask, activeTask, editTask } =
tasksSlice.actions;
export const selectTasks = (state: RootState) => state.tasks;
export const tasksMiddleware: Middleware =
({ getState }) =>
(next) =>
(action) => {
const result = next(action);
if (
addTask.match(action) ||
resetTasks.match(action) ||
activeTask.match(action) ||
editTask.match(action)
) {
localStorage.setItem("tasks", JSON.stringify(getState().tasks));
}
if (deleteTask.match(action)) {
localStorage.setItem(
"tasks",
JSON.stringify(
getState().tasks.filter(
(task: { id: string }) => task.id !== action.payload
)
)
);
}
return result;
};
export default tasksSlice.reducer;
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2017年12月23日
@author: Irony
@site: https://pyqt.site , https://github.com/PyQt5
@email: 892768447@qq.com
@file: ShowImage
@description:
"""
import sys
try:
from PyQt5.QtCore import QResource
from PyQt5.QtGui import QPixmap, QMovie
from PyQt5.QtWidgets import QWidget, QApplication, QHBoxLayout, QLabel
except ImportError:
from PySide2.QtCore import QResource
from PySide2.QtGui import QPixmap, QMovie
from PySide2.QtWidgets import QWidget, QApplication, QHBoxLayout, QLabel
from Lib.xpmres import image_head # @UnresolvedImport
class ImageView(QWidget):
def __init__(self, *args, **kwargs):
super(ImageView, self).__init__(*args, **kwargs)
self.resize(800, 600)
layout = QHBoxLayout(self)
# 从文件加载图片
layout.addWidget(QLabel(self, pixmap=QPixmap("Data/head.jpg")))
# QResource 参考 http://doc.qt.io/qt-5/resources.html
# 从资源文件中加载1 from py file
# 转换命令pyrcc5 res.qrc -o res_rc.py
# 这种方式是从通过pyrcc5转换res.qrc为res_rc.py文件,可以直接import加载
# 此时可以通过路径:/images/head.jpg来访问
layout.addWidget(QLabel(self, pixmap=QPixmap(":/images/head.jpg")))
# 从二进制资源文件res.rcc中加载
# 转换命令tools/rcc.exe -binary res2.qrc -o res.rcc
# 这里把资源前缀修改下(/myfile),见res2.qrc文件
# 此时需要注册
QResource.registerResource("Data/res.rcc")
# 注意前缀
layout.addWidget(
QLabel(self, pixmap=QPixmap(":/myfile/images/head.jpg")))
# 从xpm数组中加载
# 通过工具tools/Image2XPM.exe来转换
# 这里把转换的xpm数组直接放到py文件中当做一个变量
# 见xpmres.py中的image_head
layout.addWidget(QLabel(self, pixmap=QPixmap(image_head)))
# 加载gif图片
movie = QMovie("Data/loading.gif")
label = QLabel(self)
label.setMovie(movie)
layout.addWidget(label)
movie.start()
if __name__ == "__main__":
app = QApplication(sys.argv)
w = ImageView()
w.show()
sys.exit(app.exec_())
|
import React, { useEffect, useState } from 'react';
import { AppBar, Badge, Box, IconButton, Toolbar, Typography } from '@mui/material';
import { Link } from 'react-router-dom';
import ShopIcon from '@mui/icons-material/Shop';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import { useCookies } from 'react-cookie';
const Header = () => {
const [cookies, setCookies] = useCookies(['countProductsCart']);
const [productsOnCart, setProductsOnCart] = useState(0);
useEffect(() => {
if (cookies.countProductsCart) {
setProductsOnCart(cookies.countProductsCart);
}
}, [cookies]);
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="static" style={{ backgroundColor: 'black' }}>
<Toolbar variant="regular">
<Link style={{ textDecoration: 'none', color: 'inherit' }} to="/productList">
<IconButton edge="start" color="inherit" aria-label="menu" sx={{ mr: 2 }}>
<ShopIcon />
</IconButton>
</Link>
<Link style={{ textDecoration: 'none', color: 'inherit' }} to="/productList">
<Typography variant="h6" color="inherit" component="div">
Tienda
</Typography>
</Link>
<Box sx={{ flexGrow: 1 }} />
<Box sx={{ display: { xs: 'none', md: 'flex' } }}>
<Badge badgeContent={productsOnCart} color="primary">
<ShoppingCartIcon />
</Badge>
</Box>
</Toolbar>
</AppBar>
</Box>
);
};
export default Header;
|
import {
black,
grey,
lightBlue,
lightGrey,
primaryColour,
textColour,
textSubColour,
white,
} from 'src/styles/variables'
const theme = {
space: [],
colors: {
primary: `${primaryColour} !important`,
secondary: '',
lightGrey: `${lightGrey} !important`,
grey: `${grey} !important`,
white: `${white} !important`,
black: `${black} !important`,
lightBlue: `${lightBlue} !important`,
// text colour
text: {
primary: textColour,
secondary: textSubColour,
disabled: '',
hint: '',
},
},
// Breakpoints based on Material Design
// @see https://material-ui.com/customization/breakpoints/
breakpoints: {
xs: '0px', // 0 - 320px
sm: '321px', // 321px - 600px
md: '600px', // 600px - 960px
lg: '960px', // 960px - 1280px
xl: '1280px', // 1280px - 1920px
xxl: '1920px', // 1920px -
},
fontSizes: {
xs: '12px !important',
sm: '14px !important',
md: '16px !important',
lg: '20px !important',
xl: '24px !important',
h5: '12px !important',
h4: '18px !important',
h3: '20px !important',
h2: '24px !important',
h1: '30px !important',
},
fontWeights: {
body: 300,
heading: 500,
bold: 700,
},
lineHeights: {
body: 1.5,
heading: 1.5,
},
} as const
export type Theme = {
theme: typeof theme
}
export default theme
|
<mat-card-content>
<form [formGroup]="customerForm" [class.error]="!customerForm.valid && customerForm.touched">
<div fxLayout="row" fxLayoutAlign="center">
<mat-checkbox class="example-margin" [formControl]="selected" id="selected">Selected</mat-checkbox>
</div>
<ul class="items">
<li>
<p>Name: </p>
<div fxLayout="row" fxLayoutGap="15px" fxLayoutAlign="center">
<mat-form-field class="inputBackground">
<mat-label>First</mat-label>
<input matInput #firstName maxlength="10" class="inputField" type="text" id="first_name"
formControlName="firstName" [errorStateMatcher]="matcher" required>
<mat-hint align="end">{{ firstName.value?.length || 0 }}/10</mat-hint>
<mat-error>{{ errorMsg.required }}</mat-error>
</mat-form-field>
<mat-form-field class="inputBackground">
<mat-label>Last</mat-label>
<input matInput #lastName maxlength="10" class="inputField" type="text" id="last_name"
formControlName="lastName" [errorStateMatcher]="matcher" required>
<mat-hint align="end">{{ lastName.value?.length || 0 }}/10</mat-hint>
<mat-error>{{ errorMsg.required }}</mat-error>
</mat-form-field>
</div>
</li>
<br>
<li>
<p>Address: </p>
<div fxLayout="row" fxLayoutGap="15px" fxLayoutAlign="center">
<mat-form-field class="inputBackground">
<mat-label>Street</mat-label>
<input matInput #street maxlength="50" class="inputField" type="text" id="street" formControlName="street"
[errorStateMatcher]="matcher">
<mat-hint align="end">{{ street.value?.length || 0 }}/50</mat-hint>
</mat-form-field>
<mat-form-field class="inputBackground">
<mat-label>City/town</mat-label>
<input matInput #city maxlength="20" class="inputField" type="text" id="city" formControlName="city"
[errorStateMatcher]="matcher">
<mat-hint align="end">{{ city.value?.length || 0 }}/20</mat-hint>
</mat-form-field>
</div>
<br>
<div fxLayout="row" fxLayoutGap="15px" fxLayoutAlign="center">
<mat-form-field>
<mat-label>State</mat-label>
<mat-select type="text" id="state" formControlName="state">
<mat-option *ngFor="let state of states" [value]="state">{{ state }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="inputBackground">
<mat-label>ZIP code</mat-label>
<input matInput #zipCode maxlength="5" class="inputField" type="text" id="zip_code"
formControlName="zipCode" [errorStateMatcher]="matcher">
<mat-hint align="end">{{ zipCode.value?.length || 0 }}/5</mat-hint>
</mat-form-field>
</div>
</li>
<br>
<li>
<p>Expire In: </p>
<div fxLayout="row">
<mat-form-field class="inputBackground">
<mat-label>Milliseconds</mat-label>
<input matInput #expireIn class="inputField" type="number" id="expire_in" formControlName="expireIn"
[errorStateMatcher]="matcher">
</mat-form-field>
</div>
</li>
<br>
<li>
<div fxLayout="row">
<label>Storage: </label>
<mat-radio-group [formControl]="storage">
<mat-radio-button value="SESSION">Session</mat-radio-button>
<mat-radio-button value="LOCAL">Local</mat-radio-button>
</mat-radio-group>
</div>
</li>
<br>
</ul>
</form>
</mat-card-content>
|
#include <fluidsynth.h>
#include "m_pd.h"
static t_class *fluid_tilde_class;
typedef struct _fluid_tilde {
t_object x_obj;
fluid_synth_t *x_synth;
fluid_settings_t *x_settings;
t_outlet *x_out_left;
t_outlet *x_out_right;
} t_fluid_tilde;
t_int *fluid_tilde_perform(t_int *w)
{
t_fluid_tilde *x = (t_fluid_tilde *)(w[1]);
t_sample *left = (t_sample *)(w[2]);
t_sample *right = (t_sample *)(w[3]);
int n = (int)(w[4]);
//while (n--) *out++ = (*in1++)*(1-f_pan)+(*in2++)*f_pan;
fluid_synth_write_float(x->x_synth, n, left, 0, 1, right, 0, 1);
return (w+5);
}
static void fluid_tilde_dsp(t_fluid_tilde *x, t_signal **sp)
{
dsp_add(fluid_tilde_perform, 4, x,
sp[0]->s_vec, sp[1]->s_vec, sp[0]->s_n);
}
static void fluid_tilde_free(t_fluid_tilde *x)
{
outlet_free(x->x_out_left);
outlet_free(x->x_out_right);
}
static void fluid_help(void)
{
const char * helptext =
"_ __fluid~_ _ a soundfont external for Pd and Max/MSP \n"
"_ argument: \"/path/to/soundfont.sf\" to load on object creation\n"
"_ messages: \n"
"load /path/to/soundfont.sf2 --- Loads a Soundfont \n"
"note 0 0 0 --- Play note. Arguments: \n"
" channel-# note-# veloc-#\n"
"n 0 0 0 --- Play note, same as above\n"
"0 0 0 --- Play note, same as above\n"
"control 0 0 0 --- set controller\n"
"c 0 0 0 --- set controller, shortcut\n"
"prog 0 0 --- progam change, \n"
" args: channel-# prog-#\n"
"p 0 0 --- program change, shortcut\n"
;
post("%s", helptext);
}
static void fluid_note(t_fluid_tilde *x, t_symbol *s, int argc, t_atom *argv)
{
if (x->x_synth == NULL) return;
if (argc == 3)
{
int chan, key, vel;
chan = atom_getintarg(0, argc, argv);
key = atom_getintarg(1, argc, argv);
vel = atom_getintarg(2, argc, argv);
fluid_synth_noteon(x->x_synth, chan - 1, key, vel);
}
}
static void fluid_program_change(t_fluid_tilde *x, t_symbol *s, int argc,
t_atom *argv)
{
if (x->x_synth == NULL) return;
if (argc == 2)
{
int chan, prog;
chan = atom_getintarg(0, argc, argv);
prog = atom_getintarg(1, argc, argv);
fluid_synth_program_change(x->x_synth, chan - 1, prog);
}
}
static void fluid_control_change(t_fluid_tilde *x, t_symbol *s, int argc,
t_atom *argv)
{
if (x->x_synth == NULL) return;
if (argc == 3)
{
int chan, ctrl, val;
chan = atom_getintarg(0, argc, argv);
ctrl = atom_getintarg(1, argc, argv);
val = atom_getintarg(2, argc, argv);
fluid_synth_cc(x->x_synth, chan - 1, ctrl, val);
}
}
static void fluid_pitch_bend(t_fluid_tilde *x, t_symbol *s, int argc,
t_atom *argv)
{
if (x->x_synth == NULL) return;
if (argc == 2)
{
int chan, val;
chan = atom_getintarg(0, argc, argv);
val = atom_getintarg(1, argc, argv);
fluid_synth_pitch_bend(x->x_synth, chan - 1, val);
}
}
static void fluid_bank(t_fluid_tilde *x, t_symbol *s, int argc, t_atom *argv)
{
if (x->x_synth == NULL) return;
if (argc == 2)
{
int chan, bank;
chan = atom_getintarg(0, argc, argv);
bank = atom_getintarg(1, argc, argv);
fluid_synth_bank_select(x->x_synth, chan - 1, bank);
}
}
static void fluid_gen(t_fluid_tilde *x, t_symbol *s, int argc, t_atom *argv)
{
if (x->x_synth == NULL) return;
if (argc == 3)
{
int chan, param;
float value;
chan = atom_getintarg(0, argc, argv);
param = atom_getintarg(1, argc, argv);
value = atom_getintarg(2, argc, argv);
fluid_synth_set_gen(x->x_synth, chan - 1, param, value);
}
}
static void fluid_load(t_fluid_tilde *x, t_symbol *s, int argc, t_atom *argv)
{
if (x->x_synth == NULL)
{
post("No fluidsynth");
return;
}
if (argc >= 1 && argv->a_type == A_SYMBOL)
{
const char* filename = atom_getsymbolarg(0, argc, argv)->s_name;
if (fluid_synth_sfload(x->x_synth, filename, 0) >= 0)
{
post("Loaded Soundfont: %s", filename);
fluid_synth_program_reset(x->x_synth);
}
}
}
static void fluid_init(t_fluid_tilde *x, t_symbol *s, int argc, t_atom *argv)
{
if (x->x_synth) delete_fluid_synth(x->x_synth);
float sr = sys_getsr();
x->x_settings = new_fluid_settings();
if (x->x_settings == NULL)
{
post("fluid~: couldn't create synth settings\n");
}
else
{
// fluid_settings_setstr(settings, "audio.driver", "float");
// settings:
fluid_settings_setnum(x->x_settings, "synth.midi-channels", 16);
fluid_settings_setnum(x->x_settings, "synth.polyphony", 256);
fluid_settings_setnum(x->x_settings, "synth.gain", 0.600000);
fluid_settings_setnum(x->x_settings, "synth.sample-rate", 44100.000000);
fluid_settings_setstr(x->x_settings, "synth.chorus.active", "no");
fluid_settings_setstr(x->x_settings, "synth.reverb.active", "no");
fluid_settings_setstr(x->x_settings, "synth.ladspa.active", "no");
if (sr != 0)
{
fluid_settings_setnum(x->x_settings, "synth.sample-rate", sr);
}
// Create fluidsynth instance:
x->x_synth = new_fluid_synth(x->x_settings);
if (x->x_synth == NULL )
{
post("fluid~: couldn't create synth\n");
}
// try to load argument as soundfont
fluid_load(x, gensym("load"), argc, argv);
//if (settings != NULL )
// delete_fluid_settings(settings);
// We're done constructing:
if (x->x_synth)
post("-- fluid~ for Pd ---");
}
}
static void *fluid_tilde_new(t_symbol *s, int argc, t_atom *argv)
{
t_fluid_tilde *x = (t_fluid_tilde *)pd_new(fluid_tilde_class);
x->x_out_left = outlet_new(&x->x_obj, &s_signal);
x->x_out_right = outlet_new(&x->x_obj, &s_signal);
fluid_init(x, gensym("init"), argc, argv);
return (void *)x;
}
void fluid_tilde_setup(void)
{
fluid_tilde_class = class_new(gensym("fluid~"),
(t_newmethod)fluid_tilde_new, 0, sizeof(t_fluid_tilde),
CLASS_DEFAULT, A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_init, gensym("init"),
A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_load, gensym("load"),
A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_note, gensym("note"),
A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_program_change,
gensym("prog"), A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_control_change,
gensym("control"), A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_pitch_bend,
gensym("bend"), A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_bank, gensym("bank"),
A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_gen, gensym("gen"),
A_GIMME, 0);
// list input calls fluid_note(...)
class_addlist(fluid_tilde_class, (t_method)fluid_note);
// some alias shortcuts:
class_addmethod(fluid_tilde_class, (t_method)fluid_note, gensym("n"),
A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_program_change,
gensym("p"), A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_control_change,
gensym("c"), A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_control_change,
gensym("cc"), A_GIMME, 0);
class_addmethod(fluid_tilde_class, (t_method)fluid_pitch_bend, gensym("b"),
A_GIMME, 0);
// Simulate Flext's help message
class_addmethod(fluid_tilde_class, (t_method)fluid_help, gensym("help"),
0);
class_addmethod(fluid_tilde_class,
(t_method)fluid_tilde_dsp, gensym("dsp"), A_CANT, 0);
}
|
/*! HTML5 Boilerplate v7.3.0 | MIT License | https://html5boilerplate.com/ */
/* main.css 2.0.0 | MIT License | https://github.com/h5bp/main.css#readme */
/*
* What follows is the result of much research on cross-browser styling.
* Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
* Kroc Camen, and the H5BP dev community and team.
*/
Base styles: opinionated defaults
html {
color: #222;
font-size: 1em;
line-height: 1.4;
}
/*
* Remove text-shadow in selection highlight:
* https://twitter.com/miketaylr/status/12228805301
*
* Vendor-prefixed and regular ::selection selectors cannot be combined:
* https://stackoverflow.com/a/16982510/7133471
*
* Customize the background color to match your design.
*/
::-moz-selection {
background: #b3d4fc;
text-shadow: none;
}
::selection {
background: #b3d4fc;
text-shadow: none;
}
/*
* A better looking default horizontal rule
*/
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #ccc;
margin: 1em 0;
padding: 0;
}
/*
* Remove the gap between audio, canvas, iframes,
* images, videos and the bottom of their containers:
* https://github.com/h5bp/html5-boilerplate/issues/440
*/
audio,
canvas,
iframe,
img,
svg,
video {
vertical-align: middle;
}
/*
* Remove default fieldset styles.
*/
fieldset {
border: 0;
margin: 0;
padding: 0;
}
/*
* Allow only vertical resizing of textareas.
*/
textarea {
resize: vertical;
}
Browser Upgrade Prompt
.browserupgrade {
margin: 0.2em 0;
background: #ccc;
color: #000;
padding: 0.2em 0;
}
Author's custom styles
/*** BASE STYLES ***/
html {
font-size: 16px;
}
body {
font-size: 1em;
font-family: 'Merriweather', serif;
display: flex;
justify-content: center;
align-items: center;
margin: 0;
}
.container {
/*generic and mobile styles*/
max-width: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
}
img {
width: 100%;
}
p {
font-weight: 200;
}
a {
text-decoration: none;
}
/*** HEADER ***/
header {
background-color: #F3EBBA;
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
text-align: center;
width: 100%;
}
header h1 {
font-family: 'Lora', serif;
color: #102C00;
font-size: 2em;
}
header nav {
display: flex;
align-items: center;
justify-content: center;
padding: 20px 0;
width: 100%;
}
header nav ul {
margin: 0;
padding: 0;
}
header nav ul li {
font-family: 'Raleway', sans-serif;
font-weight: 400;
text-transform: uppercase;
list-style: none;
padding: 10px 0;
}
header nav ul li a {
color: #6D714C;
}
a:hover {
color: #102C00;
}
/*** HERO AREA ***/
.hero-area {
display: flex;
justify-content: center;
align-items: center;
background: url('../img/hero.png') center no-repeat;
background-size: cover;
width: 100%;
min-height: 500px;
}
.main-title {
color: snow;
font-family: 'Raleway', sans-serif;
font-size: 3.125em;
font-weight: 700;
line-height: 1.2em;
margin: 10px 20px;
}
/*** PORTFOLIO ***/
.portfolio-area {
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
text-align: center;
}
.portfolio-items {
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
}
.portfolio-area h3 {
color: #102C00;
font-family: 'Raleway', sans-serif;
font-size: 2em;
}
article {
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
margin: 30px 0;
}
.small-screens-heading {
font-family: 'Raleway', sans-serif;
font-size: 1.25em;
}
.big-screens-heading {
display: none;
}
.project-info h5 {
color: darkgreen;
font-family: 'Raleway', sans-serif;
font-size: 1em;
}
.project-description {
margin: 20px;
}
article a {
color: #000;
text-decoration: none;
}
figure {
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
}
/*** ABOUT ***/
.about-me {
background-color: #F3EBBA;
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
margin-top: 30px;
}
.about-me h3,
.contact-me h3 {
color: #102C00;
font-family: 'Raleway', sans-serif;
font-size: 1.625em;
text-align: center;
}
#about-info {
text-align: center;
margin: 30px 40px;
}
/*** CONTACT ***/
.contact-me {
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
}
#contact {
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
/*main axis = vertical - to dislay flex items underneath each other*/
}
#contact a {
color: black;
}
#contact a:hover {
background-color: #868542;
color: snow;
text-decoration: underline;
text-decoration-color: #868542;
}
#social {
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
}
/*** FOOTER ***/
footer {
background-color: #F3EBBA;
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
width: 100%;
}
footer p {
font-family: 'Lora', serif;
font-size: 0.875em;
}
/***Layout for tablets***/
@media only screen and (min-width: 768px) {
header nav ul {
display: flex;
justify-content: space-around;
align-items: center;
flex-flow: row wrap;
width: 80%;
}
.main-title {
margin: 30px 20px;
text-align: center;
}
.small-screens-heading {
font-size: 1.375em;
}
.project-description {
margin: 20px 30px;
}
.text {
padding: 0 20px;
}
#about {
display: flex;
justify-content: space-between;
align-items: center;
flex-flow: row wrap;
margin: 0;
}
#about figure {
width: 40%;
}
#about-info {
flex: 1 0 40%;
/*I have to take margins into account*/
margin: 15px 30px 15px 0;
}
#wrapper {
display: flex;
justify-content: center;
align-items: center;
flex-flow: row wrap;
}
#info {
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
}
.contact-me #bubble {
width: 40%;
}
footer p {
font-size: 1em;
}
}
@media only screen and (min-width: 1200px) {
header {
justify-content: space-between;
}
header h1 {
margin-left: 40px;
}
header nav {
align-items: flex-end;
width: 50%;
}
header nav ul li {
font-size: 1.125em;
}
.main-title {
font-size: 3.500em;
}
/***Portfolio ***/
.small-screens-heading {
/*hide the heading for small screens*/
display: none;
}
.project-image {
width: 49%;
}
.project-image a:hover {
border: 3px solid darkgreen;
}
.project-info {
display: flex;
align-content: flex-start;
/*align all the content (even the multi-line p) to the left*/
flex-flow: column wrap;
/*main axis = vertical*/
flex: 1 0 40%;
/*creates 2 columns*/
justify-content: center;
/*center along the main axis*/
margin-left: 20px;
}
.big-screens-heading {
/*for desktops and bigger screens*/
display: inline;
font-family: 'Raleway', sans-serif;
font-size: 1.625em;
margin: 20px 0;
}
.project-info h5 {
margin: 20px 0;
font-size: 1.125em;
}
.project-description {
width: 40%;
font-size: 1.125em;
line-height: 1.625em;
}
/*to deactivate certain mobile and tablet settings*/
.text {
padding: initial;
}
/*About*/
.about-me h3,
.contact-me h3 {
font-size: 2em;
}
#about figure {
width: 49%;
}
#about-info {
font-size: 1.25em;
line-height: 1.750em;
}
/*Contact*/
.contact-me {
width: 100%;
flex-flow: column wrap;
}
#wrapper {
width: 90%;
justify-content: space-evenly;
}
#contact p {
font-size: 1.125em;
}
.contact-me #bubble {
width: 49%;
}
#bubble img {
border-radius: 30%;
}
footer {
font-size: 1.125em;
}
}
Helper classes
/*
* Hide visually and from screen readers
*/
.hidden {
display: none !important;
}
/*
* Hide only visually, but have it available for screen readers:
* https://snook.ca/archives/html_and_css/hiding-content-for-accessibility
*
* 1. For long content, line feeds are not interpreted as spaces and small width
* causes content to wrap 1 word per line:
* https://medium.com/@jessebeach/beware-smushed-off-screen-accessible-text-5952a4c2cbfe
*/
.sr-only {
border: 0;
clip: rect(0, 0, 0, 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
white-space: nowrap;
width: 1px;
/* 1 */
}
/*
* Extends the .sr-only class to allow the element
* to be focusable when navigated to via the keyboard:
* https://www.drupal.org/node/897638
*/
.sr-only.focusable:active,
.sr-only.focusable:focus {
clip: auto;
height: auto;
margin: 0;
overflow: visible;
position: static;
white-space: inherit;
width: auto;
}
/*
* Hide visually and from screen readers, but maintain layout
*/
.invisible {
visibility: hidden;
}
/*
* Clearfix: contain floats
*
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* `contenteditable` attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that receive the `clearfix` class.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.clearfix:before,
.clearfix:after {
content: " ";
/* 1 */
display: table;
/* 2 */
}
.clearfix:after {
clear: both;
}
EXAMPLE Media Queries for Responsive Design.
These examples override the primary ('mobile first') styles.
Modify as content requires.
@media only screen and (min-width: 35em) {
/* Style adjustments for viewports that meet the condition */
}
@media print,
(-webkit-min-device-pixel-ratio: 1.25),
(min-resolution: 1.25dppx),
(min-resolution: 120dpi) {
/* Style adjustments for high resolution devices */
}
Print styles.
Inlined to avoid the additional HTTP request:
https://www.phpied.com/delay-loading-your-print-css/
@media print {
*,
*:before,
*:after {
background: transparent !important;
color: #000 !important;
/* Black prints faster */
box-shadow: none !important;
text-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " ("attr(href) ")";
}
abbr[title]:after {
content: " ("attr(title) ")";
}
/*
* Don't show links that are fragment identifiers,
* or use the `javascript:` pseudo protocol
*/
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre {
white-space: pre-wrap !important;
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
/*
* Printing Tables:
* https://web.archive.org/web/20180815150934/http://css-discuss.incutio.com/wiki/Printing_Tables
*/
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
}
|
import {Component, EventEmitter, Input, OnChanges, Output} from '@angular/core';
import {HelpOptionModel} from '../../../models/help-option-model';
import {HelpTypeEnum} from '../../../enums/help-type-enum';
@Component({
selector: 'app-help',
templateUrl: './help.component.html',
styleUrls: ['./help.component.scss'],
})
export class HelpComponent implements OnChanges {
protected readonly HelpTypeEnum = HelpTypeEnum;
@Input() public helpOptions: HelpOptionModel[];
@Output() public clueUsedEvent = new EventEmitter<number>();
protected isAudioPlaying: boolean = false;
public audioElement: HTMLAudioElement | null = null;
protected isImageShown: boolean = false;
protected imageUrl: string;
protected imageXColor: string;
public icons: string[] = ['fa-solid fa-question',
'fa-solid fa-question',
'fa-solid fa-folder-open'];
public ngOnChanges(): void {
for (let help of this.helpOptions) {
help.type = HelpTypeEnum[help.typeText];
}
this.stop();
}
public revealClue(index: number): void {
this.helpOptions[index].used = true;
this.saveUsedClue(index);
}
public play(file: string) :void {
let audio = new Audio();
audio.src = file;
audio.volume = 0.1;
audio.load();
audio.play().then(() => {
this.audioElement = audio;
});
audio.addEventListener('ended', () => {
this.audioElement = null;
});
}
public stop(): void {
if (this.audioElement) {
this.audioElement.pause();
this.audioElement = null;
this.isAudioPlaying = false;
}
}
public showImage(imgUrl: string, xColor: string): void {
this.imageUrl = imgUrl;
this.imageXColor = xColor;
this.isImageShown = true;
}
public closeImage(): void {
this.isImageShown = false;
}
private saveUsedClue(index: number): void {
this.clueUsedEvent.emit(index);
}
}
|
# SUMMARY
- [Welcome 欢迎](README.md)
## 技术
- [八股]()
- [Transformer 细节八股](/docs/nlp/models/transformers/Transformer中的细节.md)
- [T5 八股](/docs/nlp/models/transformers/t5/T5.md)
- [开源LLM八股](/docs/llm/开源LLM总结.md)
- [大模型优化八股](/docs/llm/大模型优化方法概览.md)
- [Neural Network 神经网络](/docs/nn)
- [Initialization 初始化](/docs/nn/initialization/initialization-summary.md)
- [Xavier Initialization](/docs/nn/initialization/Xavier-initialization.md)
- [He Initialization](/docs/nn/initialization/He-initialization.md)
- [BERT中的初始化](/docs/nn/initialization/BERT中的初始化.md)
- [Gradient 梯度](/docs/nn/gradient)
- [梯度消失与梯度爆炸](/docs/nn/gradient/梯度消失与梯度爆炸.md)
- [Optimizer 优化器](/docs/nn/optimizer)
- [Adam](/docs/nn/optimizer/adam.md)
- [Normalization](/docs/nn/normalization/norm-summary.md)
- [Batch Normalization](/docs/nn/normalization/Batch-Normalization.md)
- [Layer Normalization](/docs/nn/normalization/Layer-Normalization.md)
- [Batch Normalization 与 Layer Normalization 的差异](/docs/nn/normalization/Batch-Normalization-Layer-Normalization-Difference.md)
- [Loss 损失函数](/docs/nn/loss)
- [ZLPR Loss](/docs/nn/loss/zlpr.md)
- [Multi task 多任务学习](/docs/nn/multi-task)
- [MMoE 的问题和解决方法](/docs/nn/multi-task/mmoe的问题和解决方法.md)
- [Training Trick 训练技巧](/docs/nn/training)
- [Dataset 数据集准备技巧](/docs/nn/training/dataset)
- [缓解标注数据的噪声问题](/docs/nn/training/dataset/缓解标注数据的噪声问题.md)
- [Adversarial Training 对抗训练](/docs/nn/training/adversarial)
- [NLP 中的对抗训练](/docs/nn/training/adversarial/nlp-adversarial.md)
- [NLP 自然语言处理](/docs/nlp)
- [Models 模型结构](/docs/nlp/models)
- [Transformers](/docs/nlp/models/transformers)
- [Transformer中的细节](/docs/nlp/models/transformers/Transformer中的细节.md)
- [Transformer相关数值](/docs/nlp/models/transformers/Transformer相关数值.md)
- [BERT](/docs/nlp/models/transformers/bert)
- [MLM 任务](/docs/nlp/models/transformers/bert/mlm-task.md)
- [T5](/docs/nlp/models/transformers/t5/T5.md)
- [Position Encoding 位置编码](/docs/nlp/models/transformers/position-encoding)
- [RoPE](/docs/nlp/models/transformers/position-encoding/rope.md)
- [NER 实体识别](/docs/nlp/ner)
- [边界错分解决方案](/docs/nlp/ner/边界错分解决方案.md)
- [Text2Vec 文本向量表征](/docs/nlp/text2vec)
- [Contrastive Learning 对比学习](/docs/nlp/contrastive)
- [Loss 对比学习损失函数](/docs/nlp/contrastive/loss)
- [Triplet Loss](/docs/nlp/contrastive/loss/triplet-loss.md)
- [InfoNCE Loss](/docs/nlp/contrastive/loss/infonce.md)
- [Center Loss](/docs/nlp/contrastive/loss/center-loss.md)
- [ArcFace, CosFace, SphereFace](/docs/nlp/contrastive/loss/ArcFace-CosFace-and-SphereFace.md)
- [LLM 大语言模型](/docs/llm)
- [开源LLM总结](/docs/llm/开源LLM总结.md)
- [大模型优化方法概览](/docs/llm/大模型优化方法概览.md)
- [底层原理](/docs/llm/theory)
- [为什么LLM大多使用Decoder-only架构](/docs/llm/theory/为什么LLM大多使用Decoder-only架构.md)
- [LLM 每个训练阶段的作用](/docs/llm/theory/LLM每个训练阶段的作用.md)
- [开源大模型](/docs/llm/开源大模型/开源大模型对比.md)
- [ChatGLM](/docs/llm/开源大模型/chatglm)
- [GLM](/docs/llm/开源大模型/chatglm/glm.md)
- [ChatGLM](/docs/llm/开源大模型/chatglm/chatglm.md)
- [ChatGLM 推理过程](/docs/llm/开源大模型/chatglm/chatglm推理过程.md)
- [ChatGLM2](/docs/llm/开源大模型/chatglm/chatglm2.md)
- [ChatGLM2 优化内容](/docs/llm/开源大模型/chatglm/chatglm2-优化内容.md)
- [LLama](/docs/llm/开源大模型/llama)
- [LLaMA](/docs/llm/开源大模型/llama/llama.md)
- [LLaMA2 升级内容](/docs/llm/开源大模型/llama/llama2.md)
- [LLaMA2 源码解析](/docs/llm/开源大模型/llama/llama2-源码解析.md)
- [LLaMA2 预训练及SFT代码解析](/docs/llm/开源大模型/llama/llama2-预训练及SFT代码解析.md)
- [Baichuan](/docs/llm/开源大模型/baichuan)
- [Baichuan 技术方案](/docs/llm/开源大模型/baichuan/baichuan-技术方案.md)
- [Baichuan2 技术方案](/docs/llm/开源大模型/baichuan/baichuan2-技术方案.md)
- [Parallel 并行计算](/docs/llm/parallel)
- [数据并行](/docs/llm/parallel/data-parallel/数据并行.md)
- [Quantization 量化](/docs/llm/quantization)
- [浮点数的存储方式](/docs/llm/quantization/浮点数的存储方式.md)
- [混合精度训练](/docs/llm/quantization/混合精度训练.md)
- [INT8](/docs/llm/quantization/int8.md)
- [Training 训练](/docs/llm/training/tricks-summary.md)
- [7B-LLM 训练实验记录](/docs/llm/training/7B-LLM-训练实验记录.md)
- [Inference 推理](/docs/llm/inference)
- [Framework 推理框架](/docs/llm/inference/framework)
- [vLLM](/docs/llm/inference/framework/vllm/vllm.md)
- [VLLM 推理速度实验](/docs/llm/inference/framework/vllm/speed-experiment.md)
- [vLLM 的坑](/docs/llm/inference/framework/vllm/error-case.md)
- [Sampling 采样](/docs/llm/inference/sampling)
- [Min-p 采样](/docs/llm/inference/sampling/min-p.md)
- [Servering 服务](/docs/llm/servering)
- [OpenAI API](/docs/llm/servering/openai-api.md)
- [LoRA](/docs/llm/lora)
- [使用 PEFT 为大模型加载 LoRA 模型](/docs/llm/lora/使用PEFT为大模型加载LoRA模型.md)
- [ICL](/docs/llm/icl)
- [ICL 底层原理](/docs/llm/icl/theory)
- [样本 Label 到 Target 的信息流动](/docs/llm/icl/theory/样本Label到Target的信息流动.md)
- [RAG 检索增强生成](/docs/llm/rag/summary.md)
- [RAG 系统评估优化策略](/docs/llm/rag/evaluate-improve.md)
- [文本切分策略](/docs/llm/rag/split)
- [策略切分](/docs/llm/rag/split/策略切分.md)
- [检索召回](/docs/llm/rag/recall/summary.md)
- [关键词检索](/docs/llm/rag/recall/keyword.md)
- [答案生成](/docs/llm/rag/answering)
- [Chain-of-Note](/docs/llm/rag/answering/chain-of-note.md)
- [流程优化](/docs/llm/rag/flow)
- [Automix](/docs/llm/rag/flow/automix.md)
- [实验结果](/docs/llm/rag/experiment)
- [Recursive Splitter 的实验结果](/docs/llm/rag/experiment/RecursiveSplitter.md)
- [Framework 模型框架](/docs/framework)
- [Pytorch](/docs/framework/pytorch)
- [Tensor Operations](/docs/framework/pytorch/tensor-op/summary.md)
- [Basic 基础](/docs/framework/pytorch/tensor-op/basic)
- [获取 Tensor 形状](/docs/framework/pytorch/tensor-op/get-shape.md)
- [Shape mutating 形状变化](/docs/framework/pytorch/tensor-op/shape-mutating)
- [Tenosr View 机制](/docs/framework/pytorch/tensor-op/tensor-view.md)
- [expand 和 repeat](/docs/framework/pytorch/tensor-op/expand-repeat.md)
- [Operator 算子](/docs/framework/pytorch/operator)
- [一维卷积](/docs/framework/pytorch/operator/一维卷积.md)
- [Transformer相关算子](/docs/framework/pytorch/operator/transformer)
- [torch.nn.functional.scaled_dot_product_attention](/docs/framework/pytorch/operator/transformer/scaled_dot_product_attention.md)
- [Pytorch中的广播机制](/docs/framework/pytorch/Pytorch中的广播机制.md)
- [Huggingface](/docs/framework/huggingface)
- [下载huggingface中的模型](/docs/framework/huggingface/下载huggingface中的模型.md)
- [Huggingface datasets](/docs/framework/huggingface/datasets/datasets简介.md)
- [使用 Datasets 读取本地数据](/docs/framework/huggingface/datasets/读取本地数据.md)
- [使用 Datasets 读取本地数据](/docs/framework/huggingface/datasets/读取本地数据.md)
- [使用 Datasets 读取线上数据](/docs/framework/huggingface/datasets/读取线上数据.md)
- [流式读取](/docs/framework/huggingface/datasets/流式读取.md)
- [保存与读取](/docs/framework/huggingface/datasets/保存与读取.md)
- [对数据集进行重新布置](/docs/framework/huggingface/datasets/对数据集进行重新布置.md)
- [Datasets 底层原理](/docs/framework/huggingface/datasets/底层原理.md)
- [Stack 技术栈](/docs/stack)
- [Python](/docs/stack/python)
- [Fire](/docs/stack/python/fire/Python命令行工具库.md)
- [pipenv](/docs/stack/python/pipenv/什么是pipenv.md)
- [使用pipenv对项目运行环境进行管理](/docs/stack/python/pipenv/使用pipenv对项目运行环境进行管理.md)
- [Linux](/docs/stack/linux)
- [WSL2](/docs/stack/linux/wsl/wsl2环境配置.md)
- [tmux](/docs/stack/linux/tmux/tmux.md)
- [Ubuntu](/docs/stack/linux/ubuntu)
- [Ubuntu功能文件夹默认目录设置](/docs/stack/linux/ubuntu/Ubuntu功能文件夹默认目录设置.md)
- [Hive](/docs/stack/hive)
- [Hive语句执行逻辑](/docs/stack/hive/Hive语句执行逻辑.md)
- [随机采样](/docs/stack/hive/随机采样.md)
- [Gitbook](/docs/stack/gitbook)
- [Gitbook 中的配置项](/docs/stack/gitbook/gitbook中的配置项.md)
- [Solution 解决方案](/docs/solutions/summary.md)
- [QA System 问答系统](/docs/solutions/qa)
- [基于 LLM 解决专业领域问答 - 经验分享](/docs/solutions/qa/基于LLM解决专业领域问答.md)
- [ABSA 细粒度情感分析](/docs/solutions/absa/summary.md)
- [Problems 编程题](/docs/problems/算法题知识归类.md)
- [解法归类](/docs/problems/解法归类)
- [背包问题](/docs/problems/解法归类/背包问题.md)
- [二分总结](/docs/problems/解法归类/二分总结.md)
- [动态规划](/docs/problems/动态规划)
- [[10][困难][动态规划] 正则表达式匹配](/docs/problems/字符串/10-正则表达式匹配.md)
- [[279][中等][动态规划][BFS] 完全平方数](/docs/problems/动态规划/279-完全平方数.md)
- [[322][中等][动态规划][DFS] 零钱兑换](/docs/problems/动态规划/322-零钱兑换.md)
- [[343][中等][动态规划] 整数拆分](/docs/problems/动态规划/343-整数拆分.md)
- [[416][中等][动态规划] 分割等和子集](/docs/problems/动态规划/416-分割等和子集.md)
- [[474][中等][动态规划] 一和零](/docs/problems/动态规划/474-一和零.md)
- [[494][中等][动态规划] 目标和](/docs/problems/动态规划/494-目标和.md)
- [[518][中等][动态规划] 零钱兑换 II](/docs/problems/动态规划/518-零钱兑换-II.md)
- [[983][中等][动态规划] 最低票价](/docs/problems/动态规划/983-最低票价.md)
- [[1049][困难][动态规划] 最后一块石头的重量 II](/docs/problems/动态规划/1049-最后一块石头的重量-II.md)
- [[面试题 08.11][中等][动态规划] 硬币](/docs/problems/动态规划/08.11-硬币.md)
- [滑动窗口](/docs/problems/滑动窗口)
- [[3][中等][滑动窗口] 无重复字符的最长子串](/docs/problems/滑动窗口/3-无重复字符的最长子串.md)
- [[76][困难][滑动窗口] 最小覆盖子串](/docs/problems/滑动窗口/76-最小覆盖子串.md)
- [[239][困难][队列][辅助结构] 滑动窗口最大值](/docs/problems/队列/239-滑动窗口最大值.md)
- [[438][中等][滑动窗口] 找到字符串中所有字母异位词](/docs/problems/滑动窗口/438-找到字符串中所有字母异位词.md)
- [[567][中等][滑动窗口] 字符串的排列](/docs/problems/滑动窗口/567-字符串的排列.md)
- [字符串](/docs/problems/字符串)
- [[5][中等][动态规划] 最长回文子串](/docs/problems/字符串/5-最长回文子串.md)
- [[10][困难][动态规划] 正则表达式匹配](/docs/problems/字符串/10-正则表达式匹配.md)
- [[28][简单] 找出字符串中第一个匹配项的下标](/docs/problems/字符串/28-找出字符串中第一个匹配项的下标.md)
- [[44][困难][动态规划] 通配符匹配](/docs/problems/字符串/44-通配符匹配.md)
- [[72][困难][动态规划] 编辑距离](/docs/problems/字符串/72-编辑距离.md)
- [[115][困难][动态规划] 不同的子序列](/docs/problems/字符串/115-不同的子序列.md)
- [[214][困难] 最短回文串](/docs/problems/字符串/214-最短回文串.md)
- [[459][简单] 重复的子字符串](/docs/problems/字符串/459-重复的子字符串.md)
- [[712][中等][动态规划] 两个字符串的最小ASCII删除和](/docs/problems/字符串/712-两个字符串的最小ASCII删除和.md)
- [[796][简单] 旋转字符串](/docs/problems/字符串/796-旋转字符串.md)
- [[1143][中等][动态规划] 最长公共子序列](/docs/problems/字符串/1143-最长公共子序列.md)
- [[1316][困难] 不同的循环子字符串](/docs/problems/字符串/1316-不同的循环子字符串.md)
- [[1392][困难] 最长快乐前缀](/docs/problems/字符串/1392-最长快乐前缀.md)
- [堆](/docs/problems/堆/堆数据结构.md)
- [[264][中等][堆] 丑数 II](/docs/problems/堆/264-丑数-II.md)
- [[313][中等][堆] 超级丑数](/docs/problems/堆/313-超级丑数.md)
- [[1046][简单][堆] 最后一块石头的重量](/docs/problems/堆/1046-最后一块石头的重量.md)
- [栈](/docs/problems/栈)
- [[42][困难][栈][动态规划] 接雨水](/docs/problems/栈/42-接雨水.md)
- [[84][困难][栈] 柱状图中最大的矩形](/docs/problems/栈/84-柱状图中最大的矩形.md)
- [[155][简单][栈][滑动窗口] 最小栈](/docs/problems/栈/155-最小栈.md)
- [[232][简单][栈][队列] 用栈实现队列](/docs/problems/栈/232-用栈实现队列.md)
- [队列](/docs/problems/队列)
- [[225][简单][栈][队列] 用队列实现栈](/docs/problems/队列/225-用队列实现栈.md)
- [数组](/docs/problems/数组)
- [[1][简单][哈希] 两数之和](/docs/problems/数组/1-两数之和.md)
- [[4][困难][二分][双指针] 寻找两个正序数组的中位数](/docs/problems/数组/4-寻找两个正序数组的中位数.md)
- [[34][中等][二分] 在排序数组中查找元素的第一个和最后一个位置](/docs/problems/数组/34-在排序数组中查找元素的第一个和最后一个位置.md)
- [[35][简单][二分] 搜索插入位置](/docs/problems/数组/35-搜索插入位置.md)
- [[53][中等][动态规划] 最大子序和](/docs/problems/数组/53-最大子序和.md)
- [[153][中等][二分] 寻找旋转排序数组中的最小值](/docs/problems/数组/153-寻找旋转排序数组中的最小值.md)
- [[154][困难][二分] 寻找旋转排序数组中的最小值 II](/docs/problems/数组/154-寻找旋转排序数组中的最小值-II.md)
- [[167][简单][双指针][二分] 两数之和 II - 输入有序数组](/docs/problems/数组/167-两数之和-II-输入有序数组.md)
- [[215][中等][堆] 数组中的第K个最大元素](/docs/problems/数组/215-数组中的第K个最大元素.md)
- [[287][中等][双指针][二分] 寻找重复数](/docs/problems/数组/287-寻找重复数.md)
- [[300][中等][动态规划][贪心] 最长上升子序列](/docs/problems/数组/300-最长上升子序列.md)
- [[354][困难][动态规划][贪心] 俄罗斯套娃信封问题](/docs/problems/数组/354-俄罗斯套娃信封问题.md)
- [[378][中等][归并][二分] 有序矩阵中第K小的元素](/docs/problems/数组/378-有序矩阵中第K小的元素.md)
- [[435][中等][动态规划][贪心] 无重叠区间](/docs/problems/数组/435-无重叠区间.md)
- [[452][中等][动态规划][贪心] 用最少数量的箭引爆气球](/docs/problems/数组/452-用最少数量的箭引爆气球.md)
- [[456][中等][栈] 132模式](/docs/problems/数组/456-132模式.md)
- [[480][困难][堆] 滑动窗口中位数](/docs/problems/数组/480-滑动窗口中位数.md)
- [[491][中等][DFS] 递增子序列](/docs/problems/数组/491-递增子序列.md)
- [[646][中等][动态规划][贪心] 最长数对链](/docs/problems/数组/646-最长数对链.md)
- [[673][中等][动态规划][贪心] 最长递增子序列的个数](/docs/problems/数组/673-最长递增子序列的个数.md)
- [[674][简单][动态规划] 最长连续递增序列](/docs/problems/数组/674-最长连续递增序列.md)
- [[704][中等][二分] 二分查找](/docs/problems/数组/704-二分查找.md)
- [[718][中等][动态规划][滑动窗口] 最长重复子数组](/docs/problems/数组/718-最长重复子数组.md)
- [[873][中等][动态规划] 最长的斐波那契子序列的长度](/docs/problems/数组/873-最长的斐波那契子序列的长度.md)
- [[1035][中等][动态规划] 不相交的线](/docs/problems/数组/1035-不相交的线.md)
- [树](/docs/problems/树)
- [[94][中等] 二叉树的中序遍历](/docs/problems/树/94-二叉树的中序遍历.md)
- [[102][中等] 二叉树的层序遍历](/docs/problems/树/102-二叉树的层序遍历.md)
- [[108][简单][DFS] 将有序数组转换为二叉搜索树](/docs/problems/树/108-将有序数组转换为二叉搜索树.md)
- [[109][中等][DFS][双指针] 有序链表转换二叉搜索树](/docs/problems/树/109-有序链表转换二叉搜索树.md)
- [[114][中等][DFS] 二叉树展开为链表](/docs/problems/树/114-二叉树展开为链表.md)
- [[144][中等] 二叉树的前序遍历](/docs/problems/树/144-二叉树的前序遍历.md)
- [[145][困难] 二叉树的后序遍历](/docs/problems/树/145-二叉树的后序遍历.md)
- [[173][中等] 二叉搜索树迭代器](/docs/problems/树/173-二叉搜索树迭代器.md)
- [[297][困难][BFS] 二叉树的序列化与反序列化](/docs/problems/树/297-二叉树的序列化与反序列化.md)
- [[面试题 04.06][中等][DFS] 后继者](/docs/problems/树/04.06-后继者.md)
- [[剑指Offer-33][中等][分治] 二叉搜索树的后序遍历序列](/docs/problems/树/剑指Offer-33-二叉搜索树的后序遍历序列.md)
- [[剑指Offer-36][中等] 二叉搜索树与双向链表](/docs/problems/树/剑指Offer-36-二叉搜索树与双向链表.md)
- [[剑指Offer-54][简单] 二叉搜索树的第k大节点](/docs/problems/树/剑指Offer-54-二叉搜索树的第k大节点.md)
- [链表](/docs/problems/链表)
- [[23][困难][堆] 合并K个排序链表](/docs/problems/链表/23-合并K个排序链表.md)
- [[142][中等][双指针] 环形链表 II](/docs/problems/链表/142-环形链表-II.md)
- [数学](/docs/problems/数学)
- [[223][中等] 矩形面积](/docs/problems/数学/223-矩形面积.md)
- [[939][中等][哈希] 最小面积矩形](/docs/problems/数学/939-最小面积矩形.md)
- [数据流](/docs/problems/数据流)
- [[295][困难][二分][堆] 数据流的中位数](/docs/problems/数据流/295-数据流的中位数.md)
|
import { CommandBytes, STX } from "./OpticonWrapper";
import { appendCRC2 } from "./crcCalculation";
import { parseBarcode } from "./parseBarcode";
export const getData = async (port: SerialPort) => {
const writer = port.writable.getWriter();
const message = appendCRC2([CommandBytes.UploadBarcodeData, STX, 0]);
await writer.write(new Uint8Array(message));
const reader = port.readable.getReader();
// the first 10 bytes are 06 02 and the 8 bytes for the serial number
// therefore we will just "eat" them
const prefix = [];
// the first byte in barcode line is the count of bytes read for this barcode
// [typeOfBarcode, ...data bytes..., 4 bytes for the timestamp]
// ireg code suggests, that is not always for, but that is for polling
let barcodeLength = 0;
let currentBarcode: number[] = [];
const barcodes: number[][] = []
while (true){
const { value } = await reader.read();
if (prefix.length !== 10){
prefix.push(value[0]);
continue;
}
if (barcodeLength === 0 && value[0] === 0){
//last char in the stream is 0 (before the crc), so if barcode length is 0 and
//read value is 0 then we are finished
if (currentBarcode.length){
//if barcode length was 0 and current barcode has value that means we read some data
barcodes.push(currentBarcode);
currentBarcode = [];
}
break;
}
if (barcodeLength === 0){
//before each barcode there is byte describing its length, we set it here
barcodeLength = value[0];
if (currentBarcode.length){
//if barcode length was 0 and current barcode has value that means we read some data
// so lets save it
barcodes.push(currentBarcode);
currentBarcode = [];
}
} else {
// just keep reading
currentBarcode.push(value[0]);
barcodeLength--;
}
}
writer.releaseLock();
reader.releaseLock();
return parseBarcode(barcodes);
}
export const pollData = async (port: SerialPort) => {
const writer = port.writable.getWriter();
const message = appendCRC2([CommandBytes.UploadBarcodeData, STX, 0]);
await writer.write(new Uint8Array(message));
const prefix = [];
let barcodeLength = 0;
let currentBarcode: number[] = [];
const barcodes: number[][] = []
while (true){
try {
const reader = port.readable.getReader();
const timer = setTimeout(() => {
reader.releaseLock();
}, 1000);
const { value } = await reader.read();
clearTimeout(timer);
reader.releaseLock();
if (prefix.length !== 10){
prefix.push(value[0]);
continue;
}
if (barcodeLength === 0){
//before each barcode there is byte describing its length, we set it here
barcodeLength = value[0];
if (currentBarcode.length){
//if barcode length was 0 and current barcode has value that means we read some data
// so lets save it
barcodes.push(currentBarcode);
currentBarcode = [];
break;
}
} else {
// just keep reading
currentBarcode.push(value[0]);
barcodeLength--;
}
} catch (e){
writer.releaseLock();
return [];
}
}
writer.releaseLock();
return parseBarcode(barcodes);
}
|
// Copyright (c) 2021-2023 ChilliBits. All rights reserved.
#pragma once
#include <utility>
#include <model/GenericType.h>
#include <symboltablebuilder/SymbolType.h>
#include <symboltablebuilder/TypeSpecifiers.h>
namespace spice::compiler {
// Forward declarations
class ASTNode;
struct CodeLoc;
class SymbolTableEntry;
struct Param {
SymbolType type;
bool isOptional = false;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Param, type, isOptional)
};
struct NamedParam {
std::string name;
SymbolType type;
bool isOptional = false;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(NamedParam, name, type, isOptional)
};
using ParamList = std::vector<Param>;
using NamedParamList = std::vector<NamedParam>;
class Function {
public:
// Constructors
Function(std::string name, SymbolTableEntry *entry, SymbolType thisType, SymbolType returnType, ParamList paramList,
std::vector<GenericType> templateTypes, ASTNode *declNode)
: name(std::move(name)), entry(entry), thisType(std::move(thisType)), returnType(std::move(returnType)),
paramList(std::move(paramList)), templateTypes(std::move(templateTypes)), declNode(declNode) {}
Function() = default;
// Public methods
[[nodiscard]] std::vector<SymbolType> getParamTypes() const;
[[nodiscard]] std::string getSignature(bool withThisType = true) const;
[[nodiscard]] static std::string getSignature(const std::string &name, const SymbolType &thisType, const SymbolType &returnType,
const ParamList ¶mList, const std::vector<SymbolType> &concreteTemplateTypes,
bool withThisType = true);
[[nodiscard]] static std::string getSymbolTableEntryName(const std::string &functionName, const CodeLoc &codeLoc);
[[nodiscard]] ALWAYS_INLINE bool isMethod() const { return !thisType.is(TY_DYN); }
[[nodiscard]] ALWAYS_INLINE bool isFunction() const { return !returnType.is(TY_DYN); }
[[nodiscard]] ALWAYS_INLINE bool isProcedure() const { return returnType.is(TY_DYN); }
[[nodiscard]] ALWAYS_INLINE bool isNormalFunction() const { return isFunction() && !isMethod(); }
[[nodiscard]] ALWAYS_INLINE bool isNormalProcedure() const { return isProcedure() && !isMethod(); }
[[nodiscard]] ALWAYS_INLINE bool isMethodFunction() const { return isFunction() && isMethod(); }
[[nodiscard]] ALWAYS_INLINE bool isMethodProcedure() const { return isProcedure() && isMethod(); }
[[nodiscard]] bool hasSubstantiatedParams() const;
[[nodiscard]] bool hasSubstantiatedGenerics() const;
[[nodiscard]] bool isFullySubstantiated() const;
[[nodiscard]] const CodeLoc &getDeclCodeLoc() const;
// Public members
std::string name;
SymbolType thisType = SymbolType(TY_DYN);
SymbolType returnType = SymbolType(TY_DYN);
ParamList paramList;
std::vector<GenericType> templateTypes;
std::unordered_map<std::string, SymbolType> typeMapping;
SymbolTableEntry *entry = nullptr;
ASTNode *declNode = nullptr;
Scope *bodyScope = nullptr;
bool mangleFunctionName = true;
std::string predefinedMangledName;
std::string mangleSuffix;
bool genericSubstantiation = false;
bool alreadyTypeChecked = false;
bool used = false;
bool implicitDefault = false;
// Json serializer/deserializer
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Function, name, thisType, returnType, paramList, templateTypes)
};
} // namespace spice::compiler
|
# TeamStatus LED Controller
## Overview
This Python script provides a practical solution for integrating Microsoft Teams' online status with an IO-Link Master (TURCK TBEN-S2-4IOL) to control an RGB LED (BANNER K50L2). The goal is to represent Microsoft Teams' user statuses through the color of the LED, creating a visual indicator of team members' availability.
## Dependencies
Ensure you have the necessary Python libraries installed using:
```bash
pip install pyModbusTCP
```
## Hardware Configuration
1. **IO-Link Master (TURCK TBEN-S2-4IOL):**
- IP Address: 192.168.47.153
- Port: 502
- Unit ID: 1
2. **Ultrasonic Sensor (TURCK RU40U-M18M-AP8X2-H1151):**
- Connected to Port 1 of the IO-Link Master.
3. **RGB LED (BANNER K50L2):**
- Connected to Port 4 of the IO-Link Master.
## Microsoft Teams Log File
Make sure to set the correct Teams log file path in the script:
```python
TEAMS_LOG = os.path.join(os.getenv("APPDATA"), "Microsoft\\Teams\\logs.txt")
```
## Usage
Run the script by executing the following command in your terminal:
```bash
python script_name.py
```
## Microsoft Teams Status Mapping
1. **Red LED:**
- Busy, DoNotDisturb, InAMeeting, Presenting, OnThePhone
2. **Yellow LED:**
- Away, BeRightBack
3. **Green LED:**
- Available
## Debugging
To enable debug mode, set the DEBUG variable to True:
```python
DEBUG = True
```
## Notes:
- Make sure that your are in windows, if you are using Linux or MacOs make sure that you have past the right path
- The script utilizes threading for concurrently monitoring Teams status and updating the IO-Link Master.
- Microsoft Teams' presence information is extracted from the log file located at the specified path.
- Ensure the Modbus TCP parameters match your IO-Link Master configuration.
The script continuously runs until manually terminated.
Feel free to customize the script according to your specific hardware setup and preferences. If you encounter any issues, refer to the script's print statements and adjust as needed.
|
import React, { useState } from "react";
import axios from '../../../utils/axios'
import { signUpPost } from "../../../utils/Constant";
import { useNavigate } from "react-router-dom";
import Swal from "sweetalert2";
export default function RegisterForm() {
const navigate = useNavigate();
const [inputs, setInputs] = useState({
name: "",
email: "",
phone: "",
password: "",
});
const handleChange = (e) => {
setInputs((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}));
};
const handleSubmit = (event) => {
event.preventDefault();
console.log(inputs);
// Validation checks
if (!inputs.name || !inputs.email || !inputs.phone || !inputs.password) {
// Display an error message for missing fields
Swal.fire({
position: "center",
icon: "error",
title: "Please fill in all fields",
showConfirmButton: false,
timer: 1500,
});
return;
}
if (!isValidEmail(inputs.email)) {
// Display an error message for invalid email format
Swal.fire({
position: "center",
icon: "error",
title: "Invalid email address",
showConfirmButton: false,
timer: 1500,
});
return;
}
if (!isValidPhone(inputs.phone)) {
// Display an error message for invalid phone number format
Swal.fire({
position: "center",
icon: "error",
title: "Invalid phone number",
showConfirmButton: false,
timer: 1500,
});
return;
}
// Proceed with form submission
console.log(inputs);
const data = {
name: inputs.name,
email: inputs.email,
phone: inputs.phone,
password: inputs.password,
};
axios
.post("/api/register", data)
.then((response) => {
console.log(response.status);
console.log(response.data);
if (response.status === 409) {
console.log("anybody here");
Swal.fire({
position: "center",
icon: "warning",
title: "Email Already has an Account",
showConfirmButton: false,
timer: 1500,
});
} else if (response.status === 200) {
Swal.fire({
position: "center",
icon: "warning",
title: "Success",
showConfirmButton: false,
timer: 1500,
});
navigate("/login");
} else {
Swal.fire({
position: "center",
icon: "warning",
title: "Already exists",
showConfirmButton: false,
timer: 1500,
});
}
})
.catch((err) => {
Swal.fire({
position: "center",
icon: "warning",
title: "Already Exists",
showConfirmButton: true,
timer: 1500,
});
});
};
// Helper function to validate email format
const isValidEmail = (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
// Helper function to validate phone number format
const isValidPhone = (phone) => {
const phoneRegex = /^\d{10}$/; // Assumes a 10-digit phone number format
return phoneRegex.test(phone);
};
return (
<>
<div className="flex min-h-full flex-1 flex-col justify-center px-6 py-12 lg:px-8">
<div className="sm:mx-auto sm:w-full sm:max-w-sm">
<h2 className="mt-10 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">
Sign in to your account
</h2>
</div>
<div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
<form className="space-y-6" onSubmit={handleSubmit}>
<div>
<label htmlFor="name" className="block text-sm font-medium leading-6 text-gray-900">
Full Name
</label>
<div className="mt-2">
<input
id="name"
name="name"
type="text"
autoComplete="name"
required
value={inputs.name}
onChange={handleChange}
className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
/>
</div>
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium leading-6 text-gray-900">
Email address
</label>
<div className="mt-2">
<input
id="email"
name="email"
type="email"
autoComplete="email"
required
value={inputs.email}
onChange={handleChange}
className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
/>
</div>
</div>
<div>
<label htmlFor="phone" className="block text-sm font-medium leading-6 text-gray-900">
Phone Number
</label>
<div className="mt-2">
<input
id="phone"
name="phone"
type="tel"
autoComplete="tel"
required
value={inputs.phone}
onChange={handleChange}
className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
/>
</div>
</div>
<div>
<div className="flex items-center justify-between">
<label htmlFor="password" className="block text-sm font-medium leading-6 text-gray-900">
Password
</label>
<div className="text-sm">
<a href="#" className="font-semibold text-indigo-600 hover:text-indigo-500">
Forgot password?
</a>
</div>
</div>
<div className="mt-2">
<input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
value={inputs.password}
onChange={handleChange}
className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
/>
</div>
</div>
<div>
<button
type="submit"
className="flex w-full justify-center rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Sign in
</button>
</div>
</form>
<p className="mt-10 text-center text-sm text-gray-500">
Not a member?{" "}
<a href="#" className="font-semibold leading-6 text-indigo-600 hover:text-indigo-500">
Start a 14-day free trial
</a>
</p>
</div>
</div>
</>
);
}
|
/*
This code defines a React component called "Dashboard". It imports various components related to
financial information and components for a stock company, such as Profile, BalanceSheet, Ratings,
Holders, PriceGraph, and IncomeStatement. It also imports the Navbar and Footer components.
*/
// React imports
import { useState } from 'react';
// Reusable component imports
import { Box, useMediaQuery } from "@mui/material";
import '@/index.css'; // Import custom CSS
// Dashboard components imports
import Profile from "./profile";
import BalanceSheet from "./balanceSheet";
import Ratings from "./ratings";
import Holders from "./holders";
import PriceGraph from "./priceGraph";
import IncomeStatement from "./incomeStatement";
// Navbar and Footer iport
import Footer from "@/scenes/footer"; // Import Footer component
import Navbar from "@/scenes/navbar"; // Import Navbar component
// Define grid template for large screens
const gridTemplateLargeScreens = `
"i i i i i i i i i i i i"
"a a a a e e e g g g g g"
"a a a a e e e g g g g g"
"a a a a e e e g g g g g"
"a a a a e e e h h h h h"
"a a a a e e e h h h h h"
"a a a a e e e h h h h h"
"b b b b f f f h h h h h"
"b b b b f f f h h h h h"
"b b b b f f f h h h h h"
"c c c c f f f h h h h h"
"c c c c f f f h h h h h"
"c c c c f f f h h h h h"
"z z z z z z z z z z z z"
`
// Define grid template for small screens
const gridTemplateSmallScreens = `
"i"
"a"
"a"
"a"
"a"
"a"
"b"
"b"
"b"
"c"
"c"
"c"
"e"
"e"
"e"
"e"
"f"
"f"
"f"
"f"
"g"
"g"
"h"
"h"
"h"
"h"
"h"
"h"
"z"
`
const Dashboard = () => {
// Media query for screen size responsiveness
const isAboveMediumScreens = useMediaQuery("(min-width: 1200px)");
// State and handler functions for search query and ticker symbol
const [searchQuery, setSearchQuery] = useState('TSLA');
const [ticker, setTicker] = useState('TSLA');
const handleSearchChange = (query : string) => {
setSearchQuery(query);
};
const handleTickerChange = () => {
setTicker(searchQuery);
};
return (
<>
<Box
className="custom-scrollbar"
width="100%"
height="100%"
display="grid"
gap="1rem"
sx={
isAboveMediumScreens
? {
gridTemplateColumns: "repeat(12, minmax(185px, 1fr))",
gridTemplateRows: "repeat(14, minmax(60px, 1fr))",
gridTemplateAreas: gridTemplateLargeScreens,
}
: {
gridAutoColumns: "1fr",
gridAutoRows: "100px",
gridTemplateAreas: gridTemplateSmallScreens,
}
}
>
<Navbar searchQuery={searchQuery} onSearchChange={handleSearchChange} onSearchTicker={handleTickerChange} selectedPage={"Dashboard"} />
<Profile ticker={ticker}></Profile>
<BalanceSheet ticker={ticker}></BalanceSheet>
<Ratings ticker={ticker}></Ratings>
<Holders ticker={ticker}></Holders>
<PriceGraph ticker={ticker}></PriceGraph>
<IncomeStatement ticker={ticker}></IncomeStatement>
<Footer />
</Box>
</>
);
};
export default Dashboard;
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jQuery EasyUI</title>
<link rel="stylesheet" type="text/css" href="../themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../themes/icon.css">
<script type="text/javascript" src="../jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="../jquery.easyui.min.js"></script>
<style>
.toolbar{
height:30px;
padding:5px;
}
</style>
<script>
function enable(){
$('a.easyui-linkbutton').linkbutton({disabled:false});
}
function disable(){
$('a.easyui-linkbutton').linkbutton({disabled:true});
}
</script>
</head>
<body>
<h1>LinkButton</h1>
<p>A LinkButton can be created using an existing <a/> element.</p>
<div style="padding:5px;border-top:1px solid #ccc;">
<a href="#" onclick="enable()">enable</a> |
<a href="#" onclick="disable()">disable</a> |
<a href="#" onclick="javascript:$('#add').linkbutton({disabled:true})">disable add button</a> |
<a href="#" onclick="javascript:$('#add').linkbutton({disabled:false})">enable add button</a> |
<a href="#" onclick="javascript:$('a.easyui-linkbutton').linkbutton({plain:true})">make to plain</a> |
<a href="#" onclick="javascript:$('a.easyui-linkbutton').linkbutton({plain:false})">restore</a>
</div>
<h3>立体按钮演示</h3>
<div class="toolbar">
<a id="add" href="#" class="easyui-linkbutton" icon="icon-add">增加</a>
<a href="#" class="easyui-linkbutton" icon="icon-remove">移除</a>
<a href="#" class="easyui-linkbutton" icon="icon-save">保存</a>
<a href="#" disabled="true" class="easyui-linkbutton" icon="icon-cut">剪切</a>
<a href="#" class="easyui-linkbutton" onclick="javascript:alert('ttt')">文本按键</a>
</div>
<div class="toolbar">
<a href="#" class="easyui-linkbutton" icon="icon-ok">确定</a>
<a href="#" class="easyui-linkbutton" icon="icon-no">不要</a>
<a href="#" class="easyui-linkbutton" icon="icon-cancel">取消</a>
<a href="#" class="easyui-linkbutton" icon="icon-reload">刷新</a>
<a href="#" class="easyui-linkbutton" icon="icon-search">查询</a>
</div>
<div class="toolbar">
<a href="#" class="easyui-linkbutton" icon="icon-print">打印</a>
<a href="#" class="easyui-linkbutton" icon="icon-help">帮助</a>
<a href="#" class="easyui-linkbutton" icon="icon-undo">不做</a>
<a href="#" class="easyui-linkbutton" icon="icon-redo">再做</a>
<a href="#" class="easyui-linkbutton" icon="icon-back">返回</a>
</div>
<h3>平面按钮演示</h3>
<div style="height:30px;padding:5px;background:#efefef;">
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-cancel">取消</a>
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-reload">刷新</a>
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-search">查询</a>
<a href="#" class="easyui-linkbutton" plain="true">文本按键</a>
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-print">打印</a>
</div>
<h3>DEMO1</h3>
<div style="padding:5px;background:#efefef;width:500px;">
<a href="#" class="easyui-linkbutton" icon="icon-cancel">Cancel</a>
<a href="#" class="easyui-linkbutton" icon="icon-reload">Refresh</a>
<a href="#" class="easyui-linkbutton" icon="icon-search">Query</a>
<a href="#" class="easyui-linkbutton">text button</a>
<a href="#" class="easyui-linkbutton" icon="icon-print">Print</a>
</div>
<h3>DEMO2</h3>
<div style="padding:5px;background:#efefef;width:500px;">
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-cancel">Cancel</a>
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-reload">Refresh</a>
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-search">Query</a>
<a href="#" class="easyui-linkbutton" plain="true">text button</a>
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-print">Print</a>
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-help"> </a>
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-save"></a>
<a href="#" class="easyui-linkbutton" plain="true" icon="icon-back"></a>
</div>
</body>
</html>
|
import { useMutation } from "@apollo/client";
import { Modal } from "antd";
import { useRouter } from "next/router";
import { ChangeEvent, useState } from "react";
// import { useRecoilState } from "recoil";
// import { isEditState } from "../../../../commons/libraries/store";
import {
IMutation,
IMutationCreateBoardCommentArgs,
IMutationUpdateBoardCommentArgs,
IUpdateBoardCommentInput,
} from "../../../../commons/types/generated/types";
import {
FETCH_BOARD_COMMENT,
UPDATE_BOARD_COMMENT,
} from "../list/CommentsList.queries";
import CommentsWriteUI from "./Comments.presenter";
import { CREATE_BOARD_COMMENT } from "./Comments.queries";
import { ICommentsWriteProps } from "./Comments.types";
export default function CommentsWrite(props: ICommentsWriteProps) {
const router = useRouter();
const [writer, setWriter] = useState("");
const [password, setPassword] = useState("");
const [contents, setContents] = useState("");
const [value, setValue] = useState(0);
const [updateBoardComment] = useMutation<
Pick<IMutation, "updateBoardComment">,
IMutationUpdateBoardCommentArgs
>(UPDATE_BOARD_COMMENT);
// const [inputs, setInputs] = useState({
// writer: "",
// password: "",
// });
const [createBoardComment] = useMutation<
Pick<IMutation, "createBoardComment">,
IMutationCreateBoardCommentArgs
>(CREATE_BOARD_COMMENT);
const onChangeStar = (value: number) => {
setValue(value);
};
const onChangeWriter = (event: ChangeEvent<HTMLInputElement>) => {
setWriter(event.target.value);
};
const onChangeComment = (event: ChangeEvent<HTMLTextAreaElement>) => {
setContents(event.target.value);
};
const onChangePassWord = (event: ChangeEvent<HTMLInputElement>) => {
setPassword(event.target.value);
};
// const onChangeInput = (event: ChangeEvent<HTMLInputElement>) => {
// setInputs({
// ...inputs,
// [event.target.id]: event.target.value,
// });
// };
const onClickCommentSubmit = async () => {
if (!writer && !contents && !password) {
Modal.warning({ content: "내용을 입력해주세요" });
return;
}
try {
await createBoardComment({
variables: {
boardId: String(router.query._id),
createBoardCommentInput: {
writer,
password,
contents,
rating: value,
},
},
refetchQueries: [
{
query: FETCH_BOARD_COMMENT,
variables: { boardId: router.query._id },
},
],
});
} catch (error) {
if (error instanceof Error) Modal.error({ content: error.message });
}
setWriter("");
setContents("");
setPassword("");
setValue(0);
};
const onClickEditFinish = async () => {
if (!contents && !value) {
Modal.info({ content: "변경사항이 없습니다" });
return;
}
if (!password) {
Modal.warning({ content: "비밀번호를 확인해주세요" });
return;
}
try {
const updateBoardCommentInput: IUpdateBoardCommentInput = {};
if (contents) updateBoardCommentInput.contents = contents;
if (value !== props.el?.rating) updateBoardCommentInput.rating = value;
if (typeof props.el?._id !== "string") return;
await updateBoardComment({
variables: {
boardCommentId: props.el?._id,
password,
updateBoardCommentInput,
},
refetchQueries: [
{
query: FETCH_BOARD_COMMENT,
variables: { boardId: router.query._id },
},
],
});
props.setIsEdit?.(false);
Modal.success({ content: "댓글이 성공적으로 수정되었습니다" });
} catch (error) {
if (error instanceof Error) Modal.error({ content: error.message });
}
};
return (
<CommentsWriteUI
isEdit={props.isEdit}
el={props.el}
onClickCommentSubmit={onClickCommentSubmit}
// onChangeInput={onChangeInput}
onChangeWriter={onChangeWriter}
onChangeComment={onChangeComment}
onChangePassWord={onChangePassWord}
onChangeStar={onChangeStar}
writer={writer}
password={password}
contents={contents}
value={value}
setValue={setValue}
onClickEditFinish={onClickEditFinish}
/>
);
}
|
from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import render, redirect, get_object_or_404
from .models import Women, Category, TagPost
menu = [
{"title": "О сайте", "url_name": "about"},
{"title": "Добавить статью", "url_name": "add_page"},
{"title": "Обратная связь", "url_name": "contact"},
{"title": "Войти", "url_name": "login"},
]
def index(request):
posts = Women.published.all().select_related('cat')
data = {'title': 'Главная страница', 'menu': menu, "posts": posts, 'cat_selected': 0}
return render(request, 'women/index.html', context=data)
def about(request):
data = {'title': 'О сайте', 'menu': menu}
return render(request, 'women/about.html', context=data)
def show_post(request, post_slug):
post = get_object_or_404(Women, slug=post_slug)
data = {
'title': post.title,
'menu': menu,
'post': post,
'cat_selected': 1
}
return render(request, 'women/post.html', context=data)
def show_tag_postlist(request, tag_slug):
tag = get_object_or_404(TagPost, slug=tag_slug)
posts = tag.tags.filter(is_published=Women.Status.PUBLISHED).select_related("cat")
data = {'title': f'Тег: {tag.tag}', 'menu': menu, "posts": posts, 'cat_selected': 0}
return render(request, 'women/index.html', context=data)
def add_page(request):
return HttpResponse('Добавление статьи')
def contact(request):
return HttpResponse('Обратная связь')
def login(request):
return HttpResponse('Авторизация')
def show_category(request, cat_slug):
category = get_object_or_404(Category, slug=cat_slug)
posts = Women.published.filter(cat_id=category.pk).select_related("cat")
data = {'title': f'Рубрика: {category.name}', 'menu': menu, "posts": posts, 'cat_selected': category.pk}
return render(request, 'women/index.html', context=data)
def page_not_found(request, exception):
return HttpResponseNotFound('<h1>Страница не найдена</h1>')
|
import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-loading-spinner',
templateUrl: './loading-spinner.component.html',
styleUrls: ['./loading-spinner.component.scss']
})
export class LoadingSpinnerComponent {
loaded = [0];
loading!: boolean;
constructor(private router: Router) {}
ngOnInit() {
this.loadLoadingAmounts();
if (this.loaded[0] == 0) {
this.loading = true;
} else {
this.loading = false;
}
if (this.loaded[0] == 0 && this.loading) {
this.showLoadingAnimation();
this.loadWebsite();
}
this.countLoading();
}
/**
* This function count the loading acts of the user and save the amount in the session storage (loading animation should showd just once)
*
*/
countLoading() {
this.loaded[0]++;
let loadingsAsText = JSON.stringify(this.loaded);
sessionStorage.setItem('loadingActs', loadingsAsText);
}
/**
* This function loads the amount of the loading acts from the session storage
*
*/
loadLoadingAmounts() {
let loadingsAsText = sessionStorage.getItem('loadingActs');
if (loadingsAsText) {
this.loaded = JSON.parse(loadingsAsText);
}
}
/**
* Load the website, show the loading animation. In case of loading default show the loading default site with a message for the user
*
*/
loadWebsite() {
fetch('https://joerg-schmalgemeier.com/')
.then((response) => {
if (response.ok) {
return response.text();
} else {
throw new Error('Fehler beim Laden der Website-Inhalte');
}
})
.then((data) => {
// loading successfully
setTimeout(() => {
this.hideLoadingAnimation(); // finished loading, hide loading animation
}, 2000);
})
.catch((error) => {
this.router.navigateByUrl('/loading-default'); //show loading-default site
});
}
/**
* Change the CSS properties for the body for the loading animation
*
*/
showLoadingAnimation() {
document.body.classList.add('loading-body');
}
/**
* Remove the CSS properties from the body and hide the loading animation
*
*/
hideLoadingAnimation() {
document.body.classList.remove('loading-body');
this.loading = false;
}
}
|
/* CTK - The GIMP Toolkit
* testprint.c: Print example
* Copyright (C) 2006, Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <math.h>
#include <pango/pangocairo.h>
#include <ctk/ctk.h>
#include "testprintfileoperation.h"
static void
request_page_setup (CtkPrintOperation *operation,
CtkPrintContext *context,
int page_nr,
CtkPageSetup *setup)
{
/* Make the second page landscape mode a5 */
if (page_nr == 1)
{
CtkPaperSize *a5_size = ctk_paper_size_new ("iso_a5");
ctk_page_setup_set_orientation (setup, CTK_PAGE_ORIENTATION_LANDSCAPE);
ctk_page_setup_set_paper_size (setup, a5_size);
ctk_paper_size_free (a5_size);
}
}
static void
draw_page (CtkPrintOperation *operation,
CtkPrintContext *context,
int page_nr)
{
cairo_t *cr;
PangoLayout *layout;
PangoFontDescription *desc;
cr = ctk_print_context_get_cairo_context (context);
/* Draw a red rectangle, as wide as the paper (inside the margins) */
cairo_set_source_rgb (cr, 1.0, 0, 0);
cairo_rectangle (cr, 0, 0, ctk_print_context_get_width (context), 50);
cairo_fill (cr);
/* Draw some lines */
cairo_move_to (cr, 20, 10);
cairo_line_to (cr, 40, 20);
cairo_arc (cr, 60, 60, 20, 0, G_PI);
cairo_line_to (cr, 80, 20);
cairo_set_source_rgb (cr, 0, 0, 0);
cairo_set_line_width (cr, 5);
cairo_set_line_cap (cr, CAIRO_LINE_CAP_ROUND);
cairo_set_line_join (cr, CAIRO_LINE_JOIN_ROUND);
cairo_stroke (cr);
/* Draw some text */
layout = ctk_print_context_create_pango_layout (context);
pango_layout_set_text (layout, "Hello World! Printing is easy", -1);
desc = pango_font_description_from_string ("sans 28");
pango_layout_set_font_description (layout, desc);
pango_font_description_free (desc);
cairo_move_to (cr, 30, 20);
pango_cairo_layout_path (cr, layout);
/* Font Outline */
cairo_set_source_rgb (cr, 0.93, 1.0, 0.47);
cairo_set_line_width (cr, 0.5);
cairo_stroke_preserve (cr);
/* Font Fill */
cairo_set_source_rgb (cr, 0, 0.0, 1.0);
cairo_fill (cr);
g_object_unref (layout);
}
int
main (int argc, char **argv)
{
CtkPrintOperation *print;
TestPrintFileOperation *print_file;
ctk_init (&argc, &argv);
/* Test some random drawing, with per-page paper settings */
print = ctk_print_operation_new ();
ctk_print_operation_set_n_pages (print, 2);
ctk_print_operation_set_unit (print, CTK_UNIT_MM);
ctk_print_operation_set_export_filename (print, "test.pdf");
g_signal_connect (print, "draw_page", G_CALLBACK (draw_page), NULL);
g_signal_connect (print, "request_page_setup", G_CALLBACK (request_page_setup), NULL);
ctk_print_operation_run (print, CTK_PRINT_OPERATION_ACTION_EXPORT, NULL, NULL);
/* Test subclassing of CtkPrintOperation */
print_file = test_print_file_operation_new ("testprint.c");
test_print_file_operation_set_font_size (print_file, 12.0);
ctk_print_operation_set_export_filename (CTK_PRINT_OPERATION (print_file), "test2.pdf");
ctk_print_operation_run (CTK_PRINT_OPERATION (print_file), CTK_PRINT_OPERATION_ACTION_EXPORT, NULL, NULL);
return 0;
}
|
import {
createUnionType,
Field,
ID,
ObjectType,
registerEnumType,
} from 'type-graphql';
import { Shruti } from '#lib/models/Shruti/gql';
import { Sthayi } from '#lib/models/Sthayi/gql';
import {
BlockType,
ContinueBlock as ContinueBlockModel,
NoteBlock as NoteBlockModel,
UndefinedBlock as UndefinedBlockModel,
} from './index';
registerEnumType(BlockType, {
name: 'BlockType',
description: 'BlockType',
});
@ObjectType({ description: 'Continues the previous note' })
export class ContinueBlock implements ContinueBlockModel {
@Field(type => ID)
key!: string;
@Field({ nullable: true })
lyrics?: string;
@Field(type => ID)
prev!: string;
@Field(type => ID)
next!: string;
@Field(type => BlockType)
type!: BlockType.Continue;
@Field(type => Sthayi, { nullable: true })
sthayi?: Sthayi;
@Field(type => Number)
style!: 1 | 2 | 3 | 4 | 6;
}
@ObjectType({ description: 'A note that produces a sound' })
export class NoteBlock implements NoteBlockModel {
@Field(type => ID)
key!: string;
@Field({ nullable: true })
lyrics?: string;
@Field(type => ID)
prev!: string;
@Field(type => ID)
next!: string;
@Field(type => BlockType)
type!: BlockType.Note;
@Field(type => Shruti, { nullable: true })
shruti!: Shruti;
@Field(type => Sthayi, { nullable: true })
sthayi!: Sthayi;
@Field(type => Number)
style!: 1 | 2 | 3 | 4 | 6;
}
@ObjectType({ description: 'A note that has not yet been defined' })
export class UndefinedBlock implements UndefinedBlockModel {
@Field(type => ID)
key!: string;
@Field({ nullable: true })
lyrics?: string;
@Field(type => ID)
prev!: string;
@Field(type => ID)
next!: string;
@Field(type => BlockType)
type!: BlockType.Undefined;
@Field(type => Shruti, { nullable: true })
shruti?: Shruti;
@Field(type => Sthayi, { nullable: true })
sthayi?: Sthayi;
@Field(type => Number)
style!: 1 | 2 | 3 | 4 | 6;
}
export const Block = createUnionType({
name: 'Block',
types: () => [ContinueBlock, NoteBlock, UndefinedBlock] as const,
resolveType: value => {
if (value.type === BlockType.Continue) {
return ContinueBlock;
} else if (value.type === BlockType.Note) {
return NoteBlock;
} else {
return UndefinedBlock;
}
},
});
|
#!/usr/bin/env python
import os
try:
from http import server # Python 3
except ImportError:
import SimpleHTTPServer as server # Python 2
# https://gist.github.com/shivakar/82ac5c9cb17c95500db1906600e5e1ea
class RangeHTTPRequestHandler(server.SimpleHTTPRequestHandler):
"""RangeHTTPRequestHandler is a SimpleHTTPRequestHandler
with HTTP 'Range' support"""
def send_head(self):
"""Common code for GET and HEAD commands.
Return value is either a file object or None
"""
path = self.translate_path(self.path)
ctype = self.guess_type(path)
# Handling file location
## If directory, let SimpleHTTPRequestHandler handle the request
if os.path.isdir(path):
return server.SimpleHTTPRequestHandler.send_head(self)
## Handle file not found
if not os.path.exists(path):
return self.send_error(404, self.responses.get(404)[0])
## Handle file request
f = open(path, 'rb')
fs = os.fstat(f.fileno())
size = fs[6]
# Parse range header
# Range headers look like 'bytes=500-1000'
start, end = 0, size-1
if 'Range' in self.headers:
start, end = self.headers.get('Range').strip().strip('bytes=').split('-')
if start == "":
## If no start, then the request is for last N bytes
## e.g. bytes=-500
try:
end = int(end)
except ValueError as e:
self.send_error(400, 'invalid range')
start = size-end
else:
try:
start = int(start)
except ValueError as e:
self.send_error(400, 'invalid range')
if start >= size:
# If requested start is greater than filesize
self.send_error(416, self.responses.get(416)[0])
if end == "":
## If only start is provided then serve till end
end = size-1
else:
try:
end = int(end)
except ValueError as e:
self.send_error(400, 'invalid range')
## Correct the values of start and end
start = max(start, 0)
end = min(end, size-1)
self.range = (start, end)
## Setup headers and response
l = end-start+1
if 'Range' in self.headers:
self.send_response(206)
else:
self.send_response(200)
self.send_header('Content-type', ctype)
self.send_header('Accept-Ranges', 'bytes')
self.send_header('Content-Range',
'bytes %s-%s/%s' % (start, end, size))
self.send_header('Content-Length', str(l))
self.send_header('Last-Modified', self.date_time_string(int(fs.st_mtime)))
self.end_headers()
return f
def copyfile(self, infile, outfile):
"""Copies data between two file objects
If the current request is a 'Range' request then only the requested
bytes are copied.
Otherwise, the entire file is copied using SimpleHTTPServer.copyfile
"""
if not 'Range' in self.headers:
server.SimpleHTTPRequestHandler.copyfile(self, infile, outfile)
return
start, end = self.range
infile.seek(start)
bufsize=64*1024 ## 64KB
while True:
buf = infile.read(bufsize)
if not buf:
break
outfile.write(buf)
# https://stackoverflow.com/questions/12499171/can-i-set-a-header-with-pythons-simplehttpserver
class MyHTTPRequestHandler(RangeHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
server.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
# https://stackoverflow.com/questions/68592278/sharedarraybuffer-is-not-defined
self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
self.send_header("Cross-Origin-Opener-Policy", "same-origin")
# self.send_header("Access-Control-Allow-Origin", "*")
if __name__ == '__main__':
server.test(HandlerClass=MyHTTPRequestHandler)
|
// We require the Hardhat Runtime Environment explicitly here. This is optional
// but useful for running the script in a standalone fashion through `node <script>`.
// When running the script with `hardhat run <script>` you'll find the Hardhat
// Runtime Environment's members available in the global scope.
import { ethers } from "hardhat";
import { triAddress, decimals, kRecepientAddress } from "../constants";
async function main(): Promise<void> {
// Hardhat always runs the compile task when running scripts through it.
// If this runs in a standalone fashion you may want to call compile manually
// to make sure everything is compiled
// await run("compile");
// We get the contract to deploy
const [_, deployer] = await ethers.getSigners();
console.log(`Deployer address ${deployer.address}`);
const balance = await deployer.getBalance();
console.log(`Account balance: ${balance.toString()}`);
const triToken = await ethers.getContractFactory("Tri");
const tri = triToken.attach(triAddress);
console.log(`Tri address: ${tri.address}`);
const receiverAddress = kRecepientAddress;
const transferAmount = decimals.mul(1);
console.log("Sending ", transferAmount.toString(), " to ", receiverAddress);
const tx = await tri.connect(deployer).transfer(receiverAddress, transferAmount);
const receipt = await tx.wait();
console.log(receipt);
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error: Error) => {
console.error(error);
process.exit(1);
});
|
mod app_tests;
mod authentication;
mod routes;
pub mod state;
mod templates;
mod web_result;
use authentication::{session_middleware, token_middleware};
use routes::*;
use state::DogState;
pub use templates::load_templates;
use axum::{
handler::HandlerWithoutStateExt,
middleware::from_fn_with_state,
routing::{delete, get, post},
Router,
};
use tower_cookies::CookieManagerLayer;
use tower_http::services::ServeDir;
/// Return a fully-functional eardogger app! The caller is in charge of building
/// the state, but we DO need it here in order to construct our auth middleware,
/// since we're using slacker mode instead of writing proper Tower middleware types.
pub fn eardogger_app(state: DogState) -> Router {
let session_auth = from_fn_with_state(state.clone(), session_middleware);
let token_auth = from_fn_with_state(state.clone(), token_middleware);
Router::new()
.route("/", get(root))
.route("/mark/:url", get(mark_url))
.route("/mark", post(post_mark))
.route("/resume/:url", get(resume))
.route("/faq", get(faq))
.route("/account", get(account))
.route("/install", get(install))
.route("/login", post(post_login))
.route("/logout", post(post_logout))
.route("/signup", post(post_signup))
.route("/changepassword", post(post_changepassword))
.route("/change_email", post(post_change_email))
.route("/delete_account", post(post_delete_account))
.route("/fragments/dogears", get(fragment_dogears))
.route("/fragments/tokens", get(fragment_tokens))
.route("/fragments/sessions", get(fragment_sessions))
.route("/fragments/personalmark", post(post_fragment_personalmark))
.route("/tokens/:id", delete(delete_token))
.route("/sessions/:id", delete(delete_session))
.route("/api/v1/list", get(api_list))
.route("/api/v1/dogear/:id", delete(api_delete))
.route("/api/v1/create", post(api_create))
.route(
"/api/v1/update",
post(api_update).options(api_update_cors_preflight),
)
.layer(token_auth) // inner, so can override session.
.layer(session_auth)
.layer(CookieManagerLayer::new())
// put static files and 404 outside the auth layers
.nest_service(
"/public",
ServeDir::new(&state.config.assets_dir).not_found_service(four_oh_four.into_service()),
)
.route("/status", get(status))
.route("/favicon.ico", get(status))
.route("/favicon.gif", get(status))
.fallback(four_oh_four)
.with_state(state)
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<style>
.error {
color: red;
font-size: 0.8em;
}
.success {
color: blue;
font-size: 0.8em;
}
</style>
<title>회원 가입</title>
<script>
const patterns = {
username: [/^[A-Za-z0-9]{6,10}$/, '아이디는 영숫자 6~10자입니다'],
password: [/^[A-Za-z0-9]{8,10}$/, '비밀번호는 영숫자 8~10자입니다'],
email:[/^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i, '잘못된 이메일입니다'],
birthday: [/.+/, '필수입력입니다']
}
function usernameCheck() {
const $element = $('#username');
const value = $element.val();
$element.next().text('');
if(patterns.username[0].test(value)==false) {
$element.next().text(patterns.username[1]).addClass('error');
return false;
}
return true;
}
function passwordCheck() {
const $element = $('#password');
const value = $element.val();
$element.next().text('');
if(patterns.password[0].test(value)==false) {
$element.next().text(patterns.password[1]).addClass('error');
return false;
}
return true;
}
function password2Check() {
const $password = $('#password');
const $element = $('#password2');
$element.next().text('');
if($element.val()==='') {
$element.next().text('확인을 위해 새비밀번호를 다시 입력해주세요').addClass('error');
return false;
}
if($password.val()!==$element.val()) {
$element.next().text('새비밀번호가 일치하지 않습니다').addClass('error');
return false;
}
return true;
}
function emailCheck() {
const $element = $('#email');
const value = $element.val();
$element.next().text('');
if(patterns.email[0].test(value)==false) {
$element.next().text(patterns.email[1]).addClass('error');
return false;
}
return true;
}
function birthdayCheck() {
const $element = $('#birthday');
const value = $element.val();
$element.next().text('');
if(patterns.birthday[0].test(value)==false) {
$element.next().text(patterns.birthday[1]).addClass('error');
return false;
}
return true;
}
$(document).ready(function() {
$('#username').on('blur', usernameCheck);
$('#password').on('blur', passwordCheck);
$('#password2').on('blur', password2Check);
$('#email').on('blur', emailCheck);
$('#birthday').on('blur', birthdayCheck);
$('#join').on('click', function() {
const result = usernameCheck() && passwordCheck() && password2Check() && emailCheck() && birthdayCheck();
if(result==false)
return;
alert('회원가입합니다');
})
})
</script>
</head>
<body>
<div id="page">
<section>
<h1>회원 가입</h1>
<form id="join_form" method="post" action="/member/join" enctype="multipart/form-data">
<div class="mb-3 mt-3">
<label for="profile">프로필 사진:</label>
<input type="file" id="profile" name="profile" accept=".jpg,.jpeg,.png" class="form-control">
</div>
<div class="mb-3 mt-3">
<label for="username">아이디:</label>
<input type="text" name="username" id="username" class="form-control">
<span class="message"></span>
</div>
<div class="mb-3 mt-3">
<label for="password">비밀번호:</label>
<input type="password" name="password" id="password" class="form-control">
<span class="message"></span>
</div>
<div class="mb-3 mt-3">
<label for="password2">비밀번호 확인:</label>
<input type="password" id="password2" class="form-control">
<span class="message"></span>
</div>
<div class="mb-3 mt-3">
<label for="email">이메일:</label>
<input type="text" name="email" id="email" class="form-control">
<span class="message"></span>
</div>
<div class="mb-3 mt-3">
<label for="birthday">생일(선택):</label>
<input type="date" name="birthday" id="birthday" class="form-control">
<span class="message"></span>
</div>
<div class="mb-3 mt-3 d-grid">
<button id="join" type="button" class="btn btn-primary btn-block">가입</button>
</div>
</form>
</section>
</div>
</body>
</html>
|
import userEvent from '@testing-library/user-event';
import React from 'react'
import PregledService from '../services/PregledService';
import PacijentHeader from './PacijentHeader';
class PregledComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
pregledi:[]
}
}
componentDidMount() {
PregledService.getPregledi().then((response) => {
this.setState({pregledi: response.data})
});
}
render(){
console.log(this.state.pregledi);
return(
<div>
<div>
<PacijentHeader/>
</div>
<h1>Istorija pregleda</h1>
<table>
<thead>
<tr>
<td>Termin</td>
<td>Opis</td>
<td>Trajanje</td>
</tr>
</thead>
<tbody>
{
this.state.pregledi.map (
pregled =>
<tr key = {pregled.id}>
<td>{pregled.termin?.datumIVreme}</td>
<td>{pregled.opis}</td>
<td>{pregled.termin?.trajanje} min</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}
}
export default PregledComponent;
|
// rest parameters
// transforma o parâmetro de uma função em um array
// é útil para quando a gente não sabe quantos parâmetros vamos passar na função
// o exemplo é uma função de soma:
const sum = (...numbers) => numbers.reduce((acc, item)=> acc + item, 0) // crio uma função que faz uma soma
// como não sei quantos números eu tenho na soma uso o rest parameter, nesse caso posso passar quantos
// parâmetros forem necessários, visto que o ...numbers é um array
console.log(sum(1, 2, 3, 4, 5));
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Insert Your Title</title>
<style>
label {
display: block;
margin-bottom: 20px;
}
.wrap {
width: 800px;
margin: 100px auto;
border: 1px dashed #000;
}
.wrap h1 {
margin: 0 auto;
padding-bottom: 20px;
width: fit-content;
border-bottom: 1px solid #000;
}
.wrap .menu {
font-size: 24px;
width: 80%;
margin: 20px auto;
}
.wrap .menu select {
width: 200px;
height: 50px;
font-size: 28px;
margin-top: 10px;
}
.clearfix::after {
content: '';
display: block;
clear: both;
}
</style>
</head>
<body>
<div class="wrap">
<h1>커피 주문서</h1>
<div class="menu">
<form action="/coffee/result" method="post">
<label>
# 주문 목록 <br>
<select id="menu-sel" name="menu">
<option value="americano">아메리카노</option>
<option value="cafeLatte">카페라떼</option>
<option value="macchiato">카라멜 마끼아또</option>
</select>
</label>
<label class="price"># 가격: <span class="price-value">3000</span>원</label>
<!-- 화면에 렌더링은 안되지만 서버로 보낼 수 있음 -->
<input id="price-tag" type="hidden" name="price">
<label>
<button type="submit">주문하기</button>
</label>
</form>
</div>
</div>
<script>
const coffeePrice = {
americano: 3000,
cafeLatte: 4500,
macchiato: 5000
};
const $menu = document.getElementById('menu-sel');
// change: input이나 select 태그의 값이 변했을 때
$menu.onchange = e => {
// 커피를 선택하면 가격이 바뀌어야 함!
// console.log(e.target.value); -> option의 value가 잘 오고 있다!
const price = coffeePrice[e.target.value]; // 객체에서 선택된 커피의 가격을 얻어옴.
// span태그에 사용자가 선택한 커피의 가격을 화면으로 노출.
document.querySelector('.price-value').textContent = price;
// input hidden 태그에 가격을 넣어놓기 -> form을 이용해서 서버로 전달.
document.getElementById('price-tag').value = price;
}
</script>
</body>
</html>
|
use serde::ser::{Serialize, Serializer, SerializeStruct};
#[derive(Clone)]
pub enum TaskStatus {
DONE,
PENDING
}
impl TaskStatus {
pub fn stringify(&self) -> String {
match &self {
&Self::DONE => {"DONE".to_string()},
&Self::PENDING => {"PENDING".to_string()}
}
}
pub fn from_string(input_string: String) -> Self {
match input_string.as_str() {
"DONE" => TaskStatus::DONE,
"PENDING" => TaskStatus::PENDING,
_ => panic!("input {} not supported", input_string)
}
}
}
//This works because we just want the string
impl Serialize for TaskStatus {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = serializer.serialize_struct("TaskStatus", 1)?;
s.serialize_field("status", &self.stringify())?;
s.end()
}
}
//this should be good for structs?
// impl Serialize for TaskStatus {
// fn serialize<S>(&self, serializer: S) -> Result<S::Ok,
// S::Error>
// where
// S: Serializer,
// {
// let mut s = serializer.serialize_struct("TaskStatus",
// 1)?;
// s.serialize_field("status", &self.stringify())?;
// s.end()
// }
// }
//This would also need a serialized struct
// #[derive(Serialize)]
// struct TaskStatus {
// status: String
// }
|
<?php
namespace Jigoshop\Factory;
use Jigoshop\Core\Messages;
use Jigoshop\Core\Options;
use Jigoshop\Core\Types;
use Jigoshop\Entity\Customer as CustomerEntity;
use Jigoshop\Entity\Customer\CompanyAddress;
use Jigoshop\Entity\Order as Entity;
use Jigoshop\Entity\OrderInterface;
use Jigoshop\Entity\Product as ProductEntity;
use Jigoshop\Helper\Country;
use Jigoshop\Helper\Geolocation;
use Jigoshop\Helper\Product as ProductHelper;
use Jigoshop\Helper\Tax;
use Jigoshop\Shipping\Method as ShippingMethod;
use Jigoshop\Payment\Method as PaymentMethod;
use Jigoshop\Service\CouponServiceInterface;
use Jigoshop\Service\CustomerServiceInterface;
use Jigoshop\Service\PaymentServiceInterface;
use Jigoshop\Service\ProductServiceInterface;
use Jigoshop\Service\ShippingServiceInterface;
use Jigoshop\Shipping\MultipleMethod;
use WPAL\Wordpress;
class Order implements EntityFactoryInterface
{
/** @var \WPAL\Wordpress */
private $wp;
/** @var Options */
private $options;
/** @var Messages */
private $messages;
/** @var CustomerServiceInterface */
private $customerService;
/** @var ProductServiceInterface */
private $productService;
/** @var ShippingServiceInterface */
private $shippingService;
/** @var PaymentServiceInterface */
private $paymentService;
/** @var CouponServiceInterface */
private $couponService;
public function __construct(Wordpress $wp, Options $options, Messages $messages)
{
$this->wp = $wp;
$this->options = $options;
$this->messages = $messages;
}
public function init(
CustomerServiceInterface $customerService,
ProductServiceInterface $productService,
ShippingServiceInterface $shippingService,
PaymentServiceInterface $paymentService,
CouponServiceInterface $couponService
) {
$this->customerService = $customerService;
$this->productService = $productService;
$this->shippingService = $shippingService;
$this->paymentService = $paymentService;
$this->couponService = $couponService;
}
/**
* Creates new order properly based on POST variable data.
*
* @param $id int Post ID to create object for.
*
* @return Entity
*/
public function create($id)
{
$post = $this->wp->getPost($id);
$_POST = stripslashes_deep($_POST);
// Support for our own post types and "Publish" button.
if (isset($_POST['original_post_status'])) {
$post->post_status = $_POST['original_post_status'];
}
$order = $this->fetch($post);
$data = [
'updated_at' => time(),
];
if (isset($_POST['jigoshop_order']['status'])) {
$order->setStatus($_POST['jigoshop_order']['status']);
}
if (isset($_POST['post_excerpt'])) {
$data['customer_note'] = trim($_POST['post_excerpt']);
}
if (isset($_POST['jigoshop_order'])) {
$data = array_merge($data, $_POST['jigoshop_order']);
}
$data['items'] = $this->getItems($id);
$data['discounts'] = $this->getDiscounts($id);
if (isset($_POST['order']['shipping'])) {
$data['shipping'] = [
'method' => null,
'rate' => null,
'price' => -1,
];
$method = $this->shippingService->get($_POST['order']['shipping']);
if ($method instanceof MultipleMethod && isset($_POST['order']['shipping_rate'], $_POST['order']['shipping_rate'][$method->getId()])) {
$method->setShippingRate($_POST['order']['shipping_rate'][$method->getId()]);
$data['shipping']['rate'] = $method->getShippingRate();
}
$data['shipping']['method'] = $method;
}
return $order = $this->wp->applyFilters('jigoshop\factory\order\create', $this->fill($order, $data));
}
/**
* Fetches order from database.
*
* @param $post \WP_Post Post to fetch order for.
*
* @return \Jigoshop\Entity\Order
*/
public function fetch($post)
{
if ($post->post_type != Types::ORDER) {
return null;
}
$order = new Entity($this->options->get('tax.classes'));
/** @var Entity $order */
$order = $this->wp->applyFilters('jigoshop\factory\order\fetch\before', $order);
$state = [];
if ($post) {
$state = array_map(function ($item) {
return $item[0];
}, $this->wp->getPostMeta($post->ID));
$order->setId($post->ID);
if (isset($state['customer'])) {
// Customer must be unserialized twice "thanks" to WordPress second serialization.
/** @var CustomerEntity */
$state['customer'] = unserialize(unserialize($state['customer']));
/*
This code seems unecessary and was causing issues with PDF invoices.
if ($state['customer'] instanceof CustomerEntity &&
!($state['customer'] instanceof CustomerEntity\Guest) &&
$state['customer_id'] > 0
) {
$customer = $this->customerService->find($state['customer_id']);
$customer->setBillingAddress($state['customer']->getBillingAddress());
$customer->setShippingAddress($state['customer']->getShippingAddress());
$state['customer'] = $customer;
}
*/
}
$state['customer_note'] = $post->post_excerpt;
$state['status'] = $post->post_status;
$state['created_at'] = strtotime($post->post_date);
$state['items'] = $this->getItems($post->ID);
$state['discounts'] = $this->getDiscounts($post->ID);
if (isset($state['shipping'])) {
$shipping = unserialize($state['shipping']);
if (!empty($shipping['method'])) {
$state['shipping'] = [
'method' => $this->shippingService->findForState($shipping['method']),
'price' => $shipping['price'],
'rate' => isset($shipping['rate']) ? $shipping['rate'] : null,
];
}
}
if (isset($state['payment'])) {
$state['payment'] = $this->paymentService->get($state['payment']);
}
$order = $this->fill($order, $state);
}
return $this->wp->applyFilters('jigoshop\find\order', $order, $state);
}
/**
* @param $id int Order ID.
*
* @return array List of items assigned to the order.
*/
private function getItems($id)
{
$wpdb = $this->wp->getWPDB();
$query = $wpdb->prepare("
SELECT * FROM {$wpdb->prefix}jigoshop_order_item joi
LEFT JOIN {$wpdb->prefix}jigoshop_order_item_meta joim ON joim.item_id = joi.id
WHERE joi.order_id = %d
ORDER BY joi.id",
[$id]);
$results = $wpdb->get_results($query, ARRAY_A);
$items = [];
for ($i = 0, $endI = count($results); $i < $endI;) {
$id = $results[$i]['id'];
$item = new Entity\Item();
$item->setId($results[$i]['item_id']);
$item->setType($results[$i]['product_type']);
$item->setName($results[$i]['title']);
$item->setTaxClasses($results[$i]['tax_classes']);
$item->setQuantity($results[$i]['quantity']);
$item->setPrice($results[$i]['price']);
$item->setTax($results[$i]['tax']);
$product = $this->productService->find($results[$i]['product_id']);
$product = $this->wp->applyFilters('jigoshop\factory\order\find_product', $product, $item);
if ($product == null || !$product instanceof ProductEntity) {
$product = new ProductEntity\Simple();
$product->setId($results[$i]['product_id']);
}
while ($i < $endI && $results[$i]['id'] == $id) {
// Securing against empty meta's, but still no piece of code does not add the meta.
if ($results[$i]['meta_key']) {
$meta = new Entity\Item\Meta();
$meta->setKey($results[$i]['meta_key']);
$meta->setValue($results[$i]['meta_value']);
$item->addMeta($meta);
}
$i++;
}
$item->setProduct($product);
$item->setKey($this->productService->generateItemKey($item));
$items[] = $item;
}
return $items;
}
/**
* Updates order properties based on array data.
*
* @param $order \Jigoshop\Entity\Order for update.
* @param $data array of data for update.
*
* @return \Jigoshop\Entity\Order
*/
public function update(Entity $order, $data)
{
if (!empty($data)) {
$helpers = $this->wp->getHelpers();
$order = $this->fill($order, $data);
$order->restoreState($data['jigoshop_order']);
}
return $order;
}
/**
* @param $id int Order ID.
*
* @return array List of items assigned to the order.
*/
private function getDiscounts($id)
{
$wpdb = $this->wp->getWPDB();
$query = $wpdb->prepare("
SELECT * FROM {$wpdb->prefix}jigoshop_order_discount jod
LEFT JOIN {$wpdb->prefix}jigoshop_order_discount_meta jodm ON jodm.discount_id = jod.id
WHERE jod.order_id = %d
ORDER BY jod.id",
[$id]);
$results = $wpdb->get_results($query, ARRAY_A);
$discounts = [];
for ($i = 0, $endI = count($results); $i < $endI;) {
$id = $results[$i]['id'];
$discount = new Entity\Discount();
$discount->setId($results[$i]['id']);
$discount->setType($results[$i]['type']);
$discount->setCode($results[$i]['code']);
$discount->setAmount($results[$i]['amount']);
while ($i < $endI && $results[$i]['id'] == $id) {
// Securing against empty meta's, but still no piece of code does not add the meta.
if ($results[$i]['meta_key']) {
$meta = new Entity\Discount\Meta();
$meta->setKey($results[$i]['meta_key']);
$meta->setValue($results[$i]['meta_value']);
$discount->addMeta($meta);
}
$i++;
}
$discounts[] = $discount;
}
return $discounts;
}
public function fill(OrderInterface $order, array $data)
{
if (!empty($data['customer']) && is_numeric($data['customer'])) {
$data['customer'] = $this->customerService->find($data['customer']);
}
if (isset($data['customer'])) {
if (!empty($data['customer'])) {
$data['customer'] = $this->wp->getHelpers()->maybeUnserialize($data['customer']);
} else {
$data['customer'] = new CustomerEntity\Guest();
}
if (isset($data['billing_address'])) {
$data['billing_address'] = array_merge(
array_flip(array_keys(ProductHelper::getBasicBillingFields())),
$data['billing_address']
);
/** @var CustomerEntity $customer */
$customer = $data['customer'];
$customer->setBillingAddress($this->createAddress($data['billing_address']));
}
if (isset($data['shipping_address'])) {
$data['shipping_address'] = array_merge(
array_flip(array_keys(ProductHelper::getBasicShippingFields())),
$data['shipping_address']
);
/** @var CustomerEntity $customer */
$customer = $data['customer'];
$customer->setShippingAddress($this->createAddress($data['shipping_address']));
}
$order->setCustomer($data['customer']);
unset($data['customer']);
}
/** @var OrderInterface $order */
$order = $this->wp->applyFilters('jigoshop\factory\order\fetch\after_customer', $order);
if (isset($data['items'])) {
$order->removeItems();
}
if (isset($data['discounts'])) {
$order->removeDiscounts();
}
$order->restoreState($data);
// Process tax removal for new orders if we have Vat number.
if($order->getCustomer()->getBillingAddress() instanceof CompanyAddress && $this->options->get('tax.euVat.enabled') && Country::isEU($order->getCustomer()->getBillingAddress()->getCountry())) {
if($order->getCustomer()->getBillingAddress()->getVatNumber() && $order->getEuVatValidationStatus() === '') {
$euVatNumberValidationResult = Tax::validateEUVatNumber($order->getCustomer()->getBillingAddress()->getVatNumber(), $order->getCustomer()->getBillingAddress()->getCountry());
$order->setTaxRemovalState(false);
if($euVatNumberValidationResult == Tax::EU_VAT_VALIDATION_RESULT_VALID) {
if($this->options->get('general.country') == $order->getCustomer()->getBillingAddress()->getCountry()) {
if($this->options->get('tax.euVat.removeVatIfCustomerIsLocatedInShopCountry')) {
$order->setTaxRemovalState(true);
}
}
else {
$order->setTaxRemovalState(true);
}
}
elseif($euVatNumberValidationResult == Tax::EU_VAT_VALIDATION_RESULT_INVALID || $euVatNumberValidationResult == Tax::EU_VAT_VALIDATION_RESULT_ERROR) {
if($this->options->get('tax.euVat.failedValidationHandling') == 'acceptRemoveVat') {
$order->setTaxRemovalState(true);
}
}
$order->setIPAddress($_SERVER['REMOTE_ADDR']);
$order->setEUVatValidationStatus($euVatNumberValidationResult);
try {
$ipAddressCountry = Geolocation::getCountryOfIP($_SERVER['REMOTE_ADDR']);
if($ipAddressCountry !== null) {
$order->setIPAddressCountry($ipAddressCountry);
}
}
catch(Exception $e) {}
}
}
return $this->wp->applyFilters('jigoshop\factory\order\fill', $order);
}
/**
* @param OrderInterface $order
* @param $productId
* @param array $data
* @return Entity\Item
*/
public function updateOrderItemByProductId(OrderInterface $order, $productId, array $data){
/** @var ProductEntity $product */
$product = $this->productService->find($productId);
$item = new Entity\Item();
$item->setProduct($product);
$key = $this->productService->generateItemKey($item);
$orderItem = $order->getItem($key);
if($orderItem){
$order->removeItem($key);
}
$item->setKey($key);
$item->setName($product->getName());
$item->setQuantity((int)$data['quantity']);
if (isset($data['price']) && is_numeric($data['price'])) {
$item->setPrice((float)$data['price']);
}
if ($item->getQuantity() > 0) {
$item = $this->wp->applyFilters('jigoshop\admin\order\update_product', $item, $order);
}
$order->addItem($item);
return $item;
}
private function createAddress($data)
{
if (!empty($data['company']) || !empty($data['euvatno'])) {
$address = new CustomerEntity\CompanyAddress();
if(isset($data['company'])) {
$address->setCompany($data['company']);
}
if (isset($data['euvatno'])) {
$address->setVatNumber($data['euvatno']);
}
} else {
$address = new CustomerEntity\Address();
}
$address->setFirstName($data['first_name']);
$address->setLastName($data['last_name']);
$address->setAddress($data['address']);
$address->setCountry($data['country']);
$address->setState($data['state']);
$address->setCity($data['city']);
$address->setPostcode($data['postcode']);
if (isset($data['phone'])) {
$address->setPhone($data['phone']);
}
if (isset($data['email'])) {
$address->setEmail($data['email']);
}
return $address;
}
public function fromCart(\Jigoshop\Entity\Cart $cart)
{
$order = new \Jigoshop\Entity\Order($this->options->get('tax.classes'));
$state = $cart->getStateToSave();
$state['items'] = unserialize($state['items']);
$state['customer'] = unserialize($state['customer']);
unset($state['shipping'], $state['payment']);
$order->setTaxDefinitions($cart->getTaxDefinitions());
$order->restoreState($state);
$shipping = $cart->getShippingMethod();
if ($shipping && $shipping instanceof ShippingMethod) {
$order->setShippingMethod($shipping);
$order->setShippingTax($cart->getShippingTax());
}
$payment = $cart->getPaymentMethod();
if ($payment && $payment instanceof PaymentMethod) {
$order->setPaymentMethod($payment);
}
return $order;
}
}
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="edu.upenn.cis.rcr_34.reputablecoursereview.CreateAccountActivity">
<!-- Login progress -->
<ProgressBar
android:id="@+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="@+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="false">
<LinearLayout
android:id="@+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<EditText
android:id="@+id/createaccount_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="pennkey@school.upenn.edu"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="@+id/createaccount_firstname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="First Name"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="@+id/createaccount_lastname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Last Name"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="@+id/createaccount_major"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Major"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="@+id/createaccount_year"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Year of Graduation"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="@+id/createaccount_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_password"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="@+id/createaccount_passwordconfirmation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password Confirmation"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/createaccount_profile_pic_label"
android:layout_width="157dp"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:text="Profile Picture"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_gravity="center_vertical" />
<Button
android:id="@+id/createaccount_profile_pic_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:onClick="selectImageClicked"
android:text="Select" />
</LinearLayout>
<Button
android:id="@+id/createaccount_register_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="registerClicked"
android:text="@string/action_register"
android:textStyle="bold" />
<Button
android:id="@+id/createaccount_cancel_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="cancelClicked"
android:text="Cancel Registration"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>
|
"use client";
// hooks
import { useState } from "react";
import { useForm } from "react-hook-form";
// contexts
import GenerateImageContext from "../..";
// zood
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
// interfaces
import { imageFormSchema } from "@/app/[locale]/(dashboard)/(routes)/image/constants";
interface IGenerateImageProvider {
children: React.ReactNode;
}
const GenerateImageProvider: React.FC<IGenerateImageProvider> = ({
children,
}) => {
// chat images states
const [images, setImages] = useState<string[]>(
[]
);
// form values states
const form = useForm<z.infer<typeof imageFormSchema>>({
resolver: zodResolver(imageFormSchema),
defaultValues: {
prompt: "",
amount: "1",
resolution: "512x512",
},
});
// loading state
const isLoading = form.formState.isSubmitting;
return (
<GenerateImageContext.Provider
value={{
images,
setImages,
isLoading,
form,
}}
>
{children}
</GenerateImageContext.Provider>
);
};
export default GenerateImageProvider;
|
<?php
// $Id: preflang.module, v 0.001 2006-02-09 21:13:39 unconed Exp $
/**
* @file
* A simple module 2 collect info from WhatCounts campaign 0602.
*
* Our example node type will allow users to specify a "color" and a "quantity"
* for their nodes; some kind of rudimentary inventory-tracking system, perhaps?
* To store this extra information, we need an auxiliary database table.
*
* Database definition:
* @code
* CREATE TABLE preflang (
* EQid varchar(255) NOT NULL default '',
* preflang varchar(255) NOT NULL default '',
* PRIMARY KEY (EQid)
* )
* @endcode
*/
/**
* Implementation of hook_help().
*
* Throughout Drupal, hook_help() is used to display help text at the top of
* pages. Some other parts of Drupal pages get explanatory text from these hooks
* as well. We use it here to provide a description of the module on the
* module administration page.
*/
function preflang_help($section) {
switch ($section) {
case 'admin/modules#description':
// This description is shown in the listing at admin/modules.
return t('A simple module 2 collect info from WhatCounts campaign 0602.');
}
}
/**
* Implementation of hook_menu().
*
* In order for users to be able to add nodes of their own, we need to
* give them a link to the node composition form here.
*/
function preflang_menu($may_cache) {
$items = array();
if ($may_cache) {
$items[] = array(
'path' => 'preflang',
'callback' => '_preflang_page',
'access' => TRUE,
'type' => MENU_CALLBACK);
}
return $items;
}
/**
* Implementation of internal hook_page().
*
* Take data from link www...org/preflang/donaldduck@whitehouse.gov/en
*/
function _preflang_page($EQid="no", $lang="en") {
switch ($EQid) {
case 'no':
// send a new confirmation email
watchdog("preflang","no data 2 process");
drupal_goto(variable_get("site_frontpage","node"));
break;
default:
$email = db_result(db_query("SELECT email FROM {preflang} WHERE EQid = '%s'", $EQid));
if ($email) {
db_query("UPDATE {preflang} SET preflang = '%s', lastupdated=unix_timestamp() WHERE EQid = '%s'", $lang, $EQid);
drupal_set_message("User $email, your preference was processed.");
drupal_goto(variable_get("site_frontpage","node"));
// $title = "Language preference for $email";
// $out = "<p></p>";
// print theme("page",$out,$title);
} else {
watchdog("preflang","USER $EQid don't exist");
drupal_goto(variable_get("site_frontpage","node"));
}
}
}
function _preflang_setlang($EQid, $lang) {
if (db_result(db_query("SELECT EQid FROM {preflang} WHERE EQid = '%s'", $EQid))) {
db_query("UPDATE {preflang} SET preflang = '%s' WHERE EQid = '%s'", $EQid, $lang);
} else {
db_query("INSERT INTO {preflang} (EQid, preflang) VALUES ('%s', '%s')", $EQid, $lang);
}
}
?>
|
<?php
namespace Codexpert\CoDesigner;
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Typography;
use Codexpert\CoDesigner\App\Controls\Group_Control_Gradient_Text;
use Elementor\Core\Kits\Documents\Tabs\Global_Typography;
class Order_Review extends Widget_Base {
public $id;
protected $form_close='';
public function __construct( $data = [], $args = null ) {
parent::__construct( $data, $args );
$this->id = wcd_get_widget_id( __CLASS__ );
$this->widget = wcd_get_widget( $this->id );
}
public function get_script_depends() {
return [];
}
public function get_style_depends() {
return [];
}
public function get_name() {
return $this->id;
}
public function get_title() {
return $this->widget['title'];
}
public function get_icon() {
return $this->widget['icon'];
}
public function get_categories() {
return $this->widget['categories'];
}
protected function register_controls() {
$this->start_controls_section(
'order_notes_title',
[
'label' => __( 'Section Title', 'codesigner' ),
'tab' => Controls_Manager::TAB_CONTENT,
]
);
$this->add_control(
'order_review_title_show',
[
'label' => __( 'Show/Hide Title', 'codesigner' ),
'type' => Controls_Manager::SWITCHER,
'label_on' => __( 'Show', 'codesigner' ),
'label_off' => __( 'Hide', 'codesigner' ),
'return_value' => 'yes',
'default' => 'yes',
]
);
//order_button_text
$this->add_control(
'order_review_title_text',
[
'label' => __( 'Text', 'codesigner' ),
'type' => Controls_Manager::TEXT,
'default' => __( 'Order Review', 'codesigner' ) ,
'condition' => [
'order_review_title_show' => 'yes'
],
'dynamic' => [
'active' => true,
]
]
);
$this->add_control(
'order_review_title_tag',
[
'label' => __( 'HTML Tag', 'codesigner' ),
'type' => Controls_Manager::SELECT,
'default' => 'h3',
'options' => [
'h1' => __( 'H1', 'codesigner' ),
'h2' => __( 'H2', 'codesigner' ),
'h3' => __( 'H3', 'codesigner' ),
'h4' => __( 'H4', 'codesigner' ),
'h5' => __( 'H5', 'codesigner' ),
'h6' => __( 'H6', 'codesigner' ),
],
'condition' => [
'order_review_title_show' => 'yes'
],
]
);
$this->add_control(
'order_review_title_alignment',
[
'label' => __( 'Alignment', 'codesigner' ),
'type' => Controls_Manager::CHOOSE,
'options' => [
'left' => [
'title' => __( 'Left', 'codesigner' ),
'icon' => 'eicon-text-align-left',
],
'center' => [
'title' => __( 'Center', 'codesigner' ),
'icon' => 'eicon-text-align-center',
],
'right' => [
'title' => __( 'Right', 'codesigner' ),
'icon' => 'eicon-text-align-right',
],
],
'default' => 'left',
'toggle' => true,
'condition' => [
'order_review_title_show' => 'yes'
],
'selectors' => [
'{{WRAPPER}} .wl-order-review-title' => 'text-align: {{VALUE}};',
],
]
);
$this->end_controls_section();
$this->start_controls_section(
'order_review_content',
[
'label' => __( 'Table Headings', 'codesigner' ),
'tab' => Controls_Manager::TAB_CONTENT,
]
);
$this->add_control(
'order_review_table_th1',
[
'label' => __( 'Product Column Heading', 'codesigner' ),
'type' => Controls_Manager::TEXT,
'default' => __( 'Product', 'codesigner' ) ,
'dynamic' => [
'active' => true,
]
]
);
$this->add_control(
'order_review_table_th2',
[
'label' => __( 'Price Column Heading', 'codesigner' ),
'type' => Controls_Manager::TEXT,
'default' => __( 'Subtotal', 'codesigner' ) ,
'dynamic' => [
'active' => true,
]
]
);
$this->end_controls_section();
//section title style
$this->start_controls_section(
'order_review_title_style',
[
'label' => __( 'Title', 'codesigner' ),
'tab' => Controls_Manager::TAB_STYLE,
'condition' => [
'order_review_title_show' => 'yes'
],
]
);
$this->add_group_control(
Group_Control_Typography::get_type(),
[
'name' => 'order_review_title_typographyrs',
'label' => __( 'Typography', 'codesigner' ),
'global' => [
'default' => Global_Typography::TYPOGRAPHY_TEXT,
],
'selector' => '{{WRAPPER}} .wl-order-review-title',
]
);
$this->add_group_control(
Group_Control_Gradient_Text::get_type(),
[
'name' => 'order_review_title_color',
'selector' => '{{WRAPPER}} .wl-order-review-title',
]
);
$this->end_controls_section();
/**
* Table border control
*/
$this->start_controls_section(
'order_table_border_style',
[
'label' => __( 'Table Sell Border', 'codesigner' ),
'tab' => Controls_Manager::TAB_STYLE,
]
);
$this->add_group_control(
Group_Control_Border::get_type(),
[
'name' => 'table_border_type',
'label' => __( 'Border', 'codesigner' ),
'selector' => '{{WRAPPER}} .wl-or-table tr td,
{{WRAPPER}} .wl-or-table tr th',
]
);
$this->end_controls_section();
/**
* Table Header control
*/
$this->start_controls_section(
'order_table_header_style',
[
'label' => __( 'Table Header', 'codesigner' ),
'tab' => Controls_Manager::TAB_STYLE,
]
);
$this->add_group_control(
Group_Control_Typography::get_type(),
[
'name' => 'order_thead_typographyrs',
'label' => __( 'Typography', 'codesigner' ),
'global' => [
'default' => Global_Typography::TYPOGRAPHY_TEXT,
],
'selector' => '{{WRAPPER}} .wl-or-table thead tr th',
]
);
$this->add_control(
'order_thead_color',
[
'label' => __( 'Text Color', 'codesigner' ),
'type' => Controls_Manager::COLOR,
'selectors' => [
'{{WRAPPER}} .wl-or-table thead tr th' => 'color: {{VALUE}}',
],
]
);
$this->add_control(
'order_thead_bg_color',
[
'label' => __( 'Background', 'codesigner' ),
'type' => Controls_Manager::COLOR,
'selectors' => [
'{{WRAPPER}} .wl-or-table thead tr th' => 'background-color: {{VALUE}}',
],
]
);
$this->add_control(
'order_thead_alignment',
[
'label' => __( 'Alignment', 'codesigner' ),
'type' => Controls_Manager::CHOOSE,
'options' => [
'left' => [
'title' => __( 'Left', 'codesigner' ),
'icon' => 'eicon-text-align-left',
],
'center' => [
'title' => __( 'Center', 'codesigner' ),
'icon' => 'eicon-text-align-center',
],
'right' => [
'title' => __( 'Right', 'codesigner' ),
'icon' => 'eicon-text-align-right',
],
],
'default' => 'left',
'toggle' => true,
'selectors' => [
'{{WRAPPER}} .wl-or-table thead tr th' => 'text-align: {{VALUE}};',
],
]
);
$this->add_control(
'order_thead_padding',
[
'label' => __( 'Padding', 'codesigner' ),
'type' => Controls_Manager::DIMENSIONS,
'size_units' => [ 'px', '%', 'em' ],
'selectors' => [
'{{WRAPPER}} .wl-or-table thead tr th' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
],
]
);
$this->end_controls_section();
/**
* Table body control
*/
$this->start_controls_section(
'order_tbody_style',
[
'label' => __( 'Table Body', 'codesigner' ),
'tab' => Controls_Manager::TAB_STYLE,
]
);
$this->add_group_control(
Group_Control_Typography::get_type(),
[
'name' => 'order_tbody_typographyrs',
'label' => __( 'Typography', 'codesigner' ),
'global' => [
'default' => Global_Typography::TYPOGRAPHY_TEXT,
],
'selector' => '{{WRAPPER}} .wl-or-table tbody tr td',
]
);
$this->add_control(
'order_tbody_color',
[
'label' => __( 'Text Color', 'codesigner' ),
'type' => Controls_Manager::COLOR,
'selectors' => [
'{{WRAPPER}} .wl-or-table tbody tr td' => 'color: {{VALUE}}',
],
]
);
$this->add_control(
'order_tbody_bg_color',
[
'label' => __( 'Background', 'codesigner' ),
'type' => Controls_Manager::COLOR,
'selectors' => [
'{{WRAPPER}} .wl-or-table tbody tr td' => 'background-color: {{VALUE}}',
],
]
);
$this->add_control(
'order_tbody_alignment',
[
'label' => __( 'Alignment', 'codesigner' ),
'type' => Controls_Manager::CHOOSE,
'options' => [
'left' => [
'title' => __( 'Left', 'codesigner' ),
'icon' => 'eicon-text-align-left',
],
'center' => [
'title' => __( 'Center', 'codesigner' ),
'icon' => 'eicon-text-align-center',
],
'right' => [
'title' => __( 'Right', 'codesigner' ),
'icon' => 'eicon-text-align-right',
],
],
'default' => 'left',
'toggle' => true,
'selectors' => [
'{{WRAPPER}} .wl-or-table tbody tr td' => 'text-align: {{VALUE}};',
],
]
);
$this->add_control(
'order_tbody_padding',
[
'label' => __( 'Padding', 'codesigner' ),
'type' => Controls_Manager::DIMENSIONS,
'size_units' => [ 'px', '%', 'em' ],
'selectors' => [
'{{WRAPPER}} .wl-or-table tbody tr td' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
],
]
);
$this->end_controls_section();
/**
* Table footer control
*/
$this->start_controls_section(
'order_tfoot_style',
[
'label' => __( 'Table Footer', 'codesigner' ),
'tab' => Controls_Manager::TAB_STYLE,
]
);
$this->add_group_control(
Group_Control_Typography::get_type(),
[
'name' => 'order_tfoot_typographyrs',
'label' => __( 'Typography', 'codesigner' ),
'global' => [
'default' => Global_Typography::TYPOGRAPHY_TEXT,
],
'selector' => '{{WRAPPER}} .wl-or-table tfoot tr td,
{{WRAPPER}} .wl-or-table tfoot tr th',
]
);
$this->add_control(
'order_tfoot_color',
[
'label' => __( 'Text Color', 'codesigner' ),
'type' => Controls_Manager::COLOR,
'selectors' => [
'{{WRAPPER}} .wl-or-table tfoot tr td,
{{WRAPPER}} .wl-or-table tfoot tr th' => 'color: {{VALUE}}',
],
]
);
$this->add_control(
'order_tfoot_bg_color',
[
'label' => __( 'Background', 'codesigner' ),
'type' => Controls_Manager::COLOR,
'selectors' => [
'{{WRAPPER}} .wl-or-table tfoot tr td,
{{WRAPPER}} .wl-or-table tfoot tr th' => 'background-color: {{VALUE}}',
],
]
);
$this->add_control(
'order_tfoot_alignment',
[
'label' => __( 'Alignment', 'codesigner' ),
'type' => Controls_Manager::CHOOSE,
'options' => [
'left' => [
'title' => __( 'Left', 'codesigner' ),
'icon' => 'eicon-text-align-left',
],
'center' => [
'title' => __( 'Center', 'codesigner' ),
'icon' => 'eicon-text-align-center',
],
'right' => [
'title' => __( 'Right', 'codesigner' ),
'icon' => 'eicon-text-align-right',
],
],
'default' => 'left',
'toggle' => true,
'selectors' => [
'{{WRAPPER}} .wl-or-table tfoot tr td,
{{WRAPPER}} .wl-or-table tfoot tr th' => 'text-align: {{VALUE}};',
],
]
);
$this->add_control(
'order_tfoot_padding',
[
'label' => __( 'Padding', 'codesigner' ),
'type' => Controls_Manager::DIMENSIONS,
'size_units' => [ 'px', '%', 'em' ],
'selectors' => [
'{{WRAPPER}} .wl-or-table tfoot tr td,
{{WRAPPER}} .wl-or-table tfoot tr th' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
],
]
);
$this->end_controls_section();
}
protected function render() {
if( !current_user_can( 'edit_pages' ) ) return;
echo wcd_notice( sprintf( __( 'This beautiful widget, <strong>%s</strong> is a premium widget. Please upgrade to <strong>%s</strong> or activate your license if you already have upgraded!' ), $this->get_name(), '<a href="https://codexpert.io/codesigner" target="_blank">CoDesigner Pro</a>' ) );
if( file_exists( dirname( __FILE__ ) . '/assets/img/screenshot.png' ) ) {
echo "<img src='" . plugins_url( 'assets/img/screenshot.png', __FILE__ ) . "' />";
}
}
/**
* Adds the starting form tag <form>
*/
public function start_form( $start ) {
return '<form name="checkout" method="post" class="checkout woocommerce-checkout" action="" enctype="multipart/form-data" novalidate="novalidate">';
}
/**
* Adds the closing form tag </form>
*/
public function close_form( $close ) {
return '</form>';
}
}
|
<?xml version="1.0" ?>
<!DOCTYPE article PUBLIC "-//KDE//DTD DocBook XML V4.5-Based Variant V1.1//EN"
"dtd/kdedbx45.dtd" [
<!ENTITY % addindex "IGNORE">
<!ENTITY % Catalan "INCLUDE"
><!-- change language only here -->
]>
<article id="kgamma" lang="&language;">
<title
>Gamma del monitor</title>
<articleinfo>
<authorgroup>
<author
><firstname
>Michael</firstname
> <surname
>v.Ostheim</surname
> <affiliation
> <address
><email
>ostheimm@users.berlios.de</email
></address>
</affiliation>
</author>
&traductor.Antoni.Bella;
</authorgroup>
<date
>31 de juliol de 2015</date>
<releaseinfo
>Plasma 5.4</releaseinfo>
<keywordset>
<keyword
>KDE</keyword>
<keyword
>Arranjament del sistema</keyword>
<keyword
>Monitor</keyword>
<keyword
>Calibratge</keyword>
<keyword
>Gamma</keyword>
</keywordset>
</articleinfo>
<sect1 id="introduction">
<title
>Introducció</title>
<para
>Aquest mòdul és una eina per a la correcció de la gamma del monitor. Amb la configuració adequada, la visualització (de llocs web, imatges, &etc;) tindrà el mateix aspecte al vostre monitor i en el d'altres persones.</para>
<para
>Us permet modificar la correcció de la gamma del monitor del &X-Server;. Però això no és tot. Per a obtenir bons resultats cal establir la brillantor, contrast i equilibri de color correctes del vostre monitor. Això pot ser difícil i cal repetir tots els passos diverses vegades. Per a un resultat perfecte és realment necessari un maquinari bo (i car).</para>
<para
>Utilitzeu els quatre controls lliscants per a definir la correcció de la gamma, sigui com un sol valor, o per separat dels components vermell, verd i blau. La configuració predeterminada del &X-Server; per a la gamma és de 1,00 (1,80 per a Mac, 2,20 per a WinXX). Les imatges de prova us ajudaran a trobar la configuració adequada.</para>
<para
>Per a emmagatzemar la configuració de la gamma per a tot el sistema, habiliteu l'opció <guilabel
>Desa els paràmetres per a tot el sistema</guilabel
>. La configuració del sistema es restablirà en el pròxim inici del &X-Server;. Cal tenir accés de root per a utilitzar aquesta opció. Utilitzeu-la si voleu corregir la configuració de la gamma per a tots els usuaris i entorns gràfics en aquesta màquina.</para>
<para
>Per a emmagatzemar la configuració de la gamma a la vostra configuració personal del &plasma;, no habiliteu aquesta opció. La configuració de l'usuari serà restablerta al següent inici del &plasma;; i substituirà temporalment la configuració de la gamma del sistema. La configuració del sistema no serà eliminada i es restablirà en el proper inici del &X-Server;.</para>
<para
>En els sistemes de múltiples monitors, seleccioneu la pantalla que voleu modificar amb el quadre combinat. Això també funciona amb xinerama habilitat. Per a establir totes les pantalles als mateixos valors de la gamma, habiliteu l'opció <guilabel
>Sincronia de les pantalles</guilabel
>. En els sistemes amb un sol monitor aquesta opció no tindrà cap efecte.</para>
</sect1>
<sect1 id="using_test_images">
<title
>Utilitzar les Imatges de prova</title>
<para
>Aquest mòdul ofereix sis imatges de prova diferents, seleccionables des de la llista desplegable a la part superior de la finestra.</para>
<sect2 id="grey">
<title
>Imatge de prova d'escala de grisos</title>
<para
>Hauríeu de poder veure el següent:</para>
<itemizedlist>
<listitem>
<para
>Una escala de grisos amb 20 seccions diferents</para>
</listitem>
<listitem>
<para
>La secció més obscura és negre pur</para>
</listitem>
<listitem>
<para
>La secció més clara és blanc pur</para>
</listitem>
<listitem>
<para
>No hi ha rastre de cap color en els tons grisos</para>
</listitem>
</itemizedlist>
<para
>Si no podeu veure totes les seccions (20), utilitzeu la configuració de contrast dels monitors o el control lliscant de <guilabel
>Gamma:</guilabel
> per a corregir-ho. Si el negre no és negre pur, mireu d'enfosquir el monitor, si el blanc no és blanc pur, mireu d'aclarir. Si veieu els colors dels tons grisos, modifiqueu la configuració d'equilibri de color del monitor o empreu els controls lliscants <guilabel
>Vermell:</guilabel
>, <guilabel
>Verd:</guilabel
> i <guilabel
>Blau:</guilabel
>.</para>
</sect2>
<sect2 id="RGB-Scale">
<title
>Imatge de prova de l'escala RGB</title>
<para
>Haureu de ser capaç de veure les tres tires, cadascuna amb 16 seccions de tons vermell, verd o blau. Les seccions més fosques han de ser negre pur, les més brillants han de ser vermell, verd o blau purs. Si no veieu totes les seccions d'una tira de color, mireu d'aclarir o enfosquir aquest color.</para>
</sect2>
<sect2 id="CMY-Scale">
<title
>Imatge de prova de l'escala CMY</title>
<para
>Haureu de ser capaç de veure tres tires, cadascuna amb 11 seccions de tons cian, magenta o groc. Les seccions més brillants han de ser de color blanc pur, les més fosques han de ser cian, magenta o groc purs.</para>
<itemizedlist>
<listitem>
<para
>Si no podeu veure totes les seccions en cian, mireu d'aclarir o enfosquir el vermell</para>
</listitem>
<listitem>
<para
>Si no podeu veure totes les seccions magenta, mireu d'aclarir o enfosquir el verd</para>
</listitem>
<listitem>
<para
>Si no podeu veure totes les seccions grogues, mireu d'aclarir o enfosquir el blau</para>
</listitem>
</itemizedlist>
</sect2>
<sect2 id="advanced">
<title
>Imatges de prova avançades</title>
<para
>Les següents tres imatges mostren les habilitats del vostre monitor en tres punts de l'espectre de grisos. Si no podeu veure tots els detalls, no us preocupeu, o millor compreu un maquinari millor. </para>
<sect3 id="dark-gray">
<title
>Imatge de prova de gris fosc</title>
<para
>Haureu de ser capaç de veure 10 rectangles diferents de color gris fosc dins d'un requadre negre. El gràfic us mostra passos de l'1% des del negre. </para>
</sect3>
<sect3 id="mid-gray">
<title
>Imatge de prova de gris mitjà</title>
<para
>Aquesta imatge us mostra 11 rectangles grisos dins d'un requadre al 50% de gris. Haureu de ser capaç de veure tots els rectangles, excepte el del mig. Els rectangles representen els passos de 45% al 55% des del gris. </para>
</sect3>
<sect3 id="light-gray">
<title
>Imatge de prova de gris clar</title>
<para
>Haureu de ser capaç de veure 10 rectangles diferents de color gris clar dins d'un requadre blanc. El gràfic us mostra passos de l'1% des del blanc. </para>
</sect3>
</sect2>
</sect1>
</article>
<!--
Local Variables:
mode: sgml
sgml-minimize-attributes:nil
sgml-general-insert-case:lower
sgml-indent-step:0
sgml-indent-data:nil
End:
-->
|
import { ec } from "elliptic";
import SHA256 from "crypto-js/sha256";
const ecObject = new ec("secp256k1");
class Transaction {
fromAddress: string | null;
toAddress: string;
amount: number;
signature: string | null = null;
constructor(fromAddress: string | null, toAddress: string, amount: number) {
this.fromAddress = fromAddress;
this.toAddress = toAddress;
this.amount = amount;
}
calculateHash = () =>
SHA256(this.fromAddress + this.toAddress + this.amount).toString();
signTransaction = (signingKey: ec.KeyPair) => {
if (signingKey.getPublic("hex") !== this.fromAddress) {
throw new Error("Has to be signed by address owner");
}
const tx = this.calculateHash();
const signature = signingKey.sign(tx, "base64");
this.signature = signature.toDER("hex");
};
validateSignature = () => {
if (this.fromAddress === null) return true;
if (this.signature === null || this.signature.length === 0) {
throw new Error("No signature");
}
const publicKey = ecObject.keyFromPublic(this.fromAddress, "hex");
return publicKey.verify(this.calculateHash(), this.signature);
};
}
class Block {
timestamp: string;
transaction: Transaction[];
previousHash: string;
currentHash: string;
nonce: number;
constructor(
timestamp: string,
transaction: Transaction[],
previousHash: string = ""
) {
this.timestamp = timestamp;
this.transaction = transaction;
this.previousHash = previousHash;
this.currentHash = this.calculateHash();
this.nonce = 0;
}
validateTransaction = () => {
for (const tx of this.transaction) {
if (!tx.validateSignature()) {
return false;
}
}
return true;
};
calculateHash = () =>
SHA256(
this.previousHash + JSON.stringify(this.transaction) + this.nonce
).toString();
mine = (difficulity: number) => {
while (
this.currentHash.substring(0, difficulity) !==
Array(difficulity + 1).join("0")
) {
this.nonce++;
this.currentHash = this.calculateHash();
// console.log(this.currentHash);
}
// console.log(`Block mined at ${this.currentHash}`);
};
}
class Blockchain {
chain: Block[];
difficulty: number;
pendingTransaction: Transaction[];
miningReward: number;
constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 2;
this.pendingTransaction = [];
this.miningReward = 100;
}
createGenesisBlock = () =>
new Block(
new Date().toString(),
Array<Transaction>(new Transaction(null, "0", 0))
);
getLatestBlock = () => this.chain[this.chain.length - 1];
minePendingTransaction = (miningRewardAddress: string) => {
this.pendingTransaction.push(
new Transaction(null, miningRewardAddress, this.miningReward)
);
let block = new Block(new Date().toString(), this.pendingTransaction);
block.previousHash = this.getLatestBlock().currentHash;
block.mine(this.difficulty);
this.chain.push(block);
this.pendingTransaction = [];
};
addTransaction = (transaction: Transaction) => {
if (!transaction.fromAddress || !transaction.toAddress)
throw new Error("No address is given");
if (!transaction.validateSignature())
throw new Error("Invalid transaction");
this.pendingTransaction.push(transaction);
};
getBalanceOfAddress = (address: string) => {
let balance = 0;
for (const block of this.chain) {
for (const transaction of block.transaction) {
if (transaction.fromAddress === address) {
balance -= transaction.amount;
}
if (transaction.toAddress === address) {
balance += transaction.amount;
}
}
}
return balance;
};
// addBlock = (newBlock: Block) => {
// newBlock.previousHash = this.getLatestBlock().currentHash;
// newBlock.mine(this.difficulty);
// // newBlock.currentHash = newBlock.calculateHash();
// this.chain.push(newBlock);
// };
validateChain = () => {
for (let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
if (!currentBlock.validateTransaction()) return false;
if (currentBlock.currentHash !== currentBlock.calculateHash())
return false;
if (currentBlock.previousHash !== previousBlock.currentHash) return false;
}
return true;
};
}
export { Block, Blockchain, Transaction };
|
<!--
* @Author: TerryMin
* @Date: 2022-09-02 13:40:10
* @LastEditors: TerryMin
* @LastEditTime: 2022-09-10 14:56:19
* @Description: https://blog.csdn.net/mafan121/article/details/78519348
-->
<html>
<head>
<title>JS 获取光标位置概念 及demo</title>
<style>
p {
display: flex;
flex-direction: row;
}
.btn {
height: 24px;
margin: 0 10px;
}
.edit-div {
display: inline-block;
width: 225px;
border: 1px solid #decdcd;
}
</style>
<script>
function getCursortPosition(e) {
var eleP = e.target.parentNode; //获取父级元素
var pos = 0;
if (e.target.nodeName == "DIV") {
pos = getDivPosition(e.target);
} else {
pos = getPosition(e.target);
}
var spanEle = eleP.childNodes[7];
spanEle.innerText = pos;
}
//可编辑div获取坐标
const getDivPosition = function (element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
//谷歌、火狐
sel = win.getSelection();
if (sel.rangeCount > 0) {
//选中的区域
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange(); //克隆一个选中区域
preCaretRange.selectNodeContents(element); //设置选中区域的节点内容为当前节点
preCaretRange.setEnd(range.endContainer, range.endOffset); //重置选中区域的结束位置
caretOffset = preCaretRange.toString().length;
}
} else if ((sel = doc.selection) && sel.type != "Control") {
//IE
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
};
//输入框获取光标
const getPosition = function (element) {
let cursorPos = 0;
if (document.selection) {
//IE
var selectRange = document.selection.createRange();
selectRange.moveStart("character", -element.value.length);
cursorPos = selectRange.text.length;
} else if (element.selectionStart || element.selectionStart == "0") {
cursorPos = element.selectionStart;
}
return cursorPos;
};
const handlePosition = () => {
const editDiv = document.getElementById("editDiv");
setCaretPosition(editDiv,3);
};
//设置光标位置
const setCaretPosition = function (element, pos) {
var range, selection;
if (document.createRange) {
//Firefox, Chrome, Opera, Safari, IE 9+
range = document.createRange(); //创建一个选中区域
console.log(range);
range.selectNodeContents(element); //选中节点的内容
console.log(range);
console.log(element.innerHTML);
if (element.innerHTML.length > 0) {
range.setStart(element.childNodes[0], pos); //设置光标起始为指定位置
}
range.collapse(true); //设置选中区域为一个点
selection = window.getSelection(); //获取当前选中区域
selection.removeAllRanges(); //移出所有的选中范围
selection.addRange(range); //添加新建的范围
} else if (document.selection) {
//IE 8 and lower
range = document.body.createTextRange(); //Create a range (a range is a like the selection but invisible)
range.moveToElementText(element); //Select the entire contents of the element with the range
range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start
range.select(); //Select the range (make it the visible selection
}
};
</script>
</head>
<body>
<p>
<label>输入框测试:</label>
<input
type="text"
style="width: 220px"
onclick="getCursortPosition(event);"
/>
<span>光标位置:</span>
<span></span>
</p>
<p>
<label>文本框测试:</label>
<textarea
rows="5"
style="width: 220px"
onclick="getCursortPosition(event);"
></textarea>
<span>光标位置:</span>
<span></span>
</p>
<div>
<label>可编辑div:</label>
<div
contenteditable="true"
class="edit-div"
onclick="getCursortPosition(event);"
id="editDiv"
></div>
<span>光标位置:</span>
<span></span>
<button onclick="handlePosition()">设置光标位置</button>
</div>
</body>
</html>
|
<!-- Top anchor -->
<a name="readme-top"></a>
<!-- PROJECT SHIELDS -->
<!--
*** I'm using markdown "reference style" links for readability.
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
*** See the bottom of this document for the declaration of the reference variables
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
-->
<div align="center">
[![MIT License][license-shield]][license-url]
[![LinkedIn][linkedin-shield]][linkedin-url]
</div>
<!-- PROJECT LOGO -->
<br />
<div align="center">
<a href="https://github.com/Albenzoo/PokeCard-NFT">
<img src="src/assets/image/poke-favicon.png" alt="Logo" width="80" height="80">
</a>
<h3 align="center">Pokecard NFT</h3>
<p align="center">
A marketplace for create, buy, sell and display Pokemon NFT cards
<br />
<br />
<a href="https://github.com/Albenzoo/PokeCard-NFT/issues">Report Bug</a>
·
<a href="https://pokecard-nft.web.app/">View Dapp</a>
·
<a href="https://github.com/Albenzoo/PokeCard-NFT/issues">Request Feature</a>
</p>
</div>
## Features
- Create and sell your custom NFT Cards
- Buy other cards
- Display all the cards created
- Display last 4 cards minted
- Display owned cards
</br>
<!-- TABLE OF CONTENTS -->
<details>
<summary>Table of Contents</summary>
<ol>
<li>
<a href="#about-the-project">About The Project</a>
<ul>
<li><a href="#built-with">Built With</a></li>
</ul>
</li>
<li>
<a href="#project-structure">Project Structure</a>
<ul>
<li><a href="#smart-contract">Smart Contract</a></li>
<li><a href="#angular-app">Angular App</a></li>
<li><a href="#utility-scripts">Utilitis Scripts</a></li>
</ul>
</li>
<li>
<a href="#getting-started">Getting Started</a>
<ul>
<li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#installation">Installation</a></li>
</ul>
</li>
<li><a href="#usage">Usage</a>
<ul>
<li><a href="#deploying-the-contract-yourself">Deploying the contract yourself</a></li>
<li><a href="#automatic-nfts-minting">Automatic NFTs minting</a></li>
</ul>
</li>
<li><a href="#build">Build</a></li>
<li><a href="#deploy-firebase">Deploy (Firebase)</a></li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#license">License</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#acknowledgments">Acknowledgments</a></li>
</ol>
</details>
</br>
<!-- ABOUT THE PROJECT -->
## About The Project
This is an NFT marketplace based on the creation and exchange of collectible NFT cards. This app is connected with the Ethereum blockchain (by default Goerli testnet) through web3.js and interact with a smart contract.
In this project you can find everything you need to make a decentralized app:
- Smart contract used and how to deploy it
- Frontend part (NFT creation, visualization and minting)
- Script for populate smart contract with custom NFT (optional)
For the ethereum node provider was used Alchemy, and for NFT storing was used Pinata.
### Built With
* [![Angular][Angular.io]][Angular-url]
* [![Web3js][web3js-logo]][web3js-url]
* [![Solidity][solidity-logo]][solidity-url]
* [![Hardhat][hardhat-logo]][hardhat-url]
* [![Alchemy][alchemy-logo]][alchemy-url]
* [![Pinata][pinata-logo]][pinata-url]
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
<!-- PROJECT STRUCTURE -->
## Project Structure
### Smart Contract
Powering all the data for this app is an Ethereum smart contract, written in Solidity and based on OpenZeppelin ERC-721 standard. The contract is on the file `contracts/MyNFT.sol`
### Angular App
All the frontend is built with Angular, you can find all the files under folder `src`
### Utility Scripts
There are also some utility script under `scripts` folder:
- `deploy.ts`: used to deploy the smart contract
- `mint-nft.ts`: used to dinamically popolate the contract with NFT added on pinataMintCid.json
- `setenv.ts`: used to populate environment variable
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
<!-- GETTING STARTED -->
## Getting Started
To get a local copy up and running follow these simple example steps.
### Prerequisites
List of things you need to use in order to use the software and how to install them:
* npm
```sh
npm install npm@latest -g
```
* Get a free Alchemy node API Key at [https://dashboard.alchemy.com/](https://dashboard.alchemy.com/) (used to be able to load the NFTs info also for user without Metamask installed)
* Get a free Pinata JWT at [https://app.pinata.cloud/](https://app.pinata.cloud/) (used to store our NFTs information)
### Installation
1. Clone the repo
```sh
git clone https://github.com/Albenzoo/PokeCard-NFT.git
```
2. Install NPM packages
```sh
npm install
```
3. Enter your personal information in `.env` (if you have not a contract, follow the instructions <a href="#deploy-contract">below</a> to deploy a new one)
```
PUBLIC_KEY=YOUR-WALLET-PUBLIC-KEY
CONTRACT_ADDRESS=YOUR-CONTRACT-ADDRESS
PINATA_JWT=YOUR-PINATA-JWT
ALCHEMY_PROVIDER=YOUR-ALCHEMY-PROVIDER-API-KEY
```
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
<!-- USAGE EXAMPLES -->
## Usage
Run the project
```
npm start
```
it will create the environment file based on your `.env`
<!-- deploy-contract anchor -->
<a name="deploy-contract"></a>
### Deploying the contract yourself
The smart contract is the file `MyNFT.sol`
First you need to compile the contract with the command
```sh
npm run compile-contract
```
Then you can deploy a new contract instance by running the command
```sh
npm run deploy-contract
```
note that, by default, this command deploy the contract on Goerli Testnet by running the `deploy.ts` script (you can see the command detail on `package.json` file)
### Automatic NFTs minting
If you want to quickly populate your smart contract with some NFTs whose CID was created earlier, you can compile the `pinataMintCid.json` file with the CID code you want to mint in your contract. Your Pokemon on Pinata have to follow this structure: `scripts/squirtle-example.json`, then place the CID in `pinataMintCid.json` file.
In order to start the minting process run
```sh
npm run mint
```
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
## Build
```sh
npm run build
```
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
## Deploy (Firebase)
First increase the version in package.json and build the project with the command above, then run
```sh
firebase deploy
```
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
<!-- CONTRIBUTING -->
## Contributing
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
Don't forget to give the project a star! Thanks again!
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
<!-- LICENSE -->
## License
Distributed under the MIT License. See `LICENSE.txt` for more information.
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
<!-- CONTACT -->
## Contact
Alberto Presenti - alberto.presenti@yahoo.it
Project Link: [https://github.com/Albenzoo/PokeCard-NFT](https://github.com/Albenzoo/PokeCard-NFT)
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
<!-- ACKNOWLEDGMENTS -->
## Acknowledgments
* [Alchemy - 7. How to build an NFT Marketplace from Scratch - Solidity and IPFS | Road to Web3](https://www.youtube.com/watch?v=y6JfVdcJh1k)
* [Ethereum.org - How to write and deploy an NFT](https://ethereum.org/en/developers/tutorials/how-to-write-and-deploy-an-nft/)
* [OpenZeppelin contract wizard](https://wizard.openzeppelin.com/#erc721)
* [Readme Template](https://github.com/othneildrew/Best-README-Template#readme-top)
* [Angular Material v13](https://v13.material.angular.io/components/categories)
* [Google Fonts - Icons](https://fonts.google.com/icons)
<p align="right">(<a href="#readme-top">back to top 🔝</a>)</p>
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[license-shield]: https://img.shields.io/github/license/othneildrew/Best-README-Template.svg?style=for-the-badge
[license-url]: https://github.com/Albenzoo/PokeCard-NFT/blob/master/LICENSE.txt
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555
[linkedin-url]: https://www.linkedin.com/in/albertopresenti/
[product-screenshot]: images/screenshot.png
[Angular.io]: https://img.shields.io/badge/Angular-DD0031?style=for-the-badge&logo=angular&logoColor=white
[Angular-url]: https://angular.io/
[web3js-logo]: https://img.shields.io/badge/Web3.js-E3632E?style=for-the-badge&logo=web3dotjs&logoColor=grey
[web3js-url]: https://web3js.readthedocs.io/en/v1.8.1/
[solidity-logo]: https://img.shields.io/badge/Solidity-363636?style=for-the-badge&logo=solidity&logoColor=grey
[solidity-url]: https://docs.soliditylang.org/en/v0.8.17/
[hardhat-logo]: https://img.shields.io/badge/Hardhat-FFF100?style=for-the-badge&logo=hardhat&logoColor=yellow
[hardhat-url]: https://hardhat.org/
[alchemy-logo]: https://img.shields.io/badge/Alchemy-5086F9?style=for-the-badge&logo=alchemy&logoColor=blue
[alchemy-url]: https://www.alchemy.com/
[pinata-logo]: https://img.shields.io/badge/Pinata-3FBBD7?style=for-the-badge&logo=pinata&logoColor=yellow
[pinata-url]: https://www.pinata.cloud/
|
package com.ibm.academy.microservices.entities;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "pabellon", schema = "universidad")
public class Pabellon implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "metros_cuadrados")
private Double metrosCuadrados;
@Column(name = "nombre")
private String nombre;
@Column(name = "fecha_creacion")
private Date fechaCreacion;
@Column(name = "fecha_modificaion")
private Date fechaModificacion;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "codigoPostal", column = @Column(name = "codigo_postal")),
@AttributeOverride(name = "departamento", column = @Column(name = "departamento"))
})
private Direccion direccion;
@OneToMany(mappedBy = "pabellon", fetch = FetchType.LAZY)
private Set<Aula> aulas;
public Pabellon(Integer id, Double metrosCuadrados, String nombre, Direccion direccion) {
this.id = id;
this.metrosCuadrados = metrosCuadrados;
this.nombre = nombre;
this.direccion = direccion;
}
@Override
public int hashCode() {
return Objects.hash(id, nombre);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pabellon other = (Pabellon) obj;
return Objects.equals(id, other.id) && Objects.equals(nombre, other.nombre);
}
@PrePersist
private void antesPersistir() {
this.fechaCreacion = new Date();
}
@PreUpdate
private void antesModificar() {
this.fechaModificacion = new Date();
}
private static final long serialVersionUID = 4934738782346303329L;
}
|
<template>
<v-container id="regular-tables" fluid tag="section">
<section class="mb-12 text-center">
<h1 class="font-weight-light mb-2 headline" v-text="`Daftar Event`" />
<span class="font-weight-light subtitle-1"> Table Daftar Event </span>
</section>
<div class="py-3" />
<material-card
color="success"
dark
icon="mdi-clipboard-plus"
title="Table Daftar Event"
class="px-5 py-3"
>
<v-simple-table>
<thead>
<tr>
<th>ID</th>
<th>Judul</th>
<th>Tanggal</th>
<th class="text-center">Lokasi</th>
<th class="text-center">Pendaftar</th>
<th class="text-right">Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(data, index) in listEvent" :key="index" :data="data">
<td>{{ data.id }}</td>
<td>{{ data.judul }}</td>
<td>{{ data.jadwal }}</td>
<td>{{ data.jml_tiket }}</td>
<td class="text-center">
<span class="red--text">{{ data.pendaftar }}</span
>/<span class="green--text">{{ data.jumlahKursi }}</span>
</td>
<td class="text-right">
<v-menu
transition="slide-x-transition"
bottom
right
:offset-y="offset"
>
<template v-slot:activator="{ on, attrs }">
<v-btn
class="grey"
color="primary"
dark
v-bind="attrs"
v-on="on"
>
...
</v-btn>
</template>
<v-list>
<v-list-item :to="`/event-org/detail-event/${data.id}`">
<v-list-item-title>Detail</v-list-item-title>
</v-list-item>
<v-list-item :to="`/event-org/EditEvent/${data.id}`">
<v-list-item-title>Edit</v-list-item-title>
</v-list-item>
<v-list-item @click="DeleteUser(data.id, index)">
<v-list-item-title>Cancel</v-list-item-title>
</v-list-item>
</v-list>
</v-menu>
</td>
</tr>
</tbody>
</v-simple-table>
</material-card>
</v-container>
</template>
<script>
import MaterialCard from "../../components/Card/MaterialCard.vue";
export default {
layout: "EoLayout",
name: "ListUser",
components: {
MaterialCard,
},
data() {
return {
// listEvent: [
// {
// id: 1,
// judul: "Event 1",
// nomorTiket: "20220516-321-111",
// tanggal: "23 Oktober 2022",
// lokasi: "Bandung",
// pendaftar: 14,
// jumlahKursi: 24,
// },
// {
// id: 2,
// judul: "Event 2",
// nomorTiket: "20220516-321-112",
// tanggal: "23 Oktober 2022",
// lokasi: "Bandung",
// pendaftar: 20,
// jumlahKursi: 36,
// },
// {
// id: 3,
// judul: "Event 3",
// nomorTiket: "20220516-321-113",
// tanggal: "23 Oktober 2022",
// lokasi: "Bandung",
// pendaftar: 9,
// jumlahKursi: 25,
// },
// ],
offset: true,
dialog3: false,
listEvent: [],
};
},
async fetch() {
await this.$axios.get("/event").then((res) => (this.listEvent = res.data));
},
methods: {
async search() {
try {
// await this.$axios
// .get("/search/?q=" + this.location)
// .then((res) => (this.datas = res.data.results));
} catch (e) {
this.error = e.response.data.message;
}
},
async DeleteUser(id, index) {
if (confirm("Do you really want to delete?")) {
await this.$axios.delete("/event/delete/" + id);
window.location.reload(true).catch((error) => {
console.log(error);
});
}
},
},
};
</script>
|
---
title: "12-5 LASSO Regression"
output: pdf_document
---
This markdown file contains the R codes for the Video: **12-5 LASSO Regression**. We have shown the slide number associated with each chunk of code for easy reference.
In this video, we will continue to work with the `boston_housing_price` data set. Before proceeding, place the data set `boston_housing_price.csv` in the `data` folder. This R markdown file itself, `12-5_LASSO_Regression.rmd`, should be placed in `src` folder.
### Load Libraries
In the following code, we load the required libraries: `car` is required for `vif()`. `corrplot` is required for `corrplot()`. And `plotmo` is required for `plot_glmnet()`.
```{r message=FALSE}
library(DescTools)
library(car) # for vif()
library(corrplot) # for corrplot()
library(glmnet)
library(plotmo) # for plot_glmnet()
```
### Load Data
In the following code, we load the data into `df.housing` as before and prepare it to be used for training with `glmnet()` function. Note that we use the same seed, 4991 so that we train the LASSO model on the same training data as the Ridge model.
```{r}
df.housing <- read.csv("../data/boston_housing_price.csv")
# Standardise the variables
scaler <- apply(df.housing, 2, sd)
df.housing0 <- df.housing
df.housing <- as.data.frame(apply(df.housing0, 2,
function (x)
x / sd(x)))
set.seed(4991)
rate <- 0.2
train.size <- round(nrow(df.housing) * rate)
sample <- sample(nrow(df.housing), train.size)
training <- df.housing[sample,]
test <- df.housing[-sample,]
train.x <- model.matrix(Price ~ ., data = training)[, -1]
train.y <- training[, ncol(training)]
test.x <- model.matrix(Price ~ ., data = test)[, -1]
test.y <- test[, ncol(test)]
```
### Slide 12
In the following code, we train a LASSO model with $\lambda=0.1$ with the `glmnet()` function. Note that the `alpha` parameter is set to 1, for LASSO regression, whereas it is set to 0 for Ridge regression.
```{r}
model_LASSO_trial1 <- glmnet(train.x,
train.y,
alpha = 1,
lambda = 0.1)
t(coef(model_LASSO_trial1))
```
### Slide 13
In the following code, we train a LASSO model with $\lambda=0.5$.
```{r}
model_LASSO_trial2 <- glmnet(train.x,
train.y,
alpha = 1,
lambda = 0.5)
t(coef(model_LASSO_trial2))
```
In the following code, we train a LASSO model with $\lambda=1$.
```{r}
model_LASSO_trial3 <- glmnet(train.x,
train.y,
alpha = 1,
lambda = 1)
t(coef(model_LASSO_trial3))
```
### Slide 14
In the following code, we compare the coefficients of `model_LASSO_trial1` ($\lambda=0.1$), `model_LASSO_trial2` ($\lambda=0.5$) and `model_LASSO_trial3` ($\lambda=1$).
```{r}
table_summary <- cbind(coef(model_LASSO_trial1),
coef(model_LASSO_trial2),
coef(model_LASSO_trial3))
colnames(table_summary) <- c("lambda = 0.1",
"lambda = 0.5",
"lambda = 1")
table_summary
```
## Slide 15
In the following code, we train 100 LASSO models from $\lambda=10^{-5}$ to $\lambda=1$.
```{r}
lambda <- 10^seq(-5, 0, length = 100)
LASSO_model <- glmnet(train.x, train.y, alpha = 1, lambda = lambda)
```
In the following code, we plot the coefficient of each predictor against $log(\lambda)$.
```{r}
add_lbs <- function(fit, offset_x=2.5) {
L <- length(fit$lambda)
x <- log(fit$lambda[L])+ offset_x
y <- fit$beta[, L] + c(0, -0.05, 0, 0.05, 0)
labs <- names(y)
text(x, y, labels=labs, cex=1)
}
plot(LASSO_model, xvar = "lambda", label = TRUE)
title(main="Coefficients of Predictors vs. Log(Lambda)",
cex.main=1.4, adj=0, line=3)
title(sub="Number of Predictors",
cex.sub=1.1,
adj=0.55, line=-21.5)
add_lbs(LASSO_model)
legend("topright", lwd = 1, col = 1:6,
legend = colnames(train.x), cex = .7)
```
## Slide 21
In the following code, we use a simpler method to generate the same plot of the coefficient of each predictor against $log(\lambda)$.
```{r}
plot_glmnet(LASSO_model)
```
## Slide 22
In the following code, we perform 10-fold cross-validation to determine the optimal value of $\lambda$. `lambda.min` is the $\lambda$ at which the smallest MSE is achieved; and `lambda.1se` is the largest lambda at which the MSE is within one standard error of the smallest MSE.
```{r}
set.seed(123)
cv_LASSO <- cv.glmnet(train.x, train.y,
alpha = 1, type.measure = "mse")
cv_LASSO
```
## Slide 23
In the following code, we visualise the relationship between $log(\lambda)$ and the Mean-Squared Error.
```{r}
# Generate plot
plot(cv_LASSO)
# Insert and label vertical line for lambda.min
abline(v=log(cv_LASSO$lambda.min), col = "red", lty=5)
text(log(cv_LASSO$lambda.min)- 0.3, 1.4,
labels= paste0("lambda_min = ",
round(cv_LASSO$lambda.min, digits = 3)), cex = 1.4)
# Insert and label vertical line for lambda.1se
abline(v=log(cv_LASSO$lambda.1se), col = "red", lty=5)
text(log(cv_LASSO$lambda.1se)- 0.3, 1.25,
labels= paste0("lambda_1se = ",
round(cv_LASSO$lambda.1se, digits = 3)) , cex = 1.4)
```
## Slide 25
In the following code, we train a LASSO model using `lambda.min` and return its coefficients.
```{r}
glm_LASSO <- glmnet(train.x, train.y,
alpha = 1, lambda = cv_LASSO$lambda.min)
t(coef(glm_LASSO))
```
## Slide 26
In the following code, we define the function `eval_results(fit, true)` to return the evaluation metrics for a given model.
```{r}
eval_results <- function(fit, true) {
actual <- data.matrix(true)
SSE <- sum((actual - fit)^2)
SST <- sum((actual - mean(actual))^2)
R_square <- 1 - SSE / SST
data.frame(
MSE = MSE(fit, true),
MAE = MAE(fit, true),
RMSE = RMSE(fit, true),
MAPE = MAPE(fit, true),
R2 = R_square
)
}
```
In the following code, we return the evaluation metrics for the LASSO model on the training data.
```{r}
fit <- predict(glm_LASSO, train.x)
true <- train.y
summary_LASSO_train <- eval_results(fit, true)
summary_LASSO_train
```
In the following code, we return the evaluation metrics for the LASSO model on the test data.
```{r}
fit <- predict(glm_LASSO, test.x)
true <- test.y
summary_LASSO_test <- eval_results(fit, true)[-5]
summary_LASSO_test
```
In the following code, we summarise the performances of the LASSO model on the training data and the test data.
```{r}
summary_LASSO <- rbind(summary_LASSO_train[-5], summary_LASSO_test)
rownames(summary_LASSO) <- c("LASSO_train", "LASSO_test")
knitr::kable(summary_LASSO, digits = 3)
```
## Slide 27
In the following code, we inspect the residuals from the LASSO model.
```{r}
# Obtain the fitted values
fit <- predict(glm_LASSO, train.x)
# Obtain the true values
true <- train.y
# Plot the residuals
plot(fit, true - fit,
main = "Residual Plot of the LASSO Regression Model on Training data",
xlab = "Fitted Value", ylab = "Residuals")
# Insert a horizontal lines to mark where the standardised residuals
# are equal to 0, 1 and -1 respectively.
abline(h = 0, col = "red", lwd = 2)
abline(h = 1, col = "red", lty = 2, lwd = 2)
abline(h = -1, col = "red", lty = 2, lwd = 2)
```
## Slide 28: Apply: Make Predictions
In the following code, we use the LASSO model to generate a prediction for a new data point.
```{r}
new_data <- data.frame(Crime_rate = 0.00632,
Industry = 2.31,
Number_of_rooms = 6.575,
Access_to_highways = 1,
Tax_rate = 296)
new_x <- data.matrix(new_data/scaler)
predict(glm_LASSO, new_x ) * scaler[6]
```
|
<?php
namespace Drupal\Core\Entity;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
/**
* Provides a repository for installed entity definitions.
*/
class EntityLastInstalledSchemaRepository implements EntityLastInstalledSchemaRepositoryInterface {
/**
* The key-value factory.
*
* @var \Drupal\Core\KeyValueStore\KeyValueFactoryInterface
*/
protected $keyValueFactory;
/**
* The cache backend.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected $cacheBackend;
/**
* The loaded installed entity type definitions.
*
* @var array|null
*/
protected $entityTypeDefinitions = NULL;
/**
* Constructs a new EntityLastInstalledSchemaRepository.
*
* @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_factory
* The key-value factory.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
* The cache backend.
*/
public function __construct(KeyValueFactoryInterface $key_value_factory, CacheBackendInterface $cache) {
$this->keyValueFactory = $key_value_factory;
$this->cacheBackend = $cache;
}
/**
* {@inheritdoc}
*/
public function getLastInstalledDefinition($entity_type_id) {
return $this->getLastInstalledDefinitions()[$entity_type_id] ?? NULL;
}
/**
* {@inheritdoc}
*/
public function getLastInstalledDefinitions() {
if ($this->entityTypeDefinitions) {
return $this->entityTypeDefinitions;
}
elseif ($cache = $this->cacheBackend->get('entity_type_definitions.installed')) {
$this->entityTypeDefinitions = $cache->data;
return $this->entityTypeDefinitions;
}
$all_definitions = $this->keyValueFactory->get('entity.definitions.installed')->getAll();
// Filter out field storage definitions.
$filtered_keys = array_filter(array_keys($all_definitions), function ($key) {
return substr($key, -12) === '.entity_type';
});
$entity_type_definitions = array_intersect_key($all_definitions, array_flip($filtered_keys));
// Ensure that the returned array is keyed by the entity type ID.
$keys = array_keys($entity_type_definitions);
$keys = array_map(function ($key) {
$parts = explode('.', $key);
return $parts[0];
}, $keys);
$this->entityTypeDefinitions = array_combine($keys, $entity_type_definitions);
$this->cacheBackend->set('entity_type_definitions.installed', $this->entityTypeDefinitions, Cache::PERMANENT);
return $this->entityTypeDefinitions;
}
/**
* {@inheritdoc}
*/
public function setLastInstalledDefinition(EntityTypeInterface $entity_type) {
$entity_type_id = $entity_type->id();
$this->keyValueFactory->get('entity.definitions.installed')->set($entity_type_id . '.entity_type', $entity_type);
$this->cacheBackend->delete('entity_type_definitions.installed');
$this->entityTypeDefinitions = NULL;
return $this;
}
/**
* {@inheritdoc}
*/
public function deleteLastInstalledDefinition($entity_type_id) {
$this->keyValueFactory->get('entity.definitions.installed')->delete($entity_type_id . '.entity_type');
// Clean up field storage definitions as well. Even if the entity type
// isn't currently fieldable, there might be legacy definitions or an
// empty array stored from when it was.
$this->keyValueFactory->get('entity.definitions.installed')->delete($entity_type_id . '.field_storage_definitions');
$this->cacheBackend->deleteMultiple(['entity_type_definitions.installed', $entity_type_id . '.field_storage_definitions.installed']);
$this->entityTypeDefinitions = NULL;
return $this;
}
/**
* {@inheritdoc}
*/
public function getLastInstalledFieldStorageDefinitions($entity_type_id) {
if ($cache = $this->cacheBackend->get($entity_type_id . '.field_storage_definitions.installed')) {
return $cache->data;
}
$definitions = $this->keyValueFactory->get('entity.definitions.installed')->get($entity_type_id . '.field_storage_definitions', []);
$this->cacheBackend->set($entity_type_id . '.field_storage_definitions.installed', $definitions, Cache::PERMANENT);
return $definitions;
}
/**
* {@inheritdoc}
*/
public function setLastInstalledFieldStorageDefinitions($entity_type_id, array $storage_definitions) {
$this->keyValueFactory->get('entity.definitions.installed')->set($entity_type_id . '.field_storage_definitions', $storage_definitions);
$this->cacheBackend->delete($entity_type_id . '.field_storage_definitions.installed');
}
/**
* {@inheritdoc}
*/
public function setLastInstalledFieldStorageDefinition(FieldStorageDefinitionInterface $storage_definition) {
$entity_type_id = $storage_definition->getTargetEntityTypeId();
$definitions = $this->getLastInstalledFieldStorageDefinitions($entity_type_id);
$definitions[$storage_definition->getName()] = $storage_definition;
$this->setLastInstalledFieldStorageDefinitions($entity_type_id, $definitions);
}
/**
* {@inheritdoc}
*/
public function deleteLastInstalledFieldStorageDefinition(FieldStorageDefinitionInterface $storage_definition) {
$entity_type_id = $storage_definition->getTargetEntityTypeId();
$definitions = $this->getLastInstalledFieldStorageDefinitions($entity_type_id);
unset($definitions[$storage_definition->getName()]);
$this->setLastInstalledFieldStorageDefinitions($entity_type_id, $definitions);
}
}
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'car_data.dart';
import 'car_detailed.dart';
class CarManageScreen extends StatefulWidget {
@override
_CarManageScreenState createState() => _CarManageScreenState();
}
class _CarManageScreenState extends State<CarManageScreen> {
final CategoriesScroller categoriesScroller = CategoriesScroller();
ScrollController controller = ScrollController();
bool closeTopContainer = false;
double topContainer = 0;
List<Widget> itemsData = [];
void getPostsData() {
List<dynamic> responseList = CAR_DATA;
List<Widget> listItems = [];
responseList.forEach((post) {
listItems.add(
Container(
height: 110,
margin: const EdgeInsets.symmetric(
horizontal: 50, vertical: 10), //vertical: 10選項間距
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
color: Color.fromARGB(255, 155, 164, 181),
boxShadow: [
BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 10.0),
]),
child: ListTile(
title: Text(
post["name"],
style: const TextStyle(
fontSize: 20,
color: Colors.white,
),
),
subtitle: Text(
post["brand"],
style: const TextStyle(
fontSize: 15,
color: Colors.white,
height: 2.0,
),
),
leading: Icon(
FontAwesomeIcons.ambulance,
color: Colors.white,
size: 35,
),
trailing: Icon(
Icons.arrow_forward_ios_rounded,
size: 30,
color: Colors.white,
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CarDetailedScreen(),
),
);
},
),
),
);
});
setState(() {
itemsData = listItems;
});
}
@override
void initState() {
super.initState();
getPostsData();
controller.addListener(() {
double value = controller.offset / 119;
setState(() {
topContainer = value;
closeTopContainer = controller.offset > 50;
});
});
}
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
final double categoryHeight = size.height * 0; //最上正方格
return Scaffold(
backgroundColor: Color.fromRGBO(57, 72, 103, 10),
appBar: AppBar(
title: Text('車輛管理'),
centerTitle: true,
elevation: 0,
backgroundColor: Color.fromRGBO(31, 60, 136, 40),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search, color: Colors.white),
onPressed: () {},
),
],
),
body: Container(
height: size.height,
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[],
),
const SizedBox(
height: 10,
),
AnimatedOpacity(
duration: const Duration(milliseconds: 200),
opacity: closeTopContainer ? 0 : 1,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: size.width,
alignment: Alignment.topCenter,
height: closeTopContainer ? 0 : categoryHeight,
child: categoriesScroller),
),
Expanded(
child: ListView.builder(
controller: controller,
itemCount: itemsData.length,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
double scale = 1.0;
return Opacity(
opacity: scale,
child: Transform(
transform: Matrix4.identity()..scale(scale, scale),
alignment: Alignment.bottomCenter,
child: Align(
// heightFactor: 0.7, 控制堆疊
// alignment: Alignment.topCenter,
child: itemsData[index]),
),
);
})),
],
),
),
);
}
}
class CategoriesScroller extends StatelessWidget {
const CategoriesScroller();
@override
Widget build(BuildContext context) {
final double categoryHeight =
MediaQuery.of(context).size.height * 0.30 - 50;
return SingleChildScrollView(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
child: FittedBox(
fit: BoxFit.fill,
alignment: Alignment.topCenter,
child: Row(
children: <Widget>[
Container(
width: 0,
margin: EdgeInsets.only(right: 20),
height: categoryHeight,
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.all(Radius.circular(20.0))),
),
],
),
),
),
);
}
}
|
package todo.list.entities;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String senha;
@Column(nullable = false)
private String nome;
@Column(nullable = false)
private Boolean enabled = true;
@Column(nullable = false)
private Date createdAt = new Date();
@Column(nullable = true)
private Date updatedAt;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Task> tasks;
public User() {
// User Empty Constructor
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Boolean getEnabled() {
return this.enabled;
}
public void setNome(Boolean enabled){
this.enabled = enabled;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((senha == null) ? 0 : senha.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result + ((enabled == null) ? 0 : enabled.hashCode());
result = prime * result + ((createdAt == null) ? 0 : createdAt.hashCode());
result = prime * result + ((updatedAt == null) ? 0 : updatedAt.hashCode());
result = prime * result + ((tasks == null) ? 0 : tasks.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (senha == null) {
if (other.senha != null)
return false;
} else if (!senha.equals(other.senha))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (enabled == null) {
if (other.enabled != null)
return false;
} else if (!enabled.equals(other.enabled))
return false;
if (createdAt == null) {
if (other.createdAt != null)
return false;
} else if (!createdAt.equals(other.createdAt))
return false;
if (updatedAt == null) {
if (other.updatedAt != null)
return false;
} else if (!updatedAt.equals(other.updatedAt))
return false;
if (tasks == null) {
if (other.tasks != null)
return false;
} else if (!tasks.equals(other.tasks))
return false;
return true;
}
}
|
let shopingBag = [];
let amountTotal = 0;
const shopingBagDiv = document.getElementById("shoping-bag");
const bagItemCount = document.querySelectorAll(".bag-item-count");
const allTotalAmount = document.getElementById("all-total-amount");
// quentity increment
const itemIncrement = (id, name, quantity, price, totalPrice) => {
const itemIndex = shopingBag.findIndex(item => item.id === id);
if (itemIndex !== -1) {
const updatedItem = { ...shopingBag[itemIndex] };
updatedItem.quantity++;
updatedItem.totalPrice = updatedItem.quantity * updatedItem.price;
shopingBag[itemIndex] = updatedItem;
amountTotal += updatedItem.price;
allTotalAmount.innerText = amountTotal;
// Update the cart display
bagCartShow(shopingBag);
}
};
// quentity decrement
const itemDecrement = (id, name, quantity, price, totalPrice) => {
if (quantity === 1) return;
const itemIndex = shopingBag.findIndex(item => item.id === id);
if (itemIndex !== -1) {
const updatedItem = { ...shopingBag[itemIndex] };
if (updatedItem.quantity > 1) {
updatedItem.quantity--;
updatedItem.totalPrice = updatedItem.quantity * updatedItem.price;
shopingBag[itemIndex] = updatedItem;
amountTotal -= updatedItem.price;
allTotalAmount.innerText = amountTotal;
// Update the cart display
bagCartShow(shopingBag);
}
}
};
// bag cart show on div
const bagCartShow = (items) => {
shopingBagDiv.innerHTML = items.map(item => (
`
<div class="relative rounded-md border-2 p-2 flex justify-between items-center gap-2">
<div class="">
<img src=${item.image} alt="Lionel-Messi" class="rounded-md h-28 w-16 object-cover" />
</div>
<div class="">
<div class="my-2">
<h1 class="font-semibold text-sm ">${item.name}</h1>
<p class="text-xs">${item.price}$/each</p>
</div>
<div>
<button class="bg-slate-100 text-black px-[6px] py-1 rounded-l"
onclick="itemDecrement('${item.id}', '${item.name}', ${item.quantity}, ${item.price}, ${item.totalPrice})"
>
-
</button>
<button class="bg-white text-black px-4 mx-[-5px] hover:cursor-auto">${item.quantity}</button>
<button class="bg-slate-100 text-black px-1 py-1 rounded-r"
onclick="itemIncrement('${item.id}', '${item.name}', ${item.quantity}, ${item.price}, ${item.totalPrice})">
+
</button>
</div>
</div>
<div class=" mt-[5.5rem]">
<p class="font-semibold text-sm"><span>${item.totalPrice}</span><span>$</span></p>
</div>
<div>
<button
class="fa-solid fa-trash text-red-500 bg-white p-[6px] rounded-md absolute right-[-8px] top-[-8px]"
onclick="removeFromCart('${item.id}', '${item.name}', ${item.quantity}, ${item.price}, ${item.totalPrice})">
</button>
</div>
</div>
`
)).join('');
};
// add to cart
function addToCart(button) {
// check sidebar is open or not
openSidebar()
button.disabled = true;
button.classList.add('bg-slate-500');
// Get information from the parent container
const cardContainer = button.parentNode.parentNode;
// return console.log('cardContainer:', cardContainer);
const name = cardContainer.querySelector('.text-xl').innerText;
const image = cardContainer.querySelector('img').src;
// Use the correct selector for the price
const priceText = cardContainer.querySelector('.my-3 p').innerText;
const price = parseFloat(priceText.replace('$', ''));
// Create the cardItem object
let cardItem = {
id: cardContainer.id,
name: name,
image: image,
quantity: 1,
price: price,
totalPrice: price,
};
shopingBag.push(cardItem);
amountTotal = amountTotal + cardItem.totalPrice
//
bagCartShow(shopingBag);
bagItemCount[0].innerText = shopingBag.length;
bagItemCount[1].innerText = shopingBag.length;
allTotalAmount.innerText = amountTotal
};
function removeFromCart(id, name, quantity, price, totalPrice) {
const restItems = shopingBag.filter(item => item.id !== id);
shopingBag = restItems;
amountTotal = amountTotal - totalPrice;
bagItemCount[0].innerText = shopingBag.length;
bagItemCount[1].innerText = shopingBag.length;
allTotalAmount.innerText = amountTotal
const cartComponent = document.getElementById(id);
const addToCartButton = cartComponent.querySelector('.bg-red-500.text-white.px-8.rounded-md.py-2.w-full.font-semibold');
// enable and color change
addToCartButton.classList.remove('bg-slate-500');
addToCartButton.disabled = false;
if (!shopingBag.length) {
shopingBagDiv.innerHTML = "";
}
else {
//
bagCartShow(shopingBag);
}
};
// bag open
function openSidebar() {
const bagSidebar = document.getElementById("bag-sidebar");
const isOpenAlready = bagSidebar.classList.contains("bag-sidebar-open");
if (isOpenAlready) return;
console.log('isOpenAlready:', isOpenAlready);
bagSidebar.classList.remove('bag-sidebar-closed');
bagSidebar.classList.add('bag-sidebar-open');
};
// bag closed
function closedSidebar() {
const bagSidebar = document.getElementById("bag-sidebar");
const isOpenAlready = bagSidebar.classList.contains("bag-sidebar-closed");
if (isOpenAlready) return;
bagSidebar.classList.remove('bag-sidebar-open');
bagSidebar.classList.add('bag-sidebar-closed');
};
// bag toggle
function openSidebarToggle() {
const bagSidebar = document.getElementById("bag-sidebar");
const isOpenAlready = bagSidebar.classList.contains("bag-sidebar-open");
if (isOpenAlready) {
closedSidebar()
}
else {
openSidebar()
}
};
// mobile Menu toggle
function openMobileMenuToggle() {
const mobileMenuSidebar = document.getElementById("mobile-menu-sidebar");
const isOpenAlready = mobileMenuSidebar.classList.contains("mobile-menu-sidebar-open");
if (isOpenAlready) {
mobileMenuSidebar.classList.remove('mobile-menu-sidebar-open');
mobileMenuSidebar.classList.add('mobile-menu-sidebar-closed');
}
else {
mobileMenuSidebar.classList.remove('mobile-menu-sidebar-closed');
mobileMenuSidebar.classList.add('mobile-menu-sidebar-open');
}
};
|
import Vapor
enum ParameterError: Swift.Error {
case invalidRange(min: Int, max: Int)
}
struct RandomIntQuery: Content {
let min: Int
let max: Int
var result: Int {
get throws {
guard min <= max else {
throw ParameterError.invalidRange(min: min, max: max)
}
return Int.random(in: min...max)
}
}
}
struct Payload: Content {
let min: Int
let max: Int
let result: Int?
let error: String?
init(from query: RandomIntQuery) {
self.min = query.min
self.max = query.max
do {
self.result = try query.result
self.error = nil
} catch ParameterError.invalidRange(min: _, max: _) {
self.error = "Invalid Range"
self.result = nil
} catch {
self.error = "Error"
self.result = nil
}
}
}
func routes(_ app: Application) throws {
app.get { (req) async throws -> View in
do {
let query = try req.query.decode(RandomIntQuery.self)
req.logger.info("Generating a random integer between \(query.min) and \(query.max)")
let payload = Payload(from: query)
return try await req.view.render("index", payload)
} catch {
return try await req.view.render("help")
}
}
app.get("hello") { req async -> String in
"Hello, world!"
}
}
|
/**
String matching:
If we want to to match against a general pattern in a string
- All emails ending in '@gmail.com'
- All names that begin with 'A'
The LIKE operator allows us to perform pattern matching against string data with the use
of wildard charcaters:
- Percent %
- Matches any sequence of characters
- Underscore _
- Matches any single character
All names that begin with an 'A' uppercase
- WHERE name LIKE 'A%'
All names that end with a lowercase 'a'
- WHERE name LIKE '%a'
LIKE is case sensitive, we can use ILIKE whis is case-insensitive.
Using the underscore allows us to replace
just a single character.
- Get all Mission Impossible films
- WHERE LIKE 'Mission Impossible _' Where we could match one, two, three etc...
You can use multiple underscores.
Imagine if we had version string codes in the format 'Version#A4', 'Version#B7, etc...
- WHERE value LIKE 'Version#__'
We can also combine pattern matching operators to create more complex patterns
- WHERE name LIKE '_her%'
- Cheryl
- Theresa
- Sherri
*/
-- Examples
-- Let's get all first names that start with s in both case and case-insensitive.
-- Case sensitive
SELECT * FROM customer
WHERE first_name LIKE 'S%' AND last_name LIKE 'M%';
-- Case insensitive
SELECT * FROM customer
WHERE first_name ILIKE 'S%' AND last_name ILIKE 'M%';
SELECT title FROM film;
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.4;
contract Voting {
address public manager;
string public agenda;
enum Option { Yes, No, Null, Abstain }
mapping (Option => address[]) private votes;
mapping (address => bool) private residents;
event VoteRecorded(address indexed voter, Option option);
modifier onlyManager() {
require(msg.sender == manager, "Only the manager can perform this action!");
_;
}
constructor (string memory _agenda){
manager = msg.sender;
agenda = _agenda;
}
/// @dev Allows a resident to cast their vote for a specific option.
/// @param _option The chosen voting option.
function vote(Option _option) public {
require(!residents[msg.sender], "Resident has already voted!");
votes[_option].push(msg.sender);
residents[msg.sender] = true;
emit VoteRecorded(msg.sender, _option);
}
/// @dev Gets the list of voters for a specific voting option.
/// @param _option The chosen voting option.
/// @return List of addresses that voted for the specified option.
function getResult(Option _option) public view returns (address[] memory) {
return votes[_option];
}
/// @dev Allows the manager to add a new resident to the voting system.
/// @param _newResident The address of the new resident.
function addResident(address _newResident) public onlyManager {
require(!residents[_newResident], "Resident already exists!");
residents[_newResident] = true;
}
/// @dev Allows the manager to remove a resident from the voting system.
/// @param _removedResident The address of the resident to be removed.
function removeResident(address _removedResident) public onlyManager {
require(residents[_removedResident], "Resident not found!");
residents[_removedResident] = false;
}
}
|
#Sentiment Analysis - Part 1
#We will makes few procedure to prepare the tweets for the Sentiment Analysis
#First of all, we install and load packages for language recognition
install.packages("cld2")
library(cld2)
library(tidyverse)
#Now we find the file address
all_twitter_files <- list.files(path = "CSV&Files", pattern = "tweets.", full.names = T)
#We read the file to prepare the dataframe
my_df <- read.csv(all_twitter_files)
#We filter the datas and keep just the texts and the languages
my_df <- my_df[,c("text", "lang")]
my_df$search <- gsub(pattern = "CSV&Files/tweets", replacement = "", all_twitter_files)
#We need to exclude the "NA" tweets (they were created probably due to errors in the scraping)
my_df <- my_df[!is.na(my_df$text),]
#We filter and reduce the languages to just english
my_df %>% count(lang)
my_df <- my_df %>% filter(lang == "en")
#We can now remove the info on language, because it's useless
my_df$lang <- NULL
#Finally we can save the dataframe in a file
save(my_df, file = "CSV&Files/TwitterforSA.RData")
|
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using WebAPI.DevsuTest.Util.Class;
using WebAPI.DevsuTest.Commons.CapaActual;
using WebAPI.DevsuTest.DTOs.Cuenta;
using WebAPI.DevsuTest.DTOs.Comunes;
using WebAPI.DevsuTest.Interfaces.Services;
namespace WebAPI.DevsuTest.Controllers
{
[Route("[controller]")]
[ApiController]
[SwaggerTag("API que expone métodos REST de Cuenta.")]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status408RequestTimeout)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[Produces("application/json")]
[SwaggerResponse(StatusCodes.Status400BadRequest, "Indica obtención no válida.", typeof(DToResponse<string>))]
[SwaggerResponse(StatusCodes.Status401Unauthorized, "No autorizado.", typeof(DToResponse<string>))]
[SwaggerResponse(StatusCodes.Status408RequestTimeout, "Excedió el Tiempo de espera.", typeof(DToResponse<string>))]
[SwaggerResponse(StatusCodes.Status500InternalServerError, "Error general", typeof(DToResponse<string>))]
public class CuentaController : Controller
{
private readonly ICuentaService l_CuentaService;
private readonly ICapaActualService l_CapaActualService;
public CuentaController(ICapaActualService pCapaActualService, ICuentaService pCuentaService)
{
l_CapaActualService = pCapaActualService;
l_CuentaService = pCuentaService;
l_CapaActualService.pCapaActualAsignar((byte)clsEnums.ENCapaOrigenLogError.CapaControlador);
}
[HttpPost]
[Route("CuentaInsertar")]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerOperation(
Summary = "Cuenta Insertar",
Description = "Registra una nueva Cuenta.",
OperationId = "CuentaInsertar",
Tags = new[] { "Cuenta" })]
[SwaggerResponse(StatusCodes.Status200OK, "Inserción correcta de datos.", typeof(DToResponse<long>))]
[SwaggerResponse(StatusCodes.Status400BadRequest, "Inserción no válida.", typeof(DToResponse<long>))]
public async Task<DToResponse<long>> CuentaInsertar([FromBody, SwaggerRequestBody("Datos Cuenta", Required = true)] DToCuenta pobjDToCuenta, CancellationToken pCancellationToken)
{
return await l_CuentaService.SVCuentaInsertar(pobjDToCuenta, pCancellationToken);
}
[HttpGet]
[Route("CuentaObtener")]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerOperation(
Summary = "Cuenta Obtener",
Description = "Obtiene los datos de una Cuenta.",
OperationId = "CuentaObtener",
Tags = new[] { "Cuenta" })]
[SwaggerResponse(StatusCodes.Status200OK, "Obtención correcta de datos.", typeof(DToResponse<DToCuenta>))]
[SwaggerResponse(StatusCodes.Status400BadRequest, "Obtención no válida.", typeof(DToResponse<DToCuenta>))]
public async Task<DToResponse<DToCuenta>> CuentaObtener([FromQuery] long plngIdCuenta, CancellationToken pCancellationToken)
{
return await l_CuentaService.SVCuentaObtener(plngIdCuenta, pCancellationToken);
}
[HttpGet]
[Route("CuentaListar")]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerOperation(
Summary = "Cuenta Listar",
Description = "Lista las cuentas de un Cliente.",
OperationId = "CuentaListar",
Tags = new[] { "Cuenta" })]
[SwaggerResponse(StatusCodes.Status200OK, "Listado correcto de datos.", typeof(DToResponse<List<DToCuenta>>))]
[SwaggerResponse(StatusCodes.Status400BadRequest, "Listado no válido.", typeof(DToResponse<List<DToCuenta>>))]
public async Task<DToResponse<List<DToCuenta>>> CuentaListar([FromQuery] int pintIdCliente, CancellationToken pCancellationToken)
{
return await l_CuentaService.SVCuentaListar(pintIdCliente, pCancellationToken);
}
[HttpDelete]
[Route("CuentaEliminar")]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerOperation(
Summary = "Cuenta Eliminar",
Description = "Elimina una cuenta.",
OperationId = "CuentaEliminar",
Tags = new[] { "Cuenta" })]
[SwaggerResponse(StatusCodes.Status200OK, "Eliminación correcta de datos.", typeof(DToResponse<bool>))]
[SwaggerResponse(StatusCodes.Status400BadRequest, "Eliminación no válida.", typeof(DToResponse<bool>))]
public async Task<DToResponse<bool>> CuentaEliminar([FromQuery] long plngIdCuenta, CancellationToken pCancellationToken)
{
return await l_CuentaService.SVCuentaEliminar(plngIdCuenta, pCancellationToken);
}
}
}
|
/******************************************************************************
* Copyright (c) 2014, Hobu Inc. (hobu@hobu.co)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <pdal/pdal_test_main.hpp>
#include <random>
#include <pdal/PipelineManager.hpp>
#include <pdal/StageWrapper.hpp>
#include <io/LasReader.hpp>
#include <io/LasWriter.hpp>
#include <filters/SortFilter.hpp>
#include "Support.hpp"
using namespace pdal;
namespace
{
void doSort(point_count_t count, Dimension::Id dim,
const std::string & order="")
{
Options opts;
opts.add("dimension", Dimension::name(dim));
if (!order.empty())
opts.add("order", order);
SortFilter filter;
filter.setOptions(opts);
PointTable table;
PointViewPtr view(new PointView(table));
table.layout()->registerDim(dim);
table.finalize();
std::default_random_engine generator;
std::uniform_real_distribution<double> dist(0.0, (double)count);
for (PointId i = 0; i < count; ++i)
view->setField(dim, i, dist(generator));
filter.prepare(table);
FilterWrapper::ready(filter, table);
FilterWrapper::filter(filter, *view.get());
FilterWrapper::done(filter, table);
EXPECT_EQ(count, view->size());
for (PointId i = 1; i < count; ++i)
{
double d1 = view->getFieldAs<double>(dim, i - 1);
double d2 = view->getFieldAs<double>(dim, i);
if (order.empty() || order == "ASC")
EXPECT_TRUE(d1 <= d2);
else // DES(cending)
EXPECT_TRUE(d1 >= d2);
}
}
} // unnamed namespace
TEST(SortFilterTest, simple)
{
// note that this also tests default sort order ASC /**
for (point_count_t count = 3; count < 8; count++)
doSort(count, Dimension::Id::X);
}
TEST(SortFilterTest, testUnknownOptions)
{
EXPECT_THROW(doSort(1, Dimension::Id::X, "not an order"), std::exception);
}
TEST(SortFilterTest, pipelineJSON)
{
PipelineManager mgr;
mgr.readPipeline(Support::configuredpath("filters/sort.json"));
mgr.execute();
PointViewSet viewSet = mgr.views();
EXPECT_EQ(viewSet.size(), 1u);
PointViewPtr view = *viewSet.begin();
for (PointId i = 1; i < view->size(); ++i)
{
double d1 = view->getFieldAs<double>(Dimension::Id::X, i - 1);
double d2 = view->getFieldAs<double>(Dimension::Id::X, i);
EXPECT_TRUE(d1 <= d2);
}
}
TEST(SortFilterTest, issue1382)
{
LasReader r;
Options ro;
ro.add("filename", Support::datapath("autzen/autzen-utm.las"));
r.setOptions(ro);
SortFilter f;
Options fo;
fo.add("dimension", "Z");
f.setOptions(fo);
f.setInput(r);
LasWriter w;
Options wo;
wo.add("filename", Support::temppath("out.las"));
w.setOptions(wo);
w.setInput(f);
PointTable t;
w.prepare(t);
PointViewSet s = w.execute(t);
PointViewPtr v = *s.begin();
for (PointId i = 1; i < v->size(); ++i)
{
double d1 = v->getFieldAs<double>(Dimension::Id::Z, i - 1);
double d2 = v->getFieldAs<double>(Dimension::Id::Z, i);
EXPECT_TRUE(d1 <= d2);
}
}
TEST(SortFilterTest, issue1121_simpleSortOrderDesc)
{
point_count_t inc = 1;
for (point_count_t count = 3; count < 100000; count += inc, inc *= 2)
{
doSort(count, Dimension::Id::X, "ASC");
doSort(count, Dimension::Id::X, "DESC");
}
}
|
/// <reference types="@microsoft/msfs-types/js/avionics" />
import {
AbstractMapWaypointIcon, AbstractMapWaypointIconOptions, MapProjection, MapWaypointSpriteIcon, NavMath, ReadonlyFloat64Array, Subscribable, SubscribableUtils,
Waypoint
} from '@microsoft/msfs-sdk';
import { AirportWaypoint } from '../../navigation/AirportWaypoint';
/**
* An airport icon.
*/
export class MapAirportIcon<T extends AirportWaypoint> extends MapWaypointSpriteIcon<T> {
/**
* Constructor.
* @param waypoint The waypoint associated with this icon.
* @param priority The render priority of this icon. Icons with higher priorities should be rendered above those
* with lower priorities.
* @param img The image to use for the icon.
* @param size The size of this icon, as `[width, height]` in pixels, or a subscribable which provides it.
* @param options Options with which to initialize this icon.
*/
constructor(
waypoint: T,
priority: number | Subscribable<number>,
img: HTMLImageElement,
size: ReadonlyFloat64Array | Subscribable<ReadonlyFloat64Array>,
options?: AbstractMapWaypointIconOptions
) {
super(waypoint, priority, img, 32, 32, size, options);
}
// eslint-disable-next-line jsdoc/require-jsdoc
protected getSpriteFrame(mapProjection: MapProjection): number {
if (!this.waypoint.longestRunway) {
return 0;
}
const mapRotationDeg = mapProjection.getRotation() * Avionics.Utils.RAD2DEG;
return Math.round(NavMath.normalizeHeading((this.waypoint.longestRunway.direction + mapRotationDeg)) / 22.5) % 8;
}
}
/**
* Initialization options for a MapWaypointHighlightIcon.
*/
export type MapWaypointHighlightIconOptions = {
/** The buffer of the ring around the base icon, in pixels. */
ringRadiusBuffer?: number | Subscribable<number>;
/** The width of the stroke for the ring, in pixels. */
strokeWidth?: number | Subscribable<number>;
/** The color of the stroke for the ring. */
strokeColor?: string | Subscribable<string>;
/** The width of the outline for the ring, in pixels. */
outlineWidth?: number | Subscribable<number>;
/** The color of the outline for the ring. */
outlineColor?: string | Subscribable<string>;
/** The color of the ring background. */
bgColor?: string | Subscribable<string>;
}
/**
* An icon for a highlighted waypoint. This icon embellishes a pre-existing ("base") icon with a surrounding ring and
* background.
*/
export class MapWaypointHighlightIcon<T extends Waypoint> extends AbstractMapWaypointIcon<T> {
/** The buffer of the ring around this icon's base icon, in pixels. */
public readonly ringRadiusBuffer: Subscribable<number>;
/** The width of the stroke for this icon's ring, in pixels. */
public readonly strokeWidth: Subscribable<number>;
/** The color of the stroke for this icon's ring. */
public readonly strokeColor: Subscribable<string>;
/** The width of the outline for this icon's ring, in pixels. */
public readonly outlineWidth: Subscribable<number>;
/** The color of the outline for this icon's ring. */
public readonly outlineColor: Subscribable<string>;
/** The color of this icon's ring background. */
public readonly bgColor: Subscribable<string>;
/**
* Constructor.
* @param baseIcon This icon's base waypoint icon.
* @param priority The render priority of this icon. Icons with higher priorities should be rendered above those
* with lower priorities.
* @param options Options with which to initialize this icon.
*/
constructor(
private readonly baseIcon: AbstractMapWaypointIcon<T>,
priority: number | Subscribable<number>,
options?: MapWaypointHighlightIconOptions
) {
super(baseIcon.waypoint, priority, baseIcon.size, { offset: baseIcon.offset, anchor: baseIcon.anchor });
this.ringRadiusBuffer = SubscribableUtils.toSubscribable(options?.ringRadiusBuffer ?? 0, true);
this.strokeWidth = SubscribableUtils.toSubscribable(options?.strokeWidth ?? 2, true);
this.strokeColor = SubscribableUtils.toSubscribable(options?.strokeColor ?? 'white', true);
this.outlineWidth = SubscribableUtils.toSubscribable(options?.outlineWidth ?? 0, true);
this.outlineColor = SubscribableUtils.toSubscribable(options?.outlineColor ?? 'black', true);
this.bgColor = SubscribableUtils.toSubscribable(options?.bgColor ?? '#3c3c3c', true);
}
/** @inheritdoc */
protected drawIconAt(context: CanvasRenderingContext2D, mapProjection: MapProjection, left: number, top: number): void {
const size = this.baseIcon.size.get();
const radius = Math.hypot(size[0], size[1]) / 2 + this.ringRadiusBuffer.get();
const x = left + size[0] / 2;
const y = top + size[1] / 2;
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI);
this.drawRingBackground(context);
this.baseIcon.draw(context, mapProjection);
this.drawRing(context);
}
/**
* Draws the ring background for this icon.
* @param context A canvas rendering context.
*/
private drawRingBackground(context: CanvasRenderingContext2D): void {
context.fillStyle = this.bgColor.get();
context.fill();
}
/**
* Draws the ring for this icon.
* @param context A canvas rendering context.
*/
private drawRing(context: CanvasRenderingContext2D): void {
const outlineWidth = this.outlineWidth.get();
const strokeWidth = this.strokeWidth.get();
if (outlineWidth > 0) {
this.applyStroke(context, (strokeWidth + 2 * outlineWidth), this.outlineColor.get());
}
this.applyStroke(context, strokeWidth, this.strokeColor.get());
}
/**
* Applies a stroke to a canvas rendering context.
* @param context A canvas rendering context.
* @param lineWidth The width of the stroke.
* @param strokeStyle The style of the stroke.
*/
private applyStroke(context: CanvasRenderingContext2D, lineWidth: number, strokeStyle: string | CanvasGradient | CanvasPattern): void {
context.lineWidth = lineWidth;
context.strokeStyle = strokeStyle;
context.stroke();
}
}
|
package com.carlostorres.comprayventa
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.carlostorres.comprayventa.databinding.ActivitySeleccionarUbicacionBinding
import com.google.android.gms.common.api.Status
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.PlacesClient
import com.google.android.libraries.places.widget.AutocompleteSupportFragment
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener
class SeleccionarUbicacionActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var binding: ActivitySeleccionarUbicacionBinding
private companion object {
private const val DEFAULT_ZOOM = 15
}
private var mMap: GoogleMap? = null
private var mPlaceClient: PlacesClient? = null
private var mFusedLocationProviderClient: FusedLocationProviderClient? = null
private var mLastKnownLocation: Location? = null
private var selectedLatitude: Double? = null
private var selectedLongitude: Double? = null
private var direction = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySeleccionarUbicacionBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.llListo.visibility = View.GONE
val mapFragment =
supportFragmentManager.findFragmentById(R.id.mapFragment) as SupportMapFragment
mapFragment.getMapAsync(this)
Places.initialize(this, getString(R.string.mi_maps_key))
mPlaceClient = Places.createClient(this)
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
val autocompleteSupportMapFragment =
supportFragmentManager.findFragmentById(R.id.autocompletar_fragment)
as AutocompleteSupportFragment
val placeList = arrayOf(
Place.Field.ID,
Place.Field.NAME,
Place.Field.ADDRESS,
Place.Field.LAT_LNG
)
autocompleteSupportMapFragment.setPlaceFields(listOf(*placeList))
autocompleteSupportMapFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener{
override fun onPlaceSelected(place: Place) {
val id = place.id
val name = place.name
val latlng = place.latLng
selectedLatitude = latlng?.latitude
selectedLongitude = latlng?.longitude
direction = place.address ?: ""
agregarMarcador(latlng, name, direction)
}
override fun onError(p0: Status) {
Toast.makeText(applicationContext, "Busqueda Cancelada", Toast.LENGTH_SHORT).show()
}
})
binding.ibGps.setOnClickListener {
if (esGpsActivado()){
solicitarPermisoLocacion.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}else{
Toast.makeText(this, "La ubicacion no esta activada", Toast.LENGTH_SHORT).show()
}
}
binding.btnListo.setOnClickListener {
val intent = Intent()
intent.putExtra("latitud", selectedLatitude)
intent.putExtra("longitud", selectedLongitude)
intent.putExtra("direccion", direction)
setResult(Activity.RESULT_OK, intent)
finish()
}
}
private fun elegirLugarActual(){
if (mMap == null){
return
}
detectAndShowDiviceLocationMap()
}
@SuppressLint("MissingPermission")
private fun detectAndShowDiviceLocationMap(){
try {
val locationResult = mFusedLocationProviderClient!!.lastLocation
locationResult.addOnSuccessListener { location ->
if (location != null){
mLastKnownLocation = location
selectedLatitude = location.latitude
selectedLongitude = location.longitude
val latLng = LatLng(selectedLatitude!!, selectedLongitude!!)
mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM.toFloat()))
mMap!!.animateCamera(CameraUpdateFactory.zoomTo(DEFAULT_ZOOM.toFloat()))
directionLatlng(latLng)
}
}.addOnFailureListener {
}
}catch (e:Exception){
}
}
private fun esGpsActivado(): Boolean {
val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
var gpsEnable = false
var networkEnable = false
try {
gpsEnable = lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
}catch (e:Exception){
}
try {
networkEnable = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}catch (e:Exception){
}
return !(!gpsEnable && !networkEnable)
}
@SuppressLint("MissingPermission")
private val solicitarPermisoLocacion : ActivityResultLauncher<String> =
registerForActivityResult(ActivityResultContracts.RequestPermission()){
if (it){
mMap!!.isMyLocationEnabled = true
elegirLugarActual()
}else{
Toast.makeText( this, "Permiso Denegado", Toast.LENGTH_SHORT).show()
}
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
solicitarPermisoLocacion.launch(Manifest.permission.ACCESS_FINE_LOCATION)
mMap!!.setOnMapClickListener { latlng ->
selectedLatitude = latlng.latitude
selectedLongitude = latlng.longitude
directionLatlng(latlng)
}
}
private fun directionLatlng(latlng: LatLng) {
val geoCoder = Geocoder(this)
try {
val addressList = geoCoder.getFromLocation(latlng.latitude, latlng.longitude, 1)
val address = addressList!![0]
val addressLine = address.getAddressLine(0)
val subLocality = address.subLocality
direction = addressLine
agregarMarcador(latlng, subLocality, addressLine)
}catch (e:Exception){
}
}
private fun agregarMarcador(latlng: LatLng, titulo: String, direccion: String) {
mMap!!.clear()
try {
val markerOptions = MarkerOptions()
markerOptions.position(latlng)
markerOptions.title(titulo)
markerOptions.snippet(direccion)
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
mMap!!.addMarker(markerOptions)
mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, DEFAULT_ZOOM.toFloat()))
binding.llListo.visibility = View.VISIBLE
binding.tvLugarSelec.text = direccion
}catch (e:Exception){
}
}
}
|
## Note
nid: 1467927076561
model: AnKingOverhaul
tags: #AK_Original_Decks::Step_1::Zanki_Step_Decks::Zanki_Biochemistry::Molecular,_Cellular,_Genetics, #AK_Step1_v11::#B&B::06_Cell_Bio::01_Molecular::04_Transcription, #AK_Step1_v11::#FirstAid::01_Biochemistry::01_Molecular::12_RNA_Processing, #AK_Step1_v11::#FirstAid::01_Biochemistry::01_Molecular::12_RNA_Processing::Eukaryotes, #AK_Step1_v11::#NBME::16, #AK_Step1_v11::#OME_banner, #AK_Step1_v11::#Physeo::05_Biochem::01_Molecular_Biology::03_Transcription, #AK_Step1_v11::#SketchyBiochem::03_Molecular_Biology::02_RNA::02_Transcription_and_RNA_Processing, #AK_Step1_v11::^Other::^EXPN::BGedit, #AK_Step1_v11::^Other::^EXPN::Uworld, #AK_Step1_v11::^Other::^HighYield::2-RelativelyHighYield, #AK_Step1_v11::^Systems::Biochem::Molecular
markdown: false
### Text
<div>
<div>
<div>
One <i>co-transcriptional modification</i> is the addition of
a(n) <b>{{c1::7-methylguanosine cap}}</b> at the
<b>{{c2::5}}' end</b>
</div>
</div>
</div>
### Extra
<img src="paste-106424994627687.jpg">
<div>
- occurs in 2 stages, adding GTP, then methylation
</div>
<div>
- capping occurs in the nucleus as RNA is being transcribed;
functions as protection against cellular degradation / allow
escape from nucleus
</div>
### Lecture Notes
### Missed Questions
### Pathoma
### Boards and Beyond
### First Aid
<img src="tmppKZuWy.png">
### Sketchy
<img src="Transcription%20and%20RNA%20Processing.png"> <img src=
"Screen%20Shot%202022-01-30%20at%2010.00.14%20AM.png"> <a href=
"https://dashboard.sketchy.com/study/medical/courses/medical-biochemistry/units/medical-biochemistry-molecular-biology/videos/medical-biochemistry-molecular-biology-rna-transcription-and-rna-processing?utm_source=anki&utm_medium=partnership&utm_campaign=february_update&utm_content=medical">
Watch Transcription and RNA Processing</a>
### Pixorize
### Physeo
### OME
<div class="ome-widget">
<a href="https://onlinemeded.org?ref=anki"><img src=
"_OME_AnkiFlashcards_General_3.png"></a>
</div>
### Additional Resources
### One by one
|
import { InputFieldType, INPUT_TYPE_NONE, PageInputMaxCount } from '../../constants';
import { findPasswordInputs, findUsernameInputs, findVisibleInputs, getInputType } from './dom';
import { toPrecision } from './numbers';
export interface GeoType {
top: number;
topP?: number;
left: number;
leftP?: number;
width: number;
widthP?: number;
height: number;
heightP?: number
};
export interface GeoPrefixType {
[key: string]: number;
}
export interface NearestType {
typeNearestX?: string;
typeNearestY?: string;
distNearestX: number;
distNearestY: number;
distNearestXP?: number;
distNearestYP?: number;
};
export interface SpacialType {
xP: number; // coordinate x percentage
yP: number; // coordinate y percentage
wP: number; // width percentage
hP: number; // height percentage
type: InputFieldType; // it is username input or password input
}
export const addKeyPrefix = (key: string, prefix: string = '') => `${prefix}${key}`;
/**
* get geometry features, for one input, return
* {
* top: x
* topp: x%
* left: x
* leftp: x%
* width: x
* widthp: x%
* height: x
* heightp: x%
* }
* TODO: if input is in iframe, the geometry info should still base on top document
* @param inputs
*/
export const getGeoFeature = (element: HTMLElement, useRatio: boolean = true, keyPrefix: string = ''): GeoPrefixType => {
if (!element) {
const geo = {
[addKeyPrefix('top', keyPrefix)]: 0,
[addKeyPrefix('left', keyPrefix)]: 0,
[addKeyPrefix('width', keyPrefix)]: 0,
[addKeyPrefix('height', keyPrefix)]: 0
};
const geoP = {
[addKeyPrefix('topP', keyPrefix)]: 0,
[addKeyPrefix('leftP', keyPrefix)]: 0,
[addKeyPrefix('widthP', keyPrefix)]: 0,
[addKeyPrefix('heightP', keyPrefix)]: 0
};
return useRatio ? geoP : geo;
}
const bodyRect = document.body.getBoundingClientRect();
const rect = element.getBoundingClientRect();
const geo = {
[addKeyPrefix('top', keyPrefix)]: toPrecision(rect.top),
[addKeyPrefix('left', keyPrefix)]: toPrecision(rect.left),
[addKeyPrefix('width', keyPrefix)]: toPrecision(rect.width),
[addKeyPrefix('height', keyPrefix)]: toPrecision(rect.height)
}
if (bodyRect.height === 0 || bodyRect.width === 0) {
console.log('document body size = 0');
const geoP = {
[addKeyPrefix('topP', keyPrefix)]: 0,
[addKeyPrefix('leftP', keyPrefix)]: 0,
[addKeyPrefix('widthP', keyPrefix)]: 1,
[addKeyPrefix('heightP', keyPrefix)]: 1
}
return useRatio ? geoP : geo;
}
const geoP = {
[addKeyPrefix('topP', keyPrefix)]: toPrecision(rect.top / bodyRect.height),
[addKeyPrefix('leftP', keyPrefix)]: toPrecision(rect.left / bodyRect.width),
[addKeyPrefix('widthP', keyPrefix)]: toPrecision(rect.width / bodyRect.width),
[addKeyPrefix('heightP', keyPrefix)]: toPrecision(rect.height / bodyRect.height)
}
return useRatio ? geoP : geo;
};
export const getOffset = (source: HTMLElement, destination: HTMLElement, useRatio: boolean = true, keyPrefix: string = '') => {
const sourceGeo: GeoType = getGeoFeature(source, useRatio, '') as unknown as GeoType;
const destGeo: GeoType = getGeoFeature(destination, useRatio, '') as unknown as GeoType;
const sourceLeft = useRatio ? sourceGeo.leftP : sourceGeo.left;
const sourceWidth = useRatio ? sourceGeo.widthP : sourceGeo.width;
const sourceTop = useRatio ? sourceGeo.topP : sourceGeo.top;
const sourceHeight = useRatio ? sourceGeo.heightP : sourceGeo.height;
const destLeft = useRatio ? destGeo.leftP : destGeo.left;
const destWidth = useRatio ? destGeo.widthP : destGeo.width;
const destTop = useRatio ? destGeo.topP : destGeo.top;
const destHeight = useRatio ? destGeo.heightP : destGeo.height;
const sourceCenterX = sourceLeft + sourceWidth / 2;
const sourceCenterY = sourceTop + sourceHeight / 2;
const destCenterX = destLeft + destWidth / 2;
const destCenterY = destTop + destHeight / 2;
const offsetX = destCenterX - sourceCenterX;
const offsetY = destCenterY - sourceCenterY;
return {
[addKeyPrefix('offsetX', keyPrefix)]: toPrecision(offsetX),
[addKeyPrefix('offsetY', keyPrefix)]: toPrecision(offsetY)
};
};
/**
* get the sorted elements by distance on axis
* by default on x-axis
* @param element
* @param targets
* @param axis
*/
export const sortElementsByDistanceOnAxis = (element: HTMLElement, targets: HTMLElement[], useRatio: boolean = true, axis: number = 0): HTMLElement[] => {
const rect = getGeoFeature(element);
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const sortedTargets = targets.sort((a, b) => {
const rectA = getGeoFeature(a, useRatio);
const rectB = getGeoFeature(b, useRatio);
const centerXA = rectA.left + rectA.width / 2;
const centerYA = rectA.top + rectA.height / 2;
const centerXB = rectB.left + rectB.width / 2;
const centerYB = rectB.top + rectB.height / 2;
if (axis == 0) {
// sort by X axis
const distXA = Math.abs(centerX - centerXA);
const distXB = Math.abs(centerX - centerXB);
return distXA - distXB;
} else if (axis == 1) {
// sort by Y axis
const distYA = Math.abs(centerY - centerYA);
const distYB = Math.abs(centerY - centerYB);
return distYA - distYB;
} else {
// sort by distance
const distA = Math.sqrt(Math.pow(centerX - centerXA, 2) + Math.pow(centerY - centerYA, 2));
const distB = Math.sqrt(Math.pow(centerX - centerXB, 2) + Math.pow(centerY - centerYB, 2));
return distA - distB;
}
});
return sortedTargets;
};
export const getNearestInfo = (element: HTMLElement, inputs: HTMLInputElement[]): NearestType => {
if (inputs.length === 0) {
return {
distNearestX: -200,
distNearestY: -200,
distNearestXP: -1,
distNearestYP: -1
};
}
let distNearestX = Number.MAX_SAFE_INTEGER;
let distNearestY = Number.MAX_SAFE_INTEGER;
let distNearestXP = 1;
let distNearestYP = 1;
const rect = getGeoFeature(element);
const bodyRect = document.body.getBoundingClientRect();
// filter the input out from the inputs
inputs = inputs.filter(ipt => ipt != element);
const rects = inputs.map(ipt => getGeoFeature(ipt));
const cx = rect.left + rect.width / 2;
const cy = rect.top + rect.height / 2;
rects.forEach((r, i) => {
const rcx = r.left + r.width / 2;
const rcy = r.top + r.height / 2;
// distance from rect to r
// please note that the distance is directional
// if distance > 0: the nearest input is on the RIGHT/BOTTOM of the target
// if distance < 0: the nearest input is on the LEFT/TOP of the target
const distX = rcx - cx;
const distY = rcy - cy;
if (Math.abs(distX) < Math.abs(distNearestX)) {
distNearestX = distX;
distNearestXP = bodyRect.width > 0 ? distNearestX / bodyRect.width : 1;
}
if (Math.abs(distY) < Math.abs(distNearestY)) {
distNearestY = distY;
distNearestYP = bodyRect.height > 0 ? distNearestY / bodyRect.height : 1;
}
});
return {
distNearestX: toPrecision(distNearestX),
distNearestY: toPrecision(distNearestY),
distNearestXP: toPrecision(distNearestXP),
distNearestYP: toPrecision(distNearestYP)
};
};
export const PaddingSpacialFeature: SpacialType = {
xP: 0,
yP: 1,
wP: 0,
hP: 0,
type: InputFieldType.other
};
export const getUsernamePasswordGeoFeature = (visibleInputs: HTMLInputElement[]): SpacialType[] => {
const usernameInputs = findUsernameInputs(visibleInputs);
const passwordInputs = findPasswordInputs(visibleInputs);
const usernameGeo = usernameInputs.map(input => getGeoFeature(input));
const passwordGeo = passwordInputs.map(input => getGeoFeature(input));
const usernameFeature = usernameGeo.map(geo => ({
xP: toPrecision(geo.leftP),
yP: toPrecision(geo.topP),
wP: toPrecision(geo.widthP),
hP: toPrecision(geo.heightP),
type: InputFieldType.username
}));
const passwordFeature = passwordGeo.map(geo => ({
xP: toPrecision(geo.leftP),
yP: toPrecision(geo.topP),
wP: toPrecision(geo.widthP),
hP: toPrecision(geo.heightP),
type: InputFieldType.password
}));
let allInputFeature: SpacialType[] = [];
const allInputCount = usernameFeature.length + passwordFeature.length;
if (allInputCount <= PageInputMaxCount) {
allInputFeature = [...usernameFeature, ...passwordFeature]
.concat(Array(PageInputMaxCount-allInputCount).fill(PaddingSpacialFeature));
} else {
// username + password input count is larger than 10, add each of them
let inputAdded = 0;
let usernameIdx = 0;
let passwordIdx = 0;
let featureIdx = 0
while (inputAdded < PageInputMaxCount) {
const username = usernameFeature[usernameIdx];
const password = passwordFeature[passwordIdx];
if (featureIdx % 2 == 0) {
if (username) {
allInputFeature.push(username);
inputAdded++;
usernameIdx++
}
} else {
if (password) {
allInputFeature.push(password);
inputAdded++;
passwordIdx++
}
}
featureIdx++;
}
}
// sort the inputs from top to bottom
allInputFeature.sort((a, b) => a.yP - b.yP);
return allInputFeature;
};
|
package ma.nourlab.earthquakealarm.service;
import ma.nourlab.earthquakealarm.domain.MessageInfo;
import ma.nourlab.earthquakealarm.infrastructure.repository.MessageRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@SpringBootTest
public class MessageServiceTest {
@Autowired
private MessageService messageService;
@MockBean
private MessageRepository messageRepository;
//@Test
public void testCreateMessage() {
double magnitude = 7.5;
String location = "San Francisco";
String readableTime = "2022-01-01 12:00:00";
String googleMapsUrl = "https://maps.google.com";
String expected="Recent Earthquake of M 7.5 strikes off San Francisco at 2022-01-01 12:00:00. For more info: https://maps.google.com | R�cents tremblements de terre de magnitude 7.5 frappent San Francisco � 2022-01-01 12:00:00. Pour plus d'informations: https://maps.google.com";
String result = messageService.createMessage(magnitude, location, readableTime, googleMapsUrl);
assertEquals(expected, result);
}
@Test
public void testSaveToDatabase() {
String readableTime = "2022-01-01 12:00:00";
String messageText = "Test message";
messageService.saveToDatabase(readableTime, messageText);
verify(messageRepository, times(1)).save(any(MessageInfo.class));
}
}
|
import 'package:flutter/material.dart';
import 'package:meals/models/meal.dart';
import 'package:meals/widgets/meal_item_trait.dart';
import 'package:transparent_image/transparent_image.dart';
class MealItem extends StatelessWidget {
const MealItem({
super.key,
required this.meal,
required this.openMealDetails,
});
final Meal meal;
final void Function(Meal meal) openMealDetails;
String get complexityText {
return meal.complexity.name[0].toUpperCase() +
meal.complexity.name.substring(1);
}
String get affordabilityText {
return meal.affordability.name[0].toUpperCase() +
meal.affordability.name.substring(1);
}
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.all(8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
clipBehavior: Clip.hardEdge,
child: InkWell(
onTap: () => openMealDetails(meal),
child: Stack(
children: [
FadeInImage(
placeholder: MemoryImage(kTransparentImage),
image: NetworkImage(meal.imageUrl),
fit: BoxFit.cover,
height: 200,
width: double.infinity,
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
color: Colors.black54,
padding: const EdgeInsets.symmetric(
vertical: 6,
horizontal: 44,
),
child: Column(
children: [
Text(
meal.title,
maxLines: 2,
textAlign: TextAlign.center,
softWrap: true,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(
height: 12,
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
MealItemTrait(
icon: Icons.schedule,
label: '${meal.duration} min',
),
const SizedBox(
width: 12,
),
MealItemTrait(
icon: Icons.shopping_bag_rounded,
label: complexityText,
),
const SizedBox(
width: 12,
),
MealItemTrait(
icon: Icons.attach_money,
label: affordabilityText,
),
],
),
],
),
),
),
],
),
),
);
}
}
|
/*
Copyright 2022, 2023 Joel Svensson svenssonjoel@yahoo.se
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/>.
*/
/** @file lbm_version.h */
#ifndef LBM_VERSION_H_
#define LBM_VERSION_H_
#ifdef __cplusplus
extern "C" {
#endif
/** LBM major version */
#define LBM_MAJOR_VERSION 0
/** LBM minor version */
#define LBM_MINOR_VERSION 24
/** LBM patch revision */
#define LBM_PATCH_VERSION 0
#define LBM_VERSION_STRING "0.24.0"
/*! \page changelog Changelog
APR 28 2024: Version 0.24.0
- Cleaning of lispbm repository. less to maintain.
- Lots of improvements to documentation.
- lbm_memory optimization.
MAR 9 2024: Version 0.23.0
- rest-args functionality added to function application of lambda defined function.
- Improved x86 REPL.
- Refernce manual is generated from LispBM script.
- Optional env arguments for eval and eval-program.
- Backwards indexing in setix using negative numbers.
- Bug fix: type promotion
- Bug fix: addition and subtraction of byte values
DEC 26 2023: Version 0.22.0
- Built-in sort operation on lists.
- Built-in list-merge operation.
- Bugfix in map.
- Literal forms for special characters.
NOV 28 2023: Version 0.21.0
- Removed partial evaluation.
- Added a built-in loop.
- Modification to built-in implementation of map.
- Addition of pointer-reversal garbage collector. Not on by default.
- Improved error messages.
NOV 1 2023: Version 0.20.0
- Added lbm_set_error_suspect function to enable extension authors to point out in more detail what is wrong.
- Improvement to error messages in some cases.
- Changed behavior of set family on functions when variable is not already bound (now an error).
- Fix of bug in flat_value handling.
OCT 8 2023: Version 0.19.0
- Error message and callback on GC stack overflow.
- Functions for gc stack size statistics added.
- GC does not look at constant values.
- Changes to environment handling during pattern matches.
AUG 26 2023: Version 0.18.0
- Removed wait-for flags
- Fix bug in unblock_unboxed when unblocking with error value.
JUL 29 2023: Version 0.17.0
- Addition of a timeout functionality to blocked contexts.
- recv-to special form added for receives with a timeout.
- block_context_from_extension_timeout function added.
- Unified sleeping and blocked queues.
- Added a new optional argument to spawn and spawn-trap that can be used to provide a name for the thread.
- Added profiler functionality.
JUL 16 2023: Version 0.16.0
- Addition of flat values as a type in the language.
- Addition of kill function for termination of threads.
JUN 29 2023: version 0.15.0
- Bug fix in lift_array_flash.
- Bug fix in map.
- Bug fix in reader.
- Bug fix in dynamic load.
- Bug fix in quasiquotation expansion.
-
JUN 8 2023: Version 0.14.0
- wait-for that blocks code unless a flag is set.
- Bug fix in undefine.
- Lots of cleaning and refactoring.
MAJ 5 2023: Version 0.13.0
- Changed behavior of closure application to zero args. Used to be equivalent
to application to nil.
- Removed make-env and in-env.
- Refactoring for readability. allocate_closure in eval_cps.
APR 30 2023: Version 0.12.0
- added make-env and in-env for a kind of namespace management.
- Deeply nested errors are resolved using longjmp.
Apr 4 2023: Version 0.11.0
- Incremental read evaluates expressions as soon as possible while reading.
- move-to-flash for storing constant parts of program in flash.
- All arrays are now byte-arrays. [type-X 1 2 3]-syntax removed.
Mar 19 2023: Version 0.10.0
- Added deconstructive let bindings with optional dont-care fields.
- Added (var x (....)) for local bindings in progn.
- Added setq
- Curly brackets { .... } syntax as sugar over progn.
Feb 18 2023: Version 0.9.0
- Arrays in flat_value are stored verbatim, not as ptr.
- Mutex locking granularity changed in multiple places.
Feb 10 2023: Version 0.8.1
- Flat representation of heap values added.
- Added queue locking to GC
- As an experiment blocked contexts are unblocked by the evaluator in a safe state.
Jan 28 2023: Version 0.8.0
- Changed return value of define from being the bound symbol to
being the value.
- Many of the more general extensions from Benjamin's BLDC repository
has moved into the LispBM source code.
Dec 11: Version 0.7.1
- Changes to heap_allocate_cell for readability and perhaps performance.
- Added heap_allocate_list for allocation of multiple cells at once.
Nov 9: Version 0.7.1
- Bugfix: string literal lengths.
- not-eq and != added.
- Corrected behaviour for eval when applied to no argument.
- lbm_memory operations are protected by mutex.
- Fixes to eval-program.
- Added multiple condition conditional function called cond.
Oct 31: Version 0.7.1
- Added optional boolean guards to pattern matches.
- Built in map and reverse.
Oct 16: Version 0.7.0
- Refactoring for evaluation speed.
- Removed possibility to step through code.
- Oldest message is removed on mailbox full.
- Added spawn-trap inspired by Erlang (but simplified).
Sep 25: Version 0.7.0
- Removed namespaces (they were too restricted).
- Mailboxes are now stored in arrays of default size 10 mails.
Mailbox size can be changed using set-mailbox-size.
Sep 16 2022: Version 0.6.0
- Source code can be streamed onto the heap. This means there is no need
for a large buffer on the MCU (or area of flash) to parse source code
from
Sep 5 2022: Version 0.6.0
- Refactoring of array-reader. Array reading is nolonger done monolithically
inside of the tokpar framework, but rather as a cooperation between the
evaluator and the tokenizer.
Sep 3 2022: Version 0.6.0
- Round-robin scheduling + Addition of an Atomic construct to use with care.
Aug 1 2022: Version 0.5.4
- Easing use of the LBM library from C++ code.
Jul 25 2022: Version 0.5.4
- lbm_define can now create variables (#var) in variable memory from
the C side of things.
- Simple namespaces.
Jul 18 2022: Version 0.5.4
- Added pattern matching support for i64, u64 and double.
- Fixed issue with pattern matching on i32, u32.
Jul 17 2022: Version 0.5.4
- Refactoring with readability in focus.
- Computing encodings of commonly used symbol constants (for eval_cps) at compile time
rather then repeatedly at runtime.
Jul 13 2022: Version 0.5.4
- Added function that lookups based on the second field in assoc structures.
Called it "cossa" as it is like assoc but backwards.
Jul 4 2022: Version 0.5.4
- Added possibility to partially apply closures. A partially applied closure
is again a closure.
May 24 2022: Version 0.5.3
- Fixed bug related to float-array literals not accepting whole numbers unless containing a decimal (0).
May 22 2022: Version 0.5.3
- Fixed bug that could cause problems with call-cc on 64bit platforms.
- bind_to_key_rest continuation refactoring to use indexing into stack.
- Fix evaluator bug in progn that made tail-call not fire properly when there
is only one expr in the progn sequence.
May 10 2022: Version 0.5.3
- symbols starting with "ext-" will be allocated into the extensions-list
and can on the VESC version of lispbm be dynamically bound to newly loaded
extensions at runtime.
May 8 2022: Version 0.5.2
- Added new macros for 10, 12 and 14K lbm_memory sizes.
May 5 2022: Version 0.5.2
- Line and column numbers associated with read errors.
- More explanatory descriptions in error messages related to read errors.
May 2 2022: Version 0.5.2
- Performance tweaks to the evaluator. Small but positive effect.
May 1 2022: Version 0.5.2
- Added lbm_stack_reserve for allocating multiple words on stack
in one function call (and one check on stack limits).
Apr 19 2022: Version 0.5.2
- Added a reader_done_callback that is run when a context is done
with a reading task.
- Array-literal syntax.
- Restructure symbol evaluation for efficiency and readability.
- Rewrite progn to update stack in place when possible.
- Removed a bunch of convertion back and forth from C and LBM representation
of continuation identifiers in eval_cps. They are now compared in encoded
form in the evaluator.
- Added lbm_cadr and replaced lbm_car(lbm_cdr(x)) with lbm_cadr(x) in
the evaluator.
Apr 10 2022: Version 0.5.1
- Removed the prelude.lisp, prelude.xxd step of building LBM.
- A continuation created by call-cc can be applied to 0 or 1 argument.
If there are 0 arguments an implicit application to nil takes place.
Mar 26 2022: Version (0.5.0)
- Optimized code-path for closure applications.
- 64 and 32 bit support from a single source code
- Added math extensions library from Benjamin Vedder
- Added String manipulation extensions library from Benjamin Vedder
Mar 10 2022: Version (0.4.2)
- Added the lbm_set_error_reason function.
Mar 02 2022: Version (0.4.2)
- Bug fix in initialization of contexts.
Feb 28 2022: Version (0.4.2)
- First go at human-readable error messages.
- Finished contexts are immediately and completely removed.
- Context ids are now set to the index into the lbm_memory
where the context structure is stored.
Feb 21 2022: Version (0.4.1)
- Bug fixes in gc related to arrays
Feb 20 2022: Version (0.4.0)
- Adds support for macros.
- Adds call-cc for escaping and abortive continuations.
Feb 17 2022: version 0.3.0
- Added lbm_undefine to c_interop.
- Added lbm_share_array to c_interop.
- Added lbm_create_array to c_interop.
- #var variables with more efficient storage and lookup.
variables are set using `setvar`.
- Spawn optionally takes a number argument before the closure argument
to specify stack size.
- Extensions are stored in an array and occupy a range of dedicated symbol values.
Feb 14 2022: version 0.2.0
- Added GEQ >= and LEQ <= comparisons.
Feb 13 2022: version 0.1.1
- Bug fix in handling of environments in progn.
Feb 11 2022: version 0.1.0
- First state to be given a numbered version (0.1.0)
*/
#ifdef __cplusplus
}
#endif
#endif
|
const Entertainment = require("../models/entertainmentSchema");
const axios = require("axios");
module.exports.getGenres = () => {
return new Promise((resolve, reject) => {
const movieGenres = axios.get(
"https://api.themoviedb.org/3/genre/movie/list",
{
params: {
api_key: process.env.TMDB_API_KEY,
language: "en-US",
},
}
);
const tvGenres = axios.get("https://api.themoviedb.org/3/genre/tv/list", {
params: {
api_key: process.env.TMDB_API_KEY,
language: "en-US",
},
});
movieGenres
.then((response) => {
tvGenres
.then((response2) => {
resolve({
status: 200,
message: "Successfully retrieved genres",
movieGenres: response.data.genres,
tvGenres: response2.data.genres,
});
})
.catch((err) => {
reject({
status: 500,
message: err.message,
});
});
})
.catch((error) => {
reject({
status: 500,
message: error.message,
});
});
});
};
module.exports.GetDetails = (id, mvt) => {
return new Promise((resolve, reject) => {
const data = axios.get(
`https://www.movieofthenight.com/api/${mvt}/${id}/en`
);
data
.then((response) => {
if (response.data.result > 0) {
resolve({
status: 200,
message: "Successfully retrieved content",
data: response.data,
});
} else {
reject({
status: 400,
message: "Does not exist",
});
}
})
.catch((error) => {
reject({
status: 500,
message: error.message,
});
});
});
};
module.exports.Search = (req) => {
return new Promise((resolve, reject) => {
const tv = req.tv || false;
const search = axios.get(
`https://www.movieofthenight.com/api/recommend/${
tv ? "series" : "movie"
}`,
{
params: {
userLanguage: "en",
multiple: true,
country: "ca",
keyword: req.query,
genres: req.genres,
services: req.services,
movieLanguage: req.lang,
type: req.type,
},
}
);
search
.then((response) => {
resolve({
status: 200,
message: "Success",
data: response.data,
});
})
.catch((error) => {
reject({
status: 500,
message: error.message,
});
});
});
};
module.exports.GetRecommended = () => {
return new Promise((resolve, reject) => {
const search = axios.get(
`https://www.movieofthenight.com/api/recommend/movie`,
{
params: {
userLanguage: "en",
multiple: true,
country: "ca",
type: "unpopular",
yearLow: new Date().getFullYear().toString(),
yearHigh: new Date().getFullYear().toString(),
},
}
);
search
.then((response) => {
resolve({
status: 200,
message: "Success",
data: response.data,
});
})
.catch((error) => {
reject({
status: 500,
message: error.message,
});
});
});
};
module.exports.GetRandom = () => {
return new Promise((resolve, reject) => {
const search = axios.get(
`https://www.movieofthenight.com/api/recommend/series`,
{
params: {
userLanguage: "en",
multiple: true,
country: "ca",
type: "random",
},
}
);
search
.then((response) => {
resolve({
status: 200,
message: "Success",
data: response.data,
});
})
.catch((error) => {
reject({
status: 500,
message: error.message,
});
});
});
};
module.exports.AddToList = (body, fav) => {
return new Promise((resolve, reject) => {
Entertainment.find({ id: body.id, favorite: fav })
.then((entertainment) => {
if (entertainment.length > 0) {
reject({
status: 400,
message: "Already in list",
});
} else {
Entertainment.create(body)
.then((result) => {
resolve({
status: 200,
message: "Success",
data: result,
});
})
.catch((err) => {
reject({
status: 500,
message: err.message,
});
});
}
})
.catch((err) => {
reject({
status: 500,
message: err.message,
});
});
});
};
module.exports.GetList = (userID, fav) => {
return new Promise((resolve, reject) => {
Entertainment.find({ userID: userID, favorite: fav })
.then((entertainment) => {
if (entertainment.length > 0) {
resolve({
status: 200,
message: "Success",
data: entertainment,
});
} else {
reject({
status: 400,
message: "Nothing exists in list",
});
}
})
.catch((err) => {
reject({
status: 500,
message: err.message,
});
});
});
};
module.exports.RemoveFromList = (entID, userID, fav) => {
return new Promise((resolve, reject) => {
Entertainment.findOneAndDelete({
entID: entID,
userID: userID,
favorite: fav,
})
.then((entertainment) => {
if (entertainment) {
resolve({
status: 200,
message: "Success",
data: entertainment,
});
} else {
reject({
status: 400,
message: "Does not exist",
});
}
})
.catch((err) => {
reject({
status: 500,
message: err.message,
});
});
});
};
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* 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.tencentcloudapi.cdb.v20170320.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class ParamTemplateInfo extends AbstractModel{
/**
* 参数模板ID
*/
@SerializedName("TemplateId")
@Expose
private Integer TemplateId;
/**
* 参数模板名称
*/
@SerializedName("Name")
@Expose
private String Name;
/**
* 参数模板描述
*/
@SerializedName("Description")
@Expose
private String Description;
/**
* 实例引擎版本
*/
@SerializedName("EngineVersion")
@Expose
private String EngineVersion;
/**
* 获取参数模板ID
* @return TemplateId 参数模板ID
*/
public Integer getTemplateId() {
return this.TemplateId;
}
/**
* 设置参数模板ID
* @param TemplateId 参数模板ID
*/
public void setTemplateId(Integer TemplateId) {
this.TemplateId = TemplateId;
}
/**
* 获取参数模板名称
* @return Name 参数模板名称
*/
public String getName() {
return this.Name;
}
/**
* 设置参数模板名称
* @param Name 参数模板名称
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* 获取参数模板描述
* @return Description 参数模板描述
*/
public String getDescription() {
return this.Description;
}
/**
* 设置参数模板描述
* @param Description 参数模板描述
*/
public void setDescription(String Description) {
this.Description = Description;
}
/**
* 获取实例引擎版本
* @return EngineVersion 实例引擎版本
*/
public String getEngineVersion() {
return this.EngineVersion;
}
/**
* 设置实例引擎版本
* @param EngineVersion 实例引擎版本
*/
public void setEngineVersion(String EngineVersion) {
this.EngineVersion = EngineVersion;
}
/**
* 内部实现,用户禁止调用
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "TemplateId", this.TemplateId);
this.setParamSimple(map, prefix + "Name", this.Name);
this.setParamSimple(map, prefix + "Description", this.Description);
this.setParamSimple(map, prefix + "EngineVersion", this.EngineVersion);
}
}
|
package com.automation.trading.utility;
import java.io.Serializable;
import org.springframework.http.HttpStatus;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(value = Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseDTO<T> implements Serializable {
private static final long serialVersionUID = -6072518716971093796L;
private T data;
private String message;
private boolean success;
private int httpStatus;
private long timestamp = System.currentTimeMillis();
/**
* @param data
* @param message
* @param success
* @param httpStatus
*/
public ResponseDTO(T data, String message, boolean success, int httpStatus) {
super();
this.data = data;
this.message = message;
this.success = success;
this.httpStatus = httpStatus;
}
public ResponseDTO(T data) {
super();
this.data = data;
this.success = true;
this.httpStatus = HttpStatus.OK.value();
}
public ResponseDTO(T data, int httpStatus) {
super();
this.data = data;
this.success = true;
this.httpStatus = httpStatus;
}
}
|
# Simulating an "observed" dataset
n <- 50
data <- rnorm(n,10,1)
# Setting parameters for uniform priors
mu_min <- 0
mu_max <- 50
sig_min <- 0
sig_max <- 4
# Creating model parameters
mu ~ dnUnif( lower=mu_min , upper=mu_max )
sig ~ dnUnif( lower=sig_min , upper=sig_max )
# Creating stochastic nodes (Normal distributions) clamped with data
for (i in 1:n){
R[i] ~ dnNormal( mean=mu , sd=sig )
R[i].clamp(data[i])
}
# For this example, we'll use the Normal model you just set up in the last practice exercise
# Since mu is one node in our graph, we can pass it as an argument to the model constructor
myModel = model(mu)
# Setting up MCMC moves
moves = VectorMoves()
moves.append( mvSlide(mu,delta=0.1,weight=1) )
moves.append( mvSlide(sig,delta=0.1,weight=1) )
# If there were other parameters to infer, we could add additional moves here.
# Setting up MCMC monitors
monitors = VectorMonitors()
monitors.append( mnScreen(printgen=100,mu,sig) ) # This monitor prints to the screen
monitors.append( mnModel(filename="NormalModel_MCMC.log",printgen=100,stochasticOnly=TRUE) ) # To file
# Creating an MCMC object to perform inference
myMCMC = mcmc(myModel, moves, monitors)
# Run the MCMC for
ngens <- 50000
myMCMC.run(ngens)
|
import { darken, rgba } from 'polished';
import styled, { css } from 'styled-components';
type InputWrapperProps = {
isInvalid: boolean;
isDisabled: boolean;
variant?: 'primary' | 'secondary';
};
export const InputWrapper = styled.div<InputWrapperProps>`
${({ theme, isInvalid, isDisabled, variant }) => css`
padding: 0rem 0.5rem !important;
border: 2px solid ${theme.colors.backgroundContent};
background-color: ${theme.colors.backgroundContent};
border-radius: 0.3rem;
transition: color 0.3s ease 0s, border-color 0.3s ease 0s,
background-color 0.3s ease 0s;
display: flex;
flex-direction: row;
align-items: center;
gap: 0.5rem;
justify-content: space-around;
${isDisabled &&
css`
border: 2px solid ${rgba(theme.colors.backgroundContent, 0.25)};
`}
${isInvalid &&
css`
border: 2px solid ${rgba(theme.colors.danger, 0.25)};
`}
input, textarea {
width: 100%;
height: 2.333rem;
padding-left: 0rem;
padding-right: 0rem;
color: ${theme.colors.textPrimary} !important;
background-color: ${isDisabled
? darken(0.1, theme.colors.backgroundContent)
: theme.colors.backgroundContent} !important;
border: none;
cursor: text;
${isDisabled &&
css`
cursor: not-allowed;
`}
&.form-control.is-invalid {
background: none;
background-color: ${theme.colors.background};
border-color: ${theme.colors.danger};
padding-right: 0rem;
}
&::placeholder {
color: ${rgba(theme.colors.textPrimary, 0.75)};
}
}
svg {
color: ${isInvalid
? rgba(theme.colors.danger, 0.75)
: rgba(theme.colors.textPrimary, 0.5)};
font-size: 1rem;
}
&:focus-within {
box-shadow: none;
border: 2px solid
${isInvalid
? theme.colors.danger
: variant === 'secondary'
? theme.colors.secondary
: theme.colors.primary};
border-radius: 0.3rem;
input,
textarea {
&:focus {
box-shadow: none;
border: none;
background-color: ${theme.colors.background};
}
}
svg {
color: ${isInvalid
? theme.colors.danger
: variant === 'secondary'
? theme.colors.secondary
: theme.colors.primary};
}
}
`}
`;
export const LabelGroup = styled.div`
display: flex;
flex-direction: row;
margin-bottom: 5px;
gap: 5px;
`;
export const Label = styled.p<Pick<InputWrapperProps, 'variant'>>`
${({ variant, theme }) => css`
font-size: 1rem;
color: ${variant === 'secondary'
? theme.colors.secondaryDark
: theme.colors.primaryDark};
`}
`;
export const IsRequired = styled.p`
font-size: 1rem;
color: ${(props) => props.theme.colors.danger};
`;
|
import type {Meta, StoryObj} from '@storybook/react'
import {userEvent, within} from '@storybook/testing-library'
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
import BubbleButton from './BubbleButton'
const meta: Meta<typeof BubbleButton> = {
component: BubbleButton,
args: {
children: 'click me!'
},
parameters: {
backgrounds: {
values: [
{
name: 'yeelow-gradient',
value: 'linear-gradient(30deg, #f39c12 30%, #f1c40f)'
}
]
}
},
decorators: [
(Story) => {
return <div>
<Story />
</div>
}
]
}
export default meta
type Story = StoryObj<typeof BubbleButton>;
export const Primary: Story = {
args: {}
}
export const Animating: Story = {
play: async ({canvasElement}) => {
// https://storybook.js.org/docs/react/writing-stories/play-function#working-with-the-canvas
const canvas = within(canvasElement)
const element = canvas.getByRole('button')
userEvent.click(element)
// userEvent vs fireEvent:
// userEvent практически полная имитация пользовательского взаимодействия
// https://testing-library.com/docs/guide-events/
}
}
export const Params: Story = {
parameters: {
backgrounds: {
values: [
{
name: 'yeelow-gradient',
value: 'linear-gradient(30deg, #f39c12 30%, #f1c40f)'
},
{
name: 'gray',
value: '#34495e'
},
{
name: 'darkgray',
value: '#2c3e50'
}
]
}
}
}
export const AxiosPost200: Story = {
args: {
onClick: () => {
console.log('fetch fake url')
axios.post('fake-url').then(r => console.log(r))
}
},
parameters: {
axios: {
instance: axios,
adapter: (mock: MockAdapter) => {
mock.onPost('fake-url').reply(200, { test: 'some mock data' })
}
}
}
}
export const AxiosPost201: Story = {
args: {
onClick: () => {
console.log('fetch fake url')
axios.post('fake-url').then(r => console.log(r))
}
},
parameters: {
axios: {
instance: axios,
adapter: (mock: MockAdapter) => {
mock.onPost('fake-url').reply(201, {test: ''})
}
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Runtime.CompilerServices;
using System.Text;
using TwitterLitter.Server.Classes;
using TwitterLitter.Server.Interfaces;
using TwitterLitter.Shared;
using TwitterLitter.Shared.Models;
namespace TwitterLitter.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TwitterController : ControllerBase
{
private ICancellationService cancellationService;
private ITwitterStatisticsService twitterStatisticsService;
public TwitterController(ICancellationService _cancellationService, ITwitterStatisticsService _twitterStatisticsService)
{
cancellationService = _cancellationService;
twitterStatisticsService = _twitterStatisticsService;
}
[HttpGet("CancelTwitterFeed")]
public async Task<bool> CancelTwitterFeed()
{
cancellationService.Cancel();
return true;
}
[HttpGet("GetTweetsProcessedCount")]
public async Task<int> GetTweetsProcessedCount()
{
return await twitterStatisticsService.GetTweetsProcessedCount();
}
[HttpGet("GetTrendingHashtags/{count}")]
public async Task<List<HashtagResult>> GetTrendingHashtags(int count)
{
return await twitterStatisticsService.GetTrendingHashtags(count);
}
[HttpGet("GetTweetSamples/{count}")]
public async Task<List<TwitterTweetWrapper>> GetTweetSamples(int count)
{
return await twitterStatisticsService.GetTweetSamples(count);
}
}
}
|
//
// KSTLogMessage.h
// KSTLog
//
// Created by liushengxiang on 2020/6/3.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/// 日志分级
typedef NS_ENUM(NSUInteger, KSTLogLevel) {
KSTLogLevelUnknown = 0,
KSTLogLevelError = (1 << 0),
KSTLogLevelWarning = (1 << 1),
KSTLogLevelInfo = (1 << 2),
KSTLogLevelDebug = (1 << 3),
};
@interface KSTLogMessage : NSObject
@property (nonatomic) KSTLogLevel level; /**< 日志等级 */
@property (nonatomic, copy) NSString *desc; /**< 描述 */
@property (nonatomic, nullable, copy) NSString *module; /**< 模块 */
@property (nonatomic, nullable, copy) NSArray *tags; /**< 标签 */
@property (nonatomic, nullable, copy) NSDictionary *params; /**< 参数 */
@property (nonatomic, nullable, copy) NSDictionary *extend; /**< 扩展字段 */
@property (nonatomic, strong) NSDate *time; /**< 时间戳 */
@property (nonatomic, copy) NSString *fileName; /**< 文件名 */
@property (nonatomic, nullable, copy) NSString *function; /**< 函数名 */
@property (nonatomic) NSUInteger line; /**< 行数 */
@property (nonatomic, nullable, copy) NSString *threadId; /**< 线程id */
@property (nonatomic, nullable, copy) NSString *threadName; /**< 线程名称 */
@property (nonatomic, nullable, copy) NSString *queueLabel; /**< 队列标识 */
/**
* @brief 是否可输出,默认为YES
* @discussion 插件可通过预处理协议-kstLogger:willLogMessage:修改此属性,若取值为NO,表示阻止输出,将跳过后续的格式化和输出协议。
*/
@property (nonatomic) BOOL shouldLog;
/**
* @brief 格式化输出文本
* @discussion 通过logFormatter格式化协议-kstLogger:formatLogMessage:修改此属性,若取值为nil,表示无格式化输出内容,将跳过后续输出协议。
*/
@property (nonatomic, nullable, copy) NSString *formattedString;
@end
NS_ASSUME_NONNULL_END
|
import { IsEmail, IsNotEmpty, IsString, IsOptional, IsEnum, MaxLength, IsBoolean } from 'class-validator';
import { InputType, Field } from '@nestjs/graphql';
import { DeviceEnum, LangEnum, SocialProvidersEnum } from 'src/user/user.enum';
import { ErrorCodeEnum } from 'src/_common/exceptions/error-code.enum';
@InputType()
export class RegisterOrLoginBySocialAccountInput {
favLang: LangEnum;
@Field()
@IsString()
@IsNotEmpty()
providerId: string;
@Field(type => SocialProvidersEnum)
@IsNotEmpty()
provider: SocialProvidersEnum;
@IsOptional()
@IsEmail({}, { message: ErrorCodeEnum[ErrorCodeEnum.INVALID_EMAIL] })
@Field({ nullable: true })
email?: string;
@Field(type => DeviceEnum)
@IsEnum(DeviceEnum)
@IsNotEmpty()
device: DeviceEnum;
@Field(type => Boolean, { nullable: true })
@IsBoolean()
@IsNotEmpty()
emailManualInput: boolean;
@Field({ nullable: true })
@IsOptional()
verificationCode: string;
}
|
import { IAgentPlugin } from '@veramo/core'
import { schema } from '../index'
import {
events,
IRequiredContext,
IVcApiVerifierClient,
IVcApiVerifierArgs,
IVerifyCredentialArgs,
IVerifyCredentialResult,
} from '../types/IVcApiVerifierClient'
import { fetch } from 'cross-fetch'
/**
* {@inheritDoc IVcApiVerifier}
*/
export class VcApiVerifierClient implements IAgentPlugin {
readonly schema = schema.IVcApiVerfierClientAgentPlugin
readonly methods: IVcApiVerifierClient = {
vcApiClientVerifyCredential: this.vcApiClientVerifyCredential.bind(this),
}
private readonly verifyUrl: string
constructor(options: IVcApiVerifierArgs) {
this.verifyUrl = options.verifyUrl
}
/** {@inheritDoc IVcApiVerifier.vcApiClientVerifyCredential} */
private async vcApiClientVerifyCredential(args: IVerifyCredentialArgs, context: IRequiredContext): Promise<IVerifyCredentialResult> {
return await fetch(this.verifyUrl, {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ verifiableCredential: args.credential }),
})
.then(async (response) => {
if (response.status >= 400) {
throw new Error(await response.text())
} else {
return response.json()
}
})
.then(async (verificationResult) => {
await context.agent.emit(events.CREDENTIAL_VERIFIED, verificationResult)
return verificationResult
})
}
}
|
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.db.utils import IntegrityError
from rest_framework.decorators import api_view, authentication_classes
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
from datetime import datetime
from .serializers import TaskSerializer, TodoListSerializer
from .models import *
HOME = 'Todolist:todo-home'
LOGIN = 'Base:login-user'
# Create your views here.
@login_required(login_url=LOGIN)
def todo_home(request):
context = {}
lists = List.objects.filter(owner=request.user)
if lists.count() != 0:
pk = lists.first().pk
return render(request, 'todolist/todo_home.html', {})
return render(request, 'todolist/todo_home.html', {})
@api_view(['GET'])
def api_tasks(request):
tasks = Task.objects.filter(list__owner = request.user)
serializer = TaskSerializer(tasks, many = True)
return Response(serializer.data)
@api_view(['GET'])
def api_list_list(request):
lists = List.objects.filter(owner=request.user).order_by('-last_modified')
serializer = TodoListSerializer(lists, many=True)
return Response(serializer.data)
@api_view(['GET'])
def api_task_list(request, listpk):
tasks = Task.objects.filter(list = listpk)
serializer = TaskSerializer(tasks, many = True)
return Response(serializer.data)
@api_view(['GET'])
def api_task_detail(request, taskpk):
task = Task.objects.get(pk=taskpk)
serializer = TaskSerializer(task, many=False)
return Response(serializer.data)
@api_view(['POST'])
def api_task_create(request):
try:
todo_list = List.objects.get(pk=request.data['list'])
except List.DoesNotExist:
return Response('Tasks can only be added to exisiting lists!', status=400)
if todo_list.owner != request.user:
return Response('You can only add tasks to your own shopping lists', status=403)
new_task = Task(list=todo_list, title=request.data['title'], description=request.data['description'], status=request.data['status'])
try:
new_task.save()
except IntegrityError:
return Response('Could not create task!', status=400)
todo_list.save()
serializer = TaskSerializer(new_task)
return Response(serializer.data)
@api_view(['POST'])
def api_task_update(request, taskpk):
task = Task.objects.get(pk=taskpk)
serializer = TaskSerializer(instance=task, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['DELETE'])
def api_task_delete(request, taskpk):
task = Task.objects.get(pk=taskpk)
task.delete()
return Response("Task successfully deleted!")
@api_view(['PUT'])
def api_task_toggle_status(request, taskpk):
try:
task = Task.objects.get(pk=taskpk)
except Task.DoesNotExist:
return Response("Task with such id does not exists!", status=400)
# Same error as above on purpose. Do not leak that another user may own a task with this id
if (task.list.owner != request.user):
return Response("Task with such id does not exists!", status=404)
task.status = not task.status
task.save()
task.list.save()
serializer = TaskSerializer(task)
return Response(serializer.data)
@api_view(['POST'])
def api_list_create(request):
new_list = List(owner=request.user, title=request.data['title'])
try:
new_list.save()
except IntegrityError:
return Response('Could not create entry!', status=400)
serializer = TodoListSerializer(new_list)
return Response(serializer.data)
@api_view(['DELETE'])
def api_list_delete(request, listpk):
list_to_del = List.objects.get(pk=listpk)
list_to_del.delete()
return Response('list successfully deleted!')
|
=begin
Write a method that takes a single String argument and returns a new string that contains
the original value of the argument with the first character of every word capitalized and all other letters lowercase.
You may assume that words are any sequence of non-blank characters.
- write a method that takes a string
- have the method return a string that contains following changes:
- the first character of each word must be capitalised
- all other letters must be lower case
EXAMPLES
word_cap('four score and seven') == 'Four Score And Seven'
word_cap('the javaScript language') == 'The Javascript Language'
word_cap('this is a "quoted" word') == 'This Is A "quoted" Word'
DATA
ALGO
- define a method that takes a string
- split the string up into an array
- iterate and return a new array where each word is capitalised
- join the array back together
=end
def word_cap(input_string)
input_string.split.map {|word| word.capitalize }.join(' ')
end
p word_cap('four score and seven') == 'Four Score And Seven'
p word_cap('the javaScript language') == 'The Javascript Language'
p word_cap('this is a "quoted" word') == 'This Is A "quoted" Word'
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_list_push_back.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aaires-d <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/01/20 02:07:34 by aaires-d #+# #+# */
/* Updated: 2024/01/20 07:24:27 by aaires-d ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_list.h"
void ft_list_push_back(t_list **begin_last, void *data)
{
t_list *it;
it = *begin_list;
if (it)
{
while (it->next)
it = it->next;
it->next = ft_create_elem(data);
return ;
}
*begin_list = ft_create_elem(data);
}
/*
#include <stdio.h>
int main(void)
{
t_list *list = NULL;
int data_value1 = 42;
int data_value2 = 56;
ft_list_push_back(&list, &data_value1);
ft_list_push_back(&list, &data_value2);
t_list *current = list;
while (current)
{
printf("%d ", *((int *)(current->data)));
current = current->next;
}
printf("\n");
// Assuming ft_list_push_back takes care of freeing memory
// If not, free the list manually.
return 0;
}
*/
|
# ポート番号について説明できる
## 1. ポート番号とは
ポート番号とは何か、何のためにあるものか、プログラミング初心者にわかるように説明してください。
- 特定のプロセスまたはタイプのサービスが通信を行うための窓口のようなもの。ポートは「港」という意味
- ネットワーク上で通信を行う際、それぞれの通信はIPアドレスによって正しいマシンに送られるが、一つのマシンには数多くのアプリケーションやサービスが存在するため、マシンの度のサービスに通信を送ったらいいか分からない。そこでポート番号を用いることによりどのアプリケーションがその通信、メッセージを処理するかを識別する
## 2. 代表的なポート番号
代表的なポート番号はウェルノウンポートと呼ばれています。ウェルノウンポートをいくつか挙げてください。また、それぞれのポート番号が何のために使われているか説明してください。
- 20,21:FTP(ファイル転送)
- 22:SSH(暗号化されたネットワーク)
- 25:SMTP(メール送信)
- 53:DNS(ドメイン名とIPアドレスの変換)
- 80:HTTP(ウェブページの転送)
- 153:IMAP(メール受信)
- 443:HTTPS(暗号化されたウェブページの転送)
## 3. HTTP/HTTPS 通信
ブラウザでウェブページを開く際に、ポート番号を指定することができます。
`https://www.google.com/` をブラウザで開く際に `https://www.google.com:443` を指定しても同じページが開かれますが、`https://www.google.com:22` とするとページが開かれません。
その理由を説明してください。
- HTTPS通信ではデフォルトでポート番号443が使われるので、ポートをわざわざ指定しなくても通信できる。しかし、22番を指定するとSSHというネットワークを通じて他のコンピュータにログインするためのプロトコルが使われるが、ウェブサーバーは22番ポートでのリクエストを受信しないためページが開かれない
また、ブラザでウェブページを開く際に通常はポート番号を指定しませんが、その理由も説明してください。
- HTTP(Hypertext Transfer Protocol)やHTTPS(HTTP Secure)などの一部のウェルノウンプロトコルにはデフォルトのポート番号があらかじめ設定されているから
## 4. データベースへの接続
データベースに接続する際に、ポート番号を指定しています。ポート番号何番を指定しているか確認してください。
## 5. ポート番号の確認
今自分が使用しているパソコンで使用しているポート番号とそのポート番号を動かしているプログラムを調べてください。
|
function validateForm() {
// Get form inputs
let customerName = document.getElementById('customerName').value;
let nationalID = document.getElementById('nationalID').value;
let phoneNumber = document.getElementById('phoneNumber').value;
let checkInDate = document.getElementById('checkInDate').value;
let checkOutDate = document.getElementById('checkOutDate').value;
let totalRooms = document.getElementById('totalRooms').value;
let branchName = document.getElementById('branchName').value;
let roomNumbers = document.getElementsByName('RoomNumbers');
let errorDiv = document.getElementById("errordiv")
let errorMsg = document.getElementsByClassName('error-message')[0];
// Validate each input field
if (!customerName || !/^[A-Za-z]{8,}$/.test(customerName)) {
errorDiv.style.display = 'block';
errorMsg.textContent = "Please Enter Valid Named";
return false;
}
if (/^[0-9]{15}$/.test(nationalID)){
errorDiv.style.display = 'block';
errorMsg.textContent = "Please Enter Valid National ID";
return false;
}
if (/^[0-9]{11}$/.test(phoneNumber)) {
errorDiv.style.display = 'block';
errorMsg.textContent = "Please Enter Valid Phone Number";
return false;
}
if (checkInDate === '') {
errorDiv.style.display = 'block';
errorMsg.textContent = "Please Enter Check In Date";
return false;
}
if (checkOutDate === '') {
errorDiv.style.display = 'block';
errorMsg.textContent = "Please Enter Check Out Date";
return false;
}
if (totalRooms === '' || isNaN(totalRooms) || totalRooms <= 0) {
errorDiv.style.display = 'block';
errorMsg.textContent = "Please Enter Total Rooms";
return false;
}
if (branchName === '') {
errorDiv.style.display = 'block';
errorMsg.textContent = "Please Select Branch Name";
return false;
}
// If all validations pass, return true to submit the form
return true;
}
document.getElementById('bookingForm').addEventListener('submit', async function (event) {
if (!validateForm()) {
event.preventDefault();
return;
}
const form = event.target;
const formData = new FormData(form);
// Get selected room numbers
const roomNumbers = [];
form.querySelectorAll('input[name="RoomNumber"]:checked').forEach(checkbox => {
roomNumbers.push(checkbox.value);
});
console.log(roomNumbers)
// Prepare data to be sent
const data = {
CustomerName: formData.get('CustomerName'),
NationalID: formData.get('NationalID'),
PhoneNumber: formData.get('PhoneNumber'),
CheckInDate: formData.get('CheckInDate'),
CheckOutDate: formData.get('CheckOutDate'),
TotalRooms: formData.get('TotalRooms'),
RoomNumber: roomNumbers,
BranchName: formData.get('BranchName')
};
try {
const response = await fetch('/booking/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (response.ok) {
const result = await response.json();
Swal.fire({
title: 'Success',
text: 'Booking created successfully!',
icon: 'success',
confirmButtonText: 'OK'
});
} else {
const errorData = await response.json();
document.getElementById('errordiv').innerText = errorData.message || 'An error occurred';
Swal.fire({
title: 'Error',
text: errorData.message || 'An error occurred',
icon: 'error',
confirmButtonText: 'OK'
});
}
} catch (error) {
document.getElementById('errordiv').innerText = 'An error occurred';
Swal.fire({
title: 'Error',
text: 'An error occurred',
icon: 'error',
confirmButtonText: 'OK'
});
}
});
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "../Protocol.sol";
import "../interfaces/GammaInterface.sol";
import "../interfaces/IAlphaPortfolioValuesFeed.sol";
/**
* @title Lens contract to get user vault positions
*/
contract ExposureLensMK1 {
// protocol
Protocol public protocol;
/// structs ///
struct SeriesAddressDrill {
string name;
string symbol;
int256 netDhvExposure; // e18
uint64 expiration;
bool isPut;
uint128 strike; // e18
address collateralAsset;
bytes32 optionHash;
}
constructor(address _protocol) {
protocol = Protocol(_protocol);
}
function getSeriesAddressDetails(address seriesAddress) external view returns (SeriesAddressDrill memory) {
IOtoken otoken = IOtoken(seriesAddress);
uint64 expiry = uint64(otoken.expiryTimestamp());
bool isPut = otoken.isPut();
uint128 strike = uint128(otoken.strikePrice() * 1e10);
bytes32 oHash = keccak256(
abi.encodePacked(expiry, strike, isPut)
);
int256 netDhvExposure = IAlphaPortfolioValuesFeed(protocol.portfolioValuesFeed()).netDhvExposure(oHash);
SeriesAddressDrill memory seriesAddressDrill = SeriesAddressDrill(
otoken.name(),
otoken.symbol(),
netDhvExposure,
expiry,
isPut,
strike,
otoken.collateralAsset(),
oHash
);
return seriesAddressDrill;
}
}
|
import styles from "./newsListItem.module.css";
import { Link } from "react-router-dom";
import score from "../assets/score.svg";
import comment from "../assets/comment.svg";
import linkArrow from "../assets/link-arrow.svg";
import { convertTime, showUrl } from "../utils";
import useFetch from "../hooks/useFetch";
export const NewsListItem = ({ id, pageNum }) => {
const item = useFetch(`item/${id}.json`);
return (
<div className={styles.news}>
{item.url ? (
<button className={styles.button}>{showUrl(item.url)}</button>
) : (
<button className={styles.button}>hackernews.com</button>
)}
<Link to={`/News/${pageNum}/${id}`}>
<h4 className={styles.title}>{item.title}</h4>
<p
className={styles.text}
dangerouslySetInnerHTML={{ __html: item.text }}
></p>
</Link>
<strong className={styles.itemInfo}>
<img className={styles.scoreIcon} src={score} alt="score" />
{item.score}
<img className={styles.commentIcon} src={comment} alt="comment" />
{item.descendants}
</strong>
<div className={styles.footer}>
<strong>
<Link to={`/user/${item.by}`}>By {item.by + ` • `}</Link>
<span className={styles.time}>{convertTime(item.time)}</span>
</strong>
{item.url ? (
<a href={`${item.url}`}>
<img src={linkArrow} alt="link arrow" />
</a>
) : (
<Link to={`/News/${pageNum}/${id}`}>
<img src={linkArrow} alt="link arrow" />
</Link>
)}
</div>
</div>
);
};
|
<?php
session_start();
$usersFile = 'data/users.xml';
function saveUser($file, $username, $hashedPassword, $recoveryCode, $isAdmin) {
if (file_exists($file)) {
$xml = simplexml_load_file($file);
} else {
$xml = new SimpleXMLElement('<users></users>');
}
$user = $xml->addChild('user');
$user->addChild('username', $username);
$user->addChild('password', $hashedPassword);
$user->addChild('recoveryCode', $recoveryCode);
$user->addChild('isAdmin', $isAdmin);
$xml->asXML($file);
}
function generateRecoveryCode() {
return bin2hex(random_bytes(5)); // 10 characters long
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// Hash the password
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$recoveryCode = generateRecoveryCode();
$isAdmin = isset($_POST['isAdmin']) ? 'true' : 'false';
$users = simplexml_load_file($usersFile);
$usernames = [];
foreach ($users->user as $user) {
$usernames[] = (string)$user->username;
}
if (in_array($username, $usernames)) {
$error = "Username already exists. Please choose another one.";
} else {
saveUser($usersFile, $username, $hashedPassword, $recoveryCode, $isAdmin);
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$_SESSION['recoveryCode'] = $recoveryCode;
$_SESSION['isAdmin'] = $isAdmin;
header('Location: recovery.php');
exit();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<header>
<h1>Social Network</h1>
</header>
<nav>
<a href="index.php">Home</a>
<a href="login.php">Login</a>
<a href="register.php">Register</a>
</nav>
<div class="container">
<h1>Register</h1>
<?php if (isset($error)): ?>
<p><?php echo $error; ?></p>
<?php endif; ?>
<form method="post" action="register.php">
<input type="text" name="username" placeholder="Username" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<label><input type="checkbox" name="isAdmin"> Admin</label><br>
<button type="submit">Register</button>
</form>
</div>
</body>
</html>
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import {
SQLEditor,
FullSQLEditor,
MarkdownEditor,
TextAreaEditor,
CssEditor,
JsonEditor,
ConfigEditor,
AsyncAceEditorOptions,
} from '.';
type EditorType =
| 'sql'
| 'full-sql'
| 'markdown'
| 'text-area'
| 'css'
| 'json'
| 'config';
const editorTypes: EditorType[] = [
'sql',
'full-sql',
'markdown',
'text-area',
'css',
'json',
'config',
];
export default {
title: 'AsyncAceEditor',
};
const parseEditorType = (editorType: EditorType) => {
switch (editorType) {
case 'sql':
return SQLEditor;
case 'full-sql':
return FullSQLEditor;
case 'markdown':
return MarkdownEditor;
case 'text-area':
return TextAreaEditor;
case 'css':
return CssEditor;
case 'json':
return JsonEditor;
default:
return ConfigEditor;
}
};
export const AsyncAceEditor = (
args: AsyncAceEditorOptions & { editorType: EditorType },
) => {
const { editorType, ...props } = args;
const Editor = parseEditorType(editorType);
return <Editor {...props} />;
};
AsyncAceEditor.args = {
defaultTabSize: 2,
width: '100%',
height: '500px',
value: `{"text": "Simple text"}`,
};
AsyncAceEditor.argTypes = {
editorType: {
defaultValue: 'json',
control: { type: 'select', options: editorTypes },
},
defaultTheme: {
defaultValue: 'github',
control: { type: 'radio', options: ['textmate', 'github'] },
},
};
AsyncAceEditor.story = {
parameters: {
actions: {
disable: true,
},
knobs: {
disable: true,
},
},
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.