text
stringlengths
184
4.48M
import React from 'react'; import { BrowserRouter, Routes, Route } from 'react-router-dom'; import Home from './pages/Home'; import Films from './pages/Films'; import FilmID from './pages/FilmID'; import People from './pages/People'; import PersonID from './pages/PersonID'; import Navbar from './components/Navbar'; const App = () => { return ( <BrowserRouter> <Navbar /> <Routes> <Route path="/" element={<Home />}/> <Route path="/films" element={<Films />}/> <Route path="/films/:filmid" element={<FilmID />}/> <Route path="/people" element={<People />}/> <Route path="/people/:personid" element={<PersonID />}/> </Routes> </BrowserRouter> ); } export default App;
import Teoria from 'teoria' import { NOTES, SCALES, COLOR_CLASSNAMES, COLOR_NAMES, COLOR_CODES, GUITAR_TUNINGS, TUNING_NAMES, DURATION_CHARS, INTERVAL_CHARS, DURATIONS, } from './constants' const { random } = Math // TODO Please refactor this... export class Random { static arrayDouble = (arr) => [arr, arr] //* <- Genius! static range = () => random().toFixed(2) static float = (min = 0.01, max = 0.99) => (random() * (max - min) + min).toFixed(2) static number = (min = 1, max = 100) => ~~(random() * (max - min)) + min static boolean = (chance = 50) => this.number(1, 100) > chance static numbers = (size = 10, max = 100) => this.array(size).map(() => this.number(0, max)) static powerOfTwo = (max = 10) => 2 ** this.number(1, max) static numbersDeep = (len = 10, max = 4) => this.numbers(len, max).map((v) => (v > 1 ? this.numbers(v, max) : v)) static values = (arr) => this.array(10).map((v) => this.arrayElement(arr)) static array = (size = 10, fill = this.boolean(20)) => Array(size).fill(fill) static arrays = (size = 10, maxDeep = 5) => this.array(size).map((v) => this.array(this.number(2, maxDeep))) static arrayPart = (arr, chance = 20) => arr.filter((v, i) => this.boolean(chance)) static arrayGrow = (arr, growSize = 10) => [...arr, ...this.array(growSize).map((v, i) => this.arrayElement(arr))] static arrayExamples = (size = 10) => this.array(size).map((v) => this.example()) static arraySequence = (start = 1, end = 100) => this.array(end).map((v, i) => start + i) static arrayChange = (size = 10, arr) => this.arrayElement(this.array(size).map((v) => this.arrayShuffle(arr))) static arrayMerge = (arr, ...arrays) => this.arrayUnicals([...arr, ...arrays]) static arrayRepeats = (arr, repeats = 2) => this.array(repeats).reduce((acc, v) => [...acc, ...arr], arr) static arrayUnicals = (arr) => [...new Set([...arr])] static arrayShuffle = (arr) => arr.sort(() => this.range() - 0.5) static arrayShuffles = (arr, repeats = 2) => this.arrayShuffle(this.arrayRepeats(arr, repeats)) static arrayShuffleUnicals = (arr) => this.arrayUnicals(this.array(arr.length * 2).map((v) => this.arrayShuffle(arr))) static arrayIndex = (arr) => arr && this.number(0, arr.length) static arrayElement = (arr) => arr && arr[this.arrayIndex(arr)] static arrayDoubleSome = (arr) => this.arrayShuffles(arr).map((v) => (this.boolean(20) ? [v, v] : v)) static objectKey = (obj) => this.arrayElement(Object.keys(obj)) static objectProp = (obj) => obj[this.objectKey(obj)] static noteChar = () => this.arrayElement(NOTES) static octave = (min = 2, max = 4) => this.number(min, max) static note = (octave = this.octave()) => `${this.noteChar()}${octave}` static notes = (size = 10, octave) => this.array(size, (v) => this.note(octave)) static scale = () => this.arrayElement(SCALES) static durationChar = () => this.arrayElement(DURATION_CHARS) static duration = () => this.arrayElement(DURATIONS) static interval = () => this.arrayElement(INTERVAL_CHARS) static velocity = () => 0.75 + this.range() / 3 static tuningName = () => this.arrayElement(TUNING_NAMES) static tuning = () => GUITAR_TUNINGS[this.tuningName()] static noteValues = (note) => ({ note, duration: this.duration(), velocity: this.velocity() }) static noteParse = (str) => { let [note, char, octave = 1] = str.trim().match(/^([a-g#]+)(\d)$/i) return { note, char, octave } } static noteIndex = (note) => NOTES.indexOf(note.trim().match(/^([a-g#]+)/i)[1]) static noteStep = (noteChar, step = 1) => { let { char, octave } = this.noteParse(noteChar) let noteIndex = this.noteIndex(char) let newIndex = noteIndex + step const l = NOTES.length if (newIndex === l) { octave = ~~octave + 1 newIndex = 0 } else if (newIndex > l) { octave = ~~octave + ~~(newIndex / l) newIndex = newIndex % l } return `${NOTES[newIndex]}${octave}` } static getScale = (note, scale) => Teoria.note(note) .scale(scale) .simple() .map((char) => `${char}${this.octave()}`) static melody = (root, scale, size) => { const scaleNotes = this.getScale(root, scale) const melody = Array(size) .fill(root) .map(() => this.arrayElement(scaleNotes)) return this.arrayShuffles(melody) } static noteSteps = (note, size = 24) => Array(size) .fill(note) .map((v, i) => this.noteStep(v, i)) static rhythmValues = (size = 10, max = 4) => this.numbers(size, max) static rhythmValuesDeep = (size = 10, max = 4) => this.numbersDeep(size, max) static rhythmNotes = (size = 10) => this.numbers(size, 1, 4).map((v) => (v > 1 ? this.notes(v) : this.note())) static rhythmNotesDeep = (size = 10, max = 4, notes = this.notes(size)) => this.arrayDeepSome(this.rhythmNotes(size, notes), notes) static colorName = () => this.arrayElement(COLOR_NAMES) static colorHex = () => this.arrayElement(COLOR_CODES) static colorClassName = () => this.arrayElement(COLOR_CLASSNAMES) static styleColorGradient = () => `${this.colorHex()} ${this.number(0, 100)}.00%` static styleBackgroundGradient = () => `linear-gradient(${this.number(0, 120)}.00deg, ${this.styleColorGradient()}, ${this.styleColorGradient()})` }
# Looping Statement: > for loop > while loop # Branching Statement: > if-else # JavaScript Arrays: - Collection of element which are stored in continuous memory location. eg., let array = [] let array = [10, 'Rohit', true] Assignment 1: Accept a number from user and print if it is odd number or an even number? Assignment 2: Read 5 numbers from the user, store them in the array. And find which of them is the maximum number? Practice : Explore various methods of arrays: - length => returns array length eg., array.length; - pop => remove last index of array eg., array.pop(); - push => append index at last of array eg., array.push(num); array.push(num1, num2); - reverse => reverse the array eg., marks.reverse() - sort => sort array in ascending order eg., marks.sort() - slice => return index from start index to last eg., // return new array till last index. marks.slice(start-index) // return new array till end index which provided. marks.slice(start-index, end-index) - splice => deletes indexes from original array. eg., marks.splice(2,4) marks.splice(start-index,till-index) - forEach => can access each element of the given array eg., array.forEach( (x) => { console.log(x); }) - map => can multiple the original array & store in new array. eg., let newArr = marks.map(x => x*2) - concat => can append numbers in array & store in new array. eg., marks.concat(50) marks.concat(100,110,1120) - filter => can compare the values & store in new array. eg., const result = marks.filter((mark) => mark > 60);
import React, { useContext, useEffect, useState } from 'react'; import icon from '../assets/icon.png'; import CartContext from '../context/cart/CartContext'; import './SideDrawer.scss'; const SideDrawer = ({ isToggle, open }) => { const { addProductToCart, removeProductFromCart,deleteProductFromCart, carts } = useContext(CartContext); const [total, setTotal] = useState(); useEffect(() => { setTotal( carts.reduce((acc, curr) => acc + Number(curr.price) * curr.quantity, 0) ); }, [carts]); return ( <div className={`sideDrawer ${isToggle ? 'expand' : 'shrink'}`}> <img src={icon} alt="toggle-drawer" className="icon" onClick={open} /> <div className="my-cart">Your Cart</div> <div className="card"> {carts.length === 0 && ( <div style={{ fontWeight: 400 }}> {' '} There are no items in your cart. </div> )} {carts.map((prod) => ( <div className="cartitem" key={prod.id}> <button className="close-icon" onClick={() => deleteProductFromCart(prod.id)} > X </button> <div className="cartItemName">{prod.name}</div> <div className="cartItemImg"> <img src={prod.img} alt={prod.name} /> </div> <div className="quantity-section"> <button className="btn" onClick={() => removeProductFromCart(prod.id)} > - </button> <span>{prod.quantity}</span> <button className="btn" onClick={() => addProductToCart(prod)}> + </button> </div> <div className="cartItemAmount">{`£${prod.price}`}</div> {/* <div > <select className="selection" name="vat"> <option value="10%">10%</option> <option value="20%">20%</option> <option value="30%">30%</option> </select> </div> */} </div> ))} </div> {carts.length !== 0 && ( <> <hr /> <div className="check-out-section"> <div className="subtotal"> <span>Subtotal</span> <span>{total}</span> </div> <button className="checkout">Proceed to Checkout</button> </div> </> )} </div> ); }; export default SideDrawer;
import * as enums from "./enums"; import * as pulumi from "@pulumi/pulumi"; /** * Generates version number that will be latest based on existing version numbers. */ export interface DistributeVersionerLatestArgs { /** * Major version for the generated version number. Determine what is "latest" based on versions with this value as the major version. -1 is equivalent to leaving it unset. */ major?: pulumi.Input<number>; /** * Version numbering scheme to be used. * Expected value is 'Latest'. */ scheme: pulumi.Input<"Latest">; } /** * distributeVersionerLatestArgsProvideDefaults sets the appropriate defaults for DistributeVersionerLatestArgs */ export function distributeVersionerLatestArgsProvideDefaults(val: DistributeVersionerLatestArgs): DistributeVersionerLatestArgs { return { ...val, major: (val.major) ?? -1, }; } /** * Generates version number based on version number of source image */ export interface DistributeVersionerSourceArgs { /** * Version numbering scheme to be used. * Expected value is 'Source'. */ scheme: pulumi.Input<"Source">; } /** * Uploads files to VMs (Linux, Windows). Corresponds to Packer file provisioner */ export interface ImageTemplateFileCustomizerArgs { /** * The absolute path to a file (with nested directory structures already created) where the file (from sourceUri) will be uploaded to in the VM */ destination?: pulumi.Input<string>; /** * Friendly Name to provide context on what this customization step does */ name?: pulumi.Input<string>; /** * SHA256 checksum of the file provided in the sourceUri field above */ sha256Checksum?: pulumi.Input<string>; /** * The URI of the file to be uploaded for customizing the VM. It can be a github link, SAS URI for Azure Storage, etc */ sourceUri?: pulumi.Input<string>; /** * The type of customization tool you want to use on the Image. For example, "Shell" can be shell customizer * Expected value is 'File'. */ type: pulumi.Input<"File">; } /** * imageTemplateFileCustomizerArgsProvideDefaults sets the appropriate defaults for ImageTemplateFileCustomizerArgs */ export function imageTemplateFileCustomizerArgsProvideDefaults(val: ImageTemplateFileCustomizerArgs): ImageTemplateFileCustomizerArgs { return { ...val, sha256Checksum: (val.sha256Checksum) ?? "", }; } /** * Uploads files required for validation to VMs (Linux, Windows). Corresponds to Packer file provisioner */ export interface ImageTemplateFileValidatorArgs { /** * The absolute path to a file (with nested directory structures already created) where the file (from sourceUri) will be uploaded to in the VM */ destination?: pulumi.Input<string>; /** * Friendly Name to provide context on what this validation step does */ name?: pulumi.Input<string>; /** * SHA256 checksum of the file provided in the sourceUri field above */ sha256Checksum?: pulumi.Input<string>; /** * The URI of the file to be uploaded to the VM for validation. It can be a github link, Azure Storage URI (authorized or SAS), etc */ sourceUri?: pulumi.Input<string>; /** * The type of validation you want to use on the Image. For example, "Shell" can be shell validation * Expected value is 'File'. */ type: pulumi.Input<"File">; } /** * imageTemplateFileValidatorArgsProvideDefaults sets the appropriate defaults for ImageTemplateFileValidatorArgs */ export function imageTemplateFileValidatorArgsProvideDefaults(val: ImageTemplateFileValidatorArgs): ImageTemplateFileValidatorArgs { return { ...val, sha256Checksum: (val.sha256Checksum) ?? "", }; } /** * Identity for the image template. */ export interface ImageTemplateIdentityArgs { /** * The type of identity used for the image template. The type 'None' will remove any identities from the image template. */ type?: pulumi.Input<enums.ResourceIdentityType>; /** * The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. The dictionary values can be empty objects ({}) in requests. */ userAssignedIdentities?: pulumi.Input<pulumi.Input<string>[]>; } /** * Distribute as a Managed Disk Image. */ export interface ImageTemplateManagedImageDistributorArgs { /** * Tags that will be applied to the artifact once it has been created/updated by the distributor. */ artifactTags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Resource Id of the Managed Disk Image */ imageId: pulumi.Input<string>; /** * Azure location for the image, should match if image already exists */ location: pulumi.Input<string>; /** * The name to be used for the associated RunOutput. */ runOutputName: pulumi.Input<string>; /** * Type of distribution. * Expected value is 'ManagedImage'. */ type: pulumi.Input<"ManagedImage">; } /** * Describes an image source that is a managed image in customer subscription. This image must reside in the same subscription and region as the Image Builder template. */ export interface ImageTemplateManagedImageSourceArgs { /** * ARM resource id of the managed image in customer subscription */ imageId: pulumi.Input<string>; /** * Specifies the type of source image you want to start with. * Expected value is 'ManagedImage'. */ type: pulumi.Input<"ManagedImage">; } /** * Describes an image source from [Azure Gallery Images](https://docs.microsoft.com/en-us/rest/api/compute/virtualmachineimages). */ export interface ImageTemplatePlatformImageSourceArgs { /** * Image offer from the [Azure Gallery Images](https://docs.microsoft.com/en-us/rest/api/compute/virtualmachineimages). */ offer?: pulumi.Input<string>; /** * Optional configuration of purchase plan for platform image. */ planInfo?: pulumi.Input<PlatformImagePurchasePlanArgs>; /** * Image Publisher in [Azure Gallery Images](https://docs.microsoft.com/en-us/rest/api/compute/virtualmachineimages). */ publisher?: pulumi.Input<string>; /** * Image sku from the [Azure Gallery Images](https://docs.microsoft.com/en-us/rest/api/compute/virtualmachineimages). */ sku?: pulumi.Input<string>; /** * Specifies the type of source image you want to start with. * Expected value is 'PlatformImage'. */ type: pulumi.Input<"PlatformImage">; /** * Image version from the [Azure Gallery Images](https://docs.microsoft.com/en-us/rest/api/compute/virtualmachineimages). If 'latest' is specified here, the version is evaluated when the image build takes place, not when the template is submitted. */ version?: pulumi.Input<string>; } /** * Runs the specified PowerShell on the VM (Windows). Corresponds to Packer powershell provisioner. Exactly one of 'scriptUri' or 'inline' can be specified. */ export interface ImageTemplatePowerShellCustomizerArgs { /** * Array of PowerShell commands to execute */ inline?: pulumi.Input<pulumi.Input<string>[]>; /** * Friendly Name to provide context on what this customization step does */ name?: pulumi.Input<string>; /** * If specified, the PowerShell script will be run with elevated privileges using the Local System user. Can only be true when the runElevated field above is set to true. */ runAsSystem?: pulumi.Input<boolean>; /** * If specified, the PowerShell script will be run with elevated privileges */ runElevated?: pulumi.Input<boolean>; /** * URI of the PowerShell script to be run for customizing. It can be a github link, SAS URI for Azure Storage, etc */ scriptUri?: pulumi.Input<string>; /** * SHA256 checksum of the power shell script provided in the scriptUri field above */ sha256Checksum?: pulumi.Input<string>; /** * The type of customization tool you want to use on the Image. For example, "Shell" can be shell customizer * Expected value is 'PowerShell'. */ type: pulumi.Input<"PowerShell">; /** * Valid exit codes for the PowerShell script. [Default: 0] */ validExitCodes?: pulumi.Input<pulumi.Input<number>[]>; } /** * imageTemplatePowerShellCustomizerArgsProvideDefaults sets the appropriate defaults for ImageTemplatePowerShellCustomizerArgs */ export function imageTemplatePowerShellCustomizerArgsProvideDefaults(val: ImageTemplatePowerShellCustomizerArgs): ImageTemplatePowerShellCustomizerArgs { return { ...val, runAsSystem: (val.runAsSystem) ?? false, runElevated: (val.runElevated) ?? false, sha256Checksum: (val.sha256Checksum) ?? "", }; } /** * Runs the specified PowerShell script during the validation phase (Windows). Corresponds to Packer powershell provisioner. Exactly one of 'scriptUri' or 'inline' can be specified. */ export interface ImageTemplatePowerShellValidatorArgs { /** * Array of PowerShell commands to execute */ inline?: pulumi.Input<pulumi.Input<string>[]>; /** * Friendly Name to provide context on what this validation step does */ name?: pulumi.Input<string>; /** * If specified, the PowerShell script will be run with elevated privileges using the Local System user. Can only be true when the runElevated field above is set to true. */ runAsSystem?: pulumi.Input<boolean>; /** * If specified, the PowerShell script will be run with elevated privileges */ runElevated?: pulumi.Input<boolean>; /** * URI of the PowerShell script to be run for validation. It can be a github link, Azure Storage URI, etc */ scriptUri?: pulumi.Input<string>; /** * SHA256 checksum of the power shell script provided in the scriptUri field above */ sha256Checksum?: pulumi.Input<string>; /** * The type of validation you want to use on the Image. For example, "Shell" can be shell validation * Expected value is 'PowerShell'. */ type: pulumi.Input<"PowerShell">; /** * Valid exit codes for the PowerShell script. [Default: 0] */ validExitCodes?: pulumi.Input<pulumi.Input<number>[]>; } /** * imageTemplatePowerShellValidatorArgsProvideDefaults sets the appropriate defaults for ImageTemplatePowerShellValidatorArgs */ export function imageTemplatePowerShellValidatorArgsProvideDefaults(val: ImageTemplatePowerShellValidatorArgs): ImageTemplatePowerShellValidatorArgs { return { ...val, runAsSystem: (val.runAsSystem) ?? false, runElevated: (val.runElevated) ?? false, sha256Checksum: (val.sha256Checksum) ?? "", }; } /** * Specifies optimization to be performed on image. */ export interface ImageTemplatePropertiesOptimizeArgs { /** * Optimization is applied on the image for a faster VM boot. */ vmBoot?: pulumi.Input<ImageTemplatePropertiesVmBootArgs>; } /** * Configuration options and list of validations to be performed on the resulting image. */ export interface ImageTemplatePropertiesValidateArgs { /** * If validation fails and this field is set to false, output image(s) will not be distributed. This is the default behavior. If validation fails and this field is set to true, output image(s) will still be distributed. Please use this option with caution as it may result in bad images being distributed for use. In either case (true or false), the end to end image run will be reported as having failed in case of a validation failure. [Note: This field has no effect if validation succeeds.] */ continueDistributeOnFailure?: pulumi.Input<boolean>; /** * List of validations to be performed. */ inVMValidations?: pulumi.Input<pulumi.Input<ImageTemplateFileValidatorArgs | ImageTemplatePowerShellValidatorArgs | ImageTemplateShellValidatorArgs>[]>; /** * If this field is set to true, the image specified in the 'source' section will directly be validated. No separate build will be run to generate and then validate a customized image. */ sourceValidationOnly?: pulumi.Input<boolean>; } /** * imageTemplatePropertiesValidateArgsProvideDefaults sets the appropriate defaults for ImageTemplatePropertiesValidateArgs */ export function imageTemplatePropertiesValidateArgsProvideDefaults(val: ImageTemplatePropertiesValidateArgs): ImageTemplatePropertiesValidateArgs { return { ...val, continueDistributeOnFailure: (val.continueDistributeOnFailure) ?? false, sourceValidationOnly: (val.sourceValidationOnly) ?? false, }; } /** * Optimization is applied on the image for a faster VM boot. */ export interface ImageTemplatePropertiesVmBootArgs { /** * Enabling this field will improve VM boot time by optimizing the final customized image output. */ state?: pulumi.Input<enums.VMBootOptimizationState>; } /** * Reboots a VM and waits for it to come back online (Windows). Corresponds to Packer windows-restart provisioner */ export interface ImageTemplateRestartCustomizerArgs { /** * Friendly Name to provide context on what this customization step does */ name?: pulumi.Input<string>; /** * Command to check if restart succeeded [Default: ''] */ restartCheckCommand?: pulumi.Input<string>; /** * Command to execute the restart [Default: 'shutdown /r /f /t 0 /c "packer restart"'] */ restartCommand?: pulumi.Input<string>; /** * Restart timeout specified as a string of magnitude and unit, e.g. '5m' (5 minutes) or '2h' (2 hours) [Default: '5m'] */ restartTimeout?: pulumi.Input<string>; /** * The type of customization tool you want to use on the Image. For example, "Shell" can be shell customizer * Expected value is 'WindowsRestart'. */ type: pulumi.Input<"WindowsRestart">; } /** * Distribute via Azure Compute Gallery. */ export interface ImageTemplateSharedImageDistributorArgs { /** * Tags that will be applied to the artifact once it has been created/updated by the distributor. */ artifactTags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Flag that indicates whether created image version should be excluded from latest. Omit to use the default (false). */ excludeFromLatest?: pulumi.Input<boolean>; /** * Resource Id of the Azure Compute Gallery image */ galleryImageId: pulumi.Input<string>; /** * [Deprecated] A list of regions that the image will be replicated to. This list can be specified only if targetRegions is not specified. This field is deprecated - use targetRegions instead. */ replicationRegions?: pulumi.Input<pulumi.Input<string>[]>; /** * The name to be used for the associated RunOutput. */ runOutputName: pulumi.Input<string>; /** * [Deprecated] Storage account type to be used to store the shared image. Omit to use the default (Standard_LRS). This field can be specified only if replicationRegions is specified. This field is deprecated - use targetRegions instead. */ storageAccountType?: pulumi.Input<string | enums.SharedImageStorageAccountType>; /** * The target regions where the distributed Image Version is going to be replicated to. This object supersedes replicationRegions and can be specified only if replicationRegions is not specified. */ targetRegions?: pulumi.Input<pulumi.Input<TargetRegionArgs>[]>; /** * Type of distribution. * Expected value is 'SharedImage'. */ type: pulumi.Input<"SharedImage">; /** * Describes how to generate new x.y.z version number for distribution. */ versioning?: pulumi.Input<DistributeVersionerLatestArgs | DistributeVersionerSourceArgs>; } /** * imageTemplateSharedImageDistributorArgsProvideDefaults sets the appropriate defaults for ImageTemplateSharedImageDistributorArgs */ export function imageTemplateSharedImageDistributorArgsProvideDefaults(val: ImageTemplateSharedImageDistributorArgs): ImageTemplateSharedImageDistributorArgs { return { ...val, excludeFromLatest: (val.excludeFromLatest) ?? false, }; } /** * Describes an image source that is an image version in an Azure Compute Gallery or a Direct Shared Gallery. */ export interface ImageTemplateSharedImageVersionSourceArgs { /** * ARM resource id of the image version. When image version name is 'latest', the version is evaluated when the image build takes place. */ imageVersionId: pulumi.Input<string>; /** * Specifies the type of source image you want to start with. * Expected value is 'SharedImageVersion'. */ type: pulumi.Input<"SharedImageVersion">; } /** * Runs a shell script during the customization phase (Linux). Corresponds to Packer shell provisioner. Exactly one of 'scriptUri' or 'inline' can be specified. */ export interface ImageTemplateShellCustomizerArgs { /** * Array of shell commands to execute */ inline?: pulumi.Input<pulumi.Input<string>[]>; /** * Friendly Name to provide context on what this customization step does */ name?: pulumi.Input<string>; /** * URI of the shell script to be run for customizing. It can be a github link, SAS URI for Azure Storage, etc */ scriptUri?: pulumi.Input<string>; /** * SHA256 checksum of the shell script provided in the scriptUri field */ sha256Checksum?: pulumi.Input<string>; /** * The type of customization tool you want to use on the Image. For example, "Shell" can be shell customizer * Expected value is 'Shell'. */ type: pulumi.Input<"Shell">; } /** * imageTemplateShellCustomizerArgsProvideDefaults sets the appropriate defaults for ImageTemplateShellCustomizerArgs */ export function imageTemplateShellCustomizerArgsProvideDefaults(val: ImageTemplateShellCustomizerArgs): ImageTemplateShellCustomizerArgs { return { ...val, sha256Checksum: (val.sha256Checksum) ?? "", }; } /** * Runs the specified shell script during the validation phase (Linux). Corresponds to Packer shell provisioner. Exactly one of 'scriptUri' or 'inline' can be specified. */ export interface ImageTemplateShellValidatorArgs { /** * Array of shell commands to execute */ inline?: pulumi.Input<pulumi.Input<string>[]>; /** * Friendly Name to provide context on what this validation step does */ name?: pulumi.Input<string>; /** * URI of the shell script to be run for validation. It can be a github link, Azure Storage URI, etc */ scriptUri?: pulumi.Input<string>; /** * SHA256 checksum of the shell script provided in the scriptUri field */ sha256Checksum?: pulumi.Input<string>; /** * The type of validation you want to use on the Image. For example, "Shell" can be shell validation * Expected value is 'Shell'. */ type: pulumi.Input<"Shell">; } /** * imageTemplateShellValidatorArgsProvideDefaults sets the appropriate defaults for ImageTemplateShellValidatorArgs */ export function imageTemplateShellValidatorArgsProvideDefaults(val: ImageTemplateShellValidatorArgs): ImageTemplateShellValidatorArgs { return { ...val, sha256Checksum: (val.sha256Checksum) ?? "", }; } /** * Distribute via VHD in a storage account. */ export interface ImageTemplateVhdDistributorArgs { /** * Tags that will be applied to the artifact once it has been created/updated by the distributor. */ artifactTags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The name to be used for the associated RunOutput. */ runOutputName: pulumi.Input<string>; /** * Type of distribution. * Expected value is 'VHD'. */ type: pulumi.Input<"VHD">; /** * Optional Azure Storage URI for the distributed VHD blob. Omit to use the default (empty string) in which case VHD would be published to the storage account in the staging resource group. */ uri?: pulumi.Input<string>; } /** * Describes the virtual machines used to build and validate images */ export interface ImageTemplateVmProfileArgs { /** * Size of the OS disk in GB. Omit or specify 0 to use Azure's default OS disk size. */ osDiskSizeGB?: pulumi.Input<number>; /** * Optional array of resource IDs of user assigned managed identities to be configured on the build VM and validation VM. This may include the identity of the image template. */ userAssignedIdentities?: pulumi.Input<pulumi.Input<string>[]>; /** * Size of the virtual machine used to build, customize and capture images. Omit or specify empty string to use the default (Standard_D1_v2 for Gen1 images and Standard_D2ds_v4 for Gen2 images). */ vmSize?: pulumi.Input<string>; /** * Optional configuration of the virtual network to use to deploy the build VM and validation VM in. Omit if no specific virtual network needs to be used. */ vnetConfig?: pulumi.Input<VirtualNetworkConfigArgs>; } /** * imageTemplateVmProfileArgsProvideDefaults sets the appropriate defaults for ImageTemplateVmProfileArgs */ export function imageTemplateVmProfileArgsProvideDefaults(val: ImageTemplateVmProfileArgs): ImageTemplateVmProfileArgs { return { ...val, osDiskSizeGB: (val.osDiskSizeGB) ?? 0, vmSize: (val.vmSize) ?? "", vnetConfig: (val.vnetConfig ? pulumi.output(val.vnetConfig).apply(virtualNetworkConfigArgsProvideDefaults) : undefined), }; } /** * Installs Windows Updates. Corresponds to Packer Windows Update Provisioner (https://github.com/rgl/packer-provisioner-windows-update) */ export interface ImageTemplateWindowsUpdateCustomizerArgs { /** * Array of filters to select updates to apply. Omit or specify empty array to use the default (no filter). Refer to above link for examples and detailed description of this field. */ filters?: pulumi.Input<pulumi.Input<string>[]>; /** * Friendly Name to provide context on what this customization step does */ name?: pulumi.Input<string>; /** * Criteria to search updates. Omit or specify empty string to use the default (search all). Refer to above link for examples and detailed description of this field. */ searchCriteria?: pulumi.Input<string>; /** * The type of customization tool you want to use on the Image. For example, "Shell" can be shell customizer * Expected value is 'WindowsUpdate'. */ type: pulumi.Input<"WindowsUpdate">; /** * Maximum number of updates to apply at a time. Omit or specify 0 to use the default (1000) */ updateLimit?: pulumi.Input<number>; } /** * imageTemplateWindowsUpdateCustomizerArgsProvideDefaults sets the appropriate defaults for ImageTemplateWindowsUpdateCustomizerArgs */ export function imageTemplateWindowsUpdateCustomizerArgsProvideDefaults(val: ImageTemplateWindowsUpdateCustomizerArgs): ImageTemplateWindowsUpdateCustomizerArgs { return { ...val, updateLimit: (val.updateLimit) ?? 0, }; } /** * Purchase plan configuration for platform image. */ export interface PlatformImagePurchasePlanArgs { /** * Name of the purchase plan. */ planName: pulumi.Input<string>; /** * Product of the purchase plan. */ planProduct: pulumi.Input<string>; /** * Publisher of the purchase plan. */ planPublisher: pulumi.Input<string>; } /** * Describes the target region information. */ export interface TargetRegionArgs { /** * The name of the region. */ name: pulumi.Input<string>; /** * The number of replicas of the Image Version to be created in this region. Omit to use the default (1). */ replicaCount?: pulumi.Input<number>; /** * Specifies the storage account type to be used to store the image in this region. Omit to use the default (Standard_LRS). */ storageAccountType?: pulumi.Input<string | enums.SharedImageStorageAccountType>; } /** * targetRegionArgsProvideDefaults sets the appropriate defaults for TargetRegionArgs */ export function targetRegionArgsProvideDefaults(val: TargetRegionArgs): TargetRegionArgs { return { ...val, replicaCount: (val.replicaCount) ?? 1, }; } /** * Virtual Network configuration. */ export interface VirtualNetworkConfigArgs { /** * Size of the proxy virtual machine used to pass traffic to the build VM and validation VM. Omit or specify empty string to use the default (Standard_A1_v2). */ proxyVmSize?: pulumi.Input<string>; /** * Resource id of a pre-existing subnet. */ subnetId?: pulumi.Input<string>; } /** * virtualNetworkConfigArgsProvideDefaults sets the appropriate defaults for VirtualNetworkConfigArgs */ export function virtualNetworkConfigArgsProvideDefaults(val: VirtualNetworkConfigArgs): VirtualNetworkConfigArgs { return { ...val, proxyVmSize: (val.proxyVmSize) ?? "", }; }
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\blogCategory> */ use App\Models\User; class BlogCategoryFactory extends Factory { /** * Define the model's default state. * * @return array<string, mixed> */ protected $categories = [ 'Design', 'Mobile Application', 'Content Writer', 'Real Estate', 'Information Technology', 'Construction', 'Front End', 'Back End' ]; public static $counter = 0; public function definition(): array { $name = $this->categories[self::$counter++]; return [ 'name' => $name, 'slug' => $this->generateSlug($name), 'user_id' => User::where('user_type', 'admin')->inRandomOrder()->get()[0]->id, ]; } private function generateSlug($name) { return implode('-', explode(' ', strtolower($name)));; } }
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ /* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package model.dao; import java.util.List; import javax.persistence.EntityManager; import model.Professores; /** * * @author Matheus */ public class ProfessorDaoJpa implements InterfaceDao<Professores>{ @Override public void incluir(Professores entidade) throws Exception { /** *Aqui estamos fazendo basicamente o que fizemos na última aula, porém dentro de um método * Aqui é o mesmo método só mudou o nome do arquivo de BDUtils para ConnFactory que ambos tinham a mesma * funcionalidade, porém com nomes diferentes. Abrimos a transação persistindo e no final ele grava com * o commit e no final ele fecha com o close */ EntityManager em = ConnFactory.getEntityManager(); try{ em.getTransaction().begin(); em.persist(entidade); em.getTransaction().commit(); // o comit grava a ação }finally{ em.close(); } } @Override public void editar(Professores entidade) throws Exception { /* O merge usado ali ele serve para atualizar uma instância de entidade de persistencia com novos valores de um campo detached entity instancia. */ EntityManager em = ConnFactory.getEntityManager(); try{ em.getTransaction().begin(); em.merge(entidade); em.getTransaction().commit(); }finally{ em.close(); } } @Override public void excluir(Professores entidade) throws Exception { /* Para nós excluirmos alguém nós precisamos encontra-lo no nosso banco de dados para assim então excluir-lo. chegando o id ali no find, este novo registro vai receber aquele registro que foi passado ai quando eu removo é como se tivesse um ponteiro lá atrelado a essa entidade aí eu removo */ EntityManager em = ConnFactory.getEntityManager(); try{ em.getTransaction().begin(); Professores prof = em.find(Professores.class,entidade.getId()); em.remove(prof); em.getTransaction().commit(); } finally{ em.close(); } } @Override public Professores pesquisarPorId(int id) throws Exception { Professores prof = null; EntityManager em = ConnFactory.getEntityManager(); try{ em.getTransaction().begin(); prof = em.find(Professores.class,id); em.getTransaction().commit(); } finally{ em.close(); } return prof; } @Override public List<Professores> listar() throws Exception { /* Temos um método listar que retorna uma lista de Contato e ali ele recebeu essa lista recebendo null, para que de inicio ela não tenha nenhum contato. 2º Chamamos o confactory para criar a conexão, chamamos o HQL que diretamente jogaremos para uma lista de registro o resultado do sql e no final ele mostra para o usuário */ EntityManager em = ConnFactory.getEntityManager(); List<Professores> lista = null; try{ em.getTransaction().begin(); lista = em.createQuery("FROM Professores prof").getResultList(); em.getTransaction().commit(); } finally{ em.close(); } return lista; } @Override public List<Professores> filtragem(String filtro) throws Exception { List<Professores> lista = null; EntityManager em = ConnFactory.getEntityManager(); try { em.getTransaction().begin(); lista = em.createQuery("FROM Professores WHERE nomeProfessor LIKE '%" + filtro + "%'").getResultList(); em.getTransaction().commit(); } finally { em.close(); } return lista; } }
import { createError } from "../error.js"; import User from "../models/User.js"; import Video from "../models/Video.js"; export const updateUser = async (req, res, next) => { if (req.params.id === req.user.id) { try { const updatedUser = await User.findByIdAndUpdate( req.params.id, { $set: req.body, }, { new: true } ); res.status(200).json(updatedUser); } catch (err) { res.status(500).send("Internal server error"); } } else { return next(createError(403, "You can update only your account!")); } }; export const deleteUser = async (req, res, next) => { if (req.params.id === req.user.id) { try { await User.findByIdAndDelete( req.params.id, ); res.status(200).json("User deleted successfully!"); } catch (err) { res.status(500).send("Internal server error"); } } else { return next(createError(403, "You can delete only your account!")); } }; export const getUser = async (req, res, next) => { try { const user = await User.findById(req.params.id); res.status(200).json(user); } catch (err) { res.status(404).send("User not Found"); } }; export const subscribe = async (req, res, next) => { try { await User.findByIdAndUpdate(req.user.id, { $addToSet: { subscribedUsers: req.params.id }, }); await User.findByIdAndUpdate(req.params.id, { $inc: { subscribers: 1 }, }); res.status(200).json("Subscription Successfull.") } catch (err) { next(createError(403, "You are not authenticated!")) } }; export const unsubscribe = async (req, res, next) => { try { await User.findByIdAndUpdate(req.user.id, { $pull: { subscribedUsers: req.params.id }, }); await User.findByIdAndUpdate(req.params.id, { $inc: { subscribers: -1 }, }); res.status(200).json("Unsubscription successfull.") } catch (err) { next(createError(403, "You are not authenticated!")) } }; export const like = async (req, res, next) => { const id = req.user.id; const videoId = req.params.videoId; try { await Video.findByIdAndUpdate(videoId, { $addToSet: { likes: id }, $pull: { dislikes: id } }) res.status(200).json("The video has been liked"); } catch (err) { next(err); } }; export const dislike = async (req, res, next) => { const id = req.user.id; const videoId = req.params.videoId; try { await Video.findByIdAndUpdate(videoId, { $addToSet: { dislikes: id }, $pull: { likes: id } }) res.status(200).json("The video has been disliked"); } catch (err) { next(err); } }; export const addHistory = async (req, res, next) => { const id = req.user.id; const videoId = req.params.videoId; try { await User.findByIdAndUpdate(id, { $addToSet: { history: videoId } }) res.status(200).json("video added in history successfully!"); } catch (err) { next(err); } }
package main.com.kv.leetcode.easy; import com.sun.management.MissionControlMXBean; /** * An array is monotonic if it is either monotone increasing or monotone decreasing. * * An array A is monotone increasing if for all i <= j, A[i] <= A[j]. * An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. * * Return true if and only if the given array A is monotonic. * * * * Example 1: * * Input: [1,2,2,3] * Output: true * Example 2: * * Input: [6,5,4,4] * Output: true * Example 3: * * Input: [1,3,2] * Output: false * Example 4: * * Input: [1,2,4,5] * Output: true * Example 5: * * Input: [1,1,1] * Output: true * * * Note: * * 1 <= A.length <= 50000 * -100000 <= A[i] <= 100000 */ public class MonotoniArray896 { public static void main(String[] args) { int [] arr = new int[]{1,2,3,4,4,5}; System.out.println(isMonotonic(arr)); } /** * * @param A * @return */ public static boolean isMonotonic(int[] A) { boolean increase = true; boolean decrease = true; for(int i = 0; i<A.length-1;i++){ if(A[i]>A[i+1]){ increase = false; } if(A[i]<A[i+1]){ decrease = false; } if(A[i]==A[i+1]){ increase = true; decrease = true; } } return increase || decrease; } }
import { useState, useEffect, Fragment } from "react"; import styled from "styled-components"; import moment from "moment"; import { getOrdersApi } from "../../../api"; export const Transactions = () => { const [orders, setOrders] = useState([]); const [isLoading, setIsLoading] = useState(false); useEffect(() => { const fetchData = async () => { setIsLoading(true); try { const response = await getOrdersApi(); setOrders(response?.orders); } catch (err) { console.log(err); } finally { setIsLoading(false); } }; fetchData(); }, []); return ( <StyledTransaction> {isLoading ? ( <p>Transaction loading...</p> ) : ( <Fragment> <h3>Latest Transaction</h3> {orders?.map((order, _i) => ( <Transaction key={_i}> <p>{order.shipping.name}</p> <p>${(order.total / 100).toLocaleString()}</p> <p>{moment(order.createdAt).fromNow()}</p> </Transaction> ))} </Fragment> )} </StyledTransaction> ); }; const StyledTransaction = styled.div` background: rgb(48, 51, 78); color: rgba(234, 234, 255, 0.87); padding: 1rem; border-radius: 4px; `; const Transaction = styled.div` display: flex; font-size: 14px; margin-top: 1rem; padding: 0.5rem; border-radius: 4px; background: rgba(38, 198, 249, 0.12); p { flex: 1; } &:nth-child(even) { background: rgba(102, 108, 255, 0.12); } `;
<template> <Line v-if="loaded" :data="chartData" :options="options"/> </template> <script> import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from 'chart.js' import {Line} from 'vue-chartjs' import axios from "axios"; ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend ) let raw_data = new Array(3600); export default { components: { Line }, data: () => ({ chartData: { labels: ['9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00'], datasets: [ { label: 'Data One', backgroundColor: '#f87979', data: [0.3, 0.8, 0.7, 0.6, 0.5, 0.1, 0.5] }, { label: 'Data Two', backgroundColor: '#a3d9c8', data: [0.6, 0.45, 0.42, 0.12, 0.75, 0.61, 0.49] }, ], }, options: { responsive: true, }, loaded: false }), async mounted() { const url = process.env.VUE_APP_BACKEND_URL + 'api/gNbPerformanceRecord/HandoverSuccessRate'; const {data} = await axios.get(url); let cell_id_sets = new Set(); let raw_datasets = []; let raw_chart_labels = []; // this.data.labels[0] = 'ddd' // console.log(data) for (let i = data.length - 1; i >= 0; --i) { let today = new Date(); let data_datetime = new Date(data[i].createdAt); let diffMs = (today - data_datetime); // milliseconds between now & Christmas let diffMins = Math.round(diffMs / 60000) % 20; // minutes if (raw_data[diffMins] == null) { raw_data[diffMins] = [] } raw_data[diffMins].push(data[i]) cell_id_sets.add(data[i]['cell_id']) } // iter over all possible cell_id for (let key of cell_id_sets) { let r = Math.floor(Math.random() * 256) let g = Math.floor(Math.random() * 256) let b = Math.floor(Math.random() * 256) raw_datasets.push({ label: key, borderColor: 'rgba(' + r + ',' + g + ',' + b + ',0.5)', backgroundColor: 'rgba(' + r + ',' + g + ',' + b + ',0.3)', data: [] }) } // console.log(raw_datasets) // console.log(raw_data) for (let i = raw_data.length - 1; i >= 0; --i) { if (raw_data[i] === undefined) continue; const record_time = new Date(new Date() - i * 60000); raw_chart_labels.push(record_time.getMonth().toString() + '/' + record_time.getDay().toString() + ' ' + record_time.getHours() + ':' + (record_time.getMinutes() < 10 ? '0' : '') + record_time.getMinutes() + ' '); let current_minutes_cell_id_sets = new Set(); for (let j = 0; j < raw_data[i].length; j++) { if (current_minutes_cell_id_sets.has(raw_data[i][j]['cell_id'])) continue; current_minutes_cell_id_sets.add(raw_data[i][j]['cell_id']) for (let k = raw_datasets.length - 1; k >= 0; --k) { if (raw_datasets[k]['label'] === raw_data[i][j]['cell_id']) { raw_datasets[k]['data'].push(raw_data[i][j]['value']) } } } } // console.log(raw_datasets) this.chartData.datasets = raw_datasets; this.chartData.labels = raw_chart_labels; this.loaded = true // console.log(raw_data) } } </script> <style scoped> </style>
// React Profiler is a built-in tool in React that allows developers to analyze the performance ' // of their React applications, specifically tracking how long it takes for components to render. // It helps identify performance bottlenecks and optimize the rendering process. import "./App.css"; import { Profiler } from "react"; import Header from "./Components/Header"; import Footer from "./Components/Footer"; function App() { const onRenderCallback = ( id, phase, actualDuration, baseDuration, startTime, commitTime ) => { // Log performance data console.log(`Component ${id} took ${actualDuration}ms to render.`); }; return ( <div className="App"> <Profiler id="MyApp" onRender={onRenderCallback}> <Header /> <Footer /> <Memooo /> </Profiler> {/* <Dta/> */} </div> ); } export default App;
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> std::vector<std::string> getStrings() { std::vector<std::string> strings; std::string line; std::ifstream input_file("input.txt"); if (!input_file.is_open()) { std::cerr << "Error opening file" << std::endl; return {}; } while (getline(input_file, line)) { strings.push_back(line); } input_file.close(); return strings; } std::vector<int> getInts() { std::vector<int> ints; std::string line; std::ifstream input_file("input.txt"); if (!input_file.is_open()) { std::cerr << "Error opening file" << std::endl; return {}; } while (getline(input_file, line)) { ints.push_back(std::stoi(line)); } input_file.close(); return ints; } // Fast way to check if line is valid (that we can't use b/c we need the first character): // check if there are the same amount of each starting character as the ending character int main(int argc, char** argv) { std::vector<std::string> strings = getStrings(); std::vector<char> startingCharacters{'(','[','{','<'}; std::vector<char> closingCharacters{')',']','}','>'}; std::map<char, char> closingToOpening = {{')','('},{']','['},{'}','{'},{'>','<'}}; std::map<char, char> openingToClosing = {{'(',')'},{'[',']'},{'{','}'},{'<','>'}}; std::map<char, int> scoreMap = {{')',1},{']',2},{'}',3},{'>',4}}; std::vector<unsigned long long> scores{}; for (std::string s : strings) { std::vector<char> calledOpeningCharacters{}; // This will store the opening characters we have encountered, // pushing to the back of the list. If we see a closing character, it must correspond to the last item in this vector. // If it does, the last item should be removed. If it doesn't, add to the score for the line. bool isIncomplete = true; for (int i = 0; i < s.size(); i++) { char c = s[i]; if (std::find(startingCharacters.begin(), startingCharacters.end(), c) != startingCharacters.end()) { calledOpeningCharacters.push_back(c); } else if (std::find(closingCharacters.begin(), closingCharacters.end(), c) != closingCharacters.end()) { if (calledOpeningCharacters.size() == 0) { isIncomplete = false; break; } else if (closingToOpening[c] != calledOpeningCharacters[calledOpeningCharacters.size()-1]) { isIncomplete = false; break; } else { calledOpeningCharacters.pop_back(); } } } if (isIncomplete) { unsigned long score = 0; for (int i = calledOpeningCharacters.size() - 1; i >= 0; i--) { score *= 5ULL; score += scoreMap[openingToClosing[calledOpeningCharacters[i]]]; } scores.push_back(score); } } std::sort(scores.begin(), scores.end()); unsigned long median = (scores[scores.size()/2ULL]); std::cout << median << std::endl; return 0; }
# base_pretrain """ 预训练 目前针对80w 的 wiki 预训练; """ import os import sys sys.setrecursionlimit(10000) from pathlib import Path from typing import Optional from dataclasses import dataclass, field import numpy as np from nltk.translate.bleu_score import corpus_bleu import distance from rouge import Rouge import pickle import torch from torch.utils.data import DataLoader from transformers import ( HfArgumentParser, AutoProcessor ) from transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments import kp_setup import logging from libs.datasets.base_pretrain_dataset import BasePretrainDataset from libs import utils from libs.datasets.dataset_utils import custom_token_split from libs.models.MyCustomPix2StructForConditionalGeneration import MyCustomPix2StructForConditionalGeneration # 任务数据路径 data_dir = '/home/ana/data4/datasets/wiki_zh/synthdog_out/cn_wiki_500k_long' # 来自官方的预训练好的路径, 简单做了扩充 model_path = "/home/ana/data4/models/pix2struct-base-raw-enlarge-vocab-special-mean" train_file = os.path.join(data_dir, "train", "metadata.jsonl") validation_file = os.path.join(data_dir, "validation", "metadata.jsonl") test_file = validation_file # 输出路径 output_dir = "/home/ana/data4/output_models/MyMLLM/p2s_pretrain/stage0_longwiki_80w" @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( default=model_path, metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) config_name: Optional[str] = field( default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. """ task_name: Optional[str] = field(default="text-generation", metadata={"help": "The name of the task (ner, pos...)."}) language: Optional[str] = field( default='zh', metadata={"help": "The dataset in xfund to use"} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) train_file: Optional[str] = field( default=train_file, metadata={"help": "The input training data file (a csv or JSON file)."} ) validation_file: Optional[str] = field( default=validation_file, metadata={"help": "An optional input evaluation data file to evaluate on (a csv or JSON file)."}, ) test_file: Optional[str] = field( default=test_file, metadata={"help": "An optional input test data file to predict on (a csv or JSON file)."}, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." }, ) max_val_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of validation examples to this " "value if set." }, ) max_test_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of test examples to this " "value if set." }, ) segment_level_layout: bool = field(default=True) visual_embed: bool = field(default=True) data_dir: Optional[str] = field(default=data_dir) input_size: int = field(default=224, metadata={"help": "images input size for backbone"}) # 这个实现里应该没有这个 # second_input_size: int = field(default=112, metadata={"help": "images input size for discrete vae"}) train_interpolation: str = field( default='bicubic', metadata={"help": "Training interpolation (random, bilinear, bicubic)"}) second_interpolation: str = field( default='lanczos', metadata={"help": "Interpolation for discrete vae (random, bilinear, bicubic)"}) # 这部分数值貌似model_dir 有保存的 # imagenet_default_mean_and_std: bool = field(default=False, metadata={"help": ""}) decoder_max_length: int = field(default=2048, metadata={"help": "生成文本长度"}) decoder_max_input_length: int = field(default=1024, metadata={"help": "最大 prompt 长度"}) @dataclass class CustomTrainingArguments(Seq2SeqTrainingArguments): output_dir: Optional[str] = field( default=output_dir, metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) compute_counter = 0 def compute_metrics(pred, num_examples=20): global compute_counter rouge_obj = Rouge() labels_ids = pred.label_ids pred_ids = pred.predictions # dump for debug try: utils.make_sure_dir_there(training_args.output_dir) with open(os.path.join(training_args.output_dir, f'eval_token_out.{compute_counter}.txt'), 'wb') as f: pickle.dump([labels_ids, pred_ids], f) except Exception as e: logging.error(e) # pred trainer 里面 默认 pad -100,(对pred) # 截断再对比 pred_ids[pred_ids == -100] = processor.tokenizer.pad_token_id # pred_ids[labels_ids == -100] = processor.tokenizer.pad_token_id for i, pred_id in enumerate(pred_ids): i_sep_index = np.where(pred_id == processor.tokenizer.sep_token_id)[0][0] pred_ids[i][:i_sep_index + 1] = processor.tokenizer.pad_token_id decoded_pred_strs = processor.tokenizer.batch_decode(pred_ids, skip_special_tokens=False) labels_ids[labels_ids == -100] = processor.tokenizer.pad_token_id decoded_label_strs = processor.tokenizer.batch_decode(labels_ids, skip_special_tokens=False) # 去掉特殊的 pad 和 </s> cleaned_decoded_label_strs = [ s.replace(processor.tokenizer.pad_token, "").replace(processor.tokenizer.eos_token, "") for s in decoded_label_strs] cleaned_decoded_pred_strs = [s.replace(processor.tokenizer.pad_token, "").replace(processor.tokenizer.eos_token, "") for s in decoded_pred_strs] # 防止空串 label_strs = ["#" if s.strip() == "" else s for s in cleaned_decoded_label_strs] pred_strs = ["#" if s.strip() == "" else s for s in cleaned_decoded_pred_strs] # 空格分隔是为了配合后续 rouge 等计算 sep_label_strs = [" ".join(custom_token_split(x)) for x in label_strs] sep_pred_strs = [" ".join(custom_token_split(x)) for x in pred_strs] sum_distance_ratio = 0 for i_pred, i_label in zip(pred_strs, label_strs): if i_pred == '': logging.error(f"should not be empty i_pred:[f{i_pred}], i_label:[f{i_label}]") ned = distance.levenshtein(i_pred, i_label, normalized=True) sum_distance_ratio += ned # sep_pred_str = [" ".join(x) for x in pred_str] # sep_label_str = [" ".join(x) for x in label_str] levenshtein_distance_ratio = sum_distance_ratio / len(pred_strs) # rouge一句不知道为啥有个bug, 观察 try: with open(os.path.join(training_args.output_dir, f'eval_out.{compute_counter}.txt'), 'w') as f: for i_pred, i_label in zip(pred_strs, label_strs): line = "\n".join([i_pred, i_label]) f.write(line + "\n\n") except Exception as e: logging.error(e) rouge_scores = {} try: with utils.utils_timer("calculating rouge"): rouge_scores = rouge_obj.get_scores(sep_pred_strs, sep_label_strs, avg=True) except Exception as e: logging.error(e) bleu_score_corpus = 0 try: with utils.utils_timer("calculating bleu"): bleu_score_corpus = corpus_bleu([[s] for s in sep_label_strs], sep_pred_strs) except Exception as e: logging.error(e) logging.info(f"EVAL examples: {num_examples}") for i_pred, i_label in zip(pred_strs, label_strs): logging.info(f"pred:{i_pred} | label:{i_label}") num_examples -= 1 if num_examples == 0: break scores = dict() scores['NED'] = round(levenshtein_distance_ratio, 4) scores['BLEU'] = round(bleu_score_corpus, 4) for r_l, r_scores in rouge_scores.items(): for k, v in r_scores.items(): scores[f"{r_l}_{k}"] = round(v, 4) compute_counter += 1 return scores def collator(batch, max_length=2048): """ train / eval /test max_length for input """ # 当前实现就是需要有prompt tokenizer = processor.tokenizer new_batch = {"flattened_patches": [], "attention_mask": []} # prompt_and_labels = [item['prompt'] + processor.tokenizer.sep_token_id + item["labels"] for item in batch] # 计算 label ,构建 decoder_input_id # prompts = [] prompt_and_labels = [] for i, item in enumerate(batch): i_prompt_and_labels = item['prompt'] + tokenizer.sep_token + item["labels"] # shift right by hand prompt_and_labels.append(i_prompt_and_labels) # prompts.append(item['prompt']) # decoder_input text_input_ids = processor(text=prompt_and_labels, padding=True, return_tensors="pt", add_special_tokens=True, max_length=max_length, truncation=True) # decoder_input_ids, 应该仅训练的时候用到 decoder_input_ids = model._shift_right(text_input_ids.input_ids) # decoder_attention_mask = decoder_input_ids.ne(tokenizer.pad_token_id).float() # 因为 shift_right 了, 前面的pad 要被attention到 # decoder_attention_mask[:, 0] = 1 new_batch["decoder_input_ids"] = decoder_input_ids # new_batch["decoder_attention_mask"] = decoder_attention_mask # label, 前面要 -100 加持 new_batch["labels"] = text_input_ids.input_ids.clone() # 找到sep id, 然后 -100 # 每行都仅有一个 sep for i, label in enumerate(new_batch["labels"]): # sep_token_id_indexes = int(torch.where(label == tokenizer.sep_token_id)[0][0]) sep_token_indexes = torch.where(label == tokenizer.sep_token_id)[0].data.numpy() i_sep_token_index = 0 if len(sep_token_indexes) == 0: # 有时候会超长.... 这真太难了... logging.error(f"不应该找不到 sep_token_id 的位置 !! 请检查预训练任务的长度. {label}, {prompt_and_labels[i]}") raise ValueError() else: i_sep_token_index = int(sep_token_indexes[0]) label[:i_sep_token_index + 1] = -100 new_batch["labels"][i] = label # for generate utils if batch[0]['prompt'] != '': prompts = [item['prompt'] + tokenizer.sep_token for item in batch] prompts_inputs = processor(text=prompts, padding=True, return_tensors="pt", add_special_tokens=False, max_length=max_length, truncation=True) new_batch['input_ids'] = prompts_inputs['input_ids'] for item in batch: new_batch["flattened_patches"].append(item["flattened_patches"]) new_batch["attention_mask"].append(item["attention_mask"]) new_batch["flattened_patches"] = torch.stack(new_batch["flattened_patches"]) new_batch["attention_mask"] = torch.stack(new_batch["attention_mask"]) return new_batch def test_collator(batch, max_length=1024): """ 适 用于 train和eval todo: 要不要处理好label, 使得prompt部分loss 是-100 ? """ # 当前实现就是需要有prompt tokenizer = processor.tokenizer new_batch = {"flattened_patches": [], "attention_mask": []} # prompt_and_labels = [item['prompt'] + processor.tokenizer.sep_token_id + item["labels"] for item in batch] # 计算 label ,构建 decoder_input_id #prompts = [] prompt_and_labels = [] oris = [] for i, item in enumerate(batch): i_prompt_and_labels = item['prompt'] + tokenizer.sep_token + item["labels"] # shift right by hand prompt_and_labels.append(i_prompt_and_labels) # prompts.append(item['prompt']) oris.append(item['ori']) # decoder_input text_input_ids = processor(text=prompt_and_labels, padding=True, return_tensors="pt", add_special_tokens=True, max_length=max_length, truncation=True) # for generate utils if batch[0]['prompt'] != '': prompts = [item['prompt'] + tokenizer.sep_token for item in batch] prompts_inputs = processor(text=prompts, padding=True, return_tensors="pt", add_special_tokens=False, max_length=max_length, truncation=True) new_batch['input_ids'] = prompts_inputs['input_ids'] for item in batch: new_batch["flattened_patches"].append(item["flattened_patches"]) new_batch["attention_mask"].append(item["attention_mask"]) new_batch["flattened_patches"] = torch.stack(new_batch["flattened_patches"]) new_batch["attention_mask"] = torch.stack(new_batch["attention_mask"]) new_batch["ori"] = oris return new_batch if __name__ == '__main__': parser = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() processor = AutoProcessor.from_pretrained(model_args.model_name_or_path) logging.info(f'load processor from {model_args.model_name_or_path}') train_dataset, eval_dataset, test_dataset = None, None, None train_dataset = BasePretrainDataset(data_args, data_args.train_file, processor, 'train', max_records=None, image_dir='images', load_cache=True) logging.info(f"train_dataset size: {len(train_dataset)}") eval_dataset = BasePretrainDataset(data_args, data_args.validation_file, processor, 'eval', max_records=200, image_dir='images', load_cache=False) logging.info(f"eval_dataset size: {len(eval_dataset)}") test_dataset = eval_dataset # eval_dataset = BaseInsructionDataset(data_args, data_args.validation_file, processor, 'test', max_records=50, # prompt='盖章单位是:') # logging.info(f"test_dataset size: {len(test_dataset)}") # # padding = "max_length" if data_args.pad_to_max_length else False # if training_args.do_train: if True: # # 构造model # 输入上针对LayoutLM model = MyCustomPix2StructForConditionalGeneration.from_pretrained(model_args.model_name_or_path) logging.info(f"model loaded from {model_args.model_name_or_path}") # training_args.max_steps = 4800 # training_args.gradient_accumulation_steps = 16 # training_args.predict_with_generate = True # training_args.evaluation_strategy = "steps" # training_args.per_device_train_batch_size = 1 # training_args.per_device_eval_batch_size = 1 # training_args.logging_steps = 10 # # training_args.save_steps = 10 # # training_args.eval_steps = 10 # # training_args.eval_steps = 1 # # training_args.fp16 = True # training_args.overwrite_output_dir = True # training_args.generation_max_length = 2048 # training_args.generation_num_beams = 1 # 回头 model.config.max_length = 2048 model.config.num_beams = 1 print(training_args) # instantiate trainer trainer = Seq2SeqTrainer( model=model, tokenizer=processor.tokenizer, args=training_args, compute_metrics=compute_metrics, train_dataset=train_dataset, eval_dataset=eval_dataset, data_collator=collator, ) # trainer.evaluate() # trainer.train(resume_from_checkpoint=True) trainer.train() # test # if training_args.do_predict: if False: model = MyCustomPix2StructForConditionalGeneration.from_pretrained(model_args.model_name_or_path) model.to('cuda') logging.info("model loaded") model.config.max_length = 2048 model.config.num_beams = 1 max_new_tokens = 1024 num_beams = 1 all_output = [] test_dataloader = DataLoader(test_dataset, batch_size=1, collate_fn=test_collator) # 这部分要研究下了... 要支持prompt for batch in tqdm.tqdm(test_dataloader, total=len(test_dataloader)): logging.info("batch") # ori_batch = batch labels = batch.pop('labels') # batch.pop('decoder_input_ids') # prompts = batch.pop('prompt') ori_records = [json.loads(x) for x in batch.pop('ori')] for k in batch: batch[k] = batch[k].to(model.device) # print(batch) generated_ids = model.generate(**batch, max_new_tokens=max_new_tokens, num_beams=num_beams, do_sample=False) output = processor.tokenizer.batch_decode(generated_ids, skip_special_tokens=True) for pred, i_ori_rec in zip(output, range(len(ori_records))): ori_rec = ori_records[i_ori_rec] ori_rec['pred'] = pred all_output += ori_records logging.info("batch Done") print(len(output), output) print(all_output) pred_output_file = os.path.join(training_args.output_dir, 'pred_out.txt') try: with open(pred_output_file, 'w') as f: json.dump(all_output, f, ensure_ascii=False, indent=2) except Exception as e: logging.error(e)
import React, { useEffect, useState } from 'react'; import PropTypes from 'prop-types'; import { useTracker } from 'meteor/react-meteor-data'; import { makeStyles, withStyles } from '@material-ui/core/styles'; import { Card, CardHeader, CardContent, Button, Tab, Tabs, Typography, Box, TextField } from '@material-ui/core'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import { get, has, filter } from 'lodash'; import { Meteor } from 'meteor/meteor'; import { Session } from 'meteor/session'; import { HTTP } from 'meteor/http'; import JSON5 from 'json5'; import { FhirUtilities, DynamicSpacer, CodeSystems, ValueSetDetail, CodeSystemsConceptsTable } from 'meteor/clinical:hl7-fhir-data-infrastructure'; export function SearchResourceTypesDialog(props){ const [tabIndex, setTabIndex] = useState(0); const [searchText, setSearchText] = useState(""); let selectedCodeSystem = useTracker(function(){ return CodeSystems.findOne({id: 'resource-types'}); }, []); console.log('selectedCodeSystem', selectedCodeSystem) let { children, id, filter, codeSystem, errorMessage, jsonContent, ...otherProps } = props; if(codeSystem){ selectedCodeSystem = codeSystem; } let textToRender = ""; if(jsonContent && !errorMessage){ errorMessage = jsonContent; } // console.log('SearchResourceTypesDialog', errorMessage) if(errorMessage){ if(typeof errorMessage === "string"){ textToRender = errorMessage } else if(typeof errorMessage === "object") { textToRender = JSON.stringify(errorMessage, null, 2); } } function handleTabChange(event, newIndex){ setTabIndex(newIndex); } function handleSetSearchText(event){ setSearchText(event.currentTarget.value); } // -------------------------------------------------------------------------------------------------------------------------------- // Rendering let labelRowStyle = { clear: 'both' } let labelStyle = { float: 'left', width: '160px', margin: '0px' } let valueStyle = { float: 'left', whiteSpace: 'pre', textOverflow: 'ellipsis', position: 'absolute' } let blockStyle = { clear: 'both' } let separatorStyle = { marginTop: '40px', marginBottom: '20px', clear: 'both', height: '2px' } let conceptCount = 0; if(selectedCodeSystem){ if(Array.isArray(selectedCodeSystem.concept)){ conceptCount = selectedCodeSystem.concept.length; } } console.log('searchText', searchText) return( <DialogContent id={id} className="SearchResourceTypesDialog" style={{width: '100%'}} dividers={scroll === 'paper'}> <TextField id="search" type="search" label="Search Resource Types" fullWidth={true} value={ searchText } onChange={ handleSetSearchText.bind(this) } // error={Boolean(formik.errors.email && formik.touched.email)} // helperText={formik.touched.email && formik.errors.email} /> <DynamicSpacer /> {/* <ValueSetDetail valueSet={selectedCodeSystem} hideTitleElements={true} hideDescriptionElements={true} hideTable={false} hideConcepts={true} /> */} <CodeSystemsConceptsTable codeSystem={selectedCodeSystem} page={tabIndex} searchText={searchText} onSetPage={function(index){ setTabIndex(index); }} count={conceptCount} rowsPerPage={conceptCount} disablePagination={true} onRowClick={function(concept){ Session.set('SubscriptionChannelResourceType', get(concept, 'code')) Session.set('mainAppDialogOpen', false); }} /> </DialogContent> ) } SearchResourceTypesDialog.propTypes = { errorMessage: PropTypes.string, filter: PropTypes.string, codeSystem: PropTypes.object } SearchResourceTypesDialog.defaultProps = { filter: '' } export default SearchResourceTypesDialog;
% Course: Control Systems % Author: Jhon Charaja % List number: 3 % Question: 5 (c) % Info: sisotool G(s) clc, clear all, close all; % laplace operator s = tf('s'); kp = 0.09; kv = -0.532; T = kp*65/(s*s + (37 + 65*kv)*s + kp*65); % step response of open-loop system dt = 0.001; t = 0:dt:5; len = length(t); u = ones(len, 1); y = lsim(T, u, t); % plot settings img_width= 14; img_height=14; legend_list = {'system response','input signal'}; figure(1), hold on, grid on, box on, fig = get(groot,'CurrentFigure'); set(fig,'units','centimeters','position', [0 0 img_width img_height]); axis([0, t(end) 0 1.5]) plot_fig = plot(t, y,'linestyle', '-', 'linewidth', 1), hold on, box on, hold on plot(t, u,'linestyle', '-', 'linewidth', 1), hold on, box on, hold on ylabel('Amplitude', 'Interpreter','latex'), xlabel('Time (s)', 'Interpreter','latex'), ax = gca; % current axes ax.FontSize = 12; set(gca,'TickLabelInterpreter','latex') legend(legend_list, 'interpreter', 'latex', 'location', 'northoutside') datatip_index = find(y == max(y)); label_list = {'Time (s): ','Force (N): '}; add_datatip(plot_fig, datatip_index, t, y, label_list, 'northeast'); datatip_index = find(y>=1, 1); add_datatip(plot_fig, datatip_index, t, y, label_list, 'southeast'); % Save image image_path = fullfile('C:\Users\USERTEST\Desktop\control_systems_homework\list3\images\'); file_name = fullfile(image_path, 'q5_step_response_T'); saveas(gcf,file_name,'epsc') %% psi = 0.0962; tr = 1; wn = (pi- atan(sqrt(1-psi*psi)/psi)) / (tr*sqrt(1-psi*psi)); eq = s*s + 2*psi*wn*s + wn*wn
const Joi = require('joi'); const { GENDERS } = require('../user/user.constant'); const { phoneNumberFormat, emailFormat } = require('../utils/messageCustom'); const { password } = require('../utils/validateCustom'); const editUser = { body: Joi.object().keys({ phone_number: Joi.string().custom(phoneNumberFormat), email: Joi.string().custom(emailFormat).lowercase(), name: Joi.string().trim(), image: Joi.string().trim(), address: Joi.string().trim(), gender: Joi.string().valid(...Object.values(GENDERS)), dob: Joi.date(), health_insurance: Joi.string().trim(), }), }; const changePassword = { body: Joi.object().keys({ old_password: Joi.string().required(), new_password: Joi.string().required().custom(password), confirm_password: Joi.string().required(), }), }; const listUser = { query: Joi.object().keys({ id: Joi.string().uuid(), phone_number: Joi.string().custom(phoneNumberFormat), email: Joi.string().custom(emailFormat).lowercase(), name: Joi.string().trim().lowercase(), gender: Joi.string().valid(...Object.values(GENDERS)), address: Joi.string(), blocked: Joi.boolean(), order: Joi.string().valid( 'phone_number:asc', 'phone_number:desc', 'email:asc', 'email:desc', 'name:asc', 'name:desc', 'gender:asc', 'gender:desc', 'dob:asc', 'dob:desc', 'blocked:asc', 'blocked:desc' ), page: Joi.number().integer().default(1).min(1), limit: Joi.number().integer().default(10).min(1), }), }; const detailUser = { params: Joi.object().keys({ id: Joi.string().uuid().required(), }), }; module.exports = { // admin editUser, changePassword, listUser, detailUser, };
import React from "react"; import Card from "./Card"; import QRCodeModal from "@walletconnect/qrcode-modal"; import { MdSpaceDashboard } from "react-icons/md"; import { AiOutlineMenu, AiOutlineClose } from "react-icons/ai"; import { FaWallet } from "react-icons/fa"; import { SiMarketo, SiBitcoinsv } from "react-icons/si"; import { NavLink } from "react-router-dom"; import { useState, useEffect } from "react"; import { getAddress, signTransaction } from "sats-connect"; import axios from "axios"; const Navbar = () => { const [toggle, setToggle] = useState(false); const [connected, setConnected] = useState(false); const [walletAddress, setWalletAddress] = useState(null); async function handleConnectClick(props) { const getAddressOptions = { payload: { purposes: ['ordinals', 'payment'], message: 'Address for receiving Ordinals and payments', network: { type: 'Mainnet' }, }, onFinish: (response) => { console.log(response); setConnected(true); // update state when connection is successful }, onCancel: () => alert('Request canceled'), }; await getAddress(getAddressOptions); const address = await getAddress(getAddressOptions); const response = await axios.get(`https://blockstream.info/api/address/${address}/`); const balance = response.data.chain_stats.funded_txo_sum - response.data.chain_stats.spent_txo_sum; console.log(`Wallet balance: ${balance}`); setWalletBalance(balance); props.updateWalletBalance(balance); setWalletAddress(address); } return ( <> <Card> <div className="text-white flex justify-between items-center "> <h5 className="flex font-Urbanist text-lg tracking-wide font-extrabold md:text-3xl"> Bit <span className="text-orange ">Comp</span> </h5> <div className="mt-2 font-Urbanist text-lg font-semibold "> <ul className="md:flex hidden "> <NavLink to="/"> <li className="flex mx-2 hover:bg-grey px-2 rounded-2xl active:animate-ping"> <button className="flex"> <span className="mt-1"> <MdSpaceDashboard /> </span>{" "} Dashboard </button> </li> </NavLink> <NavLink to="/market"> <li className="flex mx-2 hover:bg-grey px-2 rounded-2xl active:animate-ping "> <button className="flex active:underline"> <span className="mt-1"> <SiMarketo /> </span>{" "} Market </button> </li> </NavLink> </ul> </div> <div className="flex mt-2 items-center font-Urbanist"> <div className="flex items-center mx-3"> <SiBitcoinsv className=" text-orange mx-2" /> <p className="text-lg font-Urbanist font-extrabold tracking-wider"> BTC </p> <p className="text-lg text-gray3 mx-1">Bitcoin</p> </div> <div className="mx-3 hidden md:flex"> <button className="bg-grey font-bold tracking-wide rounded-2xl border border-orange p-3" onClick={handleConnectClick}> {connected ? 'Connected' : 'Connect Wallet'} </button> </div> </div> <div className="font-bold text-xl text-gray3 flex md:hidden mt-1 items-center"> <button className="px-1"> <FaWallet /> </button> <div> <button className="px-1" onClick={() => setToggle((prev) => !prev)} > <AiOutlineMenu /> </button> {toggle ? ( <Card> <div className="mt-2 font-Urbanist text-lg font-semibold justify-center items-center bg-grey bg-opacity-90 flex overflow-x-hidden overflow-y-auto fixed transition-all ease ease-in duration-3000 inset-0 z-0"> <button className="absolute top-1 right-1 w-20 " onClick={() => setToggle((prev) => !prev)} > <AiOutlineClose className="w-10 h-full" /> </button> <ul className=" text-2xl text-center "> <NavLink to="/"> <li className="flex mx-2 hover:bg-grey px-2 rounded-2xl active:animate-ping"> <button className="flex"> <span className="mt-1"> <MdSpaceDashboard /> </span>{" "} Dashboard </button> </li> </NavLink> <hr /> <NavLink to="/market"> <li className="flex mx-2 hover:bg-grey px-2 rounded-2xl active:animate-ping "> <button className="flex active:underline"> <span className="mt-1"> <SiMarketo /> </span>{" "} Market </button> </li> </NavLink> </ul> </div> </Card> ) : null} </div> </div> </div> </Card> </> ); }; export default Navbar;
import { createAsyncThunk } from '@reduxjs/toolkit'; import { ThunkConfig } from 'app/providers/StoreProvider'; import { Article, ArticleSortType, ArticleType } from 'entities.entities/Article'; import { SortOrder } from 'shared/types'; import { getArticleSort } from 'features/ArticleSort/model/selectors/getArticleSort'; import { addQueryParams } from 'shared/lib'; import { getArticlesLimit } from '../../selectors/getArticles'; interface FetchArticleListProps { page?: number; sort?: ArticleSortType; order?: SortOrder; search?: string; replace?: boolean } export const fetchArticleList = createAsyncThunk<Article[], FetchArticleListProps, ThunkConfig<string>>( 'ArticlePage/fetchArticleList', async (props, thunkAPI) => { const { extra, rejectWithValue, getState, } = thunkAPI; const { page = 1 } = props; const sortArticle = getArticleSort(getState()); const limit = getArticlesLimit(getState()); try { addQueryParams({ ...sortArticle, }); const response = await extra.$api.get<Article[]>('/articles', { params: { _expand: 'user', _page: page, _limit: limit, _sort: sortArticle?.sort || 'createdAt', _order: sortArticle?.order || 'asc', type_like: sortArticle?.type === ArticleType.ALL ? undefined : sortArticle?.type, q: sortArticle?.search || '', }, }); if (!response.data) { throw new Error(); } return response.data; } catch (e) { console.log(e); return rejectWithValue('error'); } }, );
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Modelo de Caixas</title> <style> h1 { /* box-level */ /* display: inline; posso transformar em inline-block e não tem altura e largura */ background-color: lightgray; height: 300px; width: 300px; /* border-width: 10px; border-style: solid; border-color: darkslategrey; */ border: 10px solid darkslategray; /*shorthand*/ /* padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px; */ padding: 10px 10px 10px 10px; /*shorthand - padding: 10px muda todos - padding 10px cima baixo 20px esquerda direita*/ /* margin: auto; centraliza a box margin-top: 20px; margin-right: 20px; margin-bottom: 40px; margin-left: 20px;*/ margin: 20px 20px 40px 20px; /*shorthand - margin: 10px muda todos - margin 10px cima baixo 20px esquerda direita ou margin 10px auto centralizado*/ /* outline-width: 5px; outline-style: dashed; outline-color: salmon; */ outline: 5px dashed salmon; /*shorthand outline auto centralizado pouco usado*/ } a { /* inline-level */ border-width: 10px; border-style: solid; border-color: red; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px; } </style> </head> <body> <h1>Exemplo de caixa box-level</h1> <p>Págrafos também são exemplos de box-level, mas os <a href="#">links são exemplos de caixas inline-level</a>. Vamos ver como tudo isso funciona.</p> <p><a href="caixa02.html" target="_self" rel="prev">Voltar</a></p> </body> </html>
#include <QCoreApplication> #include <QDebug> class Book { private: QString title; QString author; QString ISBN; public: Book() : title(""), author(""), ISBN("") {} Book(const QString& title, const QString& author, const QString& ISBN) : title(title), author(author), ISBN(ISBN) {} void setTitle(const QString& newTitle) { title = newTitle; } void setAuthor(const QString& newAuthor) { author = newAuthor; } void setISBN(const QString& newISBN) { ISBN = newISBN; } QString getTitle() const { return title; } QString getAuthor() const { return author; } QString getISBN() const { return ISBN; } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Book myBook("The Great Gatsby", "F. Scott Fitzgerald", "978-3-16-148410-0"); qDebug() << "Initial Book Details:"; qDebug() << "Title:" << myBook.getTitle(); qDebug() << "Author:" << myBook.getAuthor(); qDebug() << "ISBN:" << myBook.getISBN(); myBook.setTitle("To Kill a Mockingbird"); myBook.setAuthor("Ernest Hemingway"); myBook.setISBN("908-06-108-4"); qDebug() << "\nUpdated Book Details:"; qDebug() << "Title:" << myBook.getTitle(); qDebug() << "Author:" << myBook.getAuthor(); qDebug() << "ISBN:" << myBook.getISBN(); return a.exec(); }
import { useState } from "react"; import axios from "axios"; import Button from "../Button"; import NavBar from "../Navbar"; import { BASE_URL } from "../../util/baseurl"; import "./styles.css"; type FormData = { name: string; }; type User = { url: string; followers: number; location: string; name: string; avatar_url: string; }; const FindProfile = () => { const [formdata, setFormData] = useState<FormData>({ name: "", }); const [data, setData] = useState<User>(); const handleChange = (e: any) => { const value = e.target.value; const name = e.target.name; setFormData({ ...formdata, [name]: value }); }; const handleSubmit = (e: any) => { e.preventDefault(); axios .get(`${BASE_URL}/${formdata.name}`) .then((response) => setData(response.data)) .catch((error) => console.log("Erro", error)); }; return ( <> <NavBar /> <div className="container find-Profile-container"> <h1>Encontre um perfil Github</h1> <form onSubmit={handleSubmit}> <input value={formdata.name} placeholder="Usúario" type="text" name="name" onChange={handleChange} /> <Button name="Encontrar" /> </form> </div> {data && ( <div className="container"> <div className="user-data-card-container"> <div> <img src={data?.avatar_url} alt="" /> </div> <div className="user-data-card-description"> <h2>Informações</h2> <p> <span>Perfil:</span> {data?.url} </p> <p> <span>Seguidores:</span> {data?.followers} </p> <p> <span>Localidade:</span> {data?.location} </p> <p> <span>Nome:</span> {data?.name} </p> </div> </div> </div> )} </> ); }; export default FindProfile;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var UserFetcher = /** @class */ (function () { function UserFetcher() { } UserFetcher.prototype.fetchJson = function (url) { return __awaiter(this, void 0, void 0, function () { var response, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 3, , 4]); return [4 /*yield*/, fetch(url)]; case 1: response = _a.sent(); if (!response.ok) { throw new Error("Failed to fetch data. Status: ".concat(response.status)); } return [4 /*yield*/, response.json()]; case 2: return [2 /*return*/, (_a.sent())]; case 3: error_1 = _a.sent(); throw new Error("Error fetching JSON: ".concat(error_1.message)); case 4: return [2 /*return*/]; } }); }); }; UserFetcher.prototype.getElement = function (id) { return document.getElementById(id); }; UserFetcher.prototype.showUserDetails = function (id) { return __awaiter(this, void 0, void 0, function () { var user, userDetails, userList, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.fetchJson("https://reqres.in/api/users/".concat(id))]; case 1: user = _a.sent(); userDetails = "\n <div>\n <h2>".concat(user.data.first_name, " ").concat(user.data.last_name, "</h2>\n <p>Email: ").concat(user.data.email, "</p>\n <img key=\"").concat(user.data.avatar, "\" src=\"").concat(user.data.avatar, "\">\n <hr />\n </div>"); userList = this.getElement("userslist"); if (userList) { userList.innerHTML = userDetails; } return [3 /*break*/, 3]; case 2: error_2 = _a.sent(); console.error("Error fetching user details:", error_2.message); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; UserFetcher.prototype.fetchAndDisplayUsers = function () { return __awaiter(this, void 0, void 0, function () { var data, userList_1, error_3; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.fetchJson("https://reqres.in/api/users/")]; case 1: data = _a.sent(); userList_1 = this.getElement("userslist"); if (userList_1) { data.data.forEach(function (user) { var userElement = document.createElement("div"); userElement.innerHTML = "\n <h2>".concat(user.first_name, " ").concat(user.last_name, "</h2>\n <p>Email: ").concat(user.email, "</p>\n <img key=\"").concat(user.avatar, "\" src=\"").concat(user.avatar, "\">\n <hr />"); userElement.addEventListener("click", function () { return _this.showUserDetails(user.id); }); userList_1.appendChild(userElement); }); } return [3 /*break*/, 3]; case 2: error_3 = _a.sent(); console.error("Error fetching users:", error_3.message); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; return UserFetcher; }()); var userFetcher = new UserFetcher(); userFetcher.fetchAndDisplayUsers();
// let num: number = undefined // console.log('==', num) // let some: any = 'test' // some = 7 // // some.setName("hah") // console.log(some) // let myFavoriteNumber; // myFavoriteNumber = 'seven'; // myFavoriteNumber = 7; // console.log('myFavoriteNumber' + myFavoriteNumber) // interface Person { // name: string; // age: number; // } // let tom: Person = { // name: 'Tom', // age: 10 // }; // console.log(tom) // interface Person { // name: string; // age?: number; // [propName: string]: string | number; // } // let tom: Person = { // name: 'Tom', // age: 25, // gender: 'male' // }; // function sum(arguments: any) { // let args: { // [index: number]: number; // length: number; // callee: Function; // } = arguments; // // let args: IArguments = arguments; // console.log(args) // } // sum([1,2,3]) // interface SearchFunc { // (source: string, subString: string): boolean; // } // let mySearch: SearchFunc; // mySearch = function(source: string, subString: string) { // return source.search(subString) !== -1; // } // console.log(mySearch('hah', 'a')) // function push(array: any[], ...items: any[]) { // items.forEach(function(item) { // array.push(item); // }); // } // let a = ['2']; // push(a, 1, 2, 3); // console.log('aa', a) // interface Animal { // name: string; // } // interface Cat { // name: string; // run(): void; // } // let tom: Cat = { // name: 'Tom', // run: () => { console.log('run') } // }; // let animal: Animal = tom; // console.log('animal.name', animal.name) // function getCacheData(key: string): any { // return (window as any).cache[key]; // } // interface Cat { // name: string; // run(): void; // } // const tom = getCacheData('tom') as Cat; // tom.run = function () { // console.log('aaa') // }; // interface Animal { // name: string; // run(): void; // } // interface Cat { // name: string; // } // const animal: Animal = { // name: 'tom', // run: () => {} // }; // let tom: Cat = animal; // console.log('tom', tom.name) // let tom: [string, number]; // tom = ['Tom', 25]; // tom.push('male'); // // tom.push(true); // console.log('tom', tom) // enum Days {Sun = 3, Mon = 1, Tue, Wed, Thu, Fri, Sat}; // console.log(Days["Sun"] === 3); // true // console.log(Days["Wed"] === 3); // true // console.log(Days[3] === "Sun"); // false // console.log(Days[3] === "Wed"); // true // console.log(Days) // console.log(Days[0]) // console.log(Days[1]) // 可行 // enum Color {Red, Green, Blue = "blue".length}; // 不可行 // enum Color {Blue = "blue".length, Red, Green}; // console.log(Color['Red']) // console.log(Color['Blue']) // console.log(Color[4]) // console.log(Color[2]) // console.log(Color[3]) // const enum Directions { // Up, // Down, // Left, // Right // } // let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]; // // let directions1 = [Directions[0], Directions['Down'], Directions['Left'], Directions['Right']]; // console.log('directions', directions) // console.log('directions1', Color[0]) // class Animal { // // private name; // protected name; // public constructor(name) { // console.log('11', name) // this.name = name; // console.log('this.name', this.name) // } // } // class Cat extends Animal { // constructor(name) { // super(name); // console.log(name); // // work with protected // console.log(this.name); // } // } // let a: Cat = new Cat('hah') // abstract class Animal { // public name; // public constructor(name) { // this.name = name; // } // public abstract sayHi(); // } // class Cat extends Animal { // public sayHi() { // console.log('hello hi') // } // public eat() { // console.log(`${this.name} is eating.`); // } // } // let cat = new Cat('Tom'); // cat.eat() // function swap<T, U>(tuple: [T, U]): [U, T] { // return [tuple[1], tuple[0]]; // } // let a: [number, string] = [7, 'seven']; // console.log(swap(a)); // ['seven', 7] // console.log(a); // interface Lengthwise { // length: number; // } // function loggingIdentity<T extends Lengthwise>(arg: T): T { // console.log(arg.length); // return arg; // } // loggingIdentity([7]); // function createArray<T = string>(length: number, value: T): Array<T> { // let result: T[] = []; // for (let i = 0; i < length; i++) { // result[i] = value; // } // return result; // } // console.log(createArray(10, 's')) // class GenericNumber<T, A> { // zeroValue: T; // add: (x: T, y: A) => T; // } // let myGenericNumber = new GenericNumber<number, string>(); // myGenericNumber.zeroValue = 0; // myGenericNumber.add = function(x, y) { // console.log('x' + x); // console.log('y' + y); // return x + Number(y); // }; // myGenericNumber.add(10, '110') // interface Alarm { // price: number; // } // interface Alarm { // price: number; // 类型不一致,会报错 // weight: number; // } // class Greeter { // greeting: string; // constructor(message: string) { // this.greeting = message; // } // @enumerable(true) // greet() { // return "Hello, " + this.greeting; // } // } // function enumerable(value: boolean) { // return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { // console.log('target: ' + JSON.stringify(target)); // console.log('propertyKey: ' + propertyKey); // console.log('descriptor: ' + descriptor); // for(let key in descriptor) { // console.log('key: ' + key); // } // descriptor.enumerable = value; // }; // } // let a: Greeter = new Greeter('ABC') // console.log(a.greet()) // function decorateClass<T extends { new (...args: any[]): {} }>(constructor: T){ // return class B extends constructor{ // name = 'B' // } // } // @decorateClass // class A { // name = 'A' // constructor() { // } // } // console.log(new A().name) function decorateMethod(target: any,key: string,descriptor: PropertyDescriptor){ return{ value: function(...args: any[]){ var result = descriptor.value.apply(this, args) * 2; return result; } } } class A { sum1(x: number,y: number){ return x + y } @decorateMethod sum2(x: number,y: number){ console.log('xxx', x); console.log('yyy', y); return x + y } } console.log(new A().sum1(1,2)) // 输出3 console.log(new A().sum2(1,2)) // 输出6
package com.sparta.movieplanner.justwatch.service; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.introspect.VisibilityChecker; import com.sparta.movieplanner.controllers.web.TelevisionController; import com.sparta.movieplanner.justwatch.dto.ProviderDTO; import com.sparta.movieplanner.justwatch.entity.Movie; import com.sparta.movieplanner.justwatch.entity.Offers; import com.sparta.movieplanner.justwatch.entity.Provider; import com.sparta.movieplanner.justwatch.mappers.ProviderMapper; import com.sparta.movieplanner.justwatch.repository.ProviderRepository; import org.hibernate.ObjectNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.crossstore.ChangeSetPersister; import org.springframework.stereotype.Service; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.ArrayList; import java.util.List; import java.util.MissingResourceException; @Service public class MovieServiceImpl implements MovieService { @Value("${api.token}") private String token; @Autowired private ProviderRepository providerRepository; @Autowired private ProviderMapper providerMapper; Logger log = LoggerFactory.getLogger(TelevisionController.class); @Override public Movie findMovieByTitleAndReleaseYear(String title, int year) throws IOException, InterruptedException { // Just watch endpoint (url) title = title.replaceAll("\\s", "%20"); String url = "https://apis.justwatch.com/contentpartner/v2/content/offers/object_type/movie/locale/en_GB?title=" + title + "&" + "release_year=" + year + "&token=" + token; HttpClient client = HttpClient.newHttpClient(); // Make the http request HttpRequest request = HttpRequest.newBuilder() .GET() .header("accept", "application/json") .uri(URI.create(url)) .build(); // Store the endpoint response HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ObjectMapper mapper = new ObjectMapper(); // To bypass the exception ===> com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY)); // Map the endpoint response to the Movie entity (object) Movie movie = mapper.readValue(response.body(), new TypeReference<Movie>() {}); return movie; } @Override public Movie findMovieByTMDBId(int id) throws IOException, InterruptedException { String url = "https://apis.justwatch.com/contentpartner/v2/content/offers/object_type/movie/id_type/tmdb/locale/en_GB?id=" + id + "&token=" + token; HttpClient client = HttpClient.newHttpClient(); // Make the http request HttpRequest request = HttpRequest.newBuilder() .GET() .header("accept", "application/json") .uri(URI.create(url)) .build(); // Store the endpoint response HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); if(response.statusCode() == 404){ return null; //throw new IllegalArgumentException(); } ObjectMapper mapper = new ObjectMapper(); // To bypass the exception ===> com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY)); // Map the endpoint response to the Movie entity (object) Movie movie = mapper.readValue(response.body(), new TypeReference<Movie>() {}); return movie; } @Override public List<ProviderDTO> findAllProvidersForAMovieByTMDBId(int id) throws IOException, InterruptedException { Movie movie = findMovieByTMDBId(id); List<ProviderDTO> providers = new ArrayList<>(); // e.g. movie with id 2995 gives null providers if(movie == null || movie.getOffers() == null || movie.getOffers().size() == 0) return null; //throw new MissingResourceException("The movie does not have providers", "Provider Class", "TMDB id: " + id); for(int i = 0; i < movie.getOffers().size(); i++){ Offers offer = movie.getOffers().get(i); if(!providerRepository.findById(movie.getOffers().get(i).getProvider_id()).isPresent()){ continue; } Provider provider = providerRepository.findById(movie.getOffers().get(i).getProvider_id()).get(); ProviderDTO providerDTO = providerMapper.entityToDto(provider); providerDTO.setProvider_url(offer.getUrls().getRaw_web()); if(i > 0 && providers.get(providers.size()-1).getId() == providerDTO.getId()){ providers.set(providers.size()-1, providerDTO); }else{ providers.add(new ProviderDTO(providerDTO)); } } return providers; } }
#include <TinyGPS++.h> #include <HardwareSerial.h> #include <WiFi.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <BlynkSimpleEsp32.h> float latitude , longitude; String latitude_string , longitiude_string; #define SCREEN_WIDTH 128 #define SCREEN_HEIGHT 64 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); const char *ssid = "04F2G_577470"; const char *pass = "wlana88b8f"; char auth[] = "ec8EX0fnX1y78Oo6pO8lp8Of_AWUd***"; WidgetMap myMap(V0); WiFiClient client; TinyGPSPlus gps; HardwareSerial SerialGPS(2); void setup() { Serial.begin(115200); if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println(F("SSD1306 allocation failed")); for(;;); } WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected!"); SerialGPS.begin(9600, SERIAL_8N1, 16, 17); Blynk.begin(auth, ssid, pass); Blynk.virtualWrite(V0, "clr"); } void loop() { while (SerialGPS.available() > 0) { if (gps.encode(SerialGPS.read())) { if (gps.location.isValid()) { latitude = gps.location.lat(); latitude_string = String(latitude , 6); longitude = gps.location.lng(); longitiude_string = String(longitude , 6); Serial.print("Latitude = "); Serial.println(latitude_string); Serial.print("Longitude = "); Serial.println(longitiude_string); display.clearDisplay(); display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0, 20); display.println("Latitude: "); display.setCursor(45, 20); display.print(latitude_string); display.setCursor(0, 40); display.print("Longitude: "); display.setCursor(45, 40); display.print(longitiude_string); Blynk.virtualWrite(V0, 1, latitude, longitude, "Location"); display.display(); } delay(1000); Serial.println(); } } Blynk.run(); }
import React from 'react'; import { Link } from 'react-router-dom'; import {CardContent, CardMedia, Box} from '@mui/material'; import {CheckCircle} from '@mui/icons-material'; import {demoProfilePicture} from '../utils/constans' const ChannelCard = ({channelDetail, marginTop}) => ( <Box sx={{ width: '300px', height: '300px', margin: 'auto', marginTop, display: 'flex', justifyContent: 'center', alignItems: 'center'}}> <Link to={`/channel/${channelDetail?.id?.channelId}`}> <CardContent sx={{justifyContent:'center', display: 'flex', flexDirection:'column', alignItems: 'center'}}> <CardMedia image={channelDetail?.snippet?.thumbnails?.high?.url || demoProfilePicture} alt={channelDetail?.snippet?.title} sx={{ borderRadius: '50%', height: '180px', width: '180px' }}/> <h2 style={{ color: 'var(--accent)', display: 'flex', alignItems: 'center' }}> {channelDetail?.snippet?.title} <CheckCircle style={{ color: 'whitesmoke', marginLeft: '5px' }} /> </h2> {channelDetail?.statistics?.subscriberCount && ( <h4 style={{color:'whitesmoke', margin: 0}}> {parseInt(channelDetail?.statistics?.subscriberCount).toLocaleString('en-US')} Subscribers</h4> ) } </CardContent> </Link> </Box> ); export default ChannelCard
/* * Copyright (C) 2021 Alonso del Arte * * 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/>. */ package arithmetic; import algebraics.AlgebraicDegreeOverflowException; import algebraics.AlgebraicInteger; import algebraics.IntegerRing; import algebraics.UnsupportedNumberDomainException; import algebraics.quadratics.ImaginaryQuadraticRing; import algebraics.quadratics.ImaginaryQuadraticInteger; import algebraics.quadratics.QuadraticInteger; import algebraics.quadratics.QuadraticRing; import algebraics.quadratics.RealQuadraticInteger; import algebraics.quadratics.RealQuadraticRing; import fractions.Fraction; import java.util.Arrays; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * Tests for the NotDivisibleException class. The purpose of this test class is * only to make sure the exception object works as it should. Testing whether * this exception is thrown for the right reasons or not is the responsibility * of other test classes. However, these tests do require that the division * function in the pertinent classes satisfies the requirements of the * NotDivisibleException class. * @author Alonso del Arte */ public class NotDivisibleExceptionTest { /** * The delta value to use when assertEquals() requires a delta value. */ public static final double TEST_DELTA = 0.00000001; /** * An exception to correspond to (5 + i)/(3 + i) after setUpClass(). */ private static NotDivisibleException notDivGaussian; /** * An exception to correspond to 61/(1 + 9sqrt(-3)) after setUpClass(). */ private static NotDivisibleException notDivEisenstein; /** * An exception to correspond to (3 - 8sqrt(2))/7 after setUpClass(). */ private static NotDivisibleException notDivZ2; /** * An exception to correspond to (sqrt(5))/(15/2 - 3sqrt(5)/2) after * setUpClass(). */ private static NotDivisibleException notDivZPhi; /** * Sets up the NotDivisibleException objects to use in the tests. If any of * these objects fail to initialize properly, it will have the exception * detail message "Initialization state, not the result of an actually * thrown exception." */ @BeforeClass public static void setUpClass() { QuadraticRing currRing = new ImaginaryQuadraticRing(-1); String initMsg = "Initialization state, not the result of an actually thrown exception."; ImaginaryQuadraticInteger initDividend = new ImaginaryQuadraticInteger(0, 0, currRing); ImaginaryQuadraticInteger initDivisor = new ImaginaryQuadraticInteger(1, 0, currRing); Fraction zero = new Fraction(0); Fraction[] initFracts = {zero, zero}; notDivGaussian = new NotDivisibleException(initMsg, initDividend, initDivisor, initFracts); QuadraticInteger dividend = new ImaginaryQuadraticInteger(5, 1, currRing); QuadraticInteger divisor = new ImaginaryQuadraticInteger(3, 1, currRing); QuadraticInteger division; try { division = dividend.divides(divisor); System.out.println(dividend.toASCIIString() + " divided by " + divisor.toASCIIString() + " is " + division.toASCIIString()); } catch (AlgebraicDegreeOverflowException adoe) { System.err.println("AlgebraicDegreeOverflowException should not have occurred in this context: " + adoe.getMessage()); // This would merit a fail if occurred in a test. } catch (NotDivisibleException nde) { notDivGaussian = nde; } System.out.println("NotDivisibleException for the Gaussian integers example has this message: \"" + notDivGaussian.getMessage() + "\""); currRing = new ImaginaryQuadraticRing(-3); notDivEisenstein = new NotDivisibleException(initMsg, initDividend, initDivisor, initFracts); dividend = new ImaginaryQuadraticInteger(61, 0, currRing); divisor = new ImaginaryQuadraticInteger(1, 9, currRing); try { division = dividend.divides(divisor); System.out.println(dividend.toASCIIString() + " divided by " + divisor.toASCIIString() + " is " + division.toASCIIString()); } catch (AlgebraicDegreeOverflowException adoe) { System.err.println("AlgebraicDegreeOverflowException should not have occurred in this context: " + adoe.getMessage()); } catch (NotDivisibleException nde) { notDivEisenstein = nde; } System.out.println("NotDivisibleException for the Eisenstein integers example has this message: \"" + notDivEisenstein.getMessage() + "\""); currRing = new RealQuadraticRing(2); notDivZ2 = new NotDivisibleException(initMsg, initDividend, initDivisor, initFracts); dividend = new RealQuadraticInteger(3, -8, currRing); divisor = new RealQuadraticInteger(7, 0, currRing); try { division = dividend.divides(divisor); System.out.println(dividend.toASCIIString() + " divided by " + divisor.toASCIIString() + " is " + division.toASCIIString()); } catch (AlgebraicDegreeOverflowException adoe) { System.err.println("AlgebraicDegreeOverflowException should not have occurred in this context: " + adoe.getMessage()); } catch (NotDivisibleException nde) { notDivZ2 = nde; } System.out.println("NotDivisibleException for the Z[sqrt(2)] example has this message: \"" + notDivZ2.getMessage() + "\""); currRing = new RealQuadraticRing(5); notDivZPhi = new NotDivisibleException(initMsg, initDividend, initDivisor, initFracts); dividend = new RealQuadraticInteger(0, 1, currRing); divisor = new RealQuadraticInteger(15, -3, currRing, 2); try { division = dividend.divides(divisor); System.out.println(dividend.toASCIIString() + " divided by " + divisor.toASCIIString() + " is " + division.toASCIIString()); } catch (AlgebraicDegreeOverflowException adoe) { System.err.println("AlgebraicDegreeOverflowException should not have occurred in this context: " + adoe.getMessage()); } catch (NotDivisibleException nde) { notDivZPhi = nde; } System.out.println("NotDivisibleException for the Z[phi] example has this message: \"" + notDivZPhi.getMessage() + "\""); } /** * Test of getFractions method, of class NotDivisibleException. */ @Test public void testGetFractions() { System.out.println("getFractions"); Fraction fractRe = new Fraction(8, 5); Fraction fractImMult = new Fraction(-1, 5); Fraction[] expResult = {fractRe, fractImMult}; Fraction[] result = notDivGaussian.getFractions(); assertArrayEquals(expResult, result); fractRe = new Fraction(1, 4); fractImMult = new Fraction(-9, 4); expResult[0] = fractRe; expResult[1] = fractImMult; result = notDivEisenstein.getFractions(); assertArrayEquals(expResult, result); fractRe = new Fraction(3, 7); fractImMult = new Fraction(-8, 7); expResult[0] = fractRe; expResult[1] = fractImMult; result = notDivZ2.getFractions(); assertArrayEquals(expResult, result); fractRe = new Fraction(1, 6); expResult[0] = fractRe; expResult[1] = fractRe; result = notDivZPhi.getFractions(); assertArrayEquals(expResult, result); } /** * Test of getCausingDividend method, of class NotDivisibleException. */ @Test public void testGetCausingDividend() { QuadraticRing ring = new ImaginaryQuadraticRing(-1); QuadraticInteger expResult = new ImaginaryQuadraticInteger(5, 1, ring); AlgebraicInteger result = notDivGaussian.getCausingDividend(); assertEquals(expResult, result); ring = new ImaginaryQuadraticRing(-3); expResult = new ImaginaryQuadraticInteger(61, 0, ring); result = notDivEisenstein.getCausingDividend(); assertEquals(expResult, result); } /** * Test of getCausingDividend method, of class NotDivisibleException. */ @Test public void testGetCausingDivisor() { QuadraticRing ring = new ImaginaryQuadraticRing(-1); QuadraticInteger expResult = new ImaginaryQuadraticInteger(3, 1, ring); AlgebraicInteger result = notDivGaussian.getCausingDivisor(); assertEquals(expResult, result); ring = new ImaginaryQuadraticRing(-3); expResult = new ImaginaryQuadraticInteger(1, 9, ring); result = notDivEisenstein.getCausingDivisor(); assertEquals(expResult, result); } /** * Test of getCausingRing method, of class NotDivisibleException. */ @Test public void testGetCausingRing() { System.out.println("getCausingRing"); QuadraticRing expResult = new ImaginaryQuadraticRing(-1); IntegerRing result = notDivGaussian.getCausingRing(); assertEquals(expResult, result); expResult = new ImaginaryQuadraticRing(-3); result = notDivEisenstein.getCausingRing(); assertEquals(expResult, result); expResult = new RealQuadraticRing(2); result = notDivZ2.getCausingRing(); assertEquals(expResult, result); expResult = new RealQuadraticRing(5); result = notDivZPhi.getCausingRing(); assertEquals(expResult, result); } /** * Another test of getCausingRing method, of class NotDivisibleException. * This one checks that the correct ring can be inferred if the dividend and * divisor are of different rings, and the applicable radicands are coprime. */ @Test public void testGetCausingRingInferredCoprime() { String msg = "Example with dividend and divisor from different rings"; RealQuadraticRing dividendRing = new RealQuadraticRing(21); RealQuadraticInteger dividend = new RealQuadraticInteger(0, 1, dividendRing); RealQuadraticRing divisorRing = new RealQuadraticRing(5); RealQuadraticInteger divisor = new RealQuadraticInteger(0, 1, divisorRing); Fraction regPartFract = new Fraction(0); Fraction surdPartFract = new Fraction(1, 5); Fraction[] fracts = {regPartFract, surdPartFract}; RealQuadraticRing expResult = new RealQuadraticRing(105); NotDivisibleException notDivExcForInference = new NotDivisibleException(msg, dividend, divisor, fracts); IntegerRing result = notDivExcForInference.getCausingRing(); assertEquals(expResult, result); } /** * Another test of getCausingRing method, of class NotDivisibleException. * This one checks that the correct ring can be inferred if the dividend and * divisor are of different rings, and the applicable radicands have a * common divisor greater than 1. */ @Test public void testGetCausingRingInferredCommonDivisor() { String msg = "Example with dividend and divisor from different rings"; RealQuadraticRing dividendRing = new RealQuadraticRing(21); RealQuadraticInteger dividend = new RealQuadraticInteger(0, 4, dividendRing); RealQuadraticRing divisorRing = new RealQuadraticRing(3); RealQuadraticInteger divisor = new RealQuadraticInteger(0, 3, divisorRing); Fraction regPartFract = new Fraction(0); Fraction surdPartFract = new Fraction(4, 3); Fraction[] fracts = {regPartFract, surdPartFract}; RealQuadraticRing expResult = new RealQuadraticRing(7); NotDivisibleException notDivExcForInference = new NotDivisibleException(msg, dividend, divisor, fracts); IntegerRing result = notDivExcForInference.getCausingRing(); assertEquals(expResult, result); } /** * Test of getNumericRealPart method, of class NotDivisibleException. */ @Test public void testGetNumericRealPart() { System.out.println("getNumericRealPart"); double expResult, result; expResult = 1.0 / 4.0; result = notDivEisenstein.getNumericRealPart(); assertEquals(expResult, result, TEST_DELTA); expResult = 8.0 / 5.0; result = notDivGaussian.getNumericRealPart(); assertEquals(expResult, result, TEST_DELTA); expResult = -1.18767; result = notDivZ2.getNumericRealPart(); assertEquals(expResult, result, TEST_DELTA); expResult = 0.53934; result = notDivZPhi.getNumericRealPart(); assertEquals(expResult, result, TEST_DELTA); } /** * Test of getNumericImagPart method, of class NotDivisibleException. */ @Test public void testGetNumericImagPart() { System.out.println("getNumericImagPart"); double expResult, result; expResult = -9.0 * Math.sqrt(3) / 4.0; result = notDivEisenstein.getNumericImagPart(); assertEquals(expResult, result, TEST_DELTA); expResult = -1.0 / 5.0; result = notDivGaussian.getNumericImagPart(); assertEquals(expResult, result, TEST_DELTA); expResult = 0.0; result = notDivZ2.getNumericImagPart(); assertEquals(expResult, result, TEST_DELTA); result = notDivZPhi.getNumericImagPart(); assertEquals(expResult, result, TEST_DELTA); } /** * Test of getAbs method, of class NotDivisibleException. */ @Test public void testGetAbs() { System.out.println("getNumericRealPart"); double expResult, result; expResult = 1.61245; result = notDivGaussian.getAbs(); assertEquals(expResult, result, TEST_DELTA); expResult = 3.90512; result = notDivEisenstein.getAbs(); assertEquals(expResult, result, TEST_DELTA); expResult = 1.18767; result = notDivZ2.getAbs(); assertEquals(expResult, result, TEST_DELTA); expResult = 0.53934; result = notDivZPhi.getAbs(); assertEquals(expResult, result, TEST_DELTA); } private void sortAlgIntArray(AlgebraicInteger[] algIntArray) { AlgebraicInteger swapper; boolean swapFlag; do { swapFlag = false; for (int i = 0; i < algIntArray.length - 1; i++) { if (algIntArray[i].norm() > algIntArray[i + 1].norm()) { swapper = algIntArray[i]; algIntArray[i] = algIntArray[i + 1]; algIntArray[i + 1] = swapper; swapFlag = true; } } } while (swapFlag); } /** * Test of getBoundingIntegers method, of class NotDivisibleException. */ @Test public void testGetBoundingIntegers() { System.out.println("getBoundingIntegers"); ImaginaryQuadraticInteger[] expResult = new ImaginaryQuadraticInteger[4]; QuadraticRing currRing = new ImaginaryQuadraticRing(-1); expResult[0] = new ImaginaryQuadraticInteger(1, 0, currRing); expResult[1] = new ImaginaryQuadraticInteger(1, -1, currRing); expResult[2] = new ImaginaryQuadraticInteger(2, 0, currRing); expResult[3] = new ImaginaryQuadraticInteger(2, -1, currRing); AlgebraicInteger[] result = notDivGaussian.getBoundingIntegers(); sortAlgIntArray(result); assertArrayEquals(expResult, result); currRing = new ImaginaryQuadraticRing(-3); expResult[0] = new ImaginaryQuadraticInteger(0, -2, currRing); expResult[1] = new ImaginaryQuadraticInteger(-1, -5, currRing, 2); expResult[2] = new ImaginaryQuadraticInteger(1, -5, currRing, 2); expResult[3] = new ImaginaryQuadraticInteger(0, -3, currRing); result = notDivEisenstein.getBoundingIntegers(); sortAlgIntArray(result); assertArrayEquals(expResult, result); currRing = new RealQuadraticRing(2); RealQuadraticInteger currElem = new RealQuadraticInteger(-1, 0, currRing); String msg = "Array of bounding integers for the Z[sqrt(2)] example should contain " + currElem.toASCIIString(); result = notDivZ2.getBoundingIntegers(); assertTrue(msg, Arrays.asList(result).contains(currElem)); currElem = new RealQuadraticInteger(-2, 0, currRing); msg = "Array of bounding integers for the Z[sqrt(2)] example should contain " + currElem.toASCIIString(); assertTrue(msg, Arrays.asList(result).contains(currElem)); currElem = new RealQuadraticInteger(0, -1, currRing); msg = "Array of bounding integers for the Z[sqrt(2)] example should contain " + currElem.toASCIIString(); assertTrue(msg, Arrays.asList(result).contains(currElem)); currRing = new RealQuadraticRing(5); currElem = new RealQuadraticInteger(1, 1, currRing, 2); msg = "Array of bounding integers for the Z[phi] example should contain " + currElem.toASCIIString(); result = notDivZPhi.getBoundingIntegers(); assertTrue(msg, Arrays.asList(result).contains(currElem)); } /** * Test of roundTowardsZero method, of class NotDivisibleException. In the * case of real quadratic integers, I've gone back and forth on what the * result of this function should be. For now, that part of the test is * inactive. */ @Test public void testRoundTowardsZero() { System.out.println("roundTowardsZero"); QuadraticRing currRing = new ImaginaryQuadraticRing(-1); QuadraticInteger expResult = new ImaginaryQuadraticInteger(1, 0, currRing); AlgebraicInteger result = notDivGaussian.roundTowardsZero(); assertEquals(expResult, result); currRing = new ImaginaryQuadraticRing(-3); expResult = new ImaginaryQuadraticInteger(0, -2, currRing); result = notDivEisenstein.roundTowardsZero(); assertEquals(expResult, result); // TODO: Figure out tests for real rings // currRing = new RealQuadraticRing(2); // expResult = new ImaginaryQuadraticInteger(1, 0, currRing); // result = notDivZ2.roundTowardsZero(); // assertEquals(expResult, result); // currRing = new RealQuadraticRing(5); // expResult = new ImaginaryQuadraticInteger(0, 0, currRing); // result = notDivZPhi.roundTowardsZero(); // assertEquals(expResult, result); } /** * Test of roundAwayFromZero method, of class NotDivisibleException. In the * case of real quadratic integers, I've gone back and forth on what the * result of this function should be. For now, that part of the test is * inactive. */ @Test public void testRoundAwayFromZero() { System.out.println("roundAwayFromZero"); QuadraticRing currRing = new ImaginaryQuadraticRing(-1); QuadraticInteger expResult = new ImaginaryQuadraticInteger(2, -1, currRing); AlgebraicInteger result = notDivGaussian.roundAwayFromZero(); assertEquals(expResult, result); currRing = new ImaginaryQuadraticRing(-3); expResult = new ImaginaryQuadraticInteger(0, -3, currRing); result = notDivEisenstein.roundAwayFromZero(); assertEquals(expResult, result); // TODO: Figure out tests for real rings // currRing = new RealQuadraticRing(2); // expResult = new ImaginaryQuadraticInteger(2, 0, currRing); // result = notDivZ2.roundAwayFromZero(); // assertEquals(expResult, result); // currRing = new RealQuadraticRing(5); // expResult = new ImaginaryQuadraticInteger(1, 0, currRing); // result = notDivZPhi.roundAwayFromZero(); // assertEquals(expResult, result); } /** * Test of the auxiliary NotDivisibleException constructor. This only tests * that the exception message is correctly inferred, using {@link * algebraics.quadratics.QuadraticInteger#toASCIIString()} (which is assumed * to have been properly tested in the relevant test classes). */ @Test public void testAuxiliaryConstructor() { System.out.println("Auxiliary Constructor"); QuadraticRing ring = new ImaginaryQuadraticRing(-13); ImaginaryQuadraticInteger dividend = new ImaginaryQuadraticInteger(0, 1, ring); ImaginaryQuadraticInteger divisor = new ImaginaryQuadraticInteger(2, 0, ring); Fraction fractA = new Fraction(0); Fraction fractB = new Fraction(1, 2); Fraction[] fracts = {fractA, fractB}; try { throw new NotDivisibleException(dividend, divisor, fracts); } catch (NotDivisibleException nde) { String expResult = dividend.toASCIIString() + " is not divisible by 2"; String result = nde.getMessage(); assertEquals(expResult, result); } catch (Exception e) { String msg = e.getClass().getName() + " should not have occurred for valid 3-parameter constructor call"; fail(msg); } ring = new ImaginaryQuadraticRing(-15); dividend = new ImaginaryQuadraticInteger(0, 2, ring); divisor = new ImaginaryQuadraticInteger(4, 0, ring); try { throw new NotDivisibleException(dividend, divisor, fracts); } catch (NotDivisibleException nde) { String expResult = dividend.toASCIIString() + " is not divisible by 4"; String result = nde.getMessage(); assertEquals(expResult, result); } catch (Exception e) { String msg = e.getClass().getName() + " should not have occurred for valid 3-parameter constructor call"; fail(msg); } } /** * Test of the NotDivisibleException constructor. The only thing we're * testing here is that the constructor throws IllegalArgumentException if * passed an array of fractions with a length that doesn't match the * algebraic degree of the pertinent ring. */ @Test public void testConstructor() { System.out.println("Constructor"); String excMsg = "This is an exception message for an invalidly constructed NotDivisibleException"; QuadraticRing ring = new RealQuadraticRing(19); RealQuadraticInteger initDividend = new RealQuadraticInteger(0, 0, ring); RealQuadraticInteger initDivisor = new RealQuadraticInteger(1, 0, ring); Fraction fractA = new Fraction(7); Fraction fractB = new Fraction(1, 2); Fraction fractC = new Fraction(3, 2); Fraction[] wrongLenFractArray = {fractA, fractB, fractC}; try { throw new NotDivisibleException(excMsg, initDividend, initDivisor, wrongLenFractArray); } catch (NotDivisibleException nde) { String msg = "NotDivisibleException incorrectly created: \"" + nde.getMessage() + "\""; fail(msg); } catch(IllegalArgumentException iae) { System.out.println("Attempt to create NotDivisibleException with arrays of excessive length correctly triggered IllegalArgumentException."); System.out.println("\"" + iae.getMessage() + "\""); } catch(Exception e) { String msg = e.getClass().getName() + " is the wrong exception in this situation of arrays of excessive length."; System.out.println(msg); System.out.println("\"" + e.getMessage() + "\""); } } }
<template> <TheHeader /> <div v-for="obj in todos" v-bind:key="obj.id" class="todosItem"> {{ obj.title }} </div><br> <h2>Todos em aberto</h2> <div v-for="todo in uncompleted" :key="todo.id" class="todosItem"> {{ todo.title }} </div><br> <h2>Todos completos</h2> <div v-for="todo in completed" :key="todo.id" class="todosItem"> {{ todo.title }} </div><br> <teste /> <BaseCard v-if="showAlert" :variant="variant" v-on:close="onClose()"> {{ text }} </BaseCard> </template> <script> import BaseCard from './components/BaseCard.vue'; import TheHeader from './components/TheHeader'; import teste from './components/teste'; export default { name: 'App', components: { TheHeader, teste, BaseCard }, data() { return { todos: [ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }, { "userId": 1, "id": 2, "title": "quis ut nam facilis et officia qui", "completed": false }, { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false }, { "userId": 1, "id": 4, "title": "et porro tempora", "completed": true }, { "userId": 1, "id": 5, "title": "laboriosam mollitia et enim quasi adipisci quia provident illum", "completed": false } ], showAlert: true, variant: 'success', text: 'Seu formulário foi enviado' } }, computed: { uncompleted() { return this.todos.filter(todo => !todo.completed); }, completed() { return this.todos.filter(todo => todo.completed) } }, methods: { onClose() { this.showAlert = false; console.log('on close'); } } } </script> <style> .todosItem { background: #000; color: blanchedalmond; } #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
import Image from "next/image"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { useUser } from "@/actions/useUser"; interface UserHeroProps2 { userId: string; } export default async function UserHero({ userId }: UserHeroProps2) { const user = await useUser(userId); return ( <> <div className="relative z-20 h-36 rounded-lg bg-orange-400"> {user.coverImage && ( <Image src={user.coverImage} fill alt="Cover Image" style={{ objectFit: "cover" }} /> )} </div> <Avatar className="absolute z-30 -mt-14 ml-4 h-[100px] w-[100px] border-4 border-black"> <AvatarImage src={user?.profileImage || "/images/placeholder.png"} alt="Profile" className="bg-white dark:bg-black" /> <AvatarFallback className="bg-white text-black dark:invert"> {user.name[0]} </AvatarFallback> </Avatar> </> ); }
import React, { useState } from 'react'; import axios from 'axios'; import Sidebar from '../Sidebar'; import '../styles/crudStyles.css'; // Ensure this import is here const AddConferenceInfo = () => { const [info, setInfo] = useState({ title: '', address: '' }); const [successMessage, setSuccessMessage] = useState(''); const handleSubmit = async (event) => { event.preventDefault(); try { const response = await axios.post('http://localhost:8081/api/conference-info', info); console.log(response.data); setSuccessMessage('Conference information added successfully!'); } catch (error) { console.error('Error adding conference info', error); setSuccessMessage(''); } }; const handleChange = (event) => { setInfo({ ...info, [event.target.name]: event.target.value }); }; return ( <div className="d-flex"> <Sidebar /> <div className="content-container"> {successMessage && <div className="success-message">{successMessage}</div>} <div className="form-container"> <h2>Add Conference Information</h2> <form onSubmit={handleSubmit}> <div className="form-group"> <label>Title:</label> <input type="text" name="title" value={info.title} onChange={handleChange} /> </div> <div className="form-group"> <label>Address:</label> <input type="text" name="address" value={info.address} onChange={handleChange} /> </div> <div className="form-group"> <button type="submit">Add Info</button> </div> </form> </div> </div> </div> ); }; export default AddConferenceInfo;
import { createContext, useState } from 'react'; import { SnacksProps } from './interfaces'; import { useNavigate } from 'react-router-dom'; import { PaymentUserFormProps as CustomerData } from '../pages/pagamento/paymentUserFormValidation'; interface SnackCart extends SnacksProps { quantity: number; subtotal: number; } interface CartContextProps { cart: SnackCart[]; addSnack: (snack: SnacksProps) => void; deleteSnack: (snack: SnacksProps) => void; incrementSnack: (snack: SnackCart) => void; decrementSnack: (snack: SnackCart) => void; confirmOrder: () => void; paymentOrder: (customer: CustomerData) => void; } export const CartContext = createContext({} as CartContextProps); export const CartProvider = ({ children }: { children: React.ReactNode }) => { const navigate = useNavigate(); const localStorageKey = '@NeoBistrotCart'; const [cart, setCart] = useState<SnackCart[]>(() => { const value = localStorage.getItem(localStorageKey); if (value) return JSON.parse(value) as SnackCart[]; return []; }); function saveCart(items: SnackCart[]) { setCart(items); localStorage.setItem(localStorageKey, JSON.stringify(items)); } function addSnack(snack: SnacksProps) { const snackAlreadyExist = cart.find((item) => item.name === snack.name); if (snackAlreadyExist) { const newCart = cart.map((item) => { if (item.name === snack.name) { const quantity = item.quantity + 1; const subtotal = quantity * snack.price; return { ...item, quantity, subtotal }; } return item; }); return saveCart(newCart); } const newSnack = { ...snack, quantity: 1, subtotal: snack.price }; const newCart = [...cart, newSnack]; saveCart(newCart); } function deleteSnack(snack: SnacksProps) { const newCart = cart.filter((item) => !(item.name === snack.name)); saveCart(newCart); } function updateSnack(snack: SnackCart, newQuantity: number) { if (newQuantity == 0) return; const newCart = cart.map((item) => { if (item.name !== snack.name) return item; return { ...item, quantity: newQuantity, subtotal: newQuantity * snack.price, }; }); saveCart(newCart); } function incrementSnack(snack: SnackCart) { updateSnack(snack, snack.quantity + 1); } function decrementSnack(snack: SnackCart) { updateSnack(snack, snack.quantity - 1); } function confirmOrder() { navigate('/pagamento'); } function paymentOrder(data: CustomerData) { console.log('Itens', cart, 'Cliente', data); localStorage.removeItem(localStorageKey); } return ( <CartContext.Provider value={{ cart, addSnack, deleteSnack, incrementSnack, decrementSnack, confirmOrder, paymentOrder, }} > {children} </CartContext.Provider> ); };
import copy import pytest from taxi import discovery @pytest.mark.config( TVM_ENABLED=True, BILLING_ORDERS_USE_STQ_RESCHEDULE=True, BILLING_DO_NOT_FINISH_SUBSCRIPTION_DOC=True, BILLING_ORDERS_EVENT_LIMIT_KIND_HOURS={'__default__': 10 ** 6}, ) @pytest.mark.parametrize( 'test_data_path', [ 'arbitrary_wallet/arbitrary_wallet.json', 'arbitrary_wallet/arbitrary_wallet_not_enough_funds.json', ], ) async def test_execute( test_data_path, *, load_py_json_dir, patch, patch_aiohttp_session, response_mock, taxi_billing_orders_client, request_headers, patched_tvm_ticket_check, mockserver, ): data = load_py_json_dir('test_v2_execute', test_data_path) functions_request = {} @patch_aiohttp_session(discovery.find_service('billing_docs').url, 'POST') def _patch_billing_docs_request(method, url, headers, json, **kwargs): if 'v1/docs/create' in url: found_doc = data.get('doc') if found_doc: return response_mock(json=found_doc) doc = json.copy() doc['doc_id'] = 6 doc['created'] = doc['event_at'] doc['process_at'] = doc['event_at'] doc['revision'] = 1 doc.setdefault('tags', []) return response_mock(status=200, json=doc) raise NotImplementedError(f'No mock for {url}') @patch_aiohttp_session( discovery.find_service('billing_functions').url, 'POST', ) def _patch_billing_functions_request(method, url, headers, json, **kwargs): functions_request.update(copy.deepcopy(json)) default = {'status': 'success'} json['data']['status_info'] = data.get('status_info') or default json['status'] = 'complete' return response_mock(json=json) @patch_aiohttp_session( discovery.find_service('billing_subventions').url, 'POST', ) def _patch_billing_subventions_request( method, url, headers, json, **kwargs, ): assert '/v1/rules/select' in url subvention_response = data['subvention_response'] return response_mock( status=subvention_response['status'], json=subvention_response['data'], ) response = await taxi_billing_orders_client.post( '/v2/execute', headers=request_headers, json=data['request'], ) assert response.status == data['expected_response']['status'] content = await response.json() assert content == data['expected_response']['data'] assert functions_request == data['expected_functions_request']
package com.lakesidehotel.app.room.controller; import com.lakesidehotel.app.room.dto.BookRoomDto; import com.lakesidehotel.app.room.dto.BookRoomRequest; import com.lakesidehotel.app.room.dto.GuestInfoResponse; import com.lakesidehotel.app.room.exception.LakeSideHotelException; import com.lakesidehotel.app.room.model.Room; import com.lakesidehotel.app.room.service.RoomService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/v1/lakeSideHotel/") public class RoomController { @Autowired private RoomService roomService; @PostMapping("guest/bookARoom/") public BookRoomDto bookARoom(@RequestBody BookRoomRequest roomRequest) throws LakeSideHotelException { return roomService.bookARoom(roomRequest); } @GetMapping("getAllAvailableRooms/") public List<Room> getAllAvailableRooms() throws LakeSideHotelException { return roomService.getAvailableRooms(); } @GetMapping("getGuestDetails/{roomNumber}/") public GuestInfoResponse getGuestDetails(@PathVariable int roomNumber){ return roomService.getGuestInfo(roomNumber); } @GetMapping("isRoomAvailable/{roomNumber}/") public boolean isRoomAvailable(@PathVariable int roomNumber){ return roomService.isRoomAvailable(roomNumber); } @GetMapping("checkIn/{email}") public String checkIn(@PathVariable String email) throws LakeSideHotelException { return roomService.checkIn(email); } @GetMapping("checkOut/{email}") public String checkOut(@PathVariable String email) throws LakeSideHotelException { return roomService.checkOut(email); } }
<i18n locale="zh-CN" lang="yaml"> Root: 根目录 File Service disabled: 文件服务已禁用 File Service enabled : 文件服务已启用 File Service deleted : 文件服务已删除 No File Service has ever been added: 从未添加过任何文件服务 Are you sure you want to disable the File Service?: 是否确认禁用此文件服务? Are you sure you want to delete the File Service?: 是否确认删除此文件服务? Expose folders in the Resource as File Services to allow external systems to access files directly: 将资源目录下的文件夹创建为文件服务,即可在系统外部直接访问文件 </i18n> <template> <transition name="fade"> <el-container direction="vertical" v-show="$store.state.isLoaded"> <!-- 标题区 --> <el-header height="60px"> <div class="common-page-header"> <h1>{{ $t('File Service') }}</h1> <div class="header-control"> <FuzzySearchInput :dataFilter="dataFilter"></FuzzySearchInput> <el-button @click="openSetup(null, 'add')" type="primary" size="small"> <i class="fa fa-fw fa-plus"></i> {{ $t('New') }} </el-button> </div> </div> </el-header> <!-- 列表区 --> <el-main class="common-table-container"> <div class="no-data-area" v-if="T.isNothing(data)"> <h1 class="no-data-title" v-if="T.isPageFiltered()"><i class="fa fa-fw fa-search"></i>{{ $t('No matched data found') }}</h1> <h1 class="no-data-title" v-else><i class="fa fa-fw fa-info-circle"></i>{{ $t('No File Service has ever been added') }}</h1> <p class="no-data-tip"> {{ $t('Expose folders in the Resource as File Services to allow external systems to access files directly') }} </p> </div> <el-table v-else class="common-table" height="100%" :data="data" :row-class-name="T.getHighlightRowCSS"> <el-table-column :label="$t('Root')"> <template slot-scope="scope"> <code class="file-service-title">{{ scope.row.root }}</code> <div> <span class="text-info">ID</span> &nbsp;<code class="text-main">{{ scope.row.id }}</code> <CopyButton :content="scope.row.id" /> <template v-if="scope.row.note"> <br> <span class="text-info">&#12288;{{ $t('Note') }}{{ $t(':') }}</span> <span>{{ scope.row.note }}</span> </template> </div> </template> </el-table-column> <el-table-column :label="$t('Status')" width="120"> <template slot-scope="scope"> <span v-if="scope.row.isDisabled" class="text-bad">{{ $t('Disabled') }}</span> <span v-else class="text-good">{{ $t('Enabled') }}</span> </template> </el-table-column> <el-table-column align="right" width="260"> <template slot-scope="scope"> <el-link :href="scope.row.openURL" target="_blank">{{ $t('Open') }}</el-link> <el-link v-if="scope.row.isDisabled" v-prevent-re-click @click="quickSubmitData(scope.row, 'enable')">{{ $t('Enable') }}</el-link> <el-link v-else @click="quickSubmitData(scope.row, 'disable')">{{ $t('Disable') }}</el-link> <el-link @click="openSetup(scope.row, 'setup')">{{ $t('Setup') }}</el-link> <el-link @click="quickSubmitData(scope.row, 'delete')">{{ $t('Delete') }}</el-link> </template> </el-table-column> </el-table> </el-main> <!-- 翻页区 --> <Pager :pageInfo="pageInfo" /> <FileServiceSetup ref="setup" /> </el-container> </transition> </template> <script> import FileServiceSetup from '@/components/Management/FileServiceSetup' export default { name: 'FileServiceList', components: { FileServiceSetup, }, watch: { $route: { immediate: true, async handler(to, from) { await this.loadData(); } }, '$store.state.isLoaded': function(val) { if (!val) return; setImmediate(() => this.T.autoScrollTable()); }, }, methods: { async loadData() { // 默认过滤条件 let _listQuery = this.dataFilter = this.T.createListQuery(); let apiRes = await this.T.callAPI_get('/api/v1/file-services/do/list', { query: _listQuery, }); if (!apiRes || !apiRes.ok) return; // 补齐打开路径 apiRes.data.forEach(d => { d.openURL = this.T.formatURL('/api/v1/fs/:id/', { baseURL: true, params: { id: d.id } }); }); this.data = apiRes.data; this.pageInfo = apiRes.pageInfo; this.$store.commit('updateLoadStatus', true); }, async quickSubmitData(d, operation) { switch(operation) { case 'disable': if (!await this.T.confirm(this.$t('Are you sure you want to disable the File Service?'))) return; break; case 'delete': if (!await this.T.confirm(this.$t('Are you sure you want to delete the File Service?'))) return; break; } let apiRes = null; switch(operation) { case 'disable': apiRes = await this.T.callAPI('post', '/api/v1/file-services/:id/do/modify', { params: { id: d.id }, body : { data: { isDisabled: true } }, alert : { okMessage: this.$t('File Service disabled') }, }); break; case 'enable': apiRes = await this.T.callAPI('post', '/api/v1/file-services/:id/do/modify', { params: { id: d.id }, body : { data: { isDisabled: false } }, alert : { okMessage: this.$t('File Service enabled') }, }); break; case 'delete': apiRes = await this.T.callAPI('/api/v1/file-services/:id/do/delete', { params: { id: d.id }, alert : { okMessage: this.$t('File Service deleted') }, }); break; } if (!apiRes || !apiRes.ok) return; this.$store.commit('updateHighlightedTableDataId', d.id); await this.loadData(); }, openSetup(d, target) { let nextRouteQuery = this.T.packRouteQuery(); switch(target) { case 'add': this.$refs.setup.loadData(); break; case 'setup': this.$store.commit('updateHighlightedTableDataId', d.id); this.$refs.setup.loadData(d.id); break; } }, }, computed: { }, props: { }, data() { let _pageInfo = this.T.createPageInfo(); let _dataFilter = this.T.createListQuery(); return { data : [], pageInfo: _pageInfo, dataFilter: { _fuzzySearch: _dataFilter._fuzzySearch, }, } }, created() { this.$root.$on('reload.fileServiceList', () => this.loadData()); }, destroyed() { this.$root.$off('reload.fileServiceList'); }, } </script> <style scoped> .file-service-title { font-size: 16px; } </style> <style> </style>
<?php declare(strict_types=1); namespace App\Pattern\Creational\FactoryMethod\Factory; use App\Pattern\Creational\FactoryMethod\Ferrari; use App\Pattern\Creational\FactoryMethod\Bmw; use App\Pattern\Creational\FactoryMethod\FixFactoryInterface; use App\Pattern\Creational\FactoryMethod\Lada; class CarStaticFactory2 { public static function build(string $name): FixFactoryInterface { return match ($name) { 'lada' => (new Lada())->getFactory(), 'bmw' => (new Bmw())->getFactory(), 'ferrari' => (new Ferrari())->getFactory(), default => throw new \Exception('There is no Car with name ' . $name), }; } }
import 'package:flutter/material.dart'; import 'greeting_widget.dart'; import 'counter_widget.dart'; import 'splash_screen.dart'; void main() { runApp(SplashScreenApp()); } class SplashScreenApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: SplashScreen(), ); } } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Widgets Practice'), toolbarHeight: 90, flexibleSpace: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.blue, Colors.purple], begin: Alignment.topLeft, end: Alignment.bottomRight, ), ), ), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ GreetingWidget(greetingMessage: 'Hello, Professor'), SizedBox(height: 20), CounterWidget(), ], ), ), ), ); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE-edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Education website using HTML,CSS & JavaScript</title> <link rel="stylesheet" href="https://unicons.iconscout.com/release/v2.1.6/css/unicons.css"> <link rel="stylesheet" href="./css/style.css"> <link rel="<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Montserrat+Subrayada:wght@700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="./css/style.css"> <link rel="stylesheet" href="./css/about.css"> </head> <body> <nav> <div class="container nav_container"> <a href="index.html"><h4>EGATOR</h4></a> <ul class="nav_menu"> <li><a href="index.html">Home</a></li> <li><a href="about.html">About</a></li> <li><a href="courses.html">Courses</a></li> <li><a href="contact.html">Contact</a></li> </ul> <button id="open-menu-btn"><i class="uil uil-bars"></i></button> <button id="close-menu-btn"><i class="uil uil-bars"></i></button> </div> </nav> <section class="about_achievements"> <div class="container about_achievements-container"> <div class="about_achievements-left"> <img src="./image/about achievements.svg"> </div> <div class="about_achievements-right"> <h1>Achievements</h1> <p> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Impedit, at in voluptates doloremque necessitatibus officiis aliquid aspernatur quisquam maxime dolorem exercitationem, quae animi esse sint eos! Nemo molestias consectetur error. </p> <div class="achievements_cards"> <article class="achievement_card"> <span class="achievement_icon"> <i class="uil uil-video"></i> </span> <h3>450+</h3> <p>Courses</p> </article> <article class="achievement_card"> <span class="achievement_icon"> <i class="uil users-alt"></i> </span> <h3>79,000+</h3> <p>Students</p> </article> <article class="achievement_card"> <span class="achievement_icon"> <i class="uil uil-trophy"></i> </span> <h3>26+</h3> <p>Awards</p> </article> </div> </div> </div> </section> <section class="team"> <h2>Meet Our Team</h2> <div class="container team_container"> <article class="team_member"> <div class="team_member-image"> <img src="./image/tm1.jpg"> </div> <div class="team_member-info"> <h4>Shatta Wale</h4> <p>Expert Tutor</p> </div> <div class="team_mwmber-socials"> <a href="https://instagram.com" target="_blank"><i class="uil uil-instagram"></i></a> <a href="https://twitter.com" target="_blank"><i class="uil uil-twitter-alt"></i></a> <a href="https://linkedin.com" target="_blank"><i class="uil uil-linkedin-alt"></i></a> </div> </article> <article class="team_member"> <div class="team_member-image"> <img src="./image/tm1.jpg"> </div> <div class="team_member-info"> <h4>Shatta Wale</h4> <p>Expert Tutor</p> </div> <div class="team_mwmber-socials"> <a href="https://instagram.com" target="_blank"><i class="uil uil-instagram"></i></a> <a href="https://twitter.com" target="_blank"><i class="uil uil-twitter-alt"></i></a> <a href="https://linkedin.com" target="_blank"><i class="uil uil-linkedin-alt"></i></a> </div> </article> <article class="team_member"> <div class="team_member-image"> <img src="./image/tm2.jpg"> </div> <div class="team_member-info"> <h4>Mia Jones</h4> <p>Expert Tutor</p> </div> <div class="team_mwmber-socials"> <a href="https://instagram.com" target="_blank"><i class="uil uil-instagram"></i></a> <a href="https://twitter.com" target="_blank"><i class="uil uil-twitter-alt"></i></a> <a href="https://linkedin.com" target="_blank"><i class="uil uil-linkedin-alt"></i></a> </div> </article> <article class="team_member"> <div class="team_member-image"> <img src="./image/tm3.jpg"> </div> <div class="team_member-info"> <h4>Diana Ayi</h4> <p>Expert Tutor</p> </div> <div class="team_mwmber-socials"> <a href="https://instagram.com" target="_blank"><i class="uil uil-instagram"></i></a> <a href="https://twitter.com" target="_blank"><i class="uil uil-twitter-alt"></i></a> <a href="https://linkedin.com" target="_blank"><i class="uil uil-linkedin-alt"></i></a> </div> </article> <article class="team_member"> <div class="team_member-image"> <img src="./image/tm4.jpg"> </div> <div class="team_member-info"> <h4>JOhn Dumelo</h4> <p>Expert Tutor</p> </div> <div class="team_mwmber-socials"> <a href="https://instagram.com" target="_blank"><i class="uil uil-instagram"></i></a> <a href="https://twitter.com" target="_blank"><i class="uil uil-twitter-alt"></i></a> <a href="https://linkedin.com" target="_blank"><i class="uil uil-linkedin-alt"></i></a> </div> </article> <article class="team_member"> <div class="team_member-image"> <img src="./image/tm5.jpg"> </div> <div class="team_member-info"> <h4>Ruth Sockings</h4> <p>Expert Tutor</p> </div> <div class="team_mwmber-socials"> <a href="https://instagram.com" target="_blank"><i class="uil uil-instagram"></i></a> <a href="https://twitter.com" target="_blank"><i class="uil uil-twitter-alt"></i></a> <a href="https://linkedin.com" target="_blank"><i class="uil uil-linkedin-alt"></i></a> </div> </article> <article class="team_member"> <div class="team_member-image"> <img src="./image/tm6.jpg"> </div> <div class="team_member-info"> <h4>Edem Quist</h4> <p>Expert Tutor</p> </div> <div class="team_mwmber-socials"> <a href="https://instagram.com" target="_blank"><i class="uil uil-instagram"></i></a> <a href="https://twitter.com" target="_blank"><i class="uil uil-twitter-alt"></i></a> <a href="https://linkedin.com" target="_blank"><i class="uil uil-linkedin-alt"></i></a> </div> </article> <article class="team_member"> <div class="team_member-image"> <img src="./image/tm7.jpg"> </div> <div class="team_member-info"> <h4>Lila James</h4> <p>Expert Tutor</p> </div> <div class="team_mwmber-socials"> <a href="https://instagram.com" target="_blank"><i class="uil uil-instagram"></i></a> <a href="https://twitter.com" target="_blank"><i class="uil uil-twitter-alt"></i></a> <a href="https://linkedin.com" target="_blank"><i class="uil uil-linkedin-alt"></i></a> </div> </article> <article class="team_member"> <div class="team_member-image"> <img src="./image/tm8.jpg"> </div> <div class="team_member-info"> <h4>Minz Gold</h4> <p>Expert Tutor</p> </div> <div class="team_mwmber-socials"> <a href="https://instagram.com" target="_blank"><i class="uil uil-instagram"></i></a> <a href="https://twitter.com" target="_blank"><i class="uil uil-twitter-alt"></i></a> <a href="https://linkedin.com" target="_blank"><i class="uil uil-linkedin-alt"></i></a> </div> </article> </div> </section> <footer> <div class="container footer_container"> <div class="footer_1"> <a href="index.html" class="footer_logo"><h4>EGATOR</h4></a> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit.Corporis ipsum nobis ratione. </p> </div> <div class="footer_2"> <h4>Permalinks</h4> <ul class="permalinks"> <li><a href="index.html">Home</a></li> <li><a href="about.html">About</a></li> <li><a href="courses.html">Courses</a></li> <li><a href="contact.html">Contact</a></li> </ul> </div> <div class="footer_3"> <h4>Privacy</h4> <ul class="permalinks"> <li><a href="#">Privacy policy</a></li> <li><a href="#">Terms and conditions</a></li> <li><a href="#">Refund policy</a></li> </ul> </div> <div class="footer_4"> <h4>Contact Us</h4> <div> <p>+91 123 456 7890</p> <p>[email protected]</p> </div> <ul class="footer_socials"> <li> <a href="#"><i class=uil uil-facebook-f"></i></a> </li> <li> <a href="#"><i class=uil uil-instagram-alt"></i></a> </li> <li> <a href="#"><i class=uil uil-twitter"></i></a> </li> <li> <a href="#"><i class=uil uil-linkedin-alt"></i></a> </li> </ul> </div> </div> <div class="footer_copyright"> <small>Copyright and copy;EGATOR youtube tutorials</small> </div> </footer> <script src="./main.js"></script> </body> </html>
A story about a great project which resulted in the publication of a paper in the ISPRS and me travelling to Florence to present said paper at Foss4g. It all started with my former boss and mentor, Bertil Chapuis, suggesting I do a proof of concept project to render vector tiles using WebGPU. WebGPU is an emerging web standard and JavaScript API for low-level, high-performance access to graphics and computation. I decided to do this prototype using Rust because of all the good things I had heard about it. Rust also has a great library for WebGPU called `wgpu-rs`. Learning both of these technologies at once had a steep learning curve. But the joy of having my first vector tile rendered on the screen was worth it all. <img src="assets/posts/2023-08-10-maplibre-rs/1.webp" alt="Prototype" title="Prototype" /> *Screenshot from the prototype* We used the Mapbox Vector Tile specification. It uses protocol buffers (.PBF) files to encode vector data. After parsing and loading the vector data, we have to tessellate it (triangulate) to transform the vector data into a set of triangles. Triangles is what we give to the GPU shaders. In quick, a shader is a program that runs on the GPU. We usually have two shaders, a vertex and a fragment shader. The vertex shader computes the position of vertices in 3d and the fragment shaders computes the color of each pixel on the screen. Following up on this prototype, we decided to submit a paper at Foss4g as well as a presentation. Both were accepted and we got started on the paper. Jump forward in time, we decided to collaborate with a brilliant ex-student from the university of Munich called Max which was working on a similar project with the same technologies that was more advanced than my prototype. This project then went into the maplibre foundation and became known as maplibre-rs. It was difficult but I managed to learn and participate a few features in the maplibre-rs project. Along with Max, Bertil and Jens (another teacher at HEIG-VD) we wrote and published the paper. Later on we went to Foss4g and presented the paper together with Max. Checkout the paper in the ISPRS [https://isprs-archives.copernicus.org/articles/XLVIII-4-W1-2022/35/2022/isprs-archives-XLVIII-4-W1-2022-35-2022.pdf](https://isprs-archives.copernicus.org/articles/XLVIII-4-W1-2022/35/2022/isprs-archives-XLVIII-4-W1-2022-35-2022.pdf). Checkout maplibre-rs on Github [https://github.com/maplibre/maplibre-rs](https://github.com/maplibre/maplibre-rs). <video autoplay loop muted> <source src="assets/posts/2023-08-10-maplibre-rs/1.mp4" type="video/mp4"> </video> *Maplibre-rs demo in the web*
<template> <div id="nav"> <div class="title"> <router-link to="/">Game highlights</router-link> </div> <div class="search-bar"> <input type="search" placeholder="username"/> </div> <div class="authentication"> <router-link v-if="!currentUser" id="login" to="/">Login</router-link> <router-link v-if="!currentUser" id="register" to="/register">Register</router-link> <router-link v-if="currentUser" id="upload post" to="/post-upload">Upload image</router-link> <a v-if="currentUser" @click.prevent="logout">Logout</a> </div> </div> <router-view/> </template> <script lang="ts"> import {defineComponent} from "vue"; import tokenService from "@/service/authentication/token.service"; export default defineComponent({ computed: { currentUser() { return this.$store.state.authentication.user; } }, methods: { logout() { this.$store.dispatch('authentication/logout'); this.$router.push('/login') } }, created() { console.log(process.env.API_URL); } }) </script> <style> #nav { display: flex; justify-content: space-between; flex-flow: row nowrap; padding: 30px; } #nav a { font-weight: bold; margin-right: 15px; color: #2c3e50; } #nav a.router-link-exact-active { color: #42b983; } .search-bar input{ margin: 5px; border-radius: 4px; box-sizing: border-box; box-shadow: rgb(221, 221, 221) 0px 1px 3px; border: 1px solid rgb(204, 204, 204); padding: 8px 12px; outline: none; } </style>
<script> import { useVuelidate } from "@vuelidate/core"; import { required, email } from "@vuelidate/validators"; /** * Forgot Password component */ export default { setup() { return { v$: useVuelidate() }; }, data() { return { email: "", submitted: false, error: null, title: "Recoverpwd", tryingToReset: false }; }, validations: { email: { required, email } }, methods: { // Try to register the user in with the email, fullname // and password they provided. tryToReset() { this.submitted = true; const auth = process.env.VUE_APP_DEFAULT_AUTH; // stop here if form is invalid this.v$.$touch(); if (this.v$.$invalid) { return; } else { if (auth === "firebase") { this.tryingToReset = true; // Reset the authError if it existed. this.error = null; return this.$store .dispatch("auth/resetPassword", { email: this.email }) .then((token) => { console.log("token", token); setTimeout(() => { this.tryingToReset = false; this.isResetError = false; }, 2000); }) .catch((error) => { this.tryingToReset = false; this.error = error ? error : ""; this.isResetError = true; }); } else if (auth === "fakebackend") { this.tryingToReset = true; } } } } }; </script> <template> <div> <div class="account-pages my-5 pt-sm-5"> <BContainer> <BRow class="justify-content-center"> <BCol md="8" lg="6" class="col-xl-5"> <div> <router-link to="/" class="mb-5 d-block auth-logo"> <img src="@/assets/images/logo-dark.png" alt height="22" class="logo logo-dark" /> <img src="@/assets/images/logo-light.png" alt height="22" class="logo logo-light" /> </router-link> <BCard no-body> <BCardBody class="p-4"> <div class="text-center mt-2"> <h5 class="text-primary">Reset Password</h5> <p class="text-muted">Reset Password with Minible.</p> </div> <div class="p-2 mt-4"> <div v-if="tryingToReset" class="alert alert-success text-center mb-4" role="alert" > Enter your Email and instructions will be sent to you! </div> <form> <div class="mb-3"> <label for="useremail">Email</label> <input type="email" v-model="email" class="form-control" id="useremail" placeholder="Enter email" :class="{ 'is-invalid': submitted && v$.email.$error }" /> <div v-if="submitted && v$.email.$error" class="invalid-feedback" > <span v-if="v$.email.required.$invalid" >Email is required.</span > <span v-if="v$.email.email.$invalid" >Please enter valid email.</span > </div> </div> <BRow class="mb-0"> <BCol class="col-12 text-end"> <BButton class="btn btn-primary w-sm" @click="tryToReset" > Reset </BButton> </BCol> </BRow> <div class="mt-4 text-center"> <p class="mb-0"> Remember It ? <router-link to="/login" class="fw-medium text-primary" >Signin</router-link > </p> </div> </form> </div> </BCardBody> <!-- end card-body --> </BCard> <!-- end card --> <div class="mt-5 text-center"> <p> © {{ new Date().getFullYear() }} Minible. Crafted with <i class="mdi mdi-heart text-danger"></i> by Themesbrand </p> </div> </div> <!-- end col --> </BCol> </BRow> </BContainer> </div> <!-- end row --> </div> </template>
const std = @import("std"); const utils = @import("utils"); const SplitIterator = std.mem.SplitIterator; const ArrayList = std.ArrayList; const ArrayListAligned = std.ArrayListAligned; const DirectoryNode = struct { name: []const u8, parent: ?*DirectoryNode, child: ?ArrayListAligned(*DirectoryNode, null), size: i64, }; const RowType = enum { Command, Directory, File, }; pub fn main() !void { var allocator = std.heap.page_allocator; var list: ArrayListAligned([]const u8, null) = ArrayList([]const u8).init(allocator); defer list.deinit(); try utils.getArrayListFromPath(allocator, &list, "src/input_demo.txt"); var root_node = DirectoryNode{ .name = "/", .size = 10000, .parent = null, .child = null }; var child_node = DirectoryNode{ .name = "/", .size = 10000, .parent = &root_node, .child = null }; var node_list: ArrayListAligned(*DirectoryNode, null) = ArrayList(*DirectoryNode).init(allocator); try node_list.append(&child_node); root_node.child = node_list; std.log.info("root_node: {any}", .{root_node}); for (root_node.child.?.items) |item| { std.log.info("item: {any}", .{item}); } for (list.items) |item| { var split_item: SplitIterator(u8, .any) = std.mem.splitAny(u8, item, " "); const row_type: RowType = getRowType(&split_item); _ = row_type; // std.log.info("rowType: {any}", .{row_type}); // std.log.info("item: {s}", .{item}); } // for (list.items) |item| { // std.log.info("list: {s}", .{item}); // } } fn getRowType(split_item: *SplitIterator(u8, .any)) RowType { const first_word: []const u8 = split_item.*.next() orelse ""; if (std.mem.eql(u8, first_word, "$")) { return .Command; } else if (std.mem.eql(u8, first_word, "dir")) { return .Directory; } else { return .File; } }
{% extends 'films/base.html' %} {% block title %}{{ film.title }}{%endblock%} {% block content %} <h1>{{ film.title }}</h1> <div class="card mb-3" style="max-width: 540px;"> <div class="row g-0"> <div class="col-md-4"> <img src="{{ film.image.url }}" class="img-fluid rounded-start" alt="Изображение"> </div> <div class="col-md-8"> <div class="card-body"> <p class="card-text">Жанр: {{ film.cat }}</p> <p class="card-text">Год выпуска: {{ film.release_year }}</p> </div> </div> </div> </div> <div> {{ film.description }} </div> {% if request.user.is_authenticated %} <form method="post" action="{% url 'single_film' film_slug=film.slug %}"> {% csrf_token %} {{ comment_form.as_p }} <button type="submit" class="btn btn-dark">Добавить комментарий</button> </form> {% else %} <h1>вы должны зарегистриватся чтобы оставлять комментарии</h1> {% endif %} <h1>Comments</h1> <div class="mt-3"> <ul class="list-group"> {% for comment in comments %} <li class="list-group-item {% cycle 'list-group-item-odd' 'list-group-item-even' %}"> <div class="comment-details"> <span class="small-font"> {{ comment.user }} <span class="gray-time">, {{ comment.created_at|date:"d.m.Y H:i"}}</span> </span> {% if request.user == comment.user %} <a href="{% url 'comment_delete' comment.id %}">Delete</a> {% endif %} </div> {{ comment.comment }} </li> {% endfor %} </ul> </div> {% endblock %}
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Store.Web.App_Start.NinjectWebCommon), "Start")] [assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(Store.Web.App_Start.NinjectWebCommon), "Stop")] namespace Store.Web.App_Start { using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using Ninject; using Ninject.Web.Common; using Data.Common; using System.Data.Entity; using Data; using Services.Contracts; using Services; public static class NinjectWebCommon { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summary> /// Starts the application /// </summary> public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); try { kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); return kernel; } catch { kernel.Dispose(); throw; } } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind(typeof(IDbRepository<>)).To(typeof(DbRepository<>)); kernel.Bind<DbContext>().To<StoreDbContext>().InRequestScope(); kernel.Bind<ICategoryService>().To<CategoryService>().InRequestScope(); kernel.Bind<IProductService>().To<ProductService>().InRequestScope(); kernel.Bind<ISupplierService>().To<SupplierService>().InRequestScope(); kernel.Bind<IShoppingService>().To<ShoppingService>().InRequestScope(); kernel.Bind<IPurchaseService>().To<PurchaseService>().InRequestScope(); kernel.Bind<IReviewService>().To<ReviewService>().InRequestScope(); kernel.Bind<IUserService>().To<UserService>().InRequestScope(); kernel.Bind<IAdminService>().To<AdminService>().InRequestScope(); } } }
'use client'; import { useTheme } from '@/components/ThemedHTMLClient'; import { Box } from '../../styled-system/jsx'; import { css, cx } from '../../styled-system/css'; import { icon } from '../../styled-system/recipes'; export const ThemeSwitcher = () => { const { theme, setTheme } = useTheme(); const nextTheme = theme === 'dark' ? 'light' : 'dark'; const iconText = `Switch to ${nextTheme} mode`; return ( <button onClick={() => setTheme(nextTheme)} aria-label={iconText} className={switchStyle} > <Box className={iconStyle} /> </button> ); }; const switchStyle = css({ px: '2', py: '1', textStyle: 'xl', fontWeight: 'semibold', letterSpacing: 'tight', rounded: 'md', _hover: { bg: 'bg.emphasized.hover', }, }); const iconStyle = cx( icon({ name: { base: 'game-icons:sunrise', _dark: 'game-icons:moon', }, }), css({ fontSize: 'xl' }) );
<script setup lang="ts"> import BlSidebar from './sidebar/sidebar.vue' import LayoutHeader from './bl-header.vue' import LayoutFooter from './bl-footer.vue' import BLContent from './bl-content.vue' import { useSidebar } from '../composables/sidebar' import { nextTick, onMounted, provide } from 'vue' import { rootKey } from '../tookens/index' const { hasSidebar } = useSidebar() provide(rootKey, { hasSidebar }) onMounted(() => { nextTick(() => { // rootCls?.add('dark') }) }) </script> <template> <div> <LayoutHeader /> <div class="homepage" :class="{ 'no-bg': !hasSidebar }"> <div class="homepage-body" :class="{ 'no-sider': !hasSidebar, 'bg-container': !hasSidebar }"> <BlSidebar :hasSidebar="hasSidebar" /> <BLContent :hasSidebar="hasSidebar"> <template #content-top> <slot name="content-top" /> </template> <template #content-bottom> <slot name="content-bottom" /> </template> <template #aside-top> <slot name="aside-top" /> </template> <template #aside-mid> <slot name="aside-mid" /> </template> <template #aside-bottom> <slot name="aside-bottom" /> </template> </BLContent> </div> </div> <LayoutFooter /> </div> </template> <style lang="scss" scoped> .bg-container { position: relative; } .homepage-bg { position: absolute; } .homepage.no-bg { background: url('/bl-bg.svg'); background-position: 50% 0; background-repeat: no-repeat; background-color: white; padding-bottom: 150px; } .homepage-body { width: 100%; margin-left: auto; margin-right: auto; display: grid; justify-content: center; grid-template-columns: 240px minmax(0, 1fr); align-items: flex-start; position: relative; gap: 2.5rem; max-width: 100vw; } .dark { .homepage { background: none; } } .no-sider { display: flex; } @media (min-width: 1400px) { .homepage-body { max-width: 1400px; } } </style>
// // Service.hh // #ifndef Service_hh #define Service_hh #include "../String/String.hh" #include "Query.hh" class Query::Service : private _Query_ { public: // Static methods // Get map of Ports->Services static const Query::Ports &Ports(); // Get map of Names->Service static const Query::Services &Services(); // Get port from name. // Returns BSD::NoPort if not found static BSD::Port Find(const String &name); public: // Methods Service(); inline operator const String &() const; inline const String &Name() const; inline BSD::Port Port() const; inline bool TCP() const; inline bool UDP() const; // Datagram Delivery Protocol inline bool DDP() const; inline bool Alias() const; private: // Methods Service(const String &name, BSD::Port port, bool alias); private: // Variables String name; BSD::Port port; bool alias; // According to IANA, all ports are designated for both TCP and UDP. However... bool tcp; bool udp; bool ddp;// Datagram Delivery Protocol private: // Static methods static void Add(Query::Services &services, const struct servent &entry); }; // Service inline Query::Service::operator const String &() const { return name; } // Service::operator String() inline const String &Query::Service::Name() const { return name; } // Service::Name() inline BSD::Port Query::Service::Port() const { return port; } // Service::Port() inline bool Query::Service::TCP() const { return tcp; } // Service::TCP() inline bool Query::Service::UDP() const { return udp; } // Service::UDP() inline bool Query::Service::DDP() const { return ddp; } // Service::DDP() inline bool Query::Service::Alias() const { return alias; } // Service::Alias() #endif // Service_hh
#include <stdint.h> #include <stdio.h> #include "../../../include/helper.h" #include "../../../include/vga.h" #include "../../../include/interrupts.h" extern void irq0(); extern void irq1(); extern void irq2(); extern void irq3(); extern void irq4(); extern void irq5(); extern void irq6(); extern void irq7(); extern void irq8(); extern void irq9(); extern void irq10(); extern void irq11(); extern void irq12(); extern void irq13(); extern void irq14(); extern void irq15(); extern void isr0(); extern void isr1(); extern void isr2(); extern void isr3(); extern void isr4(); extern void isr5(); extern void isr6(); extern void isr7(); extern void isr8(); extern void isr9(); extern void isr10(); extern void isr11(); extern void isr12(); extern void isr13(); extern void isr14(); extern void isr15(); extern void isr16(); extern void isr17(); extern void isr18(); extern void isr19(); extern void isr20(); extern void isr21(); extern void isr22(); extern void isr23(); extern void isr24(); extern void isr25(); extern void isr26(); extern void isr27(); extern void isr28(); extern void isr29(); extern void isr30(); extern void isr31(); #define low_16(address) (uint16_t) \ ((address) & 0xFFFF) #define high_16(address) (uint16_t) \ (((address) >> 16) & 0xFFFF) typedef struct { uint16_t limit; uint16_t base; } __attribute__((packed)) idt_register_t; typedef struct { uint16_t low_offset; uint16_t selector; uint8_t always0; uint8_t flags; uint16_t high_offset; } __attribute__((packed)) idt_gate_t; idt_gate_t idt[256]; idt_register_t idt_reg; static void __load_idt() { idt_reg.base = (uint16_t) &idt; const int idt_entries = 256; const int size_idt_gate = sizeof(idt_gate_t); const int size_all_gates = idt_entries * size_idt_gate; idt_reg.limit = size_all_gates - 1; asm volatile("lidt (%0)" : : "m" (idt_reg)); } static void __set_idt_gate(int n, uint32_t handler) { idt[n].low_offset = low_16(handler); ///kernel address idt[n].selector = 0x08; ///some bits that always need to ///be set to 0 for interrupt gates idt[n].always0 = 0; ///This flags is a concatenation os multiples fields of gate. /// [1] 1 bit to indicating whether the gate is active. Will be set to 1 /// [00] 2 bits the descriptor privilege level indicates what privilege /// is required to invoke the handler. Will be set to 00 /// [0] the bit that always 0 /// [1] 1 bit indicating whether the code segment is 32bit. Will be set /// to 1 /// [110] 3 bits indicating the gate type. Will e set to 110 as we are /// defining an interrupt gate. /// ///and 10001110 = 0x8e idt[n].flags = 0x8e; idt[n].high_offset = high_16(handler); } static char *exception_messages[] = { "Division by zero", "Debug", "NMI", "Breakpoint (which benefits from the shorter 0xCC encoding of INT 3)", "Overflow", "Bound Range Exceeded", "Invalid Opcode", "Coprocessor not available", "Double Fault", "Coprocessor Segment Overrun (386 or earlier only)", "Invalid Task State Segment", "Segment not present", "Stack Segment Fault", "General Protection Fault", "Page Fault", "Reserved", "Floating Point Exception", "Alignment Check", "Machine Check", "SIMD Floating-Point Exception", "Virtualization Exception", "Control Protection Exception (only available with CET)", }; static void __load_isr(void) { __set_idt_gate(0, (uint32_t) isr0); __set_idt_gate(1, (uint32_t) isr1); __set_idt_gate(2, (uint32_t) isr2); __set_idt_gate(3, (uint32_t) isr3); __set_idt_gate(4, (uint32_t) isr4); __set_idt_gate(5, (uint32_t) isr5); __set_idt_gate(6, (uint32_t) isr6); __set_idt_gate(7, (uint32_t) isr7); __set_idt_gate(8, (uint32_t) isr8); __set_idt_gate(9, (uint32_t) isr9); __set_idt_gate(10, (uint32_t) isr10); __set_idt_gate(11, (uint32_t) isr11); __set_idt_gate(12, (uint32_t) isr12); __set_idt_gate(13, (uint32_t) isr13); __set_idt_gate(14, (uint32_t) isr14); __set_idt_gate(15, (uint32_t) isr15); __set_idt_gate(16, (uint32_t) isr16); __set_idt_gate(17, (uint32_t) isr17); __set_idt_gate(18, (uint32_t) isr18); __set_idt_gate(19, (uint32_t) isr19); __set_idt_gate(20, (uint32_t) isr20); __set_idt_gate(21, (uint32_t) isr21); __set_idt_gate(22, (uint32_t) isr22); __set_idt_gate(23, (uint32_t) isr23); __set_idt_gate(24, (uint32_t) isr24); __set_idt_gate(25, (uint32_t) isr25); __set_idt_gate(26, (uint32_t) isr26); __set_idt_gate(27, (uint32_t) isr27); __set_idt_gate(28, (uint32_t) isr28); __set_idt_gate(29, (uint32_t) isr29); __set_idt_gate(30, (uint32_t) isr30); __set_idt_gate(31, (uint32_t) isr31); } static void __load_irq(void) { __set_idt_gate(32, (uint32_t) irq0); __set_idt_gate(33, (uint32_t) irq1); ///keyboard ps-2 __set_idt_gate(34, (uint32_t) irq2); __set_idt_gate(35, (uint32_t) irq3); __set_idt_gate(36, (uint32_t) irq4); __set_idt_gate(37, (uint32_t) irq5); __set_idt_gate(38, (uint32_t) irq6); __set_idt_gate(39, (uint32_t) irq7); __set_idt_gate(40, (uint32_t) irq8); __set_idt_gate(41, (uint32_t) irq9); __set_idt_gate(42, (uint32_t) irq10); __set_idt_gate(43, (uint32_t) irq11); __set_idt_gate(44, (uint32_t) irq12); __set_idt_gate(45, (uint32_t) irq13); __set_idt_gate(46, (uint32_t) irq14); __set_idt_gate(47, (uint32_t) irq15); } static void __remap_the_pic(void) { /// ICW1 /// the 0x11 is a initialize command. /// We must send this 0x11 for the both PICs. /// After command initialize (0x11) the PICs /// then wait for the following three inputs /// on the data ports (0x21 for the first PIC /// and 0xA1 for the secondary PIC) port_byte_out(0x20, 0x11); port_byte_out(0xA0, 0x11); /// ICW2 /// first command will be set to 0x20 (32) for the /// primary PIC and 0x28 (40) for the secondary PIC port_byte_out(0x21, 0x20); port_byte_out(0xA1, 0x28); /// ICW3 /// This is a wiring between PICs. /// We will tell the primary PIC to accept /// IRQs from the secondary PIC on IRQ1 (0x04) /// /// The secondary PIC will be marked as secondary /// by setting 0x02 port_byte_out(0x21, 0x04); port_byte_out(0xA1, 0x02); /// ICW4 /// we set 0x01 in order to enable the 8086 mode port_byte_out(0x21, 0x01); port_byte_out(0xA1, 0x01); /// OCW1 /// We finally send the first operation command word 0x00 /// to enable all IRQs. port_byte_out(0x21, 0x0); port_byte_out(0xA1, 0x0); } void __enable_external_interrupts(void) { asm volatile("sti"); } void isr_install() { __remap_the_pic(); __load_isr(); __load_irq(); __load_idt(); __enable_external_interrupts(); } typedef struct { ///data segment selector uint32_t ds; ///general purpose registers pushed by pusha uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax; ///pushed by isr/irq procedure uint32_t int_no, err_code; ///pushed by CPU automatically uint32_t eip, cs, eflags, useresp, ss; } __attribute__((packed)) registers_t; typedef void (*isr_t)(registers_t *); isr_t interrupt_handlers[256]; void irq_handler(registers_t *r) { if(interrupt_handlers[r->int_no] != 0) { isr_t handler = interrupt_handlers[r->int_no]; handler(r); } ///end of interrupts ///the primary is a 0-7 ///and the secondary 8-15 /// ///this is required for the PIC to know that ///the interrupt is handled and it can send ///further interrupts. /// if(r->int_no >= 40) { port_byte_out(0xA0, 0x20); //secondary EOI } port_byte_out(0x20, 0x20); // primary EOI } void register_interrupt_handler(uint8_t n, void (*handler)(void *)) { interrupt_handlers[n] = (isr_t) handler; } void isr_handler(registers_t *r) { print_string("received interrupt: "); char s[3]; print_string(s); print_string(exception_messages[r->int_no]); }
--Pull these extensions and provide how many of each website type exist in the accounts table select distinct(RIGHT(website,3)) from accounts ; --Use the accounts table to pull the first letter of each company name to see the distribution of company names that begin with each letter select RIGHT(name,1), count(*) from accounts group by 1 order by 2 desc; --Use the accounts table and a CASE statement to create two groups: one group of company names that start with a number --and a second group of those company names that start with a letter. What proportion of company names start with a letter? SELECT SUM(num) nums, SUM(letter) letters FROM (SELECT name, CASE WHEN LEFT(UPPER(name), 1) IN ('0','1','2','3','4','5','6','7','8','9') THEN 1 ELSE 0 END AS num, CASE WHEN LEFT(UPPER(name), 1) IN ('0','1','2','3','4','5','6','7','8','9') THEN 0 ELSE 1 END AS letter FROM accounts) t1; --Consider vowels as a, e, i, o, and u. What proportion of company names start with a vowel, and what percent start with anything else? WITH T1 AS (SELECT name, CASE WHEN LEFT(UPPER(name), 1) IN ('A','E','I','O','U') THEN 1 ELSE 0 END AS vowel, CASE WHEN LEFT(UPPER(name), 1) IN ('A','E','I','O','U') THEN 0 ELSE 1 END AS conjunction FROM accounts) select sum(vowel) as V ,sum(conjunction) as C from t1; --Use the accounts table to create first and last name columns that hold the first and last names for the primary_poc. SELECT LEFT(primary_poc,STRPOS(primary_poc,' ')-1) AS FN, RIGHT(primary_poc,LENGTH(primary_poc) - STRPOS(primary_poc,' ')) FROM accounts; --Now see if you can do the same thing for every rep name in the sales_reps table. Again provide first and last name columns. SELECT LEFT(name,STRPOS(name,' ')-1) AS FN, RIGHT(name,LENGTH(name) - STRPOS(name,' ')) AS LN FROM sales_reps; --We would also like to create an initial password, which they will change after their first log in. The first password will be the first letter of the primary_poc's first name (lowercase), then the last letter of their first name (lowercase), the first letter of their last name (lowercase), the last letter of their last name (lowercase), the number of letters in their first name, --the number of letters in their last name, and then the name of the company they are working with, all capitalized with no spaces. WITH t1 AS ( SELECT LEFT(primary_poc, STRPOS(primary_poc, ' ') -1 ) first_name, RIGHT(primary_poc, LENGTH(primary_poc) - STRPOS(primary_poc, ' ')) last_name, name FROM accounts) SELECT first_name, last_name, CONCAT(first_name, '.', last_name, '@', name, '.com'), LEFT(LOWER(first_name), 1) || RIGHT(LOWER(first_name), 1) || LEFT(LOWER(last_name), 1) || RIGHT(LOWER(last_name), 1) || LENGTH(first_name) || LENGTH(last_name) || REPLACE(UPPER(name), ' ', '') FROM t1; -- change date format to std sql format SELECT (SUBSTR(date,7,4) || '-' || SUBSTR(date,1,2) || '-' || SUBSTR(date,4,2))::date FROM sf_crime_data; -- window & running total SELECT standard_amt_usd, SUM(standard_amt_usd) OVER ( ORDER BY occurred_at) as running_total FROM orders; -- quartile function SELECT account_id,occurred_at,standard_qty, NTILE(4) OVER (PARTITION BY standard_qty ORDER BY account_id) AS Quartile FROM orders;
import 'package:flutter/material.dart'; import 'package:pmsn2023/widgets/counter.dart'; import 'package:pmsn2023/widgets/image_carousel_widget.dart'; class FruitAppScreen extends StatefulWidget { const FruitAppScreen({super.key}); @override State<FruitAppScreen> createState() => _FruitAppScreenState(); } class _FruitAppScreenState extends State<FruitAppScreen> { bool _isFavorited = true; void _toggleFavorite() { setState(() {_isFavorited = !_isFavorited;}); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( elevation: 0, backgroundColor: Colors.white, leading: Row( children: <Widget>[ const SizedBox(width: 5.0), IconButton( color: const Color.fromARGB(255, 17, 117, 51), icon: const Icon(Icons.arrow_back), onPressed: () => Navigator.pushNamed(context, '/dash'), ), ], ), actions: <Widget>[ IconButton( icon: const Icon( Icons.shopping_cart, color: Color.fromARGB(255, 17, 117, 51), ), onPressed: () {}, ), const SizedBox(width: 20.0), ], ), backgroundColor: Colors.white, body: ListView( children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ const CarouselWithIndicatorDemo(), const SizedBox(height: 50.0), Container( decoration: const BoxDecoration( color: Color.fromARGB(255, 17, 117, 51), borderRadius: BorderRadius.only( topLeft: Radius.circular(50.0), topRight: Radius.circular(50.0), ) ), height: 600, width: 500, child: Align( alignment: Alignment.bottomLeft, child: Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const SizedBox(height: 20.0), const Text( 'Flipper Zero', style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold) ), const SizedBox(height: 10.0), const Text('\$170 cada uno'), const SizedBox(height: 20.0), const CounterDesign(), const SizedBox(height: 30.0), const Text( 'Descripción del Producto', style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold) ), const SizedBox(height: 15.0), const Text( 'Flipper Zero es una multiherramienta portátil para pentesters y geeks en un cuerpo similar a un juguete.' 'Le encanta piratear material digital, como protocolos de radio, NFC, infrarrojo, hardware y más.' 'Es totalmente de código abierto y personalizable, por lo que puedes ampliarlo como quieras.', style: TextStyle(letterSpacing: 2.0, fontSize: 15.0), ), const SizedBox(height: 30.0), Row( children: <Widget>[ ButtonTheme( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), side: const BorderSide(color: Colors.white), ), height: 70.0, minWidth: 300, child: ElevatedButton( onPressed: _toggleFavorite, style: ElevatedButton.styleFrom( backgroundColor: const Color.fromARGB(255, 17, 117, 51), elevation: 0, ), child: Icon( _isFavorited ? Icons.favorite_border : Icons.favorite, color: Colors.white, ), ) ), const SizedBox(width: 20.0), ButtonTheme( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)), height: 70.0, minWidth: 300.0, child: ElevatedButton( onPressed: () {}, style: ElevatedButton.styleFrom( backgroundColor: Colors.white, elevation: 0, ), child: const Text( 'Add to cart', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black), ), ), ) ], ), ], ), ), ), ), ], ), ], ), ), ); } }
import torch import random from torchvision import transforms class flip: def __init__(self, p=0.5): self.p=p def __call__(self, x): # s h w use_flip = random.random() < self.p if use_flip: p = random.random() if p < 0.33: x = torch.flip(x, dims=[2]) elif p < 0.66: x = torch.flip(x, dims=[1]) else: x = torch.flip(x, dims=[1, 2]) return x class rotate: def __init__(self, p=0.5): self.p=p def __call__(self, x): # s h w use_rotate = random.random() < self.p if use_rotate: rotation_repeat = torch.randint(1, 4, (1,)).item() x = torch.rot90(x, rotation_repeat, (1, 2)) return x class add_noise: def __init__(self, p=0.5, std=0.01): self.p=p self.std=std def __call__(self, x): # b c s h w if random.random() < self.p: x = x + torch.randn_like(x)*self.std return x class cutout: def __init__(self, p=0.2, pixel_ratio=0.3, spectral_ratio=0.1): self.p=p self.pixel_r=pixel_ratio self.spectral_r=spectral_ratio def __call__(self, x): use_cutout = random.random() < self.p if use_cutout: s, h, w = x.size() spe_l = int(s*self.spectral_r) for i in range(h): for j in range(w): if random.random() < self.pixel_r: s_s = random.randint(0, s-1-spe_l) s_e = s_s + spe_l x[s_s:s_e, i, j] = 0 return x class rcutout: def __init__(self, p=0.2, pixel_ratio=0.3, spectral_ratio=0.1): self.p=p self.pixel_r=pixel_ratio self.spectral_r=spectral_ratio def __call__(self, x): use_cutout = random.random() < self.p if use_cutout: s, h, w = x.size() ins_pixel_r = random.uniform(0.01, self.pixel_r) ins_spectral_r = random.uniform(0.01, self.spectral_r) spe_l = int(s*ins_spectral_r) for i in range(h): for j in range(w): if random.random() < ins_pixel_r: s_s = random.randint(0, s-1-spe_l) s_e = s_s + spe_l x[s_s:s_e, i, j] = 0 return x def transforms_builder(args): t=[] if args.flip is not None: t.append(flip(args.flip)) if args.rotate is not None: t.append(rotate(args.rotate)) if args.add_noise is not None: t.append(add_noise(args.add_noise[0], args.add_noise[1])) if args.cutout is not None: t.append(cutout(args.cutout[0], args.cutout[1], args.cutout[2])) if args.rcutout is not None: t.append(rcutout(args.rcutout[0], args.rcutout[1], args.rcutout[2])) return transforms.Compose(t)
<?php namespace Database\Factories; use App\Models\CarBody; use App\Models\CarCarcase; use App\Models\CarClass; use App\Models\CarEngine; use App\Models\Image; use Illuminate\Database\Eloquent\Factories\Factory; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Car> */ class CarFactory extends Factory { /** * Define the model's default state. * * @return array<string, mixed> */ public function definition(): array { return [ 'name' => $this->faker->realText(10), 'body' => $this->faker->realText(50), 'price' => $price = $this->faker->numberBetween(500000, 50000000), 'old_price' => $this->faker->optional()->numberBetween($price*1.1, $price*1.2), 'salon' => $this->faker->optional()->realText(), 'kpp' => $this->faker->optional()->realText(), 'year' => $this->faker->optional()->year(), 'color' => $this->faker->optional()->word(), 'is_new' => $this->faker->boolean(), 'engine_id' => CarEngine::factory(), 'carcase_id' => CarCarcase::factory(), 'class_id' => CarClass::factory(), 'image_id' => Image::factory(), ]; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="./css/bootstrap.css" /> </head> <body> <div class="container"> <h1>display</h1> <h2>display: inline</h2> <div class="d-inline textwhite p-2 bg-primary">ITEM</div> <div class="d-inline textwhite p-2 bg-info">ITEM</div> <div class="d-inline textwhite p-2 bg-success">ITEM</div> <div class="d-inline textwhite p-2 bg-warning">ITEM</div> <div class="d-inline textwhite p-2 bg-danger">ITEM</div> <hr /> <h2>display: flex</h2> <div class="d-flex"> <div class="textwhite p-2 bg-primary">ITEM</div> <div class="textwhite p-2 bg-info">ITEM</div> <div class="textwhite p-2 bg-success">ITEM</div> <div class="textwhite p-2 bg-warning">ITEM</div> <div class="textwhite p-2 bg-danger">ITEM</div> </div> <hr /> <h2>隱藏元素</h2> <div class="d-lg-none bg-primary text-white">lg 尺寸以上消失</div> <div class="d-none d-lg-block bg-success text-white">lg尺寸以上會出現</div> <hr /> <h2>運用在列印的 Display</h2> <div class="d-print-none bg-danger text-white">Screen Only (Hide on print only)</div> <div class="d-none d-print-block bg-success text-white">Print Only (Hide on screen only)</div> <div class="d-none d-lg-block d-print-block bg-primary text-white"> Hide up to large on screen, but always show on print </div> </div> <script src="./js/bootstrap.bundle.min.js"></script> </body> </html>
function [y,x_,tx] = simBackwardEuler(A,B,C,D,E,u,x,Ts,Ts_sample,isDescriptor) % simBackwardEuler - Integrates sss model using backward (implicit) Euler % % Syntax: % y = simBackwardEuler(A,B,C,D,E,u,x,Ts,Ts_sample,isDescriptor) % [y,x_] = simBackwardEuler(A,B,C,D,E,u,x,Ts,Ts_sample,isDescriptor) % [y,x_,tx] = simBackwardEuler(A,B,C,D,E,u,x,Ts,Ts_sample,isDescriptor) % % Description: % Integrates sss model using backward (implicit) Euler % % Input Arguments: % -A,B,C,D,E: state-space matrices % -u: input vector/matrix with dimension Nsample x Ninput % -x: initial state vector for time integration % -Ts: sampling time % -Ts_sample: sampling time for matrix of state-vectors % -isDescriptor: isDescriptor-boolean % % Output Arguments: % -y: output vector % -x_: matrix of state vectors % -tx: time vector for X % % See Also: % sim, simForwardEuler, simRK4 % % References: % * *[1] Gear (1971)*, Numerical Initial Value Problems in % Ordinary Differential Equations. % * *[2] Shampine (1994)*, Numerical Solution of Ordinary Differential Equations, % Chapman & Hall, New York. % * *[3] Shampine and Gordon (1975)*, Computer Solution of Ordinary Differential % Equations: the Initial Value Problem, W. H. Freeman, San Francisco. % %------------------------------------------------------------------ % This file is part of <a href="matlab:docsearch sss">sss</a>, a Sparse State-Space and System Analysis % Toolbox developed at the Chair of Automatic Control in collaboration % with the Chair of Thermofluid Dynamics, Technische Universitaet Muenchen. % For updates and further information please visit <a href="https://www.rt.mw.tum.de/">www.rt.mw.tum.de</a> % For any suggestions, submission and/or bug reports, mail us at % -> <a href="mailto:[email protected]">[email protected]</a> <- % % More Toolbox Info by searching <a href="matlab:docsearch sssMOR">sssMOR</a> in the Matlab Documentation % %------------------------------------------------------------------ % Authors: Stefan Jaensch, Maria Cruz Varona, Alessandro Castagnotto % Email: <a href="mailto:[email protected]">[email protected]</a> % Website: <a href="https://www.rt.mw.tum.de/">www.rt.mw.tum.de</a> % Work Adress: Technische Universitaet Muenchen % Last Change: 04 Aug 2017 % Copyright (c) 2015-2017 Chair of Automatic Control, TU Muenchen %------------------------------------------------------------------ %% Initialize variables using common function for all simulation methods % Note: using one common simulation function having the methods as nested % functions would be much better. Due to historical reasons, the % simulation functions not have their present form. Later releases may % include some significant restructuring. ETsA = E-Ts*A; TsB = Ts*B; argin = {A,B,C,D,ETsA,u,x,Ts,Ts_sample,true}; %isDescriptor = true to always compute LU [y,x_,m,k,index,L,U,p] = simInit(argin{:},nargin==1); %common function %% Run simulation for i = 2:size(u,1) g = E*x + TsB*u(i,:)'; x = U\(L\(g(p,:))); % Update vectors [y,x_,k,index] = simUpdate(y,x_,k,index,x,u,i,m,C,D); %common function end tx = (index-1)*Ts;
package org.example.data; import org.example.model.User; import java.util.ArrayList; import java.util.List; public class UserRepository { private static UserRepository instance = null; private List<User> users; private UserRepository() { users = new ArrayList<>(); } public static UserRepository getInstance() { if (instance == null) { instance = new UserRepository(); } return instance; } public void addUser(User user) { users.add(user); } public User getUserByUsername(String username) { for (User user : users) { if (user.getUsername().equals(username)) { return user; } } return null; } public List<User> getUsers() { return users; } }
package com.example.shortstories import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.ViewModelProvider import com.example.shortstories.databinding.FragmentSignUpBinding class SignUpFragment : Fragment() { lateinit var binding: FragmentSignUpBinding lateinit var viewModel: SignUpViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentSignUpBinding.inflate(layoutInflater) return binding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(requireActivity()).get(SignUpViewModel::class.java) binding.btnSignup.setOnClickListener { if (checkInfo()) { viewModel.registerUser( binding.firstName.text.toString(), binding.lastName.text.toString(), binding.email.text.toString(), binding.password.text.toString(), ) } } viewModel.accountCreated.observe(viewLifecycleOwner) { accountCreated -> parentFragmentManager.beginTransaction() .replace(R.id.fragment_container, HomeFragment()) .commit() } viewModel.toast.observe(viewLifecycleOwner) { Toast.makeText(requireContext(), it, Toast.LENGTH_SHORT).show() } } private fun checkInfo(): Boolean { if (binding.firstName.text.toString().trim().isEmpty()) { Toast.makeText(requireContext(), "Check your data", Toast.LENGTH_LONG).show() return false } else if (binding.firstName.text.toString().trim().isEmpty()) { Toast.makeText(requireContext(), "Check your data", Toast.LENGTH_LONG).show() return false } else if (binding.lastName.text.toString().trim().isEmpty()) { Toast.makeText(requireContext(), "Check your data", Toast.LENGTH_LONG).show() return false } else if (binding.email.text.toString().trim().isEmpty()) { Toast.makeText(requireContext(), "Check your data", Toast.LENGTH_LONG).show() return false } else if (binding.password.text.toString().trim().isEmpty()) { Toast.makeText(requireContext(), "Check your data", Toast.LENGTH_LONG).show() return false } else if (binding.password.text.toString() != binding.confirmPassword.text.toString()) { Toast.makeText(requireContext(), "Check your data", Toast.LENGTH_LONG).show() return false } else { return true } } }
<script setup> import StaticPageVue from "snippets/static-page.vue"; </script> # Rendering Basics Let's start by rendering a "non-interactive" page: ```ts $app([Basics], _ => { _.$css`color: red`; _.h1("Hello, Refina!"); _.$css`border: 1px solid yellow`; _.div(_ => { _.p("This is a paragraph."); _.p(_ => _.img("https://picsum.photos/200/300", "placeholder")); }); }); ``` **Result** <StaticPageVue /> Now let's explain the code above. ### Simple Components Some simple components like `h1` and `img` can be rendered by calling the corresponding component function. Parameters of the component functions are passed in a positional way, so you needn't specify the name of the parameters. ### Nested Components Most components have content, which is usually corresponding to the content of the HTML element. You can not only pass a string or a number as the content but also pass a view function. :::tip When using view functions as the content of a component, it is recommended to use the arrow function syntax. To get the best experience, you can use [Prettier](https://prettier.io/) to format your code with the `arrowParens` option set to `"avoid"`. > If you create your project with `npm create refina@latest`, Prettier is already configured for you. ::: :::tip The curly braces around the view function can be omitted if the view function has only one statement. This is because the return value of the view function will always be ignored. You can use `&&` to connect directives which always return `true` to the component function. For example, ```ts _.div(_ => _.$css`color: red` && _.p("This is a paragraph.")); ``` and ```ts _.div(_ => { _.$css`color: red`; _.p("This is a paragraph."); }); ``` are equivalent. ::: ### Add Classes and Styles {#add-classes-and-styles} You can use the `_.$cls` directive to add classes to the next component, and `_.$css` to add styles. The styles and classes will be applied to the [primary element](./component.md#primary-element) of the following component. :::tip `_.$css` and `_.$cls` can be called multiple times in a row, and the styles and classes will be merged. ::: :::tip `_.$css` and `_.$cls` can be used as a template tag or an ordinary function, so the following two ways are equivalent: ```ts const color = "red"; _.$css`color: ${color}`; _.$css("color: " + color); ``` It is recommended to omit the semicolon at the end of the CSS text, which will be automatically added. :::
# Elaborado por: Fabian Vergel Ojeda # Colaborador: # Fecha elaboracion: 18/03/2022 # Fecha ultima modificacion: 18/03/2022 #Initial configuration rm(list = ls()) #limpiar entorno pacman::p_load(tidyverse,haven,readxl,WriteXLS) #cargar paquetes a=2 b='2' vector_c = c("hola",'a') # podemos usar ' o " para caracteres is.character(vector_c) is.character('hola') #Verifica si es un caracter char_vec = c("a","b","c","r","d","a","e","c","a","r","r") vector2 = c(1,2,"c") #ojo ?Ojo! Los elementos no son homogeneos vector3 = c(1,2) is.numeric(vector2) is.numeric(vector3) is.numeric(char_vec) as.numeric(c(1,2,'c')) #Como la c no es un numero y no la puede convertir en un numero, entonces la convierte en un "na" as.numeric(c(1,2,'3')) #Convierte el caracter '3' en un numero a=c(1,2,'3') c=as.numeric(a) char_vec[5] #ya tengo creado el vector y solicito que solo quiero la posicion del elemento 5 del conjunto de elementos char_vec[1:5] #asi solicito que quiero desde el elemento "1" hasta el "5" char_vec = char_vec[-5] #Asi le digo que sobreescriba sobre el vector original y que me elimine el elemento "5" (" (tengo que copiar en el siguiente rengl?n nuevamente el vector "char_vec" para que se ejecute bien la funci?n)) char_vec #Matrices matriz_n = matrix(rnorm(n = 25,mean = 100 ,sd = 10) , nrow = 5, ncol = 5) matriz_n[1,] #cuando digito la funcion en la consola puedo ver todo el cuadro de informacion matriz_n[1,2] #filas y columnas #Dataframes 1:10 seq(1,15,3) nota_numerica = seq(0,10,2) nota_numerica nota_alfabetica = c("a","b","b","a","c","b") nota_alfabetica dfm = data.frame(nota_numerica,nota_alfabetica) # Creamos el dataframe # elementos de un dataframe dfm dfm[5,2] dfm[,1] Lista_1=list() Lista_1[[1]]=dfm #tengo un elemento con una lista, dataframe Lista_1[[2]]= matriz_n #tengos dos elementos, el segundo es una matriz de 5x5 Lista_1[[1]] #De esta manera solicito el elemento [[1]] de la lista y puedo hacer cambios. Lista_1[[1]][,1] #De esta manera le digo que me muestre solo la columna 1 de ese dataframe Lista_1[[1]][1,] #De esta manera le digo que me muestre solo la fila 1 de ese dataframe #Importar base de datos
export function mediaFields() { return [ { type: "string", name: "title", label: "Titre", }, { type: "string", name: "description", label: "Description", ui: { component: "textarea", }, }, { type: "image", name: "bg_image", label: "Image de Background", }, { type: "object", name: "presse", label: "Presse", fields: [ { type: "boolean", name: "enable", label: "Activer", }, { type: "string", name: "header", label: "Titre", }, { type: "object", name: "cards", label: "Article de Presse", list: true, ui: { // This allows the customization of the list item UI // Data can be accessed by item?.<Name of field> itemProps: (item) => { return { label: `${item?.title} `} }, }, fields: [ { type: "datetime", name: "date", label: "Date", }, { type: "string", name: "title", label: "Titre", }, { type: "string", name: "class", label: "Type", options: [{ value: "interview", label: "Interview" }, { value: "journal", label: "Journal" }] }, { type: "string", name: "link", label: "Lien de L'article", }, { type: "image", name: "image", label: "Image", }, ], }, ], }, ]; }
library(tidyverse) library(dplyr) library("ggplot2") library(matrixStats) rg = read_csv("data/moistureVStime.csv") names(rg) # Graphs the soil moisture curves provided into a file, named after the treatments selected+ to plot. # Only plots the values for days between startDate and endDate. # @parameter ... : a variable number of strings Should be the name of a specific soil moisture sensor, # for example AO (Arborist Chips Outflow) or CI (Control Inflow) # @parameter startDate: a string that contains the earliest date you want to plot from. Must be of the format # 'YYYY-MM-DD'. Default value is 2020-02-01 (Feburary 1st, 2020) # @parameter endDate: a string that contains the latest day you want to plot to. Must be of the form # 'YYYY-MM-DD'. Default value is 2020-11-01 (November 1st, 2020) # @return: None. Just writes to a file. graphRGMoisture <- function(..., startDate="2020-02-01", endDate="2020-11-01") { treatmentNames <- list(...) startDate <- as.Date(startDate) endDate <- as.Date(endDate) summaryRG <- rg %>% mutate(X1 = NULL, Source.Name = NULL, 'Line#' = NULL, "m^3/m^3, Soil Moisture Stn" = NULL) %>% mutate(Date = as.Date(Date, format="%m/%d/%y %H:%M")) %>% rename_all(funs(str_replace_all(., " ", "_"))) %>% #Renaming columns rename_all(funs(str_replace_all(.,"-", "_"))) %>% rename_all(funs(str_replace_all(., "(_\\(m\\^3/m\\^3\\))", ""))) %>% group_by(Date) %>% summarise_if(is.numeric, funs(mean, sd)) %>%#Grouping data by day, taking MEAN instead of MEDIAN filter(Date > startDate) %>% filter(Date < endDate) #Removing rows outside our targeted date range summaryRG[summaryRG < 0] <- NA #Removing negative soil moisture values ids <- c("AI", "AO", "CI", "CO", "MI","MO", "NI", "NO") for (id in ids) { #Average soil moistures of the 4 replications replicates <- c() #The four RGs with the same treatment replicatesSD <- c() for (col_name in names(summaryRG)) { if (grepl(id, col_name, fixed=TRUE)) { if (grepl("sd", col_name, fixed=TRUE)) { replicatesSD <- c(replicatesSD, col_name) } else { replicates <- c(replicates, col_name) } } } avgMoisture <- rowMeans(summaryRG[replicates]) sdMoisture <- getSD(summaryRG[replicatesSD]) summaryRG[paste(id, "_avg", sep="")] <- avgMoisture summaryRG[paste(id, "_sd" ,sep="")] <- sdMoisture } plot <- ggplot(data=summaryRG, aes(x=Date)) lines <- "" ribbons <- "" title <- "" colors <-list() fileName <- "" for (treatmentName in treatmentNames) { lines <- paste(lines, "geom_line(aes(y=", sep="") ribbons <- paste(ribbons, "geom_ribbon(aes(ymin=", sep="") col_name <- paste(treatmentName, "_avg", sep="") col_sd_name <- paste(treatmentName, "_sd", sep="") lines <- paste(lines, col_name, ",color='", getFullName(treatmentName), "')) + ", sep="") ribbons <- paste(ribbons, col_name, "-", col_sd_name, ", ymax=", col_name, "+", col_sd_name, "), fill='", getColor(treatmentName, TRUE), "') + ", sep="") title <- paste(title, treatmentName, sep=" ") colors[[treatmentName]] <- getColor(treatmentName, FALSE) fileName <- paste(fileName, treatmentName, sep="_") } colors <- unlist(colors[order(names(colors))], use.names=FALSE) fileName <- substr(fileName, 2, nchar(fileName)) title <- paste(title, "Soil Moisture vs Time") lines <- substr(lines, 1, nchar(lines)-3) ribbons <- substr(ribbons, 1, nchar(ribbons)-3) lines <- paste("plot <- plot +", ribbons, "+", lines, sep="") eval(parse(text=lines)) legend_pls <- scale_color_manual(values=colors) labels <- labs(color="Treatments") xlabel <- xlab("Time") ylabel <- ylab("Soil Moisture") title <- ggtitle(title) plot <- plot + title + ylabel + xlabel + legend_pls + labels# + ribbon fileName <- paste("graphs/", fileName, ".png", sep="") png(file = fileName, height = 4, width = 6, units="in", res=1200) print(plot) dev.off() } # Given a treatment name, returns the color the treatment will be graphed with # @parameter treatemntName: a two character string denoting the treatment. Example: "AO", "NO", "AI" # @parameter ribbon: a boolean indicating whether we should return the color for the ribbon of a line. FALSE for the line itself # @return: a string containing the hex code of the color we will graph the treatment as. # @stop: if the inputted treatmentName is not a valid string, then we will throw an error. getColor <- function(treatmentName, ribbon) { treatmentNames <- list("AO", "NO", "MO", "CO", "AI", "NI", "CI", "MI") if (!(treatmentName %in% treatmentNames)){ stop("The treatment name provided is not valid") } else { io <- substring(treatmentName, 2, 2) type <- substring(treatmentName, 1, 1) if (io == "I") { if (ribbon) { color <- switch(type, "A" = "#a9fcc2", "N" = "#fcef99", "C"="#f9b6b6", "M" ="#a9fcfc") } else { color <- switch(type, "A" = "#58fc89", "N" = "#fcdc0a", "C"="#fc6464", "M" ="#02fcfc") } } else { if (ribbon) { color <- switch(type, "A" = "#648c70", "N" = "#c6bd83", "C"="#bc7a7a", "M" ="#71baba") } else { color <- switch(type, "A" = "#037024", "N" = "#a08b01", "C"="#990000", "M" ="#00b7b7") } } return(color) } } # Returns the correctly calculated SD of the given df. Not for general use, just a helper function # @parameter df: should be a df whose columns are the SDs of the 4 replicate treatments. These SDs are SD of each day. # @return : returns a vector with the SDs corretly aggregated. They are aggregated in the following way: # sdVector = sum(daily_sd ** 2)/ 4 over every day getSD <- function(df) { df <- df ** 2 sdAvg <- rowMeans(df) sdAvg <- sdAvg** .5 return(sdAvg) } # Given a treatment name, returns the full treatment name that will be displayed on the grah. # @parameter treatemntName: a two character string denoting the treatment. Example: "AO", "NO", "AI" # @return: a string containing the full name of the treatment. For example, "Arborist Chips Out", "Nuggets Out, "Arborist Chips In" # @stop: if the inputted treatmentName is not a valid string, then we will throw an error. getFullName <- function(treatmentName) { treatmentNames <- list("AO", "NO", "MO", "CO", "AI", "NI", "CI", "MI") if (!(treatmentName %in% treatmentNames)) { stop("The treatment name provided is not valid") } else { type <- substring(treatmentName, 1, 1) fullName <- switch(type, "A" = "Arborist Chips", "N" = "Nuggets", "C"="Control", "M" ="Medium Bark") io <- substring(treatmentName, 2, 2) end <- switch(io, "I" = "In", "O"="Out") return(paste(fullName, end)) } }
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>获得时间戳的四种方式</title> <script> // 1. 通过valueOf() getTime() (需要实例化日期对象) var date = new Date(); console.log(date.valueOf()); // 1628129559653 console.log(date.getTime()); // 1628129559653 // 2. 简单的写法(最常用) var date1 = +new Date(); // +new Date() 返回的就是总的毫秒数, 这种方法不用实例化日期对象 console.log(date1); // 1628129559653 // 3. H5新增 获得总的毫秒数 console.log(Date.now()); // 1628129559653 </script> </head> <body></body> </html>
/* eslint-disable import/no-unresolved */ import Pokemon from './entidades/pokemon.js'; import { mapearPokemon } from './mapeadores/pokemon.js'; import { conseguirInformacionPokemonId } from './pokeapi.js'; export function crearElementosTarjeta(pokemon: Pokemon): string { const ELEMENTOS: string = ` <div class="card-group tarjeta-completa"> <div class="card contenedor-tarjeta"> <div class="card contenedor-imagen"> <h5 class="card-title nombre-pokemon">${pokemon.nombre}</h5> <img src="${pokemon.imagen}" class="card-img-top"> </div> <div class="tarjeta-informacion"> <p class="card-text id">ID: <strong>${pokemon.id}</strong></p> <p class="card-text exp">EXP BASE: <strong>${pokemon.experiencia}</strong></p> <p class="card-text altura">ALTURA: <strong>${pokemon.altura}</strong></p> <p class="card-text peso">PESO: <strong>${pokemon.peso}</strong></p> <p class="card-text tipo">TIPO: <strong>${pokemon.tipo}</strong></p> </div> </div> </div> `; return ELEMENTOS; } export async function crearTarjetasPokemon( pokemonId: number, ordenFila: number, ordenTarjeta: number, ) { const RESPUESTA_JSON = await conseguirInformacionPokemonId(pokemonId); const TARJETA = document.querySelector( `.fila-${ordenFila} .tarjeta-${ordenTarjeta}`, ); const nuevoPokemon = mapearPokemon(RESPUESTA_JSON); const ELEMENTOS = crearElementosTarjeta(nuevoPokemon); if (TARJETA) { TARJETA.innerHTML = ELEMENTOS; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Storm Center</title> <meta name="description" content="Weather center allows people to report a storm or unusual weather event in his or her travel area"> <link rel="icon" href="images/icon3.png" type="image/gif"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@600&family=Roboto+Condensed&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/style.css"> <script src="js/windchill.js"></script> <script src="js/script.js"></script> </head> <body> <nav> <ul id="navigation"> <li><a class="ham" href="#">&#9776; Menu</a></li> <li><a href="https://krystianeotis.github.io/lesson9/index.html">Home</a></li> <li><a href="https://krystianeotis.github.io/lesson6/preston-6.html">Preston</a></li> <li><a href="#">Soda Springs</a></li> <li><a href="#">Fish Haven</a></li> <li><a class="active" href="https://krystianeotis.github.io/lesson8/stormcenter.html">Storm Center</a></li> <li><a href="https://krystianeotis.github.io/lesson7/gallery-7.html">Gallery</a></li> </ul> </nav> <main> <h1>Storm Center</h1> <form action="" method="get" id="container"> <section> <h2 class="subheading">Contact Information</h2> <div> <label for="name">Full Name: <input type="text" name="name" id="name" required></label> </div> <div> <label for="email">Email: <input type="email" name="email" placeholder="[email protected]" required> </label> </div> <label for="phone">Phone Number: <input type="tel" name="phone" placeholder="123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required> <label for="zip">Zip Code:</label> <input type="text" id="zip" name="zip" pattern="(\d{5}([\-]\d{4})?)" autocomplete="shipping postal-codep" required> </section> <section> <h2 class="subheading">Storm Details</h2> <div> <label>Storm Date: <input type="date" name="storm-date"></label></div> <label for="storm-type-choice">Storm Type:</label> <div> <input list="storm-type-list" id="storm-type-choice" name="storm-type-choice" /> <datalist id="storm-type-list"> <option value="Flash Flood"> <option value="Hail"> <option value="Hurricane"> <option value="Thunderstorm"> <option value="Tornado"> </datalist> </div> <div> <label class="flexly" for="rating">Storm Severity: &nbsp;&nbsp;&nbsp; <input type="range" id="rating" value="5" min="1" max="10" step="1" list="tickmarks" oninput="adjustRating(this.value)" onchange="adjustRating(this.value)"> <span id="ratingvalue">5</span> </label> <datalist id="tickmarks"> <option value="0"> <option value="1"> <option value="2"> <option value="3"> <option value="4"> <option value="5"> <option value="6"> <option value="7"> <option value="8"> <option value="9"> <option value="10"> </div> <div><label> <select name="browsers" id="selectbrowser" onchange="selectResponse()"> <option value="" disabled selected>Select a Region ...</option> <option value="Preston">Preston</option> <option value="Soda Springs">Soda Springs</option> <option value="Fish Haven">Fish Haven</option> </select></label></div> <div class="danger"> <p><b>Are You in Danger?</b><em>(Choose one)</em></p> <div> <input type="radio" id="radio1" name="time" value="8" checked> <label for="time1">Yes</label> </div> <div> <label><input type="radio" name="time" value="9">Maybe</label> </div> <div> <input type="radio" id="radio" name="time" value="10"> <label for="time3">No</label> </div> </div> </section> <section> <h3 class="subheading">Additional Information</h3> <div><label for="msg">Comments:</label> <textarea id="msg" name="user_message" placeholder="Optional"></textarea></div> <div class="button"><button type="submit">Submit Storm Report</button></div> </section> </form> </main> <footer> <div> <p class="copyright"> &copy; <span id="copyright-year"></span> | <a target="_blank" href="https://krystianeotis.github.io/index.html">Krystiane Otis</a> | Idaho | <a target="_blank" href="https://www.byui.edu/online">BYUI Online Learning</a> </p> <p class="dateupdate"> <span id="name-of-day"></span>, <span id="day"></span> <span id="month"></span> <span id="year"></span> </p> </div> </footer> <script src="js/stormcenter.js"></script> </body> </html>
%----------求解TSP问题----------% clc; clear all; close all; %给定城市坐标City_Coord,每一列代表一个城市 City_Coord = [0.4000, 0.2439, 0.1707, 0.2293, 0.5171, 0.8732, 0.6878, 0.8488, 0.6683, 0.6195; 0.4439, 0.1463, 0.2293, 0.7610, 0.9414, 0.6536, 0.5219, 0.3609, 0.2536, 0.2634]; %获取城市数量city_quantity n = size(City_Coord, 2); %City_Coord的列数即为城市数量 %计算城市之间的距离city_distance矩阵 %city_quantity行city_quantity列,第i行第j列代表城市i到城市j的距离 for i = 1:n for j = 1:n if i <= j City_Distance(i,j) = norm(City_Coord(:,i)-City_Coord(:,j)); City_Distance(j,i) = City_Distance(i,j); end end end %----------设置参数----------% m = 20; %种群个体数目 pc = 0.5; %交叉概率 pm = 0.1; %变异概率 n_loop_max = 100; %最大迭代次数 %----------一些矩阵说明----------% History_XBest = []; %存储每次循环中最优的路径,每一列为依次循环中的路径 History_X_FunctionBest = []; %存储每次循环中最优的路径长度,行向量 %----------主循环----------% for n_loop = 1:n_loop_max if n_loop == 1 X = X_init(n, m); %种群初始化 end %将当前种群最优路径存储进历史记录 X_Function = GetFunction(n, m, City_Distance, X); [min_X_Function, min_X_Function_position] = min(X_Function); History_XBest(:, n_loop) = X(:, min_X_Function_position); %存储当前最优路径 History_X_FunctionBest(n_loop) = min_X_Function; %存储当前最优路径的长度 fprintf('第%d次迭代\n',n_loop) fprintf('初始种群:') display(X) %洗牌(打乱顺序) shuffle = randperm(m); X = X(:,shuffle); fprintf('洗牌后:') display(X) %交叉 X = Cross(m, n, X, pc); fprintf('交叉后:') display(X) %变异 X = mutate(n, m, X, pm); fprintf('变异后:') display(X) %选择 X = Select(n, m, City_Distance, X); fprintf('选择后的新种群:') display(X) end %将最后一次迭代种群最优路径存储进历史记录 X_Function = GetFunction(n, m, City_Distance, X); [min_X_Function, min_X_Function_position] = min(X_Function); History_XBest(:, n_loop) = X(:, min_X_Function_position); %存储当前最优路径 History_X_FunctionBest(n_loop) = min_X_Function; %存储当前最优路径的长度 Xbest = X(:, min_X_Function_position); XFbest = min_X_Function; %**********************打印结果**********************% fprintf('二进制编码混合遗传算法:\n') fprintf('****************参数设置****************\n') fprintf('种群个体数目: %d\n', m) fprintf('交叉概率: %f\n', pc) fprintf('变异概率: %f\n', pm) fprintf('最大迭代次数: %d\n', n_loop_max) fprintf('****************迭代结果****************\n') fprintf('最优路径为: %d %d %d %d %d %d %d %d %d %d\n', Xbest) fprintf('最优路径的长度为: %f\n', XFbest) fprintf('****************************************\n') fprintf('end\n') %**********************************************************************% %****************************种群X初始化函数****************************% %**********************************************************************% function X = X_init(n, m) for i = 1:m %随机生成城市顺序 X(:, i) = randperm(n); end end %**********************************************************************% %*********************计算函数值(路径总长度)函数**********************% %**********************************************************************% function X_Function = GetFunction(n, m, City_Distance, X) for i = 1:m X_Function(i) = 0; for ii = 1:(n - 1) X_Function(i) = X_Function(i) + City_Distance(X(ii, i), X(ii+1, i)); end X_Function(i) = X_Function(i) + City_Distance(X(n, i), X(1, i)); end end %**********************************************************************% %****************************计算适应度函数****************************% %**********************************************************************% function X_Fitness = GetFitness(n, m, City_Distance, X) X_Function = GetFunction(n, m, City_Distance, X); for i = 1:m X_Fitness(i) = 1000 / X_Function(i); end end %**********************************************************************% %*********************相邻两个染色体两点交叉算法函数**********************% %**********************************************************************% function X = Cross(m, n, X, pc) if mod(m ,2) == 0 cross_num = m; %如果个体数为偶数,参与交叉个体数为全部个体数 else cross_num = m - 1; %如果个体数为奇数,参与交叉个体数为全部个体数-1,,最后一个不参与交叉 end for i = 1:2:cross_num hand_of_god = rand; %上帝之手随机做选择 if hand_of_god < pc %如果上帝手小于交叉概率pc,就进行交叉,否则不交叉 %A、B为相邻两条染色体,减少索引次数 A = X(:, i); B = X(:, i+1); %确定交叉范围 first = round(rand * (n - 1)) + 1; %交叉段起点 last = round(rand * (n - first)) + first; %交叉段结束点 %交叉 Cross_Temp = A(first:last); %Cross_Temp为临时存储 A(first:last) = B(first:last); B(first:last) = Cross_Temp; %检查并修正冲突 A = Reslove_Conflict(n, first, last, A, B); B = Reslove_Conflict(n, first, last, B, A); X(:, i) = A; X(:, i+1) = B; end end end %**********************************************************************% %***********************检查并修正冲突(交叉结束后)************************% %**********************************************************************% function A = Reslove_Conflict(n, first, last, A, B) %寻找A中重复出现的值(冲突) while 1 k = 0; for ii = 1:n for iii = ii+1 : n if A(ii) == A(iii) k = k+1; Save(1, k) = A(ii); Save(2, k) = ii; %Save为3行重复值的个数列的矩阵,第一行是重复值的数值,第二三行是重复值的位置 Save(3, k) = iii; end end end if k == 0 break end %替换A中的重复值 for ii = 1:k if Save(2, ii) >= first && Save(2, ii) <= last %找到在交叉范围内的重复值的位置,使其为position1 position1 = Save(2, ii); position2 = Save(3, ii); else position1 = Save(3, ii); position2 = Save(2, ii); end A(position2) = B(position1); end end end %**********************************************************************% %****************************变异函数****************************% %**********************************************************************% function X = mutate(n, m, X, pm) for i = 1:m hand_of_god = rand; %上帝之手随机做选择 if hand_of_god < pm %如果上帝手小于变异概率pc,就进行变异,否则不变异 Temp = X(:, i); %确定变异范围 first = round(rand * (n - 1)) + 1; %变异段起点 last = round(rand * (n - first)) + first; %变异段结束点 if last == first if last ~= n last = last + 1; else first ~= 1; first = first - 1; end end Temp(first:last) = flipud(Temp(first:last)); %逆序(变异) X(:, i) = Temp; end end end %**********************************************************************% %********************************选择函数********************************% %**********************************************************************% function X = Select(n, m, City_Distance, X) X_Fitness = GetFitness(n, m, City_Distance, X); fitness_sum = sum(X_Fitness); %适应度求和 Possibility = cumsum(X_Fitness / fitness_sum); %根据适应度计算,X_Fitness / fitness_Sum是被选择到的概率,Possibility为累积概率 for i = 1:(m - 1) %n_Population选n_Population-1,可重复选 hand_of_god = rand; %“上帝之手”转动轮盘,皮一下好开心 for ii = 1:m if hand_of_god < Possibility(ii) Temp_X(:,i) = X(:,ii); %Temp_X为临时存储选择到的值的矩阵 break end end end [~, max_x_position] = max(X_Fitness); %找出最大适应度索引 Temp_X(:, m) = X(:, max_x_position); X = Temp_X; %得到选择后的种群 end
# **************************************************************************** # @copyright 2023 e:fs TechHub GmbH ([email protected]) # # @license Apache v2.0 # # 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. # **************************************************************************** # -*- encoding: utf-8 -*- import argparse import base64 import json import logging import os import re from authentication import authentication from metadata import metadata from storage.azure import azure_storageaccess as azure from storage.s3 import s3_storageaccess as s3 from storage.storageaccess import StorageAccess ENV_STORAGE_TYPE = 'STORAGE_TYPE' def _get_argument(arg_value: str, arg_name: str, env_var_name: str): """ returns arg_value or value of fallback-environment-variable if arg_value is None, raises exception if fallback fails :param arg_value: the argument-value as passed by cli :param arg_name: the argument-name expected :param env_var_name: the name of the fallback-environment-variable :return: argument-value or value of fallback-environment-variable """ if not arg_value: if env_var_name not in os.environ: raise Exception( f'no keyname for azure event hub found - either provide via "--{arg_name}" or provide environment-variable "{env_var_name}"') else: env_var_value = os.environ[env_var_name] # check if environment-variable-value is stored in quotas regex = r"\"(.*)\"" if re.match(regex, env_var_value): for match in list(re.finditer(regex, env_var_value, re.MULTILINE)): return match.group(1) return env_var_value return arg_value def _extract_notification(origin): """ extracts decoded data-body of argo-sensor-payload :param origin: as provided by argo-sensor :return: actual payload of notification """ payload_json = json.loads(origin) data = payload_json['data'] # base64-encoded decoded_data = base64.b64decode(data).decode("utf-8").replace('\n', '') data_json = json.loads(decoded_data) body = data_json['body'] # base64-encoded decoded_body = base64.b64decode(body).decode("utf-8").replace('\n', '') return json.loads(decoded_body) def _get_storage_access() -> StorageAccess: storage_type = azure.TYPE if ENV_STORAGE_TYPE in os.environ: storage_type = os.getenv(ENV_STORAGE_TYPE) if storage_type == s3.TYPE: return s3.S3StorageAccess() if storage_type == azure.TYPE: return azure.AzureStorageAccess() raise ValueError(f'unknown storage-type {storage_type}') if __name__ == '__main__': FORMAT = '%(asctime)s %(levelname)s - %(message)s' logging.basicConfig(format=FORMAT, level=logging.INFO) parser = argparse.ArgumentParser(description='Script that create a basic set of metadata if required for a Space', ) parser.add_argument('--payload', '-p', dest='payload', type=str, required=True) parser.add_argument('--client-id', '-ci', dest='client', type=str, required=False) parser.add_argument('--client-secret', '-c', dest='secret', type=str, required=False) args = parser.parse_args() if not args.payload: raise Exception('no payload provided') payload = _extract_notification(args.payload) logging.info(payload) client_id = _get_argument(args.client, 'client-id', 'CLIENT_ID') client_secret = _get_argument(args.secret, 'client-secret', 'CLIENT_SECRET') if not client_id or not client_secret: raise Exception('client-id and client-secret must be provided') # Extract organization, space and root_dir from the payload organization = payload['accountName'] space = payload['storageName'] container = payload['containerName'] root_dir = payload['rootDir'].rstrip('/') username = payload['userName'] # Request an access_token logging.info("Fetching access_token...") access_token = authentication.get_access_token(username, client_id, client_secret) logging.info("Fetching access_token...Done!") # CUSTOM CODE logging.info("Creating metadata...") storage_access = _get_storage_access() metadata.create_basic_metadata(storage_access, access_token, organization, space, container, root_dir) logging.info("Creating metadata...Done")
{% load i18n static %} {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %} | ShareShed{% endblock %}</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static "main_website/css/base-home.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "main_website/css/base-navbar.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "main_website/css/base-footer.css" %}"> <link rel="stylesheet" type="text/css" href="{% static "main_website/css/base.css" %}"> <link rel="stylesheet" href="{% static "main_website/css/itemDetails.css" %}"> <link rel="shortcut icon" href="{% static "main_website/img/favicon.png" %}" type="image/x-icon" /> {% block head %} {% endblock %} </head> <body> <main> {% block main-nav %} <div class="navbar navbar-expand-md navbar-dark bg-dark pt-0 pb-0 pl-2 pr-2"> <a class="navbar-brand" href="{% url 'home' %}"> <img src="{% static "main_website/img/icon-shareshed.png" %}"width="45" height="45" class="d-inline-block align-top" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample04" aria-controls="navbarsExample04" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExample04"> <!-- <form class="form-inline my-2 my-md-0"> <input class="form-control" type="text" placeholder="Search items, info..."> &nbsp; <button class="btn btn-outline-light my-2 my-sm-0" type="submit">Search</button> </form> --> <ul class="navbar-nav ml-auto mr-3"> <li class="nav-item {% if request.path == "/" %} active {% endif %} "> <a class="nav-link" href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item {% if '/catalogue/' in request.path %} active {% endif %}"> <a class="nav-link" href="{% url 'catalogue' %}">Catalogue</a> </li> <li class="nav-item"> <a class="nav-link" href="https://www.shareshed.org.au/">About Us</a> </li> {% if user.is_authenticated %} <li class="nav-item dropdown {% if '/profile' in request.path %} active {% endif %}"> <!-- I use email so that the dropdown will not went out of focus. Seems like if the name is not long enough, the drop down will go out of screen --> <a class="nav-link dropdown-toggle" id="dropdown05" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{ user.email }}</a> <div class="dropdown-menu" aria-labelledby="dropdown05"> <a class="dropdown-item" href="{% url 'profile' %}">Profile</a> {% if user.is_staff %} <a class="dropdown-item" href="/admin/">Admin Dashboard</a> {% endif %} <a class="dropdown-item" href="{% url 'logout' %}">Sign Out</a> </div> </li> {% else %} <li class="nav-item"> <!-- <button class="loginBtn btn btn-link" onclick="document.getElementById('id01').style.display='block'">Login</button> --> <!-- Please take a look on registration/login.html and admin/login.html to see how they modify the login html. Unless you know how to connect views with the pop up --> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> {% endif %} </ul> </div> </div> <!-- <div id="id01" class="modal"> <form class="modal-content animate" action="/action_page.php"> <div class="imgcontainer"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span> <img src="{% static "main_website/img/icon-shareshed.png" %}" alt="Avatar" class="avatar"> </div> <div class="container"> <label for="uname"><b>Username</b></label> <input class="mb-2" type="text" placeholder="Enter Username" name="uname" id="username" required> <br> <label for="psw"><b>Password</b></label> <input class="mb-3" type="password" placeholder="Enter Password" name="psw" id="password" required> <br> <button class="btn btn-secondary btn-lg btn-block blueBtn"type="submit">Login</button> <p class="textcenter mb-3 mt-2"> Don't have an account? <a href="#">Sign Up</a></p> </div> </form> </div> --> {% endblock %} {% block content %} {% endblock %} <p style="display: none;"> {{user.membership.membership_type}} </p> </main> <footer class="footer-bs"> <div class="row"> <div class="col-md-5 footer-brand"> <div class="row"> <div class="col-lg-3"> <img src="{% static "main_website/img/icon-shareshed.png" %}" width="95" height="95" class="d-inline-block align-top footer-logo" alt=""> </div> <div class="col-lg-9"> <p>Share Shed runs on an annual membership basis. You can join online for $80 a year. You can also purchase a gift membership for someone else! We are not-for-profit so all membership fees go towards running Share Shed, fixing items or acquiring new ones.</p> {% if not user.is_authenticated %} <a href="{% url 'signup' %}#"><p>Sign up now!</p></a> {% endif %} <a href="https://www.shareshed.org.au/volunteer"><p>Become a Volunteer</p></a> <p>© Share Shed Inc</p> </div> </div> </div> <div class="col-md-3 footer-nav animated fadeInUp"> <h4>Menu —</h4> <ul class="list"> <li><a href="#">Home</a></li> <li><a href="#">Catalogue</a></li> <li><a href="#">About Us</a></li> <li><a href="#">Contact Us</a></li> </ul> </div> <div class="col-md-4 footer-social animated fadeInDown"> <h4>Follow Us</h4> <a href="#"><i class="fab fa-facebook-square fa-2x"></i></a> &nbsp;&nbsp;<a href="#"><i class="fab fa-twitter-square fa-2x"></i></a> &nbsp;&nbsp;<a href="#"><i class="fab fa-instagram fa-2x"></i></a> </div> <!-- <div class="col-md-3 footer-ns animated fadeInRight"> <h4>Subscribe to our newsletter</h4> <p>Never miss an update!</p> <p> <div class="input-group"> <input type="text" class="form-control" placeholder="Your email..." aria-label="Recipient's username" aria-describedby="basic-addon2"> <div class="input-group-append"> <span class="input-group-text" id="basic-addon2"><i class="far fa-envelope"></i></span> </div> </div> </p> </div> --> </div> </footer> <script src="{% static "main_website/js/base-navbar.js" %}"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> {% block script %} {% endblock %} </body> </html>
import { expect } from 'chai'; import { aUsersManagerFacade } from './base/aUsersManagerFacade'; import { aRegularUserRegistrationRequest } from './base/requests/aRegularUserRegistrationRequest'; import { ExceptionMessages } from '../../../main/core/domain/exceptions/ExceptionMessages'; import { NotFoundException } from '../../../main/core/domain/exceptions/NotFoundException'; describe('Get Regular User By Id', () => { const usersManager = aUsersManagerFacade(); it('should get a user by his id after registration', async () => { const registrationInfo = aRegularUserRegistrationRequest(); const { accountId } = await usersManager.registerRegularUser(registrationInfo); const { firstName, lastName, wilayaNumber } = await usersManager.getRegularUserById({ accountId, }); expect(firstName).to.equal(registrationInfo.firstName.toLowerCase()); expect(lastName).to.equal(registrationInfo.lastName.toLowerCase()); expect(wilayaNumber).to.equal(registrationInfo.wilayaNumber); }); it('should throw a not found exception when no user found with the provided id', async () => { const ID_NOT_EXIST = 'some random id'; await expect(usersManager.getRegularUserById({ accountId: ID_NOT_EXIST })) .to.eventually.be.rejectedWith(ExceptionMessages.ACCOUNT_NOT_FOUND) .and.to.be.an.instanceOf(NotFoundException); }); });
/* eslint-disable no-console */ import { useSearchParams } from 'react-router-dom'; import { useEffect, useState } from 'react'; import moment from 'moment'; import 'moment/locale/ko'; import BottomBar from 'src/components/BottomBar'; import TodoList from 'src/screen/Main/TodoList'; import styled from 'styled-components'; import { SetBackGround, TopContainer, BodyContainer, TitleContainer, Title, } from 'src/components/Styled'; import { PRIMARY } from 'src/constants'; import 'swiper/scss'; import 'swiper/scss/navigation'; import 'swiper/scss/pagination'; import { Swiper, SwiperSlide } from 'swiper/react'; import { useMutation, useQuery, useQueryClient } from 'react-query'; import { deleteTodolistId, getTodolist, postTodolist } from 'src/api/todolist'; import { getMyRooms } from 'src/api/myRooms'; import ReviseRoom from 'src/components/ReviseRoom'; import UseModal from 'src/components/UseModal'; import Tutorial1 from 'src/components/Tutorial/Tutorial1'; import Tutorial3 from 'src/components/Tutorial/Tutorial3'; import Tutorial2 from 'src/components/Tutorial/Tutorial2'; import MyGroup from './MyGroup'; import EmptyGroup from './EmptyGroup'; moment.locale('ko'); export default function Main() { const queryClient = useQueryClient(); const [swiperIdx, setSwiperIdx] = useState(0); const [params] = useSearchParams(); const [isDelete, setIsDelete] = useState(false); const [selectedDelCategory, setSelectedDelCategory] = useState(''); const [modalOpen, setModalOpen] = useState<boolean>(true); const [modalOpen2, setModalOpen2] = useState<boolean>(false); const [modalOpen3, setModalOpen3] = useState<boolean>(false); // console.log(params.get('token')); const { data: myRoomData } = useQuery(['myRoomData'], getMyRooms); const { data: todolistData } = useQuery(['todolistData'], getTodolist); // eslint-disable-next-line no-console const { open: openModal, close: closeModal, isOpen: isOpenedModal, myRoomData: meRoomData, } = UseModal(); const { mutate: addCategory } = useMutation(postTodolist, { onSuccess: () => { queryClient.invalidateQueries('todolistData'); }, onError: (err) => { console.warn(err); }, }); const { mutate: deleteCategory } = useMutation( () => deleteTodolistId(selectedDelCategory), { onSuccess: () => { queryClient.invalidateQueries('todolistData'); setIsDelete(false); }, onError: (err) => { console.warn(err); }, }, ); useEffect(() => { const kakaotoken = params.get('token'); if (kakaotoken != null) { localStorage.clear(); localStorage.setItem('token', kakaotoken); window.location.replace('/main'); } const newuser = params.get('newuser'); if (modalOpen) { if (newuser === 'true') { window.location.replace('/main?newuser=yes'); } else if (newuser === 'yes') { setModalOpen(!modalOpen); } } }, []); const handleAddCategory = () => { addCategory(); }; const delCategoryOn = () => { if (!isDelete) setIsDelete(true); else if (!selectedDelCategory) setIsDelete(false); else deleteCategory(); }; const onSelectCategory = (e: string) => { if (selectedDelCategory === e) setSelectedDelCategory(''); else setSelectedDelCategory(e); }; return ( <> <> <SetBackGround> <TopContainer> <DayOfWeek>{moment().format('dddd')}</DayOfWeek> <Date>{moment().format('M월 D일')}</Date> </TopContainer> <BodyContainer style={{ backgroundColor: 'white' }}> <TitleContainer> <Title>GROUP</Title> </TitleContainer> {myRoomData?.length ? ( <> <Swiper style={{ paddingBottom: 27, }} spaceBetween={1} slidesPerView={1} pagination={{ clickable: true }} onSlideChange={(e) => setSwiperIdx(e.snapIndex)} // onSwiper={(swiper) => console.log(swiper.el)} > {myRoomData.map((item) => { return ( <SwiperSlide key={item.roomId}> <MyGroup item={item} openModal={openModal} /> </SwiperSlide> ); })} </Swiper> <SwiperDotContainer> {myRoomData.map((item, index) => { return ( <div key={item.roomId} style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: index === swiperIdx ? PRIMARY : '#d9d9d9', }} /> ); })} </SwiperDotContainer> </> ) : ( <EmptyGroup /> )} <Divider /> <TitleContainer> <Title>TO DO LIST</Title> <div style={{ display: 'flex', gap: 8 }}> <DelButton onClick={delCategoryOn} style={{ color: isDelete ? PRIMARY : '#8f8f8f' }} > {selectedDelCategory !== '' ? '완료' : '삭제'} </DelButton> {!isDelete && ( <AddButton onClick={handleAddCategory}>추가</AddButton> )} </div> </TitleContainer> {todolistData?.map((item) => { return ( <TodoList key={item.todoListId} id={item.todoListId} selectedId={selectedDelCategory} subject={item.title} item={item.todos} isDelete={isDelete} onSelectedCategory={onSelectCategory} /> ); })} </BodyContainer> <BottomBar currentPage="Main" /> </SetBackGround> {isOpenedModal && meRoomData && ( <ReviseRoom modal={closeModal} myRoomData={meRoomData} isOpen={isOpenedModal} /> )} </> {!modalOpen && <Tutorial1 modal={setModalOpen} differ={setModalOpen2} />} {modalOpen2 && <Tutorial2 modal={setModalOpen2} differ={setModalOpen3} />} {modalOpen3 && <Tutorial3 modal={setModalOpen3} />} </> ); } const DayOfWeek = styled.div` font-size: 18px; font-weight: 600; color: white; `; const Date = styled.div` font-size: 30px; font-weight: 600; color: white; `; const Divider = styled.div` display: flex; height: 10px; background-color: #f4f4f4; margin-bottom: 18px; `; const AddButton = styled.div` display: flex; align-items: center; font-size: 16px; color: ${PRIMARY}; font-weight: 500; border: 1px solid #e8e8e8; border-radius: 5px; padding: 5px 11px; cursor: pointer; `; const DelButton = styled.div` display: flex; align-items: center; font-size: 16px; color: #8f8f8f; font-weight: 500; border: 1px solid #e8e8e8; border-radius: 5px; padding: 5px 11px; cursor: pointer; `; // const PlusIcon = styled.img` // width: 24px; // height: 24px; // `; const SwiperDotContainer = styled.div` display: flex; justify-content: center; align-items: center; gap: 6px; margin-bottom: 18px; `;
import React from 'react' // 第一层封装:将 样式对象 和 UI 结构分类 // const itemStyle = { border:'1px dashed #ccc', margin: '10px', padding: '10px', boxShadow: '0 0 10px #ccc'} // const userStyle = { fontSize: '14px' } // const contentStyle = { fontSize: '12px' } // 第二层封装:合并成一个大的样式对象 //const styles = { // item: { border:'1px dashed #ccc', margin: '10px', padding: '10px', boxShadow: '0 0 10px #ccc'}, // user: { fontSize: '14px' }, // content: { fontSize: '12px' } // } // 第三层封装:抽离为单独的样式表模块 import styles from '@/components/styles' // 使用 function 构造函数,定义普通的无状态组件 export default function CmtItems(props) { return <div style={styles.item}> <h1 style={styles.user}>评论人:{props.user}</h1> <p style={styles.content}>评论内容:{props.content}</p> </div> }
import React, { useState, useEffect } from "react"; import * as planAPI from "../../utilities/plan-api"; import * as exercisesAPI from "../../utilities/exercises-api"; import { useParams } from "react-router-dom"; import CreateWorkoutExerciseCard from "./CreateWorkoutExerciseCard"; function AddExerciseToWorkoutPlan() { const { id } = useParams(); const [exercises, setExercises] = useState([]); const [exercise, setExercise] = useState({ exercise: "", name: "", muscleGroup: "", sets: "", reps: "", duration: "", notes: "", }); // now I need to update the schema for the exercise in the plan and also drop the colection in mongo" function handleChange(e) { setExercise({ ...exercise, [e.target.name]: e.target.value }); } function handleSelectChange(e) { if (e.target.name === "exercise") { const selectedExercise = exercises.find( (exercise) => exercise._id === e.target.value ); setExercise({ ...exercise, muscleGroup: selectedExercise.muscleGroup, name: selectedExercise.name, exercise: selectedExercise._id, }); } } async function handleSubmit(e) { e.preventDefault(); window.location.replace(`/workout/${id}`); try { await planAPI.addExercise(exercise, id); } catch {} } // this is for displaying the exercises as options in the select field in the form async function fetchExercises() { const exercises = await exercisesAPI.get(); setExercises(exercises); } useEffect(() => { fetchExercises(); }, []); return ( <div className="container container-fluid d-flex flex-column justify-content-center align-items-center mt-2" style={{ minHeight: "100vh", height: "auto" }}> <h1 className="text-center mt-5"> Add Exercise</h1> <br /> <form onSubmit={handleSubmit} style={{ width: "25em", border: "solid black 3px", borderRadius: "1.5em", }} className="p-4"> <label className="form-label">Exercise</label> <br /> <select name="exercise" onChange={handleSelectChange}> <option disabled selected="selected"> Choose One </option> {exercises.map((exercise, idx) => { return ( <CreateWorkoutExerciseCard key={exercise + idx} exercise={exercise} /> ); })} </select> <br /> <label className="form-label mt-2">Sets</label> <input type="text" name="sets" onChange={handleChange} required className="form-control" /> <label className="form-label">Reps</label> <input type="text" name="reps" onChange={handleChange} required className="form-control" /> <label className="form-label">Duration</label> <input type="text" name="duration" onChange={handleChange} className="form-control" /> <label className="form-label">Initial Weight (lbs)</label> <input type="text" name="notes" onChange={handleChange} required className="form-control" /> <button type="submit" className="btn btn-dark mt-2"> Add Exercise{" "} </button> </form> </div> ); } export default AddExerciseToWorkoutPlan;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProgramDurationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('program_durations', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('uuid', 36)->unique(); $table->string('title', 191); $table->smallInteger('years')->nullable(); $table->smallInteger('months')->nullable(); $table->smallInteger('weeks')->nullable(); $table->boolean('active')->default(true); $table->unsignedBigInteger('created_by_id')->nullable()->index(); $table->unsignedBigInteger('updated_by_id')->nullable()->index(); $table->timestamps(); $table->unsignedBigInteger('deleted_by_id')->nullable()->index(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('program_durations'); } }
import { useEffect, useMemo, useState } from 'react'; export const useForm = ( initialForm = {}, formValidations = {}) => { const [ formState, setFormState ] = useState( initialForm ); const [ formValidation, setFormValidation ] = useState({}); useEffect(() => { createValidators(); },[formState]) useEffect(() => { setFormState(initialForm); },[initialForm]) const onInputChange = ({ target }) => { const { name, value } = target; setFormState({ ...formState, [ name ]: value }); } const onResetForm = () => { setFormState( initialForm ); } /** * checks for the status of validation of the form. If all the values in formValidation * are null that means that all the validations for the formState have passed successfuly * otherwise it will return false. */ const isFormValid = useMemo( () => { for (const formValue of Object.keys(formValidation)) { if ( formValidation[formValue] != null ) { return false; } } return true; }, [formValidation]) /** * validates each and every field of the forms with the functions in formValidations * creates instances that determine the state of success of every validation and store them in * formCheckvalues to set them into the state */ const createValidators = () => { const formCheckValues = {}; for (const formField of Object.keys(formValidations)) { const [ fn, errorMessage ] = formValidations[formField]; formCheckValues[`${formField}Valid`] = fn(formState[formField]) ? null : errorMessage; } setFormValidation(formCheckValues) } return { ...formState, formState, onInputChange, onResetForm, ...formValidation, isFormValid } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <style> .item{ background-color: red; color: white; font-size: 40px; display: none; @media (max-width:250px){ #item-1{ display: block; } } @media (min-width:251px) and (max-width:500px){ #item-2{ display: block; background-color: green; } } @media (min-width:501px) and (max-width:900px){ #item-3{ display: block; background-color: rgb(128, 45, 0); } } @media (min-width:901px){ #item-4{ display: block; } } </style> <div class="container"> <div class="item" id="item-1">this screen starts from 0px andends at 250px name is mobile</div> <div class="item" id="item-2">this screen starts from 251 andends at 500 name is tab</div> <div class="item" id="item-3">this screen starts from 501 andends at 900 name is desktop</div> <div class="item" id="item-4">this screen starts from 901 andends at name is large tv</div> </div> <h2>Notes</h2> <p>this tag will give us the screen size</p> <h2>Snap</h2> <img height="400px" src="./1.png" alt=""> <img src="./2.png" alt=""> <a href="./allresponsive.html"><center><button>Back</button></center></a> </body> </html>
import Layout from '../../components/Layout/Layout'; import React, { Suspense } from 'react'; import SearchForm from '../../components/SearchForm/SearchForm'; import Preloader from '../../components/Preloader/Preloader'; import styles from './Movies.scss'; function Movies({ movies, loggedIn, openPopup, setMovies, setFetchMoviesError, setMoviesToShow, ...restProps }) { const MoviesCardList = React.lazy(() => import('../../components/MoviesCardList/MoviesCardList')); return ( <Layout loggedIn={loggedIn} openPopup={openPopup}> <div className="movies__container"> <SearchForm movies={movies} setMoviesToShow={setMoviesToShow} setMovies={setMovies} setFetchMoviesError={setFetchMoviesError} ></SearchForm> <Suspense fallback={<Preloader />}> {<MoviesCardList movies={movies} setMoviesToShow={setMoviesToShow} {...restProps} />} </Suspense> </div> </Layout> ); } export default Movies;
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FilmLabBackEnd.Data; using FilmLabBackEnd.Helpers; using FilmLabBackEnd.Options; using FilmLabBackEnd.Data; using FilmLabBackEnd.Helpers; using FilmLabBackEnd.Options; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; namespace FilmLabBackEnd { public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddDirectoryBrowser(); services.AddMvc(); services.AddControllers(); services.AddScoped<DataRepository>(x => new DataRepository(Configuration.GetConnectionString("DbConnection"))); services.AddScoped<JwtService>(); services.AddCors(options => { options.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseFileServer(); app.UseRouting(); app.UseCors(options=>options .WithOrigins(new []{"http://localhost:7050","http://localhost:5043"}) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() ); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllerRoute( name: "default", pattern:"{controller=Home}/{action=Index}/{id?}"); }); } } }
import mimetypes import os import re import time from contextlib import nullcontext from itertools import islice from random import randint import numpy as np import torch from PIL import Image from einops import rearrange from ldm.util import instantiate_from_config from omegaconf import OmegaConf from pytorch_lightning import seed_everything from torch import autocast from torchvision.utils import make_grid from tqdm import tqdm, trange from transformers import logging from .optimUtils import split_weighted_subprompts, logger from ..config import ckpt_path, yaml_path logging.set_verbosity_error() mimetypes.init() mimetypes.add_type("application/javascript", ".js") def chunk(it, size): it = iter(it) return iter(lambda: tuple(islice(it, size)), ()) def load_model_from_config(ckpt, verbose=False): print(f"Loading model from {ckpt}") pl_sd = torch.load(ckpt, map_location="cpu") if "global_step" in pl_sd: print(f"Global Step: {pl_sd['global_step']}") sd = pl_sd["state_dict"] return sd config = yaml_path ckpt = ckpt_path sd = load_model_from_config(f"{ckpt}") li, lo = [], [] for key, v_ in sd.items(): sp = key.split(".") if (sp[0]) == "model": if "input_blocks" in sp: li.append(key) elif "middle_block" in sp: li.append(key) elif "time_embed" in sp: li.append(key) else: lo.append(key) for key in li: sd["model1." + key[6:]] = sd.pop(key) for key in lo: sd["model2." + key[6:]] = sd.pop(key) config = OmegaConf.load(f"{config}") model = instantiate_from_config(config.modelUNet) _, _ = model.load_state_dict(sd, strict=False) model.eval() modelCS = instantiate_from_config(config.modelCondStage) _, _ = modelCS.load_state_dict(sd, strict=False) modelCS.eval() modelFS = instantiate_from_config(config.modelFirstStage) _, _ = modelFS.load_state_dict(sd, strict=False) modelFS.eval() del sd def generate( prompt=None, scale=7, outdir=None, percentage_counter=None, ddim_steps=50, n_iter=1, batch_size=1, Height=512, Width=512, ddim_eta=0, unet_bs=1, device="cuda", seed='', img_format="jpg", turbo=False, full_precision=False, ): C = 4 f = 8 start_code = None model.unet_bs = unet_bs model.turbo = turbo model.cdevice = device modelCS.cond_stage_model.device = device if seed == "": seed = randint(0, 1000000) seed = int(seed) seed_everything(seed) # Logging logger(locals(), "logs/txt2img_gradio_logs.csv") if device != "cpu" and full_precision == False: model.half() modelFS.half() modelCS.half() tic = time.time() os.makedirs(outdir, exist_ok=True) outpath = outdir sample_path = os.path.join(outpath, "_".join(re.split(":| ", prompt)))[:150] os.makedirs(sample_path, exist_ok=True) base_count = len(os.listdir(sample_path)) # n_rows = opt.n_rows if opt.n_rows > 0 else batch_size assert prompt is not None data = [batch_size * [prompt]] if full_precision == False and device != "cpu": precision_scope = autocast else: precision_scope = nullcontext all_samples = [] seeds = "" with torch.no_grad(): all_samples = list() for _ in trange(n_iter, desc="Sampling"): for prompts in tqdm(data, desc="data"): with precision_scope("cuda"): modelCS.to(device) uc = None if scale != 1.0: uc = modelCS.get_learned_conditioning(batch_size * [""]) if isinstance(prompts, tuple): prompts = list(prompts) subprompts, weights = split_weighted_subprompts(prompts[0]) if len(subprompts) > 1: c = torch.zeros_like(uc) totalWeight = sum(weights) # normalize each "sub prompt" and add it for i in range(len(subprompts)): weight = weights[i] # if not skip_normalize: weight = weight / totalWeight c = torch.add(c, modelCS.get_learned_conditioning(subprompts[i]), alpha=weight) else: c = modelCS.get_learned_conditioning(prompts) shape = [C, Height // f, Width // f] if device != "cpu": mem = torch.cuda.memory_allocated() / 1e6 modelCS.to("cpu") while torch.cuda.memory_allocated() / 1e6 >= mem: time.sleep(1) samples_ddim = model.sample( S=ddim_steps, conditioning=c, batch_size=batch_size, seed=seed, shape=shape, verbose=False, unconditional_guidance_scale=scale, unconditional_conditioning=uc, eta=ddim_eta, x_T=start_code, percentage_counter=percentage_counter, ) modelFS.to(device) print("saving images") for i in range(batch_size): x_samples_ddim = modelFS.decode_first_stage(samples_ddim[i].unsqueeze(0)) x_sample = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0) all_samples.append(x_sample.to("cpu")) x_sample = 255.0 * rearrange(x_sample[0].cpu().numpy(), "c h w -> h w c") Image.fromarray(x_sample.astype(np.uint8)).save( os.path.join(sample_path, "seed_" + str(seed) + "_" + f"{base_count:05}.{img_format}") ) seeds += str(seed) + "," seed += 1 base_count += 1 if device != "cpu": mem = torch.cuda.memory_allocated() / 1e6 modelFS.to("cpu") while torch.cuda.memory_allocated() / 1e6 >= mem: time.sleep(1) del samples_ddim del x_sample del x_samples_ddim print("memory_final = ", torch.cuda.memory_allocated() / 1e6) toc = time.time() time_taken = (toc - tic) / 60.0 grid = torch.cat(all_samples, 0) grid = make_grid(grid, nrow=n_iter) grid = 255.0 * rearrange(grid, "c h w -> h w c").cpu().numpy() txt = ( "Samples finished in " + str(round(time_taken, 3)) + " minutes and exported to " + sample_path + "\nSeeds used = " + seeds[:-1] ) return Image.fromarray(grid.astype(np.uint8)), txt
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous" /> </head> <body> <div class="container mt-4"> <div class="row"> <div class="col-8 mx-auto"> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-primary">Left</button> <button type="button" class="btn btn-primary">Middle</button> <button type="button" class="btn btn-primary">Right</button> </div> <hr> <div class="btn-group" role="group" aria-label="Basic checkbox toggle button group"> <input type="checkbox" class="btn-check" id="btncheck1" autocomplete="off"> <label class="btn btn-outline-primary" for="btncheck1">Checkbox 1</label> <input type="checkbox" class="btn-check" id="btncheck2" autocomplete="off"> <label class="btn btn-outline-primary" for="btncheck2">Checkbox 2</label> <input type="checkbox" class="btn-check" id="btncheck3" autocomplete="off"> <label class="btn btn-outline-primary" for="btncheck3">Checkbox 3</label> </div> <div class="btn-group" role="group" aria-label="Basic radio toggle button group"> <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked> <label class="btn btn-outline-primary" for="btnradio1">Radio 1</label> <input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off"> <label class="btn btn-outline-primary" for="btnradio2">Radio 2</label> <input type="radio" class="btn-check" name="btnradio" id="btnradio3" autocomplete="off"> <label class="btn btn-outline-primary" for="btnradio3">Radio 3</label> </div> <div class="btn-toolbar mt-2" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group me-2" role="group" aria-label="First group"> <button type="button" class="btn btn-primary">1</button> <button type="button" class="btn btn-primary">2</button> <button type="button" class="btn btn-primary">3</button> <button type="button" class="btn btn-primary">4</button> </div> <div class="btn-group me-2" role="group" aria-label="Second group"> <button type="button" class="btn btn-secondary">5</button> <button type="button" class="btn btn-secondary">6</button> <button type="button" class="btn btn-secondary">7</button> </div> <div class="btn-group" role="group" aria-label="Third group"> <button type="button" class="btn btn-info">8</button> </div> </div> <div class="btn-toolbar mb-3" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group me-2" role="group" aria-label="First group"> <button type="button" class="btn btn-outline-secondary">1</button> <button type="button" class="btn btn-outline-secondary">2</button> <button type="button" class="btn btn-outline-secondary">3</button> <button type="button" class="btn btn-outline-secondary">4</button> </div> <div class="input-group"> <div class="input-group-text" id="btnGroupAddon">@</div> <input type="text" class="form-control" placeholder="Input group example" aria-label="Input group example" aria-describedby="btnGroupAddon"> </div> </div> <div class="btn-toolbar justify-content-between" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group" role="group" aria-label="First group"> <button type="button" class="btn btn-outline-secondary">1</button> <button type="button" class="btn btn-outline-secondary">2</button> <button type="button" class="btn btn-outline-secondary">3</button> <button type="button" class="btn btn-outline-secondary">4</button> </div> <div class="input-group"> <div class="input-group-text" id="btnGroupAddon2">@</div> <input type="text" class="form-control" placeholder="Input group example" aria-label="Input group example" aria-describedby="btnGroupAddon2"> </div> </div> <div class="btn-group" role="group" aria-label="Button group with nested dropdown"> <button type="button" class="btn btn-primary">1</button> <button type="button" class="btn btn-primary">2</button> <div class="btn-group" role="group"> <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Dropdown link</a></li> <li><a class="dropdown-item" href="#">Dropdown link</a></li> </ul> </div> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous" ></script> </body> </html>
//let numero = 0 // //while(isNaN(numero) || numero<1){ // numero = +prompt("Entre com um número inteiro maior do que 0") //} // // //const div = document.getElementById("resultado") // //const resultado = isPar(numero) // //const p = document.createElement("p") //p.textContent = resultado // //div.appendChild(p) // //function isPar(num) { // if (num % 2 == 0) { // return "Par" // } // return "ímpar" //} // PARADIGMA IMPERATIVO const arrayDeNumeros = [1,2,3,4,5,6,7,8] let arrayDeResultadosPares = [] for(let x=0; x < arrayDeNumeros.length; x++){ if(arrayDeNumeros[x] % 2 === 0){ arrayDeResultadosPares.push(arrayDeNumeros[x]) } } console.log(arrayDeResultadosPares) // PARADIGMA FUNCIONAL // 2º FORMA DE DECLARAR FUNÇÃO const isPar = function(num){ if (num % 2 == 0){ return true } return false } const arrayParUsandoFuncional = arrayDeNumeros.filter(isPar) console.log(arrayParUsandoFuncional) const isPar2 = function(num){ return num % 2 === 0 } // 3º FORMA DE DECLARAR FUNÇÃO // ARROW FUNCTION const isPar3 = num => num % 2 === 0 console.log(isPar3(4))
import React, { useState } from "react"; import axios from "axios"; import { Link, useNavigate } from "react-router-dom"; import "./register.scss" import Navbar from "../../Components/Navbar/Navbar" import Footer from "../../Components/Footer/Footer" import { signup } from "../../auth"; const Register = () => { const navigate = useNavigate() const [user, setUser] = useState({ username : "", email : "", password : "" }) const [registerSuccess, setRegisterSuccess] = useState(false); const handleChange = (event) => { setUser({...user, [event.target.name] : event.target.value}) }; const onSubmit = async (e) => { e.preventDefault(); const {username, email, password} = user const userRegisterDetails = { username: username, email: email, password: password, }; try { // const register_res = await axios.post( // "http://localhost:8000/api/register", // userRegisterDetails // ); signup(userRegisterDetails) setRegisterSuccess(true); navigate("/login") } catch (err) { console.log(err); } }; return ( <div className="register"> <Navbar /> <div className="form"> <div className="form_wrapper"> <div className="left"> <img src="https://www.data-science.ie/wp-content/uploads/2019/01/signup.png" alt="" /> </div> <form> <span className="heading">SignUp</span> <input type="name" name="username" value={user.username} onChange={handleChange} placeholder="Full Name" /> <input type="email" name="email" value={user.email} onChange={handleChange} placeholder="Email" /> <input type="password" name="password" value={user.password} onChange={handleChange} placeholder="Password" /> <button onClick={onSubmit}>Sign Up</button> </form> </div> </div> <Footer /> </div> ); }; export default Register;
import crypto from 'crypto'; import { NewbPayTradeInfo } from '../models/otherModel'; const NotifyURL = `${process.env.BACKEND_BASE_URL}/api/activities/spgateway_notify`; const { HASHKEY, HASHIV, MerchantID, Version, RespondType, ClientBackURL }: any = process.env; // 字串組合 function genDataChain(order: NewbPayTradeInfo, orderId: string) { // 付款期限 // 如果沒給,藍新預設為 7 天 const ExpireDate = order?.ExpireDate return `MerchantID=${MerchantID}` // 商店代號 + `&RespondType=${RespondType}` // 回傳格式 + `&TimeStamp=${order.TimeStamp}` // 時間戳 Unix 格式 + `&Version=${Version}` // 版本 + `&MerchantOrderNo=${order.MerchantOrderNo}` // 訂單編號 + `&Amt=${order.Amt}` // 金額 + `&ItemDesc=${encodeURIComponent(order.ItemDesc)}` // 商品資訊 + `&Email=${encodeURIComponent(order.Email)}` // 會員信箱 + `&NotifyURL=${NotifyURL}` // 處理付款回傳結果 // + `&ReturnURL=${ReturnURL}` // 支付完成返回商店網址 // 支付取消返回商店網址 + `&ClientBackURL=${ClientBackURL}/#/member/ticket/${orderId}` + `&ExpireDate=${ExpireDate ? ExpireDate : ''}`; // 付款期限 } // 此加密主要是提供交易內容給予藍新金流 function createMpgAesEncrypt(TradeInfo: NewbPayTradeInfo, orderId: string) { const encrypt = crypto.createCipheriv('aes256', HASHKEY, HASHIV); const enc = encrypt.update(genDataChain(TradeInfo, orderId), 'utf8', 'hex'); return enc + encrypt.final('hex'); } // 對應文件 P17:使用 sha256 加密 // 使用 HASH 再次 SHA 加密字串,作為驗證使用 // $hashs="HashKey=".$key."&".$edata1."&HashIV=".$iv; function createMpgShaEncrypt(aesEncrypt: string) { const sha = crypto.createHash('sha256'); const plainText = `HashKey=${HASHKEY}&${aesEncrypt}&HashIV=${HASHIV}`; return sha.update(plainText).digest('hex').toUpperCase(); } // 將 aes 解密 function createMpgAesDecrypt(TradeInfo: string) { const decrypt = crypto.createDecipheriv('aes256', HASHKEY, HASHIV); decrypt.setAutoPadding(false); const text = decrypt.update(TradeInfo, 'hex', 'utf8'); const plainText = text + decrypt.final('utf8'); const result = plainText.replace(/[\x00-\x20]+/g, ''); return JSON.parse(result); } export { createMpgAesEncrypt, createMpgShaEncrypt, createMpgAesDecrypt }
package edu.yu.cs.com1320.project.stage3.impl; import edu.yu.cs.com1320.project.stage3.Document; import java.net.URI; import java.util.Arrays; import java.util.HashMap; import java.util.Set; import java.util.HashSet; //import edu.yu.cs.com1320.project.impl.HashTableImpl; public class DocumentImpl implements Document{ private URI uri; private String text; private byte[] binaryData; private HashMap<String, Integer> wordMap = new HashMap<String, Integer>(); public DocumentImpl(URI uri, String txt) { if(uri == null || txt == null || uri.toString().equals("")||txt.equals("")){ throw new IllegalArgumentException(); } this.uri = uri; this.text = txt; this.binaryData = null; this.addTextToWordMap(); } public DocumentImpl(URI uri, byte[] binaryData){ if(uri == null || binaryData == null || uri.toString().equals("")||binaryData.length==0){ throw new IllegalArgumentException(); } this.uri = uri; this.binaryData = binaryData; this.text = null; } private void addTextToWordMap(){ //delete non letters and numbers /* String textString = getDocumentTxt(); for(int i = 0; i<128; i++){ if(i == 48) i = 58; if(i == 65) i = 91; if(i == 97) i = 123; textString = textString.replaceAll(""+(char)i, ""); } textString = textString.toLowerCase(); String[] wordArray = textString.split(" "); */ String textString = getDocumentTxt(); textString = textString.toLowerCase(); char[] charArray = textString.toCharArray(); String newString = ""; for(int i =0; i<charArray.length; i++){ if(charArray[i]<48&&charArray[i]!=32) charArray[i] = 0; else if(charArray[i]>57 && charArray[i]<97) charArray[i] = 0; else if(charArray[i]>122) charArray[i] = 0; else{ newString= newString+charArray[i]; } } textString = newString; System.out.println(textString); String[] wordArray = textString.split(" "); HashSet<String> wordSet = new HashSet<String>(); for(int i =0; i<wordArray.length; i++){ wordSet.add(wordArray[i]); } //count the words //for(int i =0; i<wordArray.size(); i++){ for(String word: wordSet){ int wordCount = 0; // System.out.println(wordArray[i]); while(!textString.equalsIgnoreCase(textString.replaceFirst(word.toLowerCase(), ""))){ textString = textString.replaceFirst(word.toLowerCase(), ""); wordCount++; //System.out.println(wordCount); } if(!word.equals(""))System.out.println(word + wordCount); if(!word.equals(""))this.wordMap.put(word, wordCount); } } public String getDocumentTxt(){ //if(this.text == null){ // return ""; //} /*else*/ return this.text; } public byte[] getDocumentBinaryData(){ /*if(binaryData == null){ return this.text.getBytes(); } else*/ return this.binaryData; } public URI getKey(){ return this.uri; } /** * how many times does the given word appear in the document? * @param word * @return the number of times the given words appears in the document. If it's a binary document, return 0. */ public int wordCount(String word){ if(this.getDocumentTxt() == null) return 0; if(this.wordMap.get(word.toLowerCase()) == null) return 0; return (int)this.wordMap.get(word.toLowerCase()); } /** * @return all the words that appear in the document */ public Set<String> getWords(){ return this.wordMap.keySet(); } @Override public int hashCode() { int result = uri.hashCode(); result = 31 * result + (text != null ? text.hashCode() : 0); result = 31 * result + Arrays.hashCode(binaryData); return result; } @Override public boolean equals(Object other){ if(other ==null) return false; if(!(other instanceof Document)) return false; if(other==this)return true; if(this.hashCode()==other.hashCode()) return true; return false; } }
import type { User } from "../db/users"; import * as usersDB from "../db/users"; import { getSalt, hashPassword } from "../helpers/hashPassword"; export async function createUser(user: { email: string, password: string }) { if (!user.email || user.email.length < 5 || !user.email.includes('@')) { throw new Error('Invalid email'); } const existing = await usersDB.findByEmail(user.email); if (existing) { throw new Error('User already exists'); } if (!user.password || user.password.length < 8) { throw new Error('Password too short'); } const salt = getSalt(); const userWithHash: User = { email: user.email, hash: hashPassword(salt + user.password), salt }; return usersDB.createUser(userWithHash); } export async function authenticateUser(user: { email: string, password: string }) { const existing = await usersDB.findByEmail(user.email); if (!existing) { throw new Error('User not found'); } const hash = hashPassword(existing.salt + user.password); if (hash !== existing.hash) { throw new Error('Invalid password'); } return { email: existing.email }; }
import React, { createContext, useEffect, useState } from "react"; export const MyContext = createContext(); export const ContextProvider = ({ children }) => { const [categories, setCategories] = useState([]); const fetchCategories = () => { fetch("https://api.chucknorris.io/jokes/categories") .then((response) => response.json()) .then((data) => setCategories(data)) .catch((err) => { console.error(err); throw err; }); }; const [jokes, setjokes] = useState([]); const fetchjokes = (currCategory) => { fetch(`https://api.chucknorris.io/jokes/random?category=${currCategory}`) .then((response) => response.json()) .then((data) => setjokes(data)) .catch((err) => { console.error(err); throw err; }); }; useEffect(() => { fetchCategories(); }, []); return ( <MyContext.Provider value={[categories, fetchjokes, jokes.value]} > {children} </MyContext.Provider> ); }; export const useContext = () => useContext(MyContext);
<template> <div id="my_form"> <el-form ref="form" v-loading="loading" v-bind="$attrs" :label-position="options.labelPosition" :label-width="options.labelWidth" :model="formData" :rules="langRule" :disabled="disabled" size="mini" v-on="$listeners" > <div :class="{'form-scroller':options.isScroller}" :style="{ 'height': options.isScroller ? options.scrollHeight : '', maxHeight: options.isScroller && !options.scrollHeight ? (options.scrollMaxHeight || 'calc(100vh - 260px)') : '' }" > <div v-for="(block,index) in column" :key="index" class="block" :class="{'border': block.title}"> <h3 v-if="block.title" class="header">{{ $t(`${block.title}`) }}</h3> <div class="right-btn"><slot :name="block.controlBtn" /></div> <el-row v-if="block.content" :gutter="20"> <template v-for="(item,key) in block.content" > <el-col v-if="!item.hide" :key="key" style="margin-bottom:10px;" :xl="item.xl || item.span || options.xl || 6" :lg="item.lg || item.span || options.lg || 8" :md="item.md || item.span || options.md || 8" :sm="item.sm || item.span || options.sm || 12" > <el-form-item :ref="item.prop" :label="item.label ? $t(`${item.label}`) : ''" :prop="item.prop" :rules="item.rules" :required="item.required" :style="{height: item.height || formItemHeight}" > <!-- input --> <el-input v-if="item.type == 'label_input'" v-model="formData[item.prop]" clearable :maxlength="item.maxlength" :type="item.genre?item.genre:'text'" :disabled="block.disabled || item.disabled" :placeholder="item.placeholder ? $t(`${item.placeholder}`):item.disabled ||disabled?'':$t('请输入')" :readonly="item.readonly" :show-word-limit="item.showWordLimit" :rows="item.rows ? item.rows : 2" :autosize="item.autosize ? item.autosize : false" @blur="item.handleBlur ? item.handleBlur(item.prop): ''" @clear="item.handleClear ? item.handleClear(item.prop):''" @click.native="item.handleClick?item.handleClick(item.prop):''" > <template :slot="item.slot">{{ item.html }}</template> </el-input> <!-- input-clearable --> <input-clearable v-if="item.type === 'label_input_clearable'" v-model="formData[item.prop]" :disabled="block.disabled || item.disabled" @clear="item.handleClear ? item.handleClear() : ''" @click="item.handleClick ? item.handleClick() : ''" /> <!-- select --> <el-select v-if="item.type == 'label_select'" v-model="formData[item.prop]" :disabled="block.disabled || item.disabled" :multiple="item.multiple" clearable :filterable="item.filterable || true" :placeholder="item.placeholder ? $t(`${item.placeholder}`) : $t('请选择')" @change="item.handleChange ? item.handleChange(item.prop, item, $event):''" @clear="item.handleClear ? item.handleClear(item.prop):''" > <el-option v-for="(opt,oindex) in item.options" :key="oindex" :label="$t(`${opt[item['labelName'] || 'label'] || opt['subName']}`)" :value="opt[item['labelVal'] || 'value'] || opt['subCode']" /> </el-select> <!-- cascader --> <el-cascader v-if="item.type == 'label_cascader'" v-model="formData[item.prop]" :disabled="block.disabled || item.disabled" :options="item.options" :props="item.props" @change="item.change?handleChange(item.prop):''" > <template slot-scope="{ node, data }"> <slot v-if="item.slot" :name="`form-${item.prop}`" :node="node" :data="data" /> <span v-else>{{ $t(data[item.props.label]) }}</span> </template> </el-cascader> <!-- date-picker --> <el-date-picker v-if="item.type == 'label_date_picker'" v-model="formData[item.prop]" :type="item.dateType || 'date'" clearable :picker-options="item.pickerOptions" :placeholder="item.placeholder ? $t(`${item.placeholder}`):$t('请选择')" :disabled="block.disabled || item.disabled" :range-separator="$t('至')" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" :value-format="item.format || 'yyyy-MM-dd'" :default-time="item.dateType==='daterange' && ['00:00:00', '23:59:59']" @change="item.change ? handleChange(item.prop):''" /> <!-- input_number --> <el-input-number v-if="item.type == 'label_input_number'" v-model="formData[item.prop]" :precision="item.precision" :step="item.step" :disabled="block.disabled || item.disabled" :max="item.max" :min="item.min || 0" :controls="item.controls" :controls-position="item.controlsPosition || 'right'" :placeholder="item.placeholder ? $t(`${item.placeholder}`):$t('请输入')" @change="item.handleChange?item.handleChange(item.prop):''" @blur="item.handleBlur ? item.handleBlur(item.prop): ''" /> <!-- number --> <el-input v-if="item.type == 'label_number'" v-model.number="formData[item.prop]" type="number" :disabled="block.disabled || item.disabled" :placeholder="item.placeholder ? $t(`${item.placeholder}`):$t('请输入')" @blur="item.handleBlur ? item.handleBlur(item.prop) : ''" @input="item.handleInput?item.handleInput(item.prop):''" @mousewheel.native.prevent /> <!-- checkbox --> <el-checkbox v-if="item.type == 'label_checkbox'" v-model="formData[item.prop]" :true-label="item.trueLabel" :false-label="item.falseLabel" :disabled="block.disabled || item.disabled" @change="item.change ? handleChange(item.prop):''" > <div>{{ item.text ? $t(`${item.text}`) : '' }}</div> </el-checkbox> <!-- checkbox_group --> <el-checkbox-group v-if="item.type === 'label_checkbox_group'" v-model="formData[item.prop]" :disabled="block.disabled || item.disabled" @change="item.change ? handleChange(item.prop):''" > <el-checkbox v-for="(opt,oindex) in item.options" :key="oindex" :label="opt[item['labelVal'] || 'value'] || opt['subCode']" > {{ $t(`${opt[item['labelName'] || 'label'] || opt['subName']}`) }} </el-checkbox> </el-checkbox-group> <!-- switch --> <el-switch v-if="item.type === 'label_switch'" v-model="formData[item.prop]" :active-value="item.activeValue" :inactive-value="item.inactiveValue" :active-text="$t(item.activeText)" :inactive-text="$t(item.inactiveText)" :active-color="item.activeColor" :inactive-color="item.inactiveColor" :disabled="block.disabled || item.disabled" @change="item.change?handleChange(item.prop):''" /> <!-- radio_group --> <el-radio-group v-if="item.type === 'label_radio_group'" v-model="formData[item.prop]" :disabled="block.disabled || item.disabled" @change="item.change ? handleChange(item.prop):''" > <el-radio v-for="(opt,oindex) in item.options" :key="oindex" :label="opt[item['labelVal'] || 'value'] || opt['subCode']" > {{ $t(`${opt[item['labelName'] || 'label'] || opt['subName']}`) }} </el-radio> </el-radio-group> <!-- upload_img --> <upload-img v-if="item.type === 'label_upload_img'" :fixed-number="item.fixedNumber" :output-type="item.outputType" :auto-crop-width="item.autoCropWidth" :auto-crop-height="item.autoCropHeight" :images="formData[item.prop]" @handleUpload="(val) => { $set(formData,item.prop, val); clearValidate(item.prop); item.handleUpload ? item.handleUpload(val) : ''; }" /> <!-- slot --> <template v-if="item.type === 'slot'"> <slot :name="'form-' + item.prop" /> </template> </el-form-item> </el-col> </template> </el-row> <!-- 表格 --> <div v-if="block.tableColumn"> <el-button v-if="block.tableOption.addBtnVisible" size="mini" type="primary" class="con-margin-b con-margin-t" @click="block.tableOption.onAddTableLine()" > {{ $t('添加') }} </el-button> <el-table :data="formData[block.tableOption.tableKey]" :height="block.tableOption.tableHeight" border class="con-margin-b" style="width: 100%;" > <template v-for="(tableItem,tableIndex) in block.tableColumn"> <!-- 不带分页序号列 --> <el-table-column v-if="tableItem.prop === 'ids'" :key="tableItem.prop" :prop="tableItem.prop" :label="$t(`${tableItem.label || '序号'}`)" :fixed="tableItem.fixed || 'left'" type="index" width="50" /> <el-table-column v-if="tableItem.prop !== 'ids' && !tableItem.hide" :key="tableIndex" :label="tableItem.label" :width="tableItem.width" :fixed="tableItem.fixed" > <template slot-scope="scope"> <!-- input --> <el-input v-if="tableItem.type === 'label_input'" :ref="`table_${tableItem.prop}_${scope.$index}`" v-model="scope.row[tableItem.prop]" :placeholder="tableItem.placeholder ? $t(`${tableItem.placeholder}`):$t('请输入')" :clearable="tableItem.clearable || true" :disabled="tableItem.disabled" @blur="tableItem.handleBlur?tableItem.handleBlur(scope.row[tableItem.prop], scope): ''" @clear="tableItem.handleClear ? tableItem.handleClear(scope.row[tableItem.prop], scope) : ''" /> <!-- input_number --> <el-input-number v-else-if="tableItem.type === 'label_input_number'" :ref="`table_${tableItem.prop}_${scope.$index}`" v-model="scope.row[tableItem.prop]" :precision="tableItem.precision" :step="tableItem.step" :disabled="tableItem.disabled" :max="tableItem.max" :min="tableItem.min || 0" :controls="tableItem.controls" :controls-position="tableItem.controlsPosition || 'right'" :placeholder="tableItem.placeholder ? $t(`${tableItem.placeholder}`):$t('请输入')" :clearable="tableItem.clearable || true" @blur="tableItem.handleBlur?tableItem.handleBlur(scope.row[tableItem.prop], scope): ''" /> <!-- input_clearable --> <input-clearable v-else-if="tableItem.type === 'label_input_clearable'" :ref="`table_${tableItem.prop}_${scope.$index}`" v-model="scope.row[tableItem.prop]" :disabled="tableItem.disabled" :placeholder="tableItem.placeholder ? $t(`${tableItem.placeholder}`):$t('请输入')" @clear="tableItem.handleClear ? tableItem.handleClear(scope.row[tableItem.prop], scope) : ''" @click="tableItem.handleClick ? tableItem.handleClick(scope.row[tableItem.prop], scope) : ''" /> <!-- select --> <el-select v-else-if="tableItem.type === 'label_select'" :ref="`table_${tableItem.prop}_${scope.$index}`" v-model="scope.row[tableItem.prop]" :placeholder="tableItem.placeholder ? $t(`${tableItem.placeholder}`):$t('请输入')" :clearable="tableItem.clearable || true" :filterable="tableItem.filterable || true" :disabled="tableItem.disabled" @change="tableItem.handleChange?tableItem.handleChange(scope.row[tableItem.prop], scope): ''" > <el-option v-for="(opt,oindex) in tableItem.options" :key="oindex" :label="$t(`${opt[tableItem['labelName'] || 'label'] || opt['subName']}`)" :value="opt[tableItem['labelVal'] || 'value'] || opt['subCode']" /> </el-select> <!-- 格式化列 --> <template v-else-if="tableItem.formatter"> <span v-html="tableItem.formatter(scope.row, tableItem)" /> </template> <!-- render自定义列 --> <template v-else-if="tableItem.render"> <expand-dom :column="tableItem" :row="scope.row" :render="tableItem.render" :row-index="scope.$index" :index="tableIndex" /> </template> <template v-else> <span>{{ scope.row[tableItem.prop] }}</span> </template> </template> </el-table-column> </template> </el-table> </div> </div> </div> <div v-if="btnGroupVisible" class="operate"> <el-button v-if="cancelBtnVisible" size="small" @click="handleCancel">{{ $t('取消') }}</el-button> <el-button v-if="resetBtnVisible" type="primary" plain size="small" @click="handleReset">{{ $t('重置') }}</el-button> <el-button v-if="saveBtnVisible" type="primary" size="small" :loading="saveBtnLoading" @click="handleSave()">{{ $t(options.saveBtnText ? options.saveBtnText : '保存') }}</el-button> </div> </el-form> </div> </template> <script> import uploadImg from '@/components/uploadImg' export default { name: 'MyForm', // 组件 components: { expandDom: { functional: true, props: { row: Object, render: Function, index: Number, rowIndex: Number, column: { type: Object, default: null } }, render: (h, ctx) => { const params = { row: ctx.props.row, index: ctx.props.index, rowIndex: ctx.props.rowIndex, props: ctx.props } if (ctx.props.column) params.column = ctx.props.column return ctx.props.render(h, params) } }, uploadImg }, props: { // 控制选项 options: { type: Object, default: () => { return { // 是否滚动表单区域 isScroller: false, // 滚动区域的高度 scrollHeight: '', // 滚动区域最大的高度 scrollMaxHeight: '', // label位置(默认上方对齐) labelPosition: 'top', // label宽度(默认100px) labelWidth: '100px', // 响应式布局 xl: 6, lg: 8, md: 8, sm: 12, saveBtnText: '保存' } } }, loading: { type: Boolean, default: false }, // form表单数据 formData: { type: Object, default: () => { return {} } }, // 表单校验规则 rule: { type: Object, default: () => { return {} } }, // 表单列 column: { type: Array, default: () => { return [] } }, // 禁用整个表单(默认不禁用) disabled: { type: Boolean, default: false }, // 每一项高度 formItemHeight: { type: String, // default: '60px' default: '' }, // 按钮栏 // 是否显示(默认显示) btnGroupVisible: { type: Boolean, default: true }, // 是否取消按钮(默认显示) cancelBtnVisible: { type: Boolean, default: true }, // 是否保存按钮(默认隐藏) resetBtnVisible: { type: Boolean, default: false }, // 是否保存按钮(默认显示) saveBtnVisible: { type: Boolean, default: true }, // 保存loading状态 saveBtnLoading: { type: Boolean, default: false } }, data() { return { langRule: {} } }, created() { this.getLangRule() }, methods: { // 校验规则多语言处理 getLangRule() { const ruleObj = {} if (this.rule) { Object.keys(this.rule).forEach((key) => { let obj if (this.rule[key] instanceof Array) { obj = this.rule[key].map(it => ({ ...it, message: it.message ? this.$i18n.tc(it.message) : '' })) } else { obj = { ...this.rule[key], message: this.rule[key].message ? this.$i18n.tc(this.rule[key].message) : '' } } ruleObj[key] = obj }) this.langRule = ruleObj } }, // change事件 handleChange(prop) { this.$emit('handleChange', prop, this.formData[prop]) }, // clear事件 handleClear(prop) { this.$emit('handleClear', prop, this.formData[prop]) }, // blur事件 handleBlur(prop) { this.$emit('handleBlur', prop, this.formData[prop]) }, // 取消 handleCancel() { this.$emit('handleCancel') }, // 重置 handleReset() { this.$refs.form.resetFields() this.$emit('handleReset') }, // 保存 handleSave() { this.$refs['form'].validate((valid, object) => { if (valid) { this.$emit('handleSave') } else { this.scrollView(object) } }) }, // 滚动到固定地方 scrollView(object) { for (const i in object) { let dom = this.$refs[i] // 这里是针对遍历的情况(多个输入框),取值为数组 if (Object.prototype.toString.call(dom) !== '[object Object]') { dom = dom[0] } // 第一种方法(包含动画效果) dom.$el.scrollIntoView({ // 滚动到指定节点 // 值有start,center,end,nearest,当前显示在视图区域中间 block: 'center', // 值有auto、instant,smooth,缓动动画(当前是慢速的) behavior: 'smooth' }) break // 因为我们只需要检测一项,所以就可以跳出循环了 } }, // 清除校验信息 clearValidate(props) { this.$refs.form.clearValidate(props) } } } </script> <style lang="scss"> #my_form { background: white; padding-bottom: 40px; .el-cascader, .el-date-editor, .el-input-number, .el-select { width: 100%; } .el-input-number .el-input__inner { text-align: left; } .el-form-item__label{ width: 100%; text-align: left; } .el-form--label-top .el-form-item__label { padding-bottom: 0; } .el-form-item--mini.el-form-item { margin-bottom: 0; min-height: 58px; } .formUpload { display: flex; flex-wrap: nowrap; box-sizing: border-box; .el-input { width: auto; } .operateBtn { margin-left: 10px; } } .operate { display: flex; justify-content: center; position: absolute; width: 100%; bottom: 0; padding: 10px 0; background-color: #ffffff; left: 0; } .imgReview{ width: 100%; } .block { position: relative; margin-bottom: 15px; &.border { border: 1px dashed #d2d6de; padding: 20px 20px 10px; margin-bottom: 20px; } .header { position: absolute; background-color: #ffffff; z-index: 10; top: -26px; left: 10px; font-size: 15px; padding: 0 10px 5px; color: #333; } } .right-btn { position: absolute; right: 20px; top: 0; } .form-scroller { overflow-y: auto; overflow-x: hidden; padding-top: 10px; position: relative; padding-right: 5px; &::-webkit-scrollbar{ width:5px; background-color:transparent; } &::-webkit-scrollbar-thumb{ background:#ddd; } } .el-table th { background-color: #eff3f8; border-bottom: 1px solid #ccc; } .el-table--border td, .el-table--border th, .el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed { border-color: #e4e8f3; } .el-input-number.is-controls-right .el-input__inner{ padding-right: 0; } .el-col{ margin-bottom: 8px !important; } } </style>
from naff import listen from naff.api.events import RawGatewayEvent from extensions.template import Template class GuildMonitor(Template): def __init__(self, bot): self.known_fields = [ "id", "name", "icon", "icon_hash", "splash", "discovery_splash", "owner", "owner_id", "permissions", "region", "afk_channel_id", "afk_timeout", "widget_enabled", "widget_channel_id", "verification_level", "default_message_notifications", "explicit_content_filter", "roles", "emojis", "features", "mfa_level", "application_id", "system_channel_id", "system_channel_flags", "rules_channel_id", "max_presences", "max_members", "vanity_url_code", "description", "banner", "premium_tier", "premium_subscription_count", "preferred_locale", "public_updates_channel_id", "max_video_channel_users", "approximate_member_count", "approximate_presence_count", "welcome_screen", "nsfw_level", "stickers", "premium_progress_bar_enabled", "joined_at", "large", "unavailable", "member_count", "voice_states", "members", "channels", "threads", "presences", "stage_instances", "guild_scheduled_events", ] @listen() async def on_raw_guild_create(self, event: RawGatewayEvent): await self.dict_parser(event.data) @listen() async def on_raw_guild_update(self, event: RawGatewayEvent): await self.dict_parser(event.data) @listen() async def on_raw_guild_delete(self, event: RawGatewayEvent): await self.dict_parser(event.data) async def dict_parser(self, data: dict): new_fields = [k for k in data if k not in self.known_fields] if new_fields: await self.update_fields(new_fields) self.log.warning(f"New fields in guild: {new_fields}") return await self.bot.report_new_feature( f"New fields detected in guild object", data, new_fields=new_fields ) def setup(bot): GuildMonitor(bot)
#include <iostream> using namespace std; void PrintMessage(string message); template <typename T> void PrintMessage(string message, T number); template <typename T, typename... Args> T Add(T first, Args... args); template <typename T> T Add(T v); int main() { // func call int i = Add(1); float f = Add(3.3f, 6.6f, 15.5f, 88.3f); double d = Add(4.4, 2.4); PrintMessage("Testing Overloaded Functions:"); PrintMessage("Integer Add = ", i); PrintMessage("Float add = ", f); PrintMessage("Double add = ", d); } void PrintMessage(string message) { cout << message << endl; } template <typename T> void PrintMessage(string message, T number) { cout << message << number << endl; } template <typename T, typename... Args> T Add(T first, Args... args) { return first + Add(args...); } template <typename T> T Add(T v) { return v; }
import VectorLayer from 'ol/layer/Vector'; import VectorSource, { Options as VectorSourceOptions } from 'ol/source/Vector'; import { Feature } from 'ol'; import { Circle, LineString, Point, Polygon } from 'ol/geom'; import { Coordinate } from 'ol/coordinate'; import { Fill, Stroke, Style, Icon } from 'ol/style'; import { Options as VectorLayerOptions } from 'ol/layer/BaseVector'; import { asArray, asString } from 'ol/color'; import { api } from '@/app'; import { EVENT_NAMES } from '@/api/events/event-types'; import { generateId, setAlphaColor } from '@/core/utils/utilities'; import { payloadIsACircleConfig, payloadIsAMarkerConfig, payloadIsAPolygonConfig, payloadIsAPolylineConfig, payloadIsAGeometryConfig, GeometryPayload, } from '@/api/events/payloads'; import { TypeFeatureCircleStyle, TypeFeatureStyle, TypeIconStyle } from './geometry-types'; /** * Store a group of features */ interface FeatureCollection { geometryGroupId: string; vectorLayer: VectorLayer<VectorSource>; vectorSource: VectorSource; } /** * Class used to manage vector geometries (Polyline, Polygon, Circle, Marker...) * * @exports * @class Geometry */ export class Geometry { // reference to the map id #mapId: string; // used to store geometry groups geometryGroups: FeatureCollection[] = []; // contains all the added geometries geometries: Feature[] = []; // default geometry group name defaultGeometryGroupId = 'defaultGeomGroup'; // index of the active geometry group used to add new geometries in the map activeGeometryGroupIndex = 0; /** * Initialize map, vectors, and listen to add geometry events * * @param {string} mapId map id */ constructor(mapId: string) { this.#mapId = mapId; // create default geometry group this.createGeometryGroup(this.defaultGeometryGroupId); // listen to add geometry events api.event.on( EVENT_NAMES.GEOMETRY.EVENT_GEOMETRY_ADD, (payload) => { if (payloadIsACircleConfig(payload)) { this.addCircle(payload.coordintate, payload.options, payload.id); } else if (payloadIsAPolygonConfig(payload)) { this.addPolygon(payload.points, payload.options, payload.id); } else if (payloadIsAPolylineConfig(payload)) { this.addPolyline(payload.points, payload.options, payload.id); } else if (payloadIsAMarkerConfig(payload)) { this.addMarkerIcon(payload.coordinate, payload.options, payload.id); } }, this.#mapId ); // listen to outside events to remove geometries api.event.on( EVENT_NAMES.GEOMETRY.EVENT_GEOMETRY_REMOVE, (payload) => { if (payloadIsAGeometryConfig(payload)) { // remove geometry from outside this.deleteGeometry(payload.id!); } }, this.#mapId ); // listen to outside events to turn on geometry groups api.event.on( EVENT_NAMES.GEOMETRY.EVENT_GEOMETRY_ON, () => { this.setGeometryGroupAsVisible(); }, this.#mapId ); // listen to outside events to turn off geometry groups api.event.on( EVENT_NAMES.GEOMETRY.EVENT_GEOMETRY_OFF, () => { this.setGeometryGroupAsInvisible(); }, this.#mapId ); } /** * Create a polyline using an array of lng/lat points * * @param {Coordinate} points points of lng/lat to draw a polyline * @param options polyline options including styling * @param {string} id an optional id to be used to manage this geometry * * @returns {Feature} a geometry containing the id and the created geometry */ addPolyline = ( points: Coordinate, options?: { projection?: number; geometryLayout?: 'XY' | 'XYZ' | 'XYM' | 'XYZM'; style?: TypeFeatureStyle; }, id?: string ): Feature => { const polylineOptions = options || {}; const featureId = generateId(id); // create a line geometry const polyline = new Feature({ geometry: new LineString(points, polylineOptions.geometryLayout).transform( `EPSG:${options?.projection || 4326}`, api.projection.projections[api.maps[this.#mapId].currentProjection] ), }); // if style is provided then set override the vector layer style for this feature if (polylineOptions.style) { let fill: Fill | undefined; let stroke: Stroke | undefined; if (polylineOptions.style.fillColor) { fill = new Fill({ color: asString(setAlphaColor(asArray(polylineOptions.style.fillColor), polylineOptions.style.fillOpacity || 1)), }); } if (polylineOptions.style.strokeColor || polylineOptions.style.strokeOpacity || polylineOptions.style.strokeWidth) { stroke = new Stroke({ color: asString(setAlphaColor(asArray(polylineOptions.style.strokeColor || 'blue'), polylineOptions.style.strokeOpacity || 1)), width: polylineOptions.style.strokeWidth || 1, }); } polyline.setStyle( new Style({ fill, stroke, }) ); } // set a feature id and a geometry group index for this geometry polyline.set('featureId', featureId); polyline.set('GeometryGroupIndex', this.activeGeometryGroupIndex); // add geometry to feature collection this.geometryGroups[this.activeGeometryGroupIndex].vectorSource.addFeature(polyline); // add the geometry to the geometries array this.geometries.push(polyline); // emit an event that a polyline geometry has been added api.event.emit(GeometryPayload.forPolyline(EVENT_NAMES.GEOMETRY.EVENT_GEOMETRY_ADDED, this.#mapId, polyline)); return polyline; }; /** * Create a new polygon * * @param {Coordinate} points array of points to create the polygon * @param options polygon options including styling * @param {string} optionalFeatureId an optional id to be used to manage this geometry * * @returns {Feature} a geometry containing the id and the created geometry */ addPolygon = ( points: number[] | Coordinate[][], options?: { projection?: number; geometryLayout?: 'XY' | 'XYZ' | 'XYM' | 'XYZM'; style?: TypeFeatureStyle; }, optionalFeatureId?: string ): Feature => { const polygonOptions = options || {}; const featureId = generateId(optionalFeatureId); // create a line geometry const polygon = new Feature({ geometry: new Polygon(points, polygonOptions.geometryLayout).transform( `EPSG:${options?.projection || 4326}`, api.projection.projections[api.maps[this.#mapId].currentProjection] ), }); // if style is provided then set override the vector layer style for this feature if (polygonOptions.style) { let fill: Fill | undefined; let stroke: Stroke | undefined; if (polygonOptions.style.fillColor) { fill = new Fill({ color: asString(setAlphaColor(asArray(polygonOptions.style.fillColor), polygonOptions.style.fillOpacity || 1)), }); } if (polygonOptions.style.strokeColor || polygonOptions.style.strokeOpacity || polygonOptions.style.strokeWidth) { stroke = new Stroke({ color: asString(setAlphaColor(asArray(polygonOptions.style.strokeColor || 'blue'), polygonOptions.style.strokeOpacity || 1)), width: polygonOptions.style.strokeWidth || 1, }); } polygon.setStyle( new Style({ fill, stroke, }) ); } // set a feature id and a geometry group index for this geometry polygon.set('featureId', featureId); polygon.set('GeometryGroupIndex', this.activeGeometryGroupIndex); // add geometry to feature collection this.geometryGroups[this.activeGeometryGroupIndex].vectorSource.addFeature(polygon); // add the geometry to the geometries array this.geometries.push(polygon); // emit an event that a polygon geometry has been added api.event.emit(GeometryPayload.forPolygon(EVENT_NAMES.GEOMETRY.EVENT_GEOMETRY_ADDED, this.#mapId, polygon)); return polygon; }; /** * Create a new circle * * @param {Coordinate} coordinate long lat coordinate of the circle * @param options circle options including styling * @param {string} optionalFeatureId an optional id to be used to manage this geometry * * @returns {Feature} a geometry containing the id and the created geometry */ addCircle( coordinate: Coordinate, options?: { projection?: number; geometryLayout?: 'XY' | 'XYZ' | 'XYM' | 'XYZM'; style?: TypeFeatureCircleStyle; }, optionalFeatureId?: string ): Feature { const circleOptions = options || {}; const featureId = generateId(optionalFeatureId); // get radius, if not define, set default const radius = circleOptions.style !== undefined ? circleOptions.style.radius || 1 : 1; // create a line geometry const circle = new Feature({ geometry: new Circle(coordinate, radius, circleOptions.geometryLayout).transform( `EPSG:${options?.projection || 4326}`, api.projection.projections[api.maps[this.#mapId].currentProjection] ), }); // if style is provided then set override the vector layer style for this feature if (circleOptions.style) { let fill: Fill | undefined; let stroke: Stroke | undefined; if (circleOptions.style.fillColor) { fill = new Fill({ color: asString(setAlphaColor(asArray(circleOptions.style.fillColor), circleOptions.style.fillOpacity || 1)), }); } if (circleOptions.style.strokeColor || circleOptions.style.strokeOpacity || circleOptions.style.strokeWidth) { stroke = new Stroke({ color: asString(setAlphaColor(asArray(circleOptions.style.strokeColor || 'blue'), circleOptions.style.strokeOpacity || 1)), width: circleOptions.style.strokeWidth || 1, }); } circle.setStyle( new Style({ fill, stroke, }) ); } // set a feature id and a geometry group index for this geometry circle.set('featureId', featureId); circle.set('GeometryGroupIndex', this.activeGeometryGroupIndex); // add geometry to feature collection this.geometryGroups[this.activeGeometryGroupIndex].vectorSource.addFeature(circle); // add the geometry to the geometries array this.geometries.push(circle); // emit an event that a circle geometry has been added api.event.emit(GeometryPayload.forCircle(EVENT_NAMES.GEOMETRY.EVENT_GEOMETRY_ADDED, this.#mapId, circle)); return circle; } /** * Create a new marker icon * * @param {Coordinate} coordinate the long lat position of the marker * @param options marker options including styling * @param {string} optionalFeatureId an optional id to be used to manage this geometry * * @returns {Feature} a geometry containing the id and the created geometry */ addMarkerIcon = ( coordinate: Coordinate, options?: { projection?: number; geometryLayout?: 'XY' | 'XYZ' | 'XYM' | 'XYZM'; style?: TypeIconStyle; }, optionalFeatureId?: string ): Feature => { // Read the params and set defaults when needed const markerOptions = options || { style: { anchor: [0.5, 256], size: [256, 256], scale: 0.1, anchorXUnits: 'fraction', anchorYUnits: 'pixels', src: './img/Marker.png', }, }; const featureId = generateId(optionalFeatureId); // create a point feature const marker = new Feature({ geometry: new Point(coordinate, markerOptions.geometryLayout).transform( `EPSG:${options?.projection || 4326}`, api.projection.projections[api.maps[this.#mapId].currentProjection] ), }); marker.setStyle( new Style({ // eslint-disable-next-line @typescript-eslint/no-explicit-any image: new Icon(markerOptions.style as any), }) ); // set a feature id and a geometry group index for this geometry marker.set('featureId', featureId); marker.set('GeometryGroupIndex', this.activeGeometryGroupIndex); // add geometry to feature collection this.geometryGroups[this.activeGeometryGroupIndex].vectorSource.addFeature(marker); // add the geometry to the geometries array this.geometries.push(marker); // emit an event that a marker geometry has been added api.event.emit(GeometryPayload.forMarker(EVENT_NAMES.GEOMETRY.EVENT_GEOMETRY_ADDED, this.#mapId, marker)); return marker; }; /** * Find a feature using it's id * * @param {string} featureId the id of the feature to return * * @returns {Feature} a feature having the specified id */ getGeometry = (featureId: string): Feature => { return this.geometries.filter((layer) => layer.get('featureId') === featureId)[0]; }; /** * Delete a feature using the id and delete it from the groups and the map * * @param {string} featureId the id of the feature to delete */ deleteGeometry = (featureId: string): void => { for (let i = 0; i < this.geometries.length; i++) { if (this.geometries[i].get('featureId') === featureId) { this.deleteGeometryFromGroups(featureId); this.geometries[i].dispose(); this.geometries.splice(i, 1); break; } } }; /** * Create a new geometry group to manage multiple geometries at once * * @param {string} geometryGroupId the id of the group to use when managing this group * @param options an optional vector layer and vector source options * @returns {FeatureCollection} created geometry group */ createGeometryGroup( geometryGroupId: string, options?: { vectorLayerOptions?: VectorLayerOptions<VectorSource>; vectorSourceOptions?: VectorSourceOptions; } ): FeatureCollection { const geometryGroupOptions = options || {}; let geometryGroup = this.getGeometryGroup(geometryGroupId); if (!geometryGroup) { const vectorSource = new VectorSource(geometryGroupOptions.vectorSourceOptions); const vectorLayer = new VectorLayer({ ...geometryGroupOptions.vectorLayerOptions, source: vectorSource, }); geometryGroup = { geometryGroupId, vectorLayer, vectorSource, }; if (geometryGroup.vectorLayer.getVisible()) { api.maps[this.#mapId].map.addLayer(geometryGroup.vectorLayer); geometryGroup.vectorLayer.changed(); } this.geometryGroups.push(geometryGroup); } return geometryGroup; } /** * set the active geometry group (the geometry group used when adding geometries). * If id is not specified, use the default geometry group. * * @param {string} id optional the id of the group to set as active */ setActiveGeometryGroup = (id?: string): void => { // if group name not give, add to default group const geometryGroupId = id || this.defaultGeometryGroupId; for (let i = 0; i < this.geometryGroups.length; i++) { if (this.geometryGroups[i].geometryGroupId === geometryGroupId) { this.activeGeometryGroupIndex = i; break; } } }; /** * Get the active geometry group * * @returns {FeatureCollection} the active geometry group */ getActiveGeometryGroup = (): FeatureCollection => { return this.geometryGroups[this.activeGeometryGroupIndex]; }; /** * Get the geometry group by using the ID specified when the group was created * if geometryGroupid is not provided, return the active geometry group * * @param {string} geometryGroupId the id of the geometry group to return * * @returns the geomtry group */ getGeometryGroup(geometryGroupId?: string): FeatureCollection | undefined { if (geometryGroupId) { const geometryGroupIndex = this.geometryGroups.findIndex((theGeometryGroup) => theGeometryGroup.geometryGroupId === geometryGroupId); if (geometryGroupIndex === -1) return undefined; return this.geometryGroups[geometryGroupIndex]; } return this.geometryGroups[this.activeGeometryGroupIndex]; } /** * Find the groups that contain the geometry using it's id * * @param {string} featureId the id of the geometry * * @returns {FeatureCollection[]} the groups that contain the geometry */ getGeometryGroupsByFeatureId = (featureId: string): FeatureCollection[] => { const returnValue: FeatureCollection[] = []; for (let i = 0; i < this.geometryGroups.length; i++) { const geometries = this.geometryGroups[i].vectorLayer.getSource()?.getFeatures() || []; for (let j = 0; j < geometries.length; j++) { const geometry = geometries[j]; if (geometry.get('featureId') === featureId) returnValue.push(this.geometryGroups[i]); } } return returnValue; }; /** * Show the identified geometry group on the map * if geometryGroupId is not provided, use the active geometry group * * @param {string} geometryGroupId optional the id of the group to show on the map */ setGeometryGroupAsVisible = (geometryGroupId?: string): void => { const geometryGroup = this.getGeometryGroup(geometryGroupId)!; geometryGroup.vectorLayer.setVisible(true); geometryGroup.vectorLayer.changed(); }; /** * hide the identified geometry group from the map * if groupId is not provided, use the active geometry group * * @param {string} geometryGroupId optional the id of the group to show on the map */ setGeometryGroupAsInvisible = (geometryGroupId?: string): void => { const geometryGroup = this.getGeometryGroup(geometryGroupId)!; geometryGroup.vectorLayer.setVisible(false); geometryGroup.vectorLayer.changed(); }; /** * Add a new geometry to the group whose identifier is equal to geometryGroupId. * if geometryGroupId is not provided, use the active geometry group. If the * geometry group doesn't exist, create it. * * @param {Feature} geometry the geometry to be added to the group * @param {string} geometryGroupId optional id of the group to add the geometry to */ addToGeometryGroup = (geometry: Feature, geometryGroupId?: string): void => { let geometryGroup: FeatureCollection; if (geometryGroupId) { // create geometry group if it does not exist geometryGroup = this.createGeometryGroup(geometryGroupId); } else { geometryGroup = this.geometryGroups[this.activeGeometryGroupIndex]; } try { geometryGroup.vectorLayer.getSource()?.addFeature(geometry); geometryGroup.vectorLayer.changed(); } catch (error) { // eslint-disable-next-line no-console console.error(error); } }; /** * Find the groups that the feature exists in and delete the feature from those groups * * @param {string} featureId the geometry id */ deleteGeometryFromGroups = (featureId: string): void => { const geometry = this.getGeometry(featureId); for (let i = 0; i < this.geometryGroups.length; i++) { this.geometryGroups[i].vectorLayer .getSource() ?.getFeatures() .forEach((layerGeometry) => { if (geometry === layerGeometry) { this.geometryGroups[i].vectorLayer.getSource()?.removeFeature(geometry); } }); this.geometryGroups[i].vectorLayer.changed(); } }; /** * Delete a specific feature from a group using the feature id * If geometryGroupid is not provided, the active geometry group is used. * * @param {string} featureId the feature id to be deleted * @param {string} geometryGroupid optional group id */ deleteGeometryFromGroup = (featureId: string, geometryGroupid?: string): void => { const geometry = this.getGeometry(featureId); const geometryGroup = this.getGeometryGroup(geometryGroupid)!; geometryGroup.vectorLayer .getSource() ?.getFeatures() .forEach((layerGeometry) => { if (geometry === layerGeometry) { geometryGroup.vectorLayer.getSource()?.removeFeature(geometry); } }); geometryGroup.vectorLayer.changed(); }; /** * Delete all geometries from the geometry group but keep the group * If geometryGroupid is not provided, the active geometry group is used. * * @param {string} geometryGroupid optional group id * @returns {FeatureCollection} the group with empty layers */ deleteGeometriesFromGroup = (geometryGroupid?: string): FeatureCollection => { const geometryGroup = this.getGeometryGroup(geometryGroupid)!; geometryGroup.vectorLayer .getSource() ?.getFeatures() .forEach((geometry) => { geometryGroup.vectorLayer.getSource()?.removeFeature(geometry); }); geometryGroup.vectorLayer.changed(); return geometryGroup; }; /** * Delete a geometry group and all the geometries from the map. * If geometryGroupid is not provided, the active geometry group is used. * The default geometry group can't be deleted. * * @param {string} geometryGroupid optional id of the geometry group to delete */ deleteGeometryGroup = (geometryGroupid?: string): void => { const geometryGroup = this.deleteGeometriesFromGroup(geometryGroupid); if (geometryGroup.geometryGroupId !== this.defaultGeometryGroupId) { for (let i = 0; i < this.geometryGroups.length; i++) { if (this.geometryGroups[i].geometryGroupId === geometryGroup.geometryGroupId) { this.geometryGroups.splice(i, 1); } } } }; }
package com.example.madencigozlugu; import androidx.appcompat.app.AppCompatActivity; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { TextView mail_et; TextView password_et; Button giris_btn; String URL = "https://madencigozlugu.com.tr/api/loginServis.php?token=emre"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //------toolbar kaldırma getSupportActionBar().hide(); //---- mail_et = (TextView) findViewById(R.id.mail_et); password_et = (TextView) findViewById(R.id.password_et); giris_btn = (Button) findViewById(R.id.giris_btn); giris_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mail_et.getText().toString().matches("") || password_et.getText().toString().matches("")) { Toast.makeText(getApplicationContext(), "BOŞ BIRAKMAYINIZ!", Toast.LENGTH_LONG).show(); } else { //--------volley post (login) işlemi---------------- RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this); JSONObject postData = new JSONObject(); try { postData.put("umail", mail_et.getText().toString()); postData.put("usifre", password_et.getText().toString()); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, postData, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { boolean giris = response.getBoolean("success"); // burası api de tanımlanan success=true if (giris == true) { JSONArray arrayJson = response.getJSONArray("Uyeler"); JSONObject bilgiler = arrayJson.getJSONObject(0); alt_menu.u_isim = bilgiler.getString("uisim"); alt_menu.u_tel = bilgiler.getString("utel"); alt_menu.u_mail = bilgiler.getString("umail"); alt_menu.u_sifre = bilgiler.getString("usifre"); alt_menu.u_id = bilgiler.getInt("uid"); alt_menu.u_sirket = bilgiler.getInt("usirket"); Toast.makeText(getApplicationContext(), "HOŞ GELDİNİZ SAYIN " + bilgiler.getString("uisim"), Toast.LENGTH_LONG).show(); Intent i = new Intent(MainActivity.this, blueToothAyar.class); startActivity(i); } else { Toast.makeText(getApplicationContext(), "HATALI GİRİŞ!", Toast.LENGTH_LONG).show(); } } catch (JSONException e) { throw new RuntimeException(e); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); Toast.makeText(getApplicationContext(), "BAĞLANTI HATASI!\nİnternetinizi Kontrol Edniz...", Toast.LENGTH_LONG).show(); } }); requestQueue.add(jsonObjectRequest); //------------------volley post bitimi------------ } }}); } }
package wails import ( "io" "log" "os" "strings" "time" "github.com/wailsapp/wails/v2/pkg/logger" ) // MultiLogger is a utility to log messages to a number of destinations type MultiLogger struct { filename string logFile *os.File multiWriter io.Writer } // NewMultiLogger creates a new Logger. func NewMultiLogger(filename string) logger.Logger { return &MultiLogger{ filename: filename, } } // Print works like Sprintf. func (l *MultiLogger) Print(message string) { if l.multiWriter == nil { f, err := os.OpenFile(l.filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { log.Fatalln("OpenFile Error:", err.Error()) log.Print(message) return } l.logFile = f l.multiWriter = io.MultiWriter(f, os.Stdout) } if _, err := l.multiWriter.Write([]byte(message)); err != nil { if strings.Contains(err.Error(), "write /dev/stdout: The handle is invalid") { l.multiWriter = l.logFile l.Print(message) return } log.Println(err.Error()) log.Println(message) return } } func (l *MultiLogger) Println(message string) { dataTime := time.Now().Format(time.DateTime) l.Print(dataTime + " | " + message + "\n") } // Trace level logging. Works like Sprintf. func (l *MultiLogger) Trace(message string) { l.Println("TRACE | " + message) } // Debug level logging. Works like Sprintf. func (l *MultiLogger) Debug(message string) { l.Println("DEBUG | " + message) } // Info level logging. Works like Sprintf. func (l *MultiLogger) Info(message string) { l.Println("INFO | " + message) } // Warning level logging. Works like Sprintf. func (l *MultiLogger) Warning(message string) { l.Println("WARN | " + message) } // Error level logging. Works like Sprintf. func (l *MultiLogger) Error(message string) { l.Println("ERROR | " + message) } // Fatal level logging. Works like Sprintf. func (l *MultiLogger) Fatal(message string) { l.Println("FATAL | " + message) os.Exit(1) }
# SPDX-FileCopyrightText: © 2022 Foundation Devices, Inc. <[email protected]> # SPDX-License-Identifier: GPL-3.0-or-later # # health_check_flow.py - Scan and process a health check QR code in `crypto-request` format from flows import Flow from pages import ErrorPage, SuccessPage from pages.show_qr_page import ShowQRPage from utils import validate_sign_text, spinner_task from tasks import sign_text_file_task from public_constants import AF_CLASSIC, RFC_SIGNATURE_TEMPLATE from data_codecs.qr_type import QRType from foundation import ur class HealthCheckQRFlow(Flow): def __init__(self, context=None): super().__init__(initial_state=self.scan_qr, name='HealthCheckQRFlow') self.service_name = context self.text = None self.subpath = None async def scan_qr(self): from pages import ErrorPage from flows import ScanQRFlow data_description = 'a {} health check'.format(self.service_name) result = await ScanQRFlow(qr_types=[QRType.UR2], ur_types=[ur.Value.BYTES], data_description=data_description).run() if result is None: self.set_result(False) return try: data = result.unwrap_bytes().decode('utf-8') lines = data.split('\n') if len(lines) != 2: await ErrorPage('Health check format is invalid.').show() self.set_result(False) return self.text = lines[0] self.subpath = lines[1] except Exception as e: await ErrorPage('Health check format is invalid.').show() self.set_result(False) return # Validate (subpath, error) = validate_sign_text(self.text, self.subpath) if error is not None: await ErrorPage(text=error).show() self.set_result(False) return self.subpath = subpath self.goto(self.sign_health_check) async def sign_health_check(self): (signature, address, error) = await spinner_task('Performing Health Check', sign_text_file_task, args=[self.text, self.subpath, AF_CLASSIC]) if error is None: self.signature = signature self.address = address self.goto(self.show_signed_message, save_curr=False) else: await ErrorPage(text='Error while signing file: {}'.format(error)).show() self.set_result(False) return async def show_signed_message(self): from ubinascii import b2a_base64 sig = b2a_base64(self.signature).decode('ascii').strip() signed_message = ur.new_bytes(RFC_SIGNATURE_TEMPLATE.format(addr=self.address, msg=self.text, blockchain='BITCOIN', sig=sig)) result = await ShowQRPage( qr_type=QRType.UR2, qr_data=signed_message, caption='Signed Health Check' ).show() if not result: self.back() else: self.set_result(True)
package com.joshuashields.helloworldapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { // used as a key to retrieve the message as an extra from the intent in the next activity public static final String EXTRA_MESSAGE = "com.joshuashields.helloworldapp.EXTRA_MESSAGE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void sendMessage(View view) { Intent intent = new Intent(this, DisplayMessageActivity.class); // explicitly cast View returned by findViewById to EditText subclass EditText editText = (EditText) findViewById(R.id.editText); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } }
import React, { useEffect, useState } from "react"; import { Chart } from "chart.js/auto"; import { useNavigate } from "react-router-dom"; function Dashboard() { const navigate = useNavigate(); const [username, setUsername] = useState('example'); const [user, setUser] = useState({}); const [repositories, setRepositories] = useState([]); const [followers, setFollowers] = useState(0); const [selectedRepo, setSelectedRepo] = useState(null); const [showPassword, setShowPassword] = useState(false); const [showConfirmPassword, setShowConfirmPassword] = useState(false); useEffect(() => { if (username.trim() === "") { // Display an alert if username is empty alert("Please enter a GitHub username."); return; // Stop further API requests } // Fetch user data and repositories from the GitHub API fetch(`https://api.github.com/users/${username}`) .then((response) => response.json()) .then((data) => { setUser(data); setFollowers(data.followers); }); fetch(`https://api.github.com/users/${username}/repos`) .then((response) => response.json()) .then((data) => setRepositories(data)); }, [username]); useEffect(() => { // Calculate the number of projects and forks const numProjects = repositories.filter((repo) => !repo.fork).length; const numForks = repositories.filter((repo) => repo.fork).length; // Create a chart to display project stats (Pie Chart) const projectStatsCtx = document.getElementById("projectStatsChart"); if (projectStatsCtx) { // Destroy the existing chart if it exists if (projectStatsCtx.chart) { projectStatsCtx.chart.destroy(); } projectStatsCtx.chart = new Chart(projectStatsCtx, { type: "pie", data: { labels: ["Projects", "Forks"], datasets: [ { data: [numProjects, numForks], backgroundColor: ["#36A2EB", "#FFCE56"], }, ], }, }); } // Create a chart to display repositories by year (Bar Chart) const repoByYearCtx = document.getElementById("repoByYearChart"); if (repoByYearCtx) { // Destroy the existing chart if it exists if (repoByYearCtx.chart) { repoByYearCtx.chart.destroy(); } // Extract and process data for the bar graph const repoYears = {}; repositories.forEach((repo) => { const year = new Date(repo.created_at).getFullYear(); if (repoYears[year]) { repoYears[year]++; } else { repoYears[year] = 1; } }); const years = Object.keys(repoYears); const repoCounts = years.map((year) => repoYears[year]); repoByYearCtx.chart = new Chart(repoByYearCtx, { type: "bar", data: { labels: years, datasets: [ { label: "Repositories", data: repoCounts, backgroundColor: "#4CAF50", }, ], }, }); } }, [repositories]); // Function to handle repository click const handleRepoClick = (repo) => { setSelectedRepo(repo); }; const handleLogout = () => { navigate('/'); } return ( <div className="main"> <div className="dashboard"> <header className="header"> <h1 className="dashboard-title">GitHub Dashboard</h1> <div className='buttonsignout'> <button className="btn btn-outline-success" style={{ marginLeft: '1000px' }} onClick={handleLogout}>Logout</button> </div> </header> <main className="content"> <div className="search-container"> <input type="text" placeholder="Search GitHub User" value={username} onChange={(e) => setUsername(e.target.value)} /> </div> {/* User Profile */} <aside className="profile"> <img className="profile-avatar" src={user.avatar_url} alt="User Avatar" /> <h3 className="profile-name">{user.login}</h3> <p className="profile-info">Followers: {followers}</p> {/* Add more user profile details here */} </aside> {/* Project Stats and Repositories by Year Charts */} <div style={{ display: 'flex', justifyContent: 'space-around' }}> <section className="chart"> <h2 className="section-title">Project Stats</h2> <div id="chartContainer" style={{ width: "200px", height: "200px" }}> <canvas id="projectStatsChart" style={{ width: "100%", height: "100%" }}></canvas> </div> </section> <section className="chart"> <h2 className="section-title">Repositories by Year</h2> <div id="repoChartsContainer" style={{ display: 'flex', width: '100%' }}> <div id="repoByYearContainer" style={{ width: "100%", height: "100%" }}> <canvas id="repoByYearChart" style={{ width: "100%", height: "100%" }} ></canvas> </div> </div> </section> </div> <section className="repositories"> <h2 className="section-title">Repositories</h2> <table className="table"> <thead> <tr> <th>Name</th> <th>Start Date</th> <th>End Date</th> </tr> </thead> <tbody> {repositories.map((repo) => ( <tr key={repo.id} onClick={() => handleRepoClick(repo)}> <td> <a href={repo.html_url} target="_blank" rel="noopener noreferrer" > {repo.name} </a> </td> <td> {new Date(repo.created_at).toLocaleDateString()} </td> <td>{new Date(repo.updated_at).toLocaleDateString()}</td> </tr> ))} </tbody> </table> </section> </main> <footer className="footer"> <p className="footer-text"> &copy; {new Date().getFullYear()} GitHub Dashboard </p> </footer> </div> </div> ); } export default Dashboard;
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html lang="pt"> <head> <%@ page contentType="text/html; charset=UTF-8" %> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> <script src="https://kit.fontawesome.com/0a1ada860a.js" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/dataTables.bootstrap5.min.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.js"></script> <script src="${pageContext.request.contextPath}/js/fun_tables.js"></script> <link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css"/> <title>Centro Hospitalar Upskill</title> </head> <body> <jsp:include page="sidebar.jsp"/> <div class="main"> <div class="profile-container"> <div class="page-title"> <h2><img src="/images_web/caminho.svg" alt=""><span class="title-logo">Detalhes de Perfil</span></h2> </div> <div class="profile-page"> <form action="/update-utente/${utente.getIdUtente()}" method="post" class="form-edit-patient"> <div class="personal-details-card"> <div class="personal-details-card-left"> <div class="personal-details-card-left-top"> <img src="https://www.placecage.com/150/150" alt="" class="avatar-utente"> <figcaption>${utente.getNome()}</figcaption> <p>${utente.getEmail()}</p> </div> <div class="personal-details-card-left-bottom"> <div class="personal-details-group"> <div class="personal-details-row personal-details-row-left"> <label>Data Nascimento</label> <p>${utente.getDataNascimento()}</p> </div> <div class="personal-details-row personal-details-row-right"> <label>Género</label> <p>${utente.getGenero()}</p> </div> </div> <div class="personal-details-group"> <div class="personal-details-row personal-details-row-left"> <label for="edit_phonenr">Telefone</label> <input type="text" id="edit_phonenr" name="telefone" value="${utente.getTelefone()}"> </div> <div class="personal-details-row personal-details-row-right"> <label for="edit_cellphonenr">Telemóvel</label> <input type="text" id="edit_cellphonenr" name="telemovel" value="${utente.getTelemovel()}"> </div> </div> </div> </div> <div class="personal-details-card-right"> <h4>Dados Adicionais</h4> <div class="personal-details-group"> <div class="personal-details-row personal-details-row-left"> <label>NIF</label> <p>${utente.getNif()}</p> </div> <div class="personal-details-row personal-details-row-right"> <label>Nº SNS</label> <p>${utente.getSns()}</p> </div> </div> <div class="personal-details-row"> <label for="edit_morada">Endereço</label><br> <textarea id="edit_morada" name="morada" rows="2">${utente.getMorada()}</textarea> </div> <div class="personal-details-group"> <div class="personal-details-row personal-details-row-left"> <label for="edit_postal-code">Código Postal</label><br> <input type="text" id="edit_postal-code" name="codigoPostal" value="${utente.getCodigoPostal()}"> </div> <div class="personal-details-row personal-details-row-right"> <label for="edit_locality">Localidade</label><br> <input type="text" id="edit_locality" name="localidade" value="${utente.getLocalidade()}"> </div> </div> </div> </div> <div class="personal-notes-card"> <label for="edit_notes">Notas</label><br> <textarea name="observacoes" id="edit_notes" rows="10">${utente.getObservacoes()}</textarea> <button type="submit" class="btn btn-editar-utente">Atualizar</button> </div> </form> </div> </div> </div> </body> </html>
# DIMO Token and Governance ## Documentation - [Dimo documentation](https://docs.dimo.zone/docs) The contracts are organized into different files by network and purpose: ``` 📦 contracts ┗ 📂 Mainnet ┗ 📂 DimoV1 ┗ 📜 Dimo.sol ┗ 📂 DimoV2 ┣ 📜 DimoV2.sol ┗ 📜 StorageV1.sol ┗ 📂 Mumbai ┣ 📜 Omid.sol ┗ 📜 OmidV2.sol ┗ 📂 Polygon ┗ 📂 ChildToken ┣ 📜 Dimo.sol ┗ 📜 DimoV2.sol ┗ 📂 TestDev ┗ 📜 TestDev.sol ┗ 📂 Governance ┣ 📜 DimoGovernorUpgradeable.sol ┗ 📜 TimeLockUpgradeable.sol ``` ## How to run You can execute the following commands to build the project and run additional scripts: ```sh # Installs dependencies npm i # Clears cache, compiles contracts and generates typechain files npm run build ``` ### Scripts You can deploy the contracts running the following scripts, where `network_name` is one of the networks available in [hardhat.config.ts](./hardhat.config.ts): ```sh # Deploys/upgrade token in the Mainnet npx hardhat run scripts/deployMainnetUpgrade.ts --network mainnet # Deploys/upgrade token in Polygon npx hardhat run scripts/deployPolygonDimoV2.ts --network polygon # Deploys/upgrade governance in Polygon npx hardhat run scripts/deployGovernance.ts --network polygon ``` You can also verify contracts in etherscan/polygonscan/etc running the following command. Remove `<constructor_arguments>` if there isn't any. ```sh npx hardhat verify '<deployed_contract_address>' '<constructor_arguments>' --network '<network_name>' # Use this flag to specify the contract implementation if needed npx hardhat verify '<deployed_contract_address>' '<constructor_arguments>' --network '<network_name>' --contract '<contract_path>:<contract_name>' ``` You can print the order in which inherited contracts are linearized: ```sh npx hardhat print-linearization contracts/../<ContractName>.sol:<ContractName> ``` ## Testing You can run the test suite with the following command: ```sh # Runs test suite npm run test ```
package com.rumakin.universityschedule.dto; import javax.validation.constraints.*; import com.rumakin.universityschedule.validation.annotation.*; import io.swagger.annotations.ApiModel; @UniqueBuildingName @UniqueBuildingAddress @ApiModel public class BuildingDto { private Integer id; @NotBlank(message = "{com.rumakin.universityschedule.validation.mandatory.name}") @Size(min = 2, max = 50, message = "{com.rumakin.universityschedule.validation.length.name}") @Pattern(regexp = "[A-Z][a-z]+(\\s[A-Z]*[a-z]+)*", message = "{com.rumakin.universityschedule.validation.illegal.buildingname}") private String name; @NotBlank(message = "{com.rumakin.universityschedule.validation.mandatory.building.address}") @Size(min = 2, max = 200, message = "{com.rumakin.universityschedule.validation.length.address}") @Pattern(regexp = "[A-Z][a-z]+(\\s[A-Z]*[a-z]+)*", message = "{com.rumakin.universityschedule.validation.illegal.buildingaddress}") private String address; public BuildingDto() { } public Integer getId() { return id; } public String getName() { return name; } public String getAddress() { return address; } public void setId(Integer id) { this.id = id; } public void setName(String name) { this.name = name; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "BuildingDto [id=" + id + ", name=" + name + ", address=" + address + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof BuildingDto)) return false; BuildingDto dto = (BuildingDto) obj; return getId().equals(dto.getId()); } }
import compression from 'compression' import cors from 'cors' import express, { Application } from 'express' import helmet from 'helmet' import { Server } from 'http' import morgan from 'morgan' import { AddressInfo } from 'net' import path from 'path' import { useExpressServer } from 'routing-controllers' import { inject, injectable } from 'tsyringe' import { IAppEnvironment, ILogger, IServer } from './@types' import DI_TYPES from './ioc/type' @injectable() export default class ExpressServerImpl implements IServer { public server: Server public app: Application constructor( @inject(DI_TYPES.APP_ENV) private readonly _env: IAppEnvironment, @inject(DI_TYPES.WINSTON_LOGGER) private readonly _logger: ILogger ) { this._configureExpressPipeline() this._configureServer() } start = (): Promise<void> => new Promise<void>((resolve) => { this.server = this.app.listen(this._env.port, () => { const { port } = this.server.address() as AddressInfo this._logger.info(`Application running at http://localhost:${port}/api`) return resolve() }) }) stop = (): Promise<void> => new Promise<void>((resolve) => { this.server.close() return resolve() }) private _configureServer = () => { useExpressServer(this.app, { controllers: [path.join(__dirname, 'controllers/**/*.controller.*')], middlewares: [path.join(__dirname, 'middlewares/**/*.middleware.*')], }) } private _configureExpressPipeline = () => { this.app = express() this.app .use(cors()) .use(helmet()) .use(compression()) .use(express.json()) .use(express.urlencoded({ extended: false })) .use( morgan('tiny', { skip: () => this._env.env !== 'development', stream: { write: (value) => this._logger.http(value) }, }) ) } }
#include <stdio.h> #include <stdlib.h> #include <time.h> // For seeding the random number generator void generateRandomMatrix(int rows, int cols, int matrix[rows][cols]) { // Generate random values for the matrix for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] = rand() % 100 +1; // Generate random values between 1 and 100 including 1 and 100... } } } void printMatrix(int rows, int cols, int matrix[rows][cols]) { //Function to print the matrix... for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%3d ", matrix[i][j]); } printf("\n"); } } int main() { int rows1,rows2,cols1,cols2; printf("Enter the number of rows of 1st matrix: "); scanf("%d",&rows1); printf("Enter the number of columns of 1st matrix: "); scanf("%d",&cols1); printf("Enter the number of rows of 2nd matrix: "); scanf("%d",&rows2); printf("Enter the number of columns of 2nd matrix: "); scanf("%d",&cols2); if(cols1!=rows2) { printf("Matrix Multiplication is not possible!"); return 0; } int matrix1[rows1][cols1]; int matrix2[rows2][cols2]; generateRandomMatrix(rows1, cols1, matrix1); srand(time(NULL)); // Seed the random number generator with the current time generateRandomMatrix(rows2, cols2, matrix2); printf("Matrix 1:\n"); printMatrix(rows1, cols1, matrix1); printf("\nMatrix 2:\n"); printMatrix(rows2, cols2, matrix2); return 0; }
import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from "@angular/common/http"; import {Observable} from "rxjs"; @Injectable({ providedIn: 'root' }) export class DataService { httOptions = { headers : new HttpHeaders({ 'Authorization': 'Basic ZGVtbzpkZW1vdXNlcg==' }) } //base de datos local public urlBuscador = "http://localhost:33333/contents/content?columns=content_name,content_id" public urlMejoresPeliculas = "http://localhost:33333/contents/bestMoviesRating?columns=content_name,content_id,content_poster_path,content_total_rating,content_total_vote,content_release_date" public urlMejoresSeries = "http://localhost:33333/contents/bestShowsRating?columns=content_name,content_id,content_poster_path,content_total_rating,content_total_vote,content_release_date" public urlUltimasPeliculas = "http://localhost:33333/contents/latestMovies?columns=content_name,content_id,content_poster_path,content_total_rating,content_total_vote,content_release_date" public urlUltimasSeries = "http://localhost:33333/contents/latestShows?columns=content_name,content_id,content_poster_path,content_total_rating,content_total_vote,content_release_date" public urlContentSearch = "http://localhost:33333/contents/content/search" public urlCastById = "http://localhost:33333/cast/cast/search" public urlCastByContId = "http://localhost:33333/cast/castByContentId/search" public urlGenres = "http://localhost:33333/genres/genres?columns=genre_id,genre_name" //Api externa public urlTheMovieDBlive = "https://api.themoviedb.org/3/movie/now_playing?api_key=1f14a389068de8968d5e828110abf4d7&language=es-Es&page=1" constructor(private http:HttpClient) { } getBuscador(): Observable<any[]>{ return this.http.get<any>(this.urlBuscador, this.httOptions) } getUltimasPeliculas() : Observable<any[]>{ const postBody = {"columns": [ "content_name","content_id","content_poster_path","content_total_rating","content_total_vote","content_plot","content_release_date" ] } return this.http.post<any>(this.urlUltimasPeliculas,postBody, this.httOptions); } getUltimasSeries() : Observable<any[]>{ const postBody = {"columns": [ "content_name","content_id","content_poster_path","content_total_rating","content_total_vote","content_plot","content_release_date" ] } return this.http.post<any>(this.urlUltimasSeries,postBody, this.httOptions); } getMejoresPeliculas() : Observable<any[]>{ const postBody = {"columns": [ "content_name","content_id","content_poster_path","content_total_rating", "content_total_vote","content_plot", "content_release_date" ] } return this.http.post<any>(this.urlMejoresPeliculas,postBody, this.httOptions); } getMejoresSeries() : Observable<any[]>{ const postBody = {"columns": [ "content_name","content_id","content_poster_path","content_total_rating","content_total_vote","content_plot","content_release_date" ] } return this.http.post<any>(this.urlMejoresSeries,postBody, this.httOptions); } getContByid(content_id : Number) : Observable<any[]>{ const postBody = { "filter": { "content_id": +content_id }, "columns": [ "content_name","content_id","content_poster_path","content_total_rating", "content_total_vote","content_plot", "content_release_date","content_trailer","content_nationality","content_type", "content_duration" ] } return this.http.post<any>(this.urlContentSearch,postBody, this.httOptions); } getCastById(cast_id : Number) : Observable<any[]>{ const postBody = { "filter": { "cast_id": +cast_id }, "columns": [ "cast_id","cast_name","cast_birth_date","cast_dead_date" ,"cast_birth_place","cast_nationality","cast_pic" ] } return this.http.post<any>(this.urlCastById,postBody, this.httOptions); } getCastByContId(content_id : Number) : Observable<any[]>{ const postBody = { "filter": { "content_id": +content_id }, "columns": [ "cast_name","cast_id" ] } return this.http.post<any>(this.urlCastByContId,postBody, this.httOptions); } getPeliculasLive(){ return this.http.get<any>(this.urlTheMovieDBlive) } getGenres(){ return this.http.get<any>(this.urlGenres, this.httOptions) } getContentByGenre(genre_id: Number){ const postBody = { "filter": { "genre_id": +genre_id }, "columns": [ "content_name","content_id","content_poster_path","content_total_rating", "content_total_vote","content_plot", "content_release_date","content_trailer","content_nationality","content_type", "content_duration" ] } return this.http.post<any>(this.urlContentSearch,postBody, this.httOptions); } }
package com.example.crudJava.Repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.example.crudJava.entities.Editora; public interface RepositorioEditora extends JpaRepository<Editora, Long> { /* RepositorioEditora é uma interface que estende JpaRepository, que é fornecida pelo Spring Data JPA. Essa interface fornece métodos de acesso aos dados do tipo Editora no banco de dados. Editora é o tipo de entidade com o qual essa interface está associada. Long especifica o tipo de dados do ID da entidade, que neste caso é Editora. Ou seja, os IDs das editoras são do tipo Long. Com essa interface, é possível ter acesso a métodos como save, findById, findAll, delete, entre outros, para realizar operações de CRUD no banco de dados associadas à entidade Editora. O Spring Data JPA implementa esses métodos automaticamente com base nas convenções de nomenclatura e mapeamento da entidade.*/ }
/** * @author Mireya Sánchez Pinzón * @author Alejandro Sánchez Monzón */ package es.dam.adp03_springmongodb.mappers import es.dam.adp03_springmongodb.dto.UsuarioAPIDTO import es.dam.adp03_springmongodb.models.TipoUsuario import es.dam.adp03_springmongodb.utils.cifrarPassword import es.dam.adp03_springmongodb.utils.randomUserType import org.bson.types.ObjectId import java.util.* import database.Usuario as UsuarioSQL import es.dam.adp03_springmongodb.models.Usuario as UsuarioModelo /** * Esta función de extensión del Usuario de la base de datos se ocupa de convertir los datos del objeto del fichero .sq a modelo para * pasar la información al sistema y de esta forma poder trabajar con él tanto en la base de datos de Mongo como en la caché. * * @return UsuarioModelo, el objeto convertido a Usuario modelo. */ fun UsuarioSQL.toModel(): UsuarioModelo { return UsuarioModelo( id = ObjectId(id.padStart(24, '0')), uuid = uuid, nombre = nombre, apellido = apellido, email = email, password = password, rol = TipoUsuario.valueOf(rol) ) } /** * Esta función de extensión del Usuario de la API REST se ocupa de convertir los datos del objeto procedente de la API a modelo para * pasar la información al sistema y de esta forma poder trabajar con él tanto en la base de datos de Mongo como en la caché. * * @return UsuarioModelo, el objeto convertido a Usuario modelo. */ fun UsuarioModelo.toUsuarioSQL(): UsuarioSQL { return UsuarioSQL( id = id.toString(), uuid = uuid, nombre = nombre, apellido = apellido, email = email, password = password, rol = rol.toString() ) } /** * Función de extensión que mapea el objeto Usuario al objeto UsuarioAPIDTO, el cual utilizamos para trabajar en la API. * * @return UsuarioAPIDTO, el objeto convertido del objeto Usuario. */ suspend fun UsuarioAPIDTO.toModelUsuario(): UsuarioModelo { return UsuarioModelo( id = ObjectId(id.padStart(24, '0')), uuid = UUID.randomUUID().toString(), nombre = name, apellido = username, email = email, password = cifrarPassword(username), rol = randomUserType() ) } fun UsuarioModelo.toUsuarioAPIDTO(): UsuarioAPIDTO { return UsuarioAPIDTO( id = id.toString(), address = null, company = null, name = nombre, username = apellido, email = email, phone = null, website = null ) }