text
stringlengths
1
1.05M
cat - | cut -f 2-
<filename>src/main/java/com/netcracker/ncstore/model/Company.java package com.netcracker.ncstore.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.Type; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.MapsId; import javax.persistence.OneToOne; import java.time.LocalDate; import java.util.UUID; /** * Class that defines company data of user of the system. * Used if user is a company, not an individual. */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Entity public class Company { @Id private UUID userId; private String companyName; @Lob @Type(type = "org.hibernate.type.TextType") private String description; private LocalDate foundationDate; @OneToOne @JoinColumn(name = "user_id") @MapsId private User user; public Company(String companyName, String description, LocalDate foundationDate, User user) { this.companyName = companyName; this.description = description; this.foundationDate = foundationDate; this.user = user; } }
import { graphqlHTTP } from 'express-graphql'; import { GraphQLSchema } from 'graphql'; import { createGraphQLSchema } from "openapi-to-graphql"; import { Singleton } from '../../injector'; import { AbstractGraphQlProvider } from './AbstractGraphQlProvider'; @Singleton() export class OpenApiToGraphQlProvider extends AbstractGraphQlProvider { public createGraphQlSchema = async (): Promise<GraphQLSchema> => { this.logger.info('Generating GraphQL Assets..'); const oas = require(this.getSwaggerSpecPath()); const result = await createGraphQLSchema(oas, {}); this.logger.debug('Finished. (Report:', JSON.stringify(result.report) + ')'); return result.schema; }; public useMiddleware = (schema: GraphQLSchema): void => { const { endpoint, graphiql } = this.config.get('graphQl'); this.logger.info(`GraphQL API Service enabled @ ${endpoint}`); this.server.use(endpoint, graphqlHTTP({ schema, graphiql })); }; private getSwaggerSpecPath = (): string => { return this.swagger.getPathToSpecFile(); }; }
TERMUX_PKG_HOMEPAGE=https://jfrog.com/getcli TERMUX_PKG_DESCRIPTION="A CLI for JFrog products." TERMUX_PKG_LICENSE="Apache-2.0" TERMUX_PKG_VERSION=1.39.1 TERMUX_PKG_SRCURL=https://github.com/jfrog/jfrog-cli/archive/v$TERMUX_PKG_VERSION.tar.gz TERMUX_PKG_SHA256=fc98becb6aa47a84427312caf2d698caef79a1dc258402bb9566594f32196125 TERMUX_PKG_DEPENDS="libc++" termux_step_make() { termux_setup_golang export GOPATH=$TERMUX_PKG_BUILDDIR cd $TERMUX_PKG_SRCDIR go build \ -o "$TERMUX_PREFIX/bin/jfrog" \ -tags "linux extended" \ main.go # "linux" tag should not be necessary # try removing when golang version is upgraded #Building for host to generate manpages and completion. chmod 700 -R $GOPATH/pkg && rm -rf $GOPATH/pkg unset GOOS GOARCH CGO_LDFLAGS unset CC CXX CFLAGS CXXFLAGS LDFLAGS go build \ -o "$TERMUX_PKG_BUILDDIR/jfrog" \ -tags "linux extended" \ main.go # "linux" tag should not be necessary # try removing when golang version is upgraded } termux_step_make_install() { mkdir -p $TERMUX_PREFIX/share/bash-completion/completions $TERMUX_PKG_BUILDDIR/jfrog completion bash cp ~/.jfrog/jfrog_bash_completion $TERMUX_PREFIX/share/bash-completion/completions/jfrog }
<reponame>ziaukhan/angular import { describe, beforeEach, it, expect, ddescribe, iit, SpyObject, el, proxy } from 'angular2/test_lib'; import {DOM} from 'angular2/src/dom/dom_adapter'; import {Content} from 'angular2/src/render/dom/shadow_dom/content_tag'; var _scriptStart = `<script start=""></script>`; export function main() { describe('Content', function() { var parent; var content; beforeEach(() => { parent = el(`<div>${_scriptStart}</div>`); let contentStartMarker = DOM.firstChild(parent); content = new Content(contentStartMarker, ''); }); it("should insert the nodes", () => { content.init(null); content.insert([el("<a>A</a>"), el("<b>B</b>")]); expect(parent).toHaveText('AB'); }); it("should remove the nodes from the previous insertion", () => { content.init(null); content.insert([el("<a>A</a>")]); content.insert([el("<b>B</b>")]); expect(parent).toHaveText('B'); }); it("should clear nodes on inserting an empty list", () => { content.init(null); content.insert([el("<a>A</a>")]); content.insert([]); expect(parent).toHaveText(''); }); }); }
<reponame>wl04/HackerRank-solutions import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class Result { // Solution public static List<Integer> gradingStudents(List<Integer> grades) { for (int i = 0; i < grades.size(); i++) { int curGr = grades.get(i); // Only grade above 38 modified if (curGr >= 38) { int nextMult = curGr; // Finding next multiple of 5 while (nextMult % 5 != 0){ nextMult++; } // If difference is less than 3 then round to multiple of 5 if (nextMult - curGr < 3) { grades.set(i, nextMult); } } } return grades; } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int gradesCount = Integer.parseInt(bufferedReader.readLine().trim()); List<Integer> grades = IntStream.range(0, gradesCount).mapToObj(i -> { try { return bufferedReader.readLine().replaceAll("\\s+$", ""); } catch (IOException ex) { throw new RuntimeException(ex); } }) .map(String::trim) .map(Integer::parseInt) .collect(toList()); List<Integer> result = Result.gradingStudents(grades); bufferedWriter.write( result.stream() .map(Object::toString) .collect(joining("\n")) + "\n" ); bufferedReader.close(); bufferedWriter.close(); } }
/** * Apple WebAuthn Root CA * * Downloaded from https://www.apple.com/certificateauthority/Apple_WebAuthn_Root_CA.pem * * Valid until 2045-03-14 @ 17:00 PST * * SHA256 Fingerprint * 09:15:DD:5C:07:A2:8D:B5:49:D1:F6:77:BB:5A:75:D4:BF:BE:95:61:A7:73:42:43:27:76:2E:9E:02:F9:BB:29 */ export const Apple_WebAuthn_Root_CA = `-----BEGIN CERTIFICATE----- <KEY> <KEY> <KEY> <KEY> <KEY> pcoRf7XkOtO4o1qlcaNCMEAwDwY<KEY> -----END CERTIFICATE----- `;
#!/bin/sh # first argument is the directory where everthing should be setup # cd ../TestMin/bugs/stan1308 cd $1 echo $pwd if [ ! -d "cmdstan-2.6.0" ]; then wget https://github.com/stan-dev/cmdstan/releases/download/v2.6.0/cmdstan-2.6.0.tar.gz tar -xf cmdstan-2.6.0.tar.gz fi cd cmdstan-2.6.0 make build if [ ! -d "stan1308" ]; then mkdir stan1308 fi # translate template to stan here=`realpath ../` echo $here (cd ../../../../translators/ && ./teststan.py -o $here/stan1308.template && cp stan1308.stan $here/stan1308.stan && cp stan1308.data.R $here/stan1308.data.R) if [ $? -ne 0 ]; then echo "Translate failed" echo "Failed" exit 2 fi echo $pwd diff ../stan1308.stan stan1308/stan1308.stan #if [ $? -ne 0 ]; then cp ../*.R ../*.stan stan1308/ #fi pwd echo "making..." rm -f stan1308/stan1308 make stan1308/stan1308 cd ./stan1308/ pwd START=$(date +%N) ./stan1308 diagnose data file=stan1308.data.R random seed=5 > stanout 2>&1 nans=`grep -wi "\-nan" stanout | wc -l` if [ $nans -gt 0 ]; then echo "Passed" else echo "Failed" fi
x = 5 y = 10 sum = x + y console.log sum # Output: 15
import click from py42.clients.trustedactivities import TrustedActivityType from code42cli.bulk import generate_template_cmd_factory from code42cli.bulk import run_bulk_process from code42cli.click_ext.groups import OrderedGroup from code42cli.errors import Code42CLIError from code42cli.file_readers import read_csv_arg from code42cli.options import format_option from code42cli.options import sdk_options from code42cli.output_formats import OutputFormatter resource_id_arg = click.argument("resource-id", type=int) type_option = click.option( "--type", help=f"Type of trusted activity. Valid types include {', '.join(TrustedActivityType.choices())}.", type=click.Choice(TrustedActivityType.choices()), ) value_option = click.option( "--value", help="The value of the trusted activity, such as the domain or Slack workspace name.", ) description_option = click.option( "--description", help="The description of the trusted activity." ) def _get_trust_header(): return { "resourceId": "Resource Id", "type": "Type", "value": "Value", "description": "Description", "updatedAt": "Last Update Time", "updatedByUsername": "Last Updated By (Username)", "updatedByUserUid": "Last updated By (UserUID)", } @click.group(cls=OrderedGroup) @sdk_options(hidden=True) def trusted_activities(state): """Manage trusted activities and resources.""" pass @trusted_activities.command() @click.argument("type", type=click.Choice(TrustedActivityType.choices())) @click.argument("value") @description_option @sdk_options() def create(state, type, value, description): """Create a trusted activity. VALUE is the name of the domain or Slack workspace. """ state.sdk.trustedactivities.create( type, value, description=description, ) @trusted_activities.command() @resource_id_arg @value_option @description_option @sdk_options() def update(state, resource_id, value, description): """Update a trusted activity. Requires the activity's resource ID.""" state.sdk.trustedactivities.update( resource_id, value=value, description=description, ) @trusted_activities.command() @resource_id_arg @sdk_options() def remove(state, resource_id): """Remove a trusted activity. Requires the activity's resource ID.""" state.sdk.trustedactivities.delete(resource_id) @trusted_activities.command("list") @click.option("--type", type=click.Choice(TrustedActivityType.choices())) @format_option @sdk_options() def _list(state, type, format): """List all trusted activities.""" pages = state.sdk.trustedactivities.get_all(type=type) formatter = OutputFormatter(format, _get_trust_header()) trusted_resources = [ resource for page in pages for resource in page["trustResources"] ] if trusted_resources: formatter.echo_formatted_list(trusted_resources) else: click.echo("No trusted activities found.") @trusted_activities.group(cls=OrderedGroup) @sdk_options(hidden=True) def bulk(state): """Tools for executing bulk trusted activity actions.""" pass TRUST_CREATE_HEADERS = [ "type", "value", "description", ] TRUST_UPDATE_HEADERS = [ "resource_id", "value", "description", ] TRUST_REMOVE_HEADERS = [ "resource_id", ] trusted_activities_generate_template = generate_template_cmd_factory( group_name="trusted_activities", commands_dict={ "create": TRUST_CREATE_HEADERS, "update": TRUST_UPDATE_HEADERS, "remove": TRUST_REMOVE_HEADERS, }, help_message="Generate the CSV template needed for bulk trusted-activities commands", ) bulk.add_command(trusted_activities_generate_template) @bulk.command( name="create", help="Bulk create trusted activities using a CSV file with " f"format: {','.join(TRUST_CREATE_HEADERS)}.\b\n\n" f"Available `type` values are: {'|'.join(TrustedActivityType.choices())}", ) @read_csv_arg(headers=TRUST_CREATE_HEADERS) @sdk_options() def bulk_create(state, csv_rows): """Bulk create trusted activities.""" sdk = state.sdk def handle_row(type, value, description): if type not in TrustedActivityType.choices(): message = f"Invalid type {type}, valid types include {', '.join(TrustedActivityType.choices())}." raise Code42CLIError(message) if type is None: message = "'type' is a required field to create a trusted activity." raise Code42CLIError(message) if value is None: message = "'value' is a required field to create a trusted activity." raise Code42CLIError(message) sdk.trustedactivities.create(type, value, description) run_bulk_process( handle_row, csv_rows, progress_label="Creating trusting activities:", ) @bulk.command( name="update", help="Bulk update trusted activities using a CSV file with " f"format: {','.join(TRUST_UPDATE_HEADERS)}.", ) @read_csv_arg(headers=TRUST_UPDATE_HEADERS) @sdk_options() def bulk_update(state, csv_rows): """Bulk update trusted activities.""" sdk = state.sdk def handle_row(resource_id, value, description): if resource_id is None: message = "'resource_id' is a required field to update a trusted activity." raise Code42CLIError(message) _check_resource_id_type(resource_id) sdk.trustedactivities.update(resource_id, value, description) run_bulk_process( handle_row, csv_rows, progress_label="Updating trusted activities:" ) @bulk.command( name="remove", help="Bulk remove trusted activities using a CSV file with " f"format: {','.join(TRUST_REMOVE_HEADERS)}.", ) @read_csv_arg(headers=TRUST_REMOVE_HEADERS) @sdk_options() def bulk_remove(state, csv_rows): """Bulk remove trusted activities.""" sdk = state.sdk def handle_row(resource_id): if resource_id is None: message = "'resource_id' is a required field to remove a trusted activity." raise Code42CLIError(message) _check_resource_id_type(resource_id) sdk.trustedactivities.delete(resource_id) run_bulk_process( handle_row, csv_rows, progress_label="Removing trusted activities:", ) def _check_resource_id_type(resource_id): def raise_error(resource_id): message = f"Invalid resource ID {resource_id}. Must be an integer." raise Code42CLIError(message) try: if not float(resource_id).is_integer(): raise_error(resource_id) except ValueError: raise_error(resource_id)
#!/bin/bash -eu ./configure make -j$(nproc) clean make -j$(nproc) all # Do not make check as there are tests that fail when compiled with MSAN. # make -j$(nproc) check $CXX $CXXFLAGS -std=c++11 -I. \ $SRC/zlib_uncompress_fuzzer.cc -o $OUT/zlib_uncompress_fuzzer \ $LIB_FUZZING_ENGINE ./libz.a zip $OUT/seed_corpus.zip *.* for f in $(find $SRC -name '*_fuzzer.c'); do b=$(basename -s .c $f) $CC $CFLAGS -I. $f -c -o /tmp/$b.o $CXX $CXXFLAGS -o $OUT/$b /tmp/$b.o -stdlib=libc++ $LIB_FUZZING_ENGINE ./libz.a rm -f /tmp/$b.o ln -sf $OUT/seed_corpus.zip $OUT/${b}_seed_corpus.zip done
package binding_constructors import "github.com/kurtosis-tech/kurtosis-client/golang/kurtosis_core_rpc_api_bindings" // The generated bindings don't come with constructors (leaving it up to the user to initialize all the fields), so we // add them so that our code is safer // ============================================================================================== // Load Module // ============================================================================================== func NewLoadModuleArgs(moduleId string, containerImage string, serializedParams string) *kurtosis_core_rpc_api_bindings.LoadModuleArgs { return &kurtosis_core_rpc_api_bindings.LoadModuleArgs{ ModuleId: moduleId, ContainerImage: containerImage, SerializedParams: serializedParams, } } // ============================================================================================== // Unload Module // ============================================================================================== func NewUnloadModuleArgs(moduleId string) *kurtosis_core_rpc_api_bindings.UnloadModuleArgs { return &kurtosis_core_rpc_api_bindings.UnloadModuleArgs{ ModuleId: moduleId, } } // ============================================================================================== // Execute Module // ============================================================================================== func NewExecuteModuleArgs(moduleId string, serializedParams string) *kurtosis_core_rpc_api_bindings.ExecuteModuleArgs { return &kurtosis_core_rpc_api_bindings.ExecuteModuleArgs{ ModuleId: moduleId, SerializedParams: serializedParams, } } func NewExecuteModuleResponse(serializedResult string) *kurtosis_core_rpc_api_bindings.ExecuteModuleResponse { return &kurtosis_core_rpc_api_bindings.ExecuteModuleResponse{ SerializedResult: serializedResult, } } // ============================================================================================== // Get Module Info // ============================================================================================== func NewGetModuleInfoArgs(moduleId string) *kurtosis_core_rpc_api_bindings.GetModuleInfoArgs { return &kurtosis_core_rpc_api_bindings.GetModuleInfoArgs{ ModuleId: moduleId, } } func NewGetModuleInfoResponse(ipAddr string) *kurtosis_core_rpc_api_bindings.GetModuleInfoResponse { return &kurtosis_core_rpc_api_bindings.GetModuleInfoResponse{ IpAddr: ipAddr, } } // ============================================================================================== // Register Files Artifacts // ============================================================================================== func NewRegisterFilesArtifactArgs(filesArtifactUrls map[string]string) *kurtosis_core_rpc_api_bindings.RegisterFilesArtifactsArgs { return &kurtosis_core_rpc_api_bindings.RegisterFilesArtifactsArgs{ FilesArtifactUrls: filesArtifactUrls, } } // ============================================================================================== // Register Service // ============================================================================================== func NewRegisterServiceArgs(serviceId string, partitionId string) *kurtosis_core_rpc_api_bindings.RegisterServiceArgs { return &kurtosis_core_rpc_api_bindings.RegisterServiceArgs{ ServiceId: serviceId, PartitionId: partitionId, } } func NewRegisterServiceResponse(ipAddr string) *kurtosis_core_rpc_api_bindings.RegisterServiceResponse { return &kurtosis_core_rpc_api_bindings.RegisterServiceResponse{IpAddr: ipAddr} } // ============================================================================================== // Start Service // ============================================================================================== func NewStartServiceArgs( serviceId string, image string, usedPorts map[string]bool, entrypointArgs []string, cmdArgs []string, envVars map[string]string, enclaveDataDirMntDirpath string, filesArtifactMountDirpaths map[string]string) *kurtosis_core_rpc_api_bindings.StartServiceArgs { return &kurtosis_core_rpc_api_bindings.StartServiceArgs{ ServiceId: serviceId, DockerImage: image, UsedPorts: usedPorts, EntrypointArgs: entrypointArgs, CmdArgs: cmdArgs, DockerEnvVars: envVars, EnclaveDataDirMntDirpath: enclaveDataDirMntDirpath, FilesArtifactMountDirpaths: filesArtifactMountDirpaths, } } func NewStartServiceResponse(usedPortsHostPortBindings map[string]*kurtosis_core_rpc_api_bindings.PortBinding) *kurtosis_core_rpc_api_bindings.StartServiceResponse { return &kurtosis_core_rpc_api_bindings.StartServiceResponse{ UsedPortsHostPortBindings: usedPortsHostPortBindings, } } func NewPortBinding(interfaceIp string, interfacePort string) *kurtosis_core_rpc_api_bindings.PortBinding { return &kurtosis_core_rpc_api_bindings.PortBinding{ InterfaceIp: interfaceIp, InterfacePort: interfacePort, } } // ============================================================================================== // Get Service Info // ============================================================================================== func NewGetServiceInfoArgs(serviceId string) *kurtosis_core_rpc_api_bindings.GetServiceInfoArgs { return &kurtosis_core_rpc_api_bindings.GetServiceInfoArgs{ ServiceId: serviceId, } } func NewGetServiceInfoResponse(ipAddr string, enclaveDataDirMountDirpath string) *kurtosis_core_rpc_api_bindings.GetServiceInfoResponse { return &kurtosis_core_rpc_api_bindings.GetServiceInfoResponse{ IpAddr: ipAddr, EnclaveDataDirMountDirpath: enclaveDataDirMountDirpath, } } // ============================================================================================== // Remove Service // ============================================================================================== func NewRemoveServiceArgs(serviceId string, containerStopTimeoutSeconds uint64) *kurtosis_core_rpc_api_bindings.RemoveServiceArgs { return &kurtosis_core_rpc_api_bindings.RemoveServiceArgs{ ServiceId: serviceId, ContainerStopTimeoutSeconds: containerStopTimeoutSeconds, } } // ============================================================================================== // Repartition // ============================================================================================== func NewRepartitionArgs( partitionServices map[string]*kurtosis_core_rpc_api_bindings.PartitionServices, partitionConnections map[string]*kurtosis_core_rpc_api_bindings.PartitionConnections, defaultConnection *kurtosis_core_rpc_api_bindings.PartitionConnectionInfo) *kurtosis_core_rpc_api_bindings.RepartitionArgs { return &kurtosis_core_rpc_api_bindings.RepartitionArgs{ PartitionServices: partitionServices, PartitionConnections: partitionConnections, DefaultConnection: defaultConnection, } } func NewPartitionServices(serviceIdSet map[string]bool) *kurtosis_core_rpc_api_bindings.PartitionServices { return &kurtosis_core_rpc_api_bindings.PartitionServices{ ServiceIdSet: serviceIdSet, } } func NewPartitionConnections(connectionInfo map[string]*kurtosis_core_rpc_api_bindings.PartitionConnectionInfo) *kurtosis_core_rpc_api_bindings.PartitionConnections { return &kurtosis_core_rpc_api_bindings.PartitionConnections{ ConnectionInfo: connectionInfo, } } func NewPartitionConnectionInfo(isBlocked bool) *kurtosis_core_rpc_api_bindings.PartitionConnectionInfo { return &kurtosis_core_rpc_api_bindings.PartitionConnectionInfo{ IsBlocked: isBlocked, } } // ============================================================================================== // Exec Command // ============================================================================================== func NewExecCommandArgs(serviceId string, commandArgs []string) *kurtosis_core_rpc_api_bindings.ExecCommandArgs { return &kurtosis_core_rpc_api_bindings.ExecCommandArgs{ ServiceId: serviceId, CommandArgs: commandArgs, } } func NewExecCommandResponse(exitCode int32, logOutput string) *kurtosis_core_rpc_api_bindings.ExecCommandResponse { return &kurtosis_core_rpc_api_bindings.ExecCommandResponse{ ExitCode: exitCode, LogOutput: logOutput, } } // ============================================================================================== // Wait For Http Get Endpoint Availability // ============================================================================================== func NewWaitForHttpGetEndpointAvailabilityArgs( serviceId string, port uint32, path string, initialDelayMilliseconds uint32, retries uint32, retriesDelayMilliseconds uint32, bodyText string) *kurtosis_core_rpc_api_bindings.WaitForHttpGetEndpointAvailabilityArgs { return &kurtosis_core_rpc_api_bindings.WaitForHttpGetEndpointAvailabilityArgs{ ServiceId: serviceId, Port: port, Path: path, InitialDelayMilliseconds: initialDelayMilliseconds, Retries: retries, RetriesDelayMilliseconds: retriesDelayMilliseconds, BodyText: bodyText, } } // ============================================================================================== // Wait For Http Post Endpoint Availability // ============================================================================================== func NewWaitForHttpPostEndpointAvailabilityArgs( serviceId string, port uint32, path string, requestBody string, initialDelayMilliseconds uint32, retries uint32, retriesDelayMilliseconds uint32, bodyText string) *kurtosis_core_rpc_api_bindings.WaitForHttpPostEndpointAvailabilityArgs { return &kurtosis_core_rpc_api_bindings.WaitForHttpPostEndpointAvailabilityArgs{ ServiceId: serviceId, Port: port, Path: path, RequestBody: requestBody, InitialDelayMilliseconds: initialDelayMilliseconds, Retries: retries, RetriesDelayMilliseconds: retriesDelayMilliseconds, BodyText: bodyText, } } // ============================================================================================== // Execute Bulk Commands // ============================================================================================== func NewExecuteBulkCommandsArgs(serializedCommands string) *kurtosis_core_rpc_api_bindings.ExecuteBulkCommandsArgs { return &kurtosis_core_rpc_api_bindings.ExecuteBulkCommandsArgs{ SerializedCommands: serializedCommands, } }
package pd.someserver.demo.rpcserver; import java.util.HashMap; public class ServiceRegistry { public static String getInterfaceClassName(Class<?> interfaceClass) { return interfaceClass.getCanonicalName(); } private boolean isFrozen = false; private final HashMap<String, Class<?>> registry = new HashMap<>(); public void freeze() { isFrozen = true; } public Class<?> getImplementationClass(String interfaceClassName) { return registry.get(interfaceClassName); } public boolean register(Class<?> interfaceClass, Class<?> implementationClass) { if (isFrozen) { return false; } registry.put(getInterfaceClassName(interfaceClass), implementationClass); return true; } }
if [ -z "$1" ]; then echo "email argument not set" exit 1 fi curl -d "to=$1&code=passcode" -X POST http://localhost:8002/send
#ifndef __graph_h__ #define __graph_h__ typedef struct { int n; unsigned m; int* out_array; unsigned* out_degree_list; int max_degree_vert; double avg_out_degree; } graph; #define out_degree(g, n) (g->out_degree_list[n+1] - g->out_degree_list[n]) #define out_vertices(g, n) (&g->out_array[g->out_degree_list[n]]) #endif
import argparse import sys def add_parser(config): # Implementation of add_parser function is not provided as it is not relevant to the problem def process_arguments(parsed_args): if parsed_args.get('verbose'): print("Verbose mode enabled") if 'file' in parsed_args: try: with open(parsed_args['file'], 'r') as file: print(file.read()) except FileNotFoundError: print("Error: File not found") if 'output' in parsed_args: try: with open(parsed_args['output'], 'w') as output_file: output_file.write("Output file created") except IOError: print("Error: Unable to create output file") # Example usage if __name__ == "__main__": parser = add_parser(config) # Assuming config is provided args = None # For demonstration purposes, assuming args are not provided if args is None: kwargs = vars(parser.parse_args()) sys_exit = exit process_arguments(kwargs)
<filename>Modules/Filtering/Path/include/otbImageToPathFilter.hxx /* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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. */ #ifndef otbImageToPathFilter_hxx #define otbImageToPathFilter_hxx #include "otbImageToPathFilter.h" namespace otb { /** * Constructor. */ template <class TInputImage, class TOutputPath> ImageToPathFilter<TInputImage, TOutputPath> ::ImageToPathFilter() { this->SetNumberOfRequiredInputs(1); } /** * Input image setter. */ template <class TInputImage, class TOutputPath> void ImageToPathFilter<TInputImage, TOutputPath> ::SetInput(const InputImageType * image) { this->ProcessObjectType::SetNthInput(0, const_cast<InputImageType *>(image)); } /** * Input image getter. */ template <class TInputImage, class TOutputPath> const typename ImageToPathFilter<TInputImage, TOutputPath>::InputImageType * ImageToPathFilter<TInputImage, TOutputPath> ::GetInput(void) { return static_cast<const TInputImage *>(this->ProcessObjectType::GetInput(0)); } /** * PrintSelf Method. */ template <class TInputImage, class TOutputPath> void ImageToPathFilter<TInputImage, TOutputPath> ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } } // end namespace otb #endif
# audit_pass_req # # Set PASSREQ to YES in /etc/default/login to prevent users from loging on # without a password #. audit_pass_req () { if [ "$os_name" = "SunOS" ]; then verbose_message "Ensure password required" check_file="/etc/default/login" check_file_value is $check_file PASSREQ eq YES hash fi }
<filename>lessons/js-arrays/big-o.js // sc: https://ru.hexlet.io/courses/js-arrays/lessons/big-o/exercise_unit // arrays.js // Реализуйте и экспортируйте по умолчанию функцию getIntersectionOfSortedArrays, которая принимает // на вход два отсортированных массива и находит их пересечение. // Алгоритм // Поиск пересечения двух неотсортированных массивов — операция, в рамках которой // выполняется вложенный цикл с полной проверкой каждого элемента первого массива на вхождение во // второй. // Сложность данного алгоритма O(n * m) (произведение n и m), где n и m — размерности массивов. Если // массивы отсортированы, то можно реализовать алгоритм, сложность которого уже O(n + m), что // значительно лучше. // Суть алгоритма довольно проста. В коде вводятся два указателя (индекса) на каждый из массивов. // Начальное значение каждого указателя 0. Затем идёт проверка элементов, находящихся под этими // индексами в обоих массивах. Если они совпадают, то значение заносится в результирующий массив, а // оба индекса инкрементируются. Если значение в первом массиве больше, чем во втором, то // инкрементируется указатель второго массива, иначе — первого. export default (numsA, numsB) => { const intersection = []; let a = 0; let b = 0; while (a < numsA.length && b < numsB.length) { if (numsA[a] === numsB[b]) { intersection.push(numsA[a]); a += 1; b += 1; } else if (numsA[a] > numsB[b]) { b += 1; } else { a += 1; } } return intersection; }; const bad = (numsA, numsB) => { const intersection = []; let a = 0; let b = 0; const fns = { 0: () => { intersection.push(numsA[a]); a += 1; b += 1; }, 1: () => { b += 1; }, '-1': () => { a += 1; }, }; while (a < numsA.length && b < numsB.length) { fns[Math.sign(numsA[a], numsB[b])](); } return intersection; };
def remove_duplicates(items): no_duplicates = [] for item in items: if item not in no_duplicates: no_duplicates.append(item) return no_duplicates items = [1, 2, 3, 2, 4, 1] result = remove_duplicates(items) print(result) # [1, 2, 3, 4]
#!/bin/sh set -e DIR=`mktemp -d` cd $DIR wget "https://github.com/darealshinji/debian-packaging/archive/master.tar.gz" tar xvf master.tar.gz cd debian-packaging-master/games/unityengine2deb && make PBUILDER=0
""" Python program with a class to compute the average of the elements in a list """ class AverageCalculator(): def __init__(self, numbers): self.numbers = numbers def get_average(self): total = 0 for number in self.numbers: total += number return total/len(self.numbers) if __name__ == '__main__': numbers = [3, 4, 5, 6, 7] average_calculator = AverageCalculator(numbers) print(average_calculator.get_average()) # 5.0
module App1 { m$.ready(() => { loadPeoplePicker('peoplePickerDiv'); }); //Load the people picker function loadPeoplePicker(peoplePickerElementId: string) { var schema: ISPClientPeoplePickerSchema = { PrincipalAccountType: 'User,DL,SecGroup,SPGroup', SearchPrincipalSource: 15, ResolvePrincipalSource: 15, AllowMultipleValues: true, MaximumEntitySuggestions :50, Width: 280, OnUserResolvedClientScript: onUserResolvedClientScript } SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema); } function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) { var keys = ""; // Get information about all users. var userInfo = ''; for (var i = 0; i < users.length; i++) { var user = users[i]; keys += user.Key + ","; for (var userProperty in user) { userInfo += userProperty + ': ' + user[userProperty] + '<br>'; } } $('#resolvedUsers').html(userInfo); // Get user keys. $('#userKeys').html(keys); } }
<filename>src/main/java/com/engg/digitalorg/managers/UrlManager.java package com.engg.digitalorg.managers; import com.engg.digitalorg.exception.NotFoundException; import com.engg.digitalorg.model.entity.Card; import com.engg.digitalorg.model.entity.Url; import com.engg.digitalorg.repository.CardRepository; import com.engg.digitalorg.repository.UrlRepository; import com.engg.digitalorg.util.BaseConversion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Date; import java.util.NoSuchElementException; import java.util.Optional; /** * The type Url manager. */ @Component public class UrlManager { @Autowired private UrlRepository urlRepository; @Autowired private CardRepository cardRepository; /** * The Base conversion. */ @Autowired BaseConversion baseConversion; /** * Gets original url. * * @param shortUrl the short url * @return the original url */ public String getOriginalUrl(String shortUrl) { Optional<Url> entity; try { int id = baseConversion.decode(shortUrl); Optional<Card> card = cardRepository.findById(id); entity = urlRepository.findById(card.get().getUrl_id()); if (entity.get() == null) { throw new NotFoundException("There is no record with " + shortUrl); } if (entity.get().getExpires_date() != null && entity.get().getExpires_date().before(new Date())) { // urlRepository.delete(entity.get()); throw new NotFoundException("Link expired!"); } } catch (NoSuchElementException exception) { throw new NotFoundException("There is no record with " + shortUrl); } return entity.get().getLong_url(); } }
# -*- encoding: utf-8 -*- # this is required because of the use of eval interacting badly with require_relative require 'razor/acceptance/utils' confine :except, :roles => %w{master dashboard database frictionless} test_name 'Delete tag with non-existent tag' step 'https://testrail.ops.puppetlabs.net/index.php?/cases/view/677' reset_database razor agents, 'delete-tag --name does-not-exist' do |agent, output| assert_match /No change. Tag does-not-exist does not exist./, output end
<html> <head> <title>Students Marks</title> </head> <body> <table> <tr> <th>Name</th> <th>Marks</th> </tr> <tr> <td>John</td> <td>80</td> </tr> <tr> <td>Maria</td> <td>90</td> </tr> <tr> <td>Amanda</td> <td>85</td> </tr> </table> </body> </html>
/* Copyright 2017 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ibm.cloud.appid.android.internal.registrationmanager; public enum RegistrationStatus { NOT_REGISTRED { public String getDescription() { return "OAuth client not registered"; } }, REGISTERED_SUCCESSFULLY { public String getDescription(){ return "OAuth client successfully registered"; } }, FAILED_TO_REGISTER { public String getDescription(){ return "Failed to register OAuth client"; } }, FAILED_TO_SAVE_REGISTRATION_DATA { public String getDescription(){ return "Failed to save OAuth client registration data"; } }, FAILED_TO_CREATE_REGISTRATION_PARAMETERS { public String getDescription(){ return "Failed to create registration parameters"; } }; public abstract String getDescription(); }
SELECT cust_id FROM orders GROUP BY cust_id HAVING COUNT(*) > 1;
#!/bin/bash ################################################################################ ## File: git.sh ## Team: CI-Platform ## Desc: Installs Git ################################################################################ # Source the helpers for use with the script source $HELPER_SCRIPTS/document.sh ## Install git add-apt-repository ppa:git-core/ppa -y apt-get update apt-get install git -y git --version # Install git-lfs curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | bash apt-get install -y --no-install-recommends git-lfs # Run tests to determine that the software installed as expected echo "Testing to make sure that script performed as expected, and basic scenarios work" if ! command -v git; then echo "git was not installed" exit 1 fi # Document what was added to the image echo "Lastly, documenting what we added to the metadata file" DocumentInstalledItem "Git ($(git --version))"
<reponame>Fourdee/mayan-edms<gh_stars>1-10 from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from drf_yasg.views import get_schema_view from rest_framework import permissions from rest_api.schemas import openapi_info admin.autodiscover() schema_view = get_schema_view( openapi_info, validators=['flex', 'ssv'], public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^swagger(?P<format>.json|.yaml)$', schema_view.without_ui(cache_timeout=None), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=None), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=None), name='schema-redoc'), ] if settings.DEBUG: from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if 'rosetta' in settings.INSTALLED_APPS: urlpatterns += [ url(r'^rosetta/', include('rosetta.urls'), name='rosetta') ] if 'debug_toolbar' in settings.INSTALLED_APPS: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)) ]
SELECT Name FROM Employees WHERE DepartmentID > 10;
words = ["these", "are", "some", "words"] for word in words: print(word)
import elasticsearch import logging def connect_to_elasticsearch(url, logger): try: es_client = elasticsearch.Elasticsearch([url]) except elasticsearch.exceptions.ConnectionError as e: logger.error('Connection error: Elasticsearch unavailable on "{}".\nPlease check your configuration'.format(url)) raise e return es_client
const getMax = (a, b) => { return a > b ? a : b; }
money_expected = int(input()) entries = 0 cash = 0 card = 0 total = 0 people_cash = 0 people_card = 0 command = input() while command != "End": money_entered = int(command) entries += 1 if entries % 2 == 0: if money_entered < 10: print(f"Error in transaction!") else: card += money_entered total += money_entered people_card += 1 print(f"Product sold!") if total >= money_expected: print(f"Average CS: {(cash / people_cash):.2f}") print(f"Average CC: {(card / people_card):.2f}") break else: if money_entered > 100: print(f"Error in transaction!") else: cash += money_entered total += money_entered people_cash += 1 print(f"Product sold!") if total >= money_expected: print(f"Average CS: {(cash / people_cash):.2f}") print(f"Average CC: {(card / people_card):.2f}") break command = input() if command == "End": print(f"Failed to collect required money for charity.")
<gh_stars>0 package examen1_fabiohenriquez; import java.util.Date; import java.util.Scanner; import javax.swing.JOptionPane; public class Examen1_FabioHenriquez { static Carpeta raiz = new Carpeta(); static Date fecha = new Date(); static Sistema sistemas = new Sistema(); static Scanner lea = new Scanner(System.in); public static void main(String[] args) { int res = 0; do { switch (MenuArchivos()) { case 2: if (raiz.getDocumentos().size() < 1) { JOptionPane.showMessageDialog(null, "No hay carpetas o archivos"); } else { EntraSub(raiz); } break; case 3: JOptionPane.showMessageDialog(null, "Esta en la raiz"); Regresar(raiz); break; case 4: CrearArchivo(raiz); break; case 1: String nombre = JOptionPane.showInputDialog(null, "Ingrese el nombre del sistema: \n"); String usuario = JOptionPane.showInputDialog(null, "Ingrese el Usuario: \n"); Double bytes = Double.parseDouble(JOptionPane.showInputDialog("Ingrese el tamaño (en bytes)")); sistemas.setNombre(nombre); sistemas.setUsuario(usuario); sistemas.setCapacidad(bytes); JOptionPane.showMessageDialog(null, "Sistema creado usted esta en : "+ sistemas.toString()); break; case 5: Listac(raiz); break; case 6: Listaall(); break; }//Fin del switch menu res = JOptionPane.showConfirmDialog(null, "¿Desea salir del sistema?", "Confirmacion", JOptionPane.YES_NO_OPTION); } while (res == 1); }//Fin del main public static int MenuArchivos() { int opcion = Integer.parseInt(JOptionPane.showInputDialog(null, "Gestor de Archivos \n" + " --Menu--\n" + "1.Crear el sistema \n" + "2. Entrar en una subcarpeta \n" + "3. Regresar a una carpeta anterior \n" + "4. Comandos para Crear un Archivo \n" + "5. Comandos para modificar \n" + "6. Comando para Listar \n")); return opcion; } //SIstema de archivos public static void SistemaArchivos() { switch (MenuArchivos()) { case 2: if (raiz.getDocumentos().size() < 1) { JOptionPane.showMessageDialog(null, "No hay carpetas o archivos"); } else { EntraSub(raiz); } break; case 3: JOptionPane.showMessageDialog(null, "Esta en la raiz"); Regresar(raiz); break; case 4: CrearArchivo(raiz); break; case 5: modificar_Archivo(raiz); break; case 6: Listac(raiz); break; } }//Fin del metodo sistemaarchivos //archivo public static void modificar_Archivo(Carpeta c){ } public static void EntraSub(Carpeta c) { String s = ""; boolean aux=true; for (Archivo t : c.getDocumentos()) { if (t instanceof Carpeta) { s += c.getDocumentos().indexOf(t) + " - " + t + "\n"; } } int opcion=0; opcion = Integer.parseInt(JOptionPane.showInputDialog(null, "Elija a que carpeta acceder\n" + s,"Elija",JOptionPane.DEFAULT_OPTION)); switch (MenuArchivos()) { case 1: EntraSub(((Carpeta) c.getDocumentos().get(opcion))); break; case 2: break; case 3: CrearArchivo((Carpeta) c.getDocumentos().get(opcion)); break; case 4: Listac((Carpeta) c.getDocumentos().get(opcion)); break; case 5: Listaall(); break; } } public static void Regresar(Carpeta c) { switch (MenuArchivos()) { case 1: EntraSub(c); break; case 2: Regresar(c); break; case 3: CrearArchivo(c); break; case 4: Listac(c); break; case 5: Listaall(); break; } }//Fin metod regresa public static void CrearArchivo(Carpeta c) { String comando = JOptionPane.showInputDialog(null,"Usted esta en : "+ sistemas.toString()); String com = comando.split(" ")[0]; String nom= comando.split(" ")[1]; String size = comando.split(" ")[2]; if (com.equals("mkdir")) { sistemas.getArchivos().add(new Carpeta(nom, size, new Date(), new Date())); JOptionPane.showMessageDialog(null, "Carpeta Creada"); sistemas.setCarpeta_Raiz(nom); }else if(com.equals("cat")){ String algo = JOptionPane.showInputDialog(null,"Ingrese el archivo de texto"); sistemas.getArchivos().add(new Archivo_Texto(algo)); }else if (com.equals("mod") ){ String algo = JOptionPane.showInputDialog(null,"Aun no se puede modificar | espere la proxima actualizacion"); } }//Fin metodo creararchivo public static void Listac(Carpeta c) { String s = ""; for (Archivo t : c.getDocumentos()) { s += c.getDocumentos().indexOf(t) + " - " + c.toString() + "\n"; } JOptionPane.showMessageDialog(null, s); } public static void Listaall() { String s = ""; for (Archivo t : raiz.getDocumentos()) { s += raiz.getDocumentos().indexOf(t) + " - " + t + "\n"; } JOptionPane.showMessageDialog(null, s); } }
def find_min_max_avg(arr): # set the min, max numbers to the first item in the array min_num = arr[0] max_num = arr[0] # keep track of the sum of all the numbers sum_num = 0 # iterate through the array for item in arr: # find smallest number if item < min_num: min_num = item # find largest number elif item > max_num: max_num = item # add each number to the sum sum_num += item # calculate the average avg_num = sum_num / len(arr) print("Smallest Number: {}\nLargest Number: {}".format(min_num, max_num)) return avg_num
class Register: def __init__(self): self.value = 0 def __str__(self): return str(self.value) class Accumulator(Register): bitsize = 8 def add(self, value): self.value = (self.value + value) & 0xFF # Ensure the result fits within 8 bits def subtract(self, value): self.value = (self.value - value) & 0xFF # Ensure the result fits within 8 bits def bitwise_and(self, value): self.value &= value def bitwise_or(self, value): self.value |= value class Temporary(Register): def __init__(self): super().__init__() self.stack = [] def push(self, value): self.stack.append(value) def pop(self): if self.stack: return self.stack.pop() else: return None
<reponame>LarsBehrenberg/e-wallet import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Grid, Button, List, ListItem, Tooltip, TextField } from '@material-ui/core'; import hero4 from '../../../assets/images/hero-bg/hero-2.jpg'; export default function LivePreviewExample() { return ( <> <div className="app-wrapper min-vh-100 bg-white"> <div className="app-main min-vh-100"> <div className="app-content p-0"> <div className="app-inner-content-layout--main"> <div className="flex-grow-1 w-100 d-flex align-items-center"> <div className="bg-composed-wrapper--content"> <Grid container spacing={0} className="min-vh-100"> <Grid item lg={7} xl={6} className="d-flex align-items-center"> <Grid item md={10} lg={8} xl={7} className="mx-auto"> <div className="py-4"> <div className="text-center"> <h3 className="display-4 mb-2 font-weight-bold"> Create account </h3> <p className="font-size-lg mb-5 text-black-50"> Start using our tools right away! Create an account today! </p> </div> <div className="mb-3"> <label className="font-weight-bold mb-2"> Email address </label> <TextField variant="outlined" size="small" fullWidth placeholder="Enter your email address" type="email" /> </div> <div className="mb-3"> <div className="d-flex justify-content-between"> <label className="font-weight-bold mb-2"> Password </label> </div> <TextField variant="outlined" size="small" fullWidth placeholder="Enter your password" type="password" /> </div> <div className="mb-3"> <label className="font-weight-bold mb-2"> First name </label> <TextField variant="outlined" size="small" fullWidth placeholder="Enter your first name" /> </div> <div className="mb-3"> <label className="font-weight-bold mb-2"> Last name </label> <TextField variant="outlined" size="small" fullWidth placeholder="Enter your last name" /> </div> <div className="form-group mb-5"> By clicking the <strong>Create account</strong>{' '} button below you agree to our terms of service and privacy statement. </div> <Button size="large" fullWidth className="btn-primary mb-5"> Create Account </Button> </div> </Grid> </Grid> <Grid item lg={5} xl={6} className="d-flex"> <div className="hero-wrapper w-100 bg-composed-wrapper bg-dark min-vh-lg-100"> <div className="flex-grow-1 w-100 d-flex align-items-center"> <div className="bg-composed-wrapper--image opacity-5" style={{ backgroundImage: 'url(' + hero4 + ')' }} /> <div className="bg-composed-wrapper--bg bg-second opacity-5" /> <div className="bg-composed-wrapper--bg bg-deep-sky opacity-2" /> <div className="bg-composed-wrapper--content text-center p-5"> <div className="text-white px-0 px-lg-2 px-xl-4"> <h1 className="display-3 mb-4 font-weight-bold"> Bamburgh React Admin Dashboard with Material-UI PRO </h1> <p className="font-size-lg mb-0 opacity-8"> Premium admin template powered by the most popular UI components framework available for React: Material-UI. Features hundreds of examples making web development fast and easy. Start from one of the individual apps included or from the general dashboard and build beautiful scalable applications and presentation websites. </p> <div className="divider mx-auto border-1 my-5 border-light opacity-2 rounded w-25" /> <div> <Button className="btn-warning px-5 font-size-sm font-weight-bold btn-animated-icon text-uppercase rounded shadow-none py-3 hover-scale-sm hover-scale-lg"> <span className="btn-wrapper--label"> Subscription Options </span> <span className="btn-wrapper--icon"> <FontAwesomeIcon icon={['fas', 'arrow-right']} /> </span> </Button> </div> </div> </div> </div> <div className="hero-footer pb-4"> <List component="div" className="nav-pills nav-neutral-secondary d-flex"> <Tooltip title="Facebook" arrow> <ListItem component="a" button href="#/" onClick={(e) => e.preventDefault()} className="font-size-lg text-white-50"> <FontAwesomeIcon icon={['fab', 'facebook']} /> </ListItem> </Tooltip> <Tooltip title="Twitter" arrow> <ListItem component="a" button href="#/" onClick={(e) => e.preventDefault()} className="font-size-lg text-white-50"> <FontAwesomeIcon icon={['fab', 'twitter']} /> </ListItem> </Tooltip> <Tooltip title="Google" arrow> <ListItem component="a" button href="#/" onClick={(e) => e.preventDefault()} className="font-size-lg text-white-50"> <FontAwesomeIcon icon={['fab', 'google']} /> </ListItem> </Tooltip> <Tooltip title="Instagram" arrow> <ListItem component="a" button href="#/" onClick={(e) => e.preventDefault()} className="font-size-lg text-white-50"> <FontAwesomeIcon icon={['fab', 'instagram']} /> </ListItem> </Tooltip> </List> </div> </div> </Grid> </Grid> </div> </div> </div> </div> </div> </div> </> ); }
#!/bin/bash # profiles = xccdf_org.ssgproject.content_profile_pci-dss # remediation = bash # platform = Red Hat Enterprise Linux 7,Fedora mkdir -p /etc/audit/rules.d ./generate_privileged_commands_rule.sh 1000 privileged /etc/audit/rules.d/privileged.rules
<gh_stars>10-100 package com.springcryptoutils.digest; /** * Generic interface for getting message digests * in raw bytes format. * * @author <NAME> (<EMAIL>) */ public interface Digester { /** * Returns the message digest in raw bytes format. * * @param message the message * @return the message digest in raw bytes format */ byte[] digest(byte[] message); }
def count_characters(str): count = 0 for char in str: if char != ' ': count += 1 return count num_characters = count_characters("Hello World") print(num_characters)
class TrialContainer extends Template { constructor() { super('html/trialContainer.html', 'div#trial-container'); this.rowTemplate = new Template('html/trialContainerRow.html', null); this.listElement = null; this.actionSelectElement = null; } load() { return Promise.all([ super.load(), this.rowTemplate.load() ]); } validate() { var b = super.validate(); if (b) { this.listElement = this.element.querySelector('div#trial-list ul'); this.actionSelectElement = this.element.querySelector('div#controls select[name="trial-action"]'); } return b; } addTrial(trial) { this.rowTemplate.appendTo(this.listElement, { 'trial\\.scriptId': trial.scriptId, 'trial\\.scriptName': trial.scriptName, 'trial\\.userId': trial.userId, 'trial\\.userName': trial.userName, 'trial\\.entryDate': trial.entryDate, 'trial\\.expirationDate': trial.expirationDate, 'trial\\.expired': trial.expired, 'trial\\.duration': trial.duration }); } getSelectedRows() { return Array.from(this.listElement.querySelectorAll('li')) .filter(li => li.querySelector('input[type="checkbox"]:checked')); } getSelectedUsers() { return this.getSelectedRows().map(li => li.dataset); } getSelectedAction() { return this.actionSelectElement.value; } }
define(['./MarkerCluster'], function (MarkerCluster) { var MarkersPanel = function (wwd, navigator, controls) { this.wwd = wwd; this.myMarkers = {}; var self = this; this.index = 0; this.controls = controls; this.fileTypeMarkers = 0; $("#fileTypeMarkers").change(function () { var val = $("#fileTypeMarkers").val(); if (val == "0") { $("#csv-Markers").hide(); $("#markersUrl").show(); self.fileTypeMarkers = 0; } else { $("#csv-Markers").show(); $("#markersUrl").hide(); self.fileTypeMarkers = 1; } }); $("#loadMarkersBtn").on("click", function () { self.addMarkers(self.wwd); }) }; MarkersPanel.prototype.addMarkers = function (wwd) { var self = this; if (this.fileTypeMarkers == 1) { var resourcesUrl = $("#csv-Markers").get(0).files[0]; } else { var resourcesUrl = document.getElementById("markersUrl").value; } resourcesUrl = resourcesUrl.replace(/ /g, ''); var markerCluster = new MarkerCluster(wwd, { name: "Cluster", controls: self.controls, navigator: wwd.controller, maxLevel: 7, clusterSources: ["images/marker/low.png", "images/marker/medium.png", "images/marker/high.png", "images/marker/vhigh.png"] }); this.myMarkers[this.index] = markerCluster.layer; getJSON(resourcesUrl, function (results) { markerCluster.generateJSONCluster(results); }); function getJSON(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.onload = function () { if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300 && xhr.response) { callback(xhr.response); } }; xhr.send(); } wwd.redraw(); this.createInterface(wwd); }; MarkersPanel.prototype.createInterface = function (wwd) { $("#MarkersList").html(""); var self = this; for (var key in self.myMarkers) { var name = self.myMarkers[key].displayName + " " + key; var myDiv = $("<div key=" + key + " class='listJson'>&#10060;" + name + "</div>"); $("#MarkersList").append(myDiv); myDiv.on('click', function () { var myKey = $(this).attr("key"); wwd.removeLayer(self.myMarkers[myKey]); $(this).remove(); delete(self.myMarkers[myKey]); wwd.redraw(); }); } }; return MarkersPanel; });
<filename>sandbox/src/main/java/pl/kasieksoft/sandbox/PointMain.java package pl.kasieksoft.sandbox; public class PointMain { public static void main(String[] args) { Point point1 = new Point(2.0, 3.0); Point point2 = new Point(4.0, 5.0); System.out.println("Distance between points equals " + distance(point1, point2)); System.out.println("Distance between points equals " + point1.distance(point2)); } private static double distance(Point p1, Point p2) { return Math.sqrt(Math.pow(p2.getX() - p1.getX(), 2) + Math.pow(p2.getY() - p1.getY(), 2)); } }
<reponame>flast1k/graphql-faker import { Kind, Source, DocumentNode, GraphQLError, GraphQLSchema, parse, validate, extendSchema, buildASTSchema, validateSchema, isObjectType, isInterfaceType, ValuesOfCorrectTypeRule, } from 'graphql'; // FIXME import { validateSDL } from 'graphql/validation/validate'; const fakeDefinitionAST = parse(/* GraphQL */ ` enum fake__Locale { az cz de de_AT de_CH en en_AU en_BORK en_CA en_GB en_IE en_IND en_US en_au_ocker es es_MX fa fr fr_CA ge id_ID it ja ko nb_NO nep nl pl pt_BR ru sk sv tr uk vi zh_CN zh_TW } enum fake__Types { zipCode city streetName "Configure address with option \`useFullAddress\`" streetAddress secondaryAddress county country countryCode state stateAbbr latitude longitude colorName productCategory productName "Sum of money. Configure with options \`minMoney\`/\`maxMoney\` and 'decimalPlaces'." money productMaterial product companyName companyCatchPhrase companyBS dbColumn dbType dbCollation dbEngine """ By default returns dates beetween 2000-01-01 and 2030-01-01. Configure date format with options \`dateFormat\` \`dateFrom\` \`dateTo\`. """ date "Configure date format with option \`dateFormat\`" pastDate "Configure date format with option \`dateFormat\`" futureDate "Configure date format with option \`dateFormat\`" recentDate financeAccountName financeTransactionType currencyCode currencyName currencySymbol bitcoinAddress internationalBankAccountNumber bankIdentifierCode hackerAbbreviation hackerPhrase "An image url. Configure image with options: \`imageCategory\`, \`imageWidth\`, \`imageHeight\` and \`randomizeImageUrl\`" imageUrl "An URL for an avatar" avatarUrl "Configure email provider with option: \`emailProvider\`" email url domainName ipv4Address ipv6Address userAgent "Configure color with option: \`baseColor\`" colorHex macAddress "Configure password with option \`passwordLength\`" password "Lorem Ipsum text. Configure size with option \`loremSize\`" lorem firstName lastName fullName jobTitle phoneNumber number uuid word words locale filename mimeType fileExtension semver } input fake__imageSize { width: Int! height: Int! } enum fake__loremSize { word words sentence sentences paragraph paragraphs } input fake__color { red255: Int = 0 green255: Int = 0 blue255: Int = 0 } input fake__options { "Only for type \`streetAddress\`" useFullAddress: Boolean "Only for type \`money\`" minMoney: Float "Only for type \`money\`" maxMoney: Float "Only for type \`money\`" decimalPlaces: Int "Only for type \`imageUrl\`" imageSize: fake__imageSize "Only for type \`imageUrl\`. Example value: \`[\\"nature\\", \\"water\\"]\`." imageKeywords: [String!] "Only for type \`imageUrl\`" randomizeImageUrl: Boolean "Only for type \`email\`" emailProvider: String "Only for type \`password\`" passwordLength: Int "Only for type \`lorem\`" loremSize: fake__loremSize "Only for types \`*Date\`. Example value: \`YYYY MM DD\`. [Full Specification](http://momentjs.com/docs/#/displaying/format/)" dateFormat: String = "YYYY-MM-DDTHH:mm:ss[Z]" "Only for types \`betweenDate\`. Example value: \`1986-11-02\`." dateFrom: String = "2010-01-01" "Only for types \`betweenDate\`. Example value: \`2038-01-19\`." dateTo: String = "2030-01-01" "Only for type \`colorHex\`. [Details here](https://stackoverflow.com/a/43235/4989887)" baseColor: fake__color = { red255: 0, green255: 0, blue255: 0 } "Only for type \`number\`" minNumber: Float "Only for type \`number\`" maxNumber: Float "Only for type \`number\`" precisionNumber: Float } directive @fake( type: fake__Types! options: fake__options = {} locale: fake__Locale ) on FIELD_DEFINITION | SCALAR directive @listLength(min: Int!, max: Int!) on FIELD_DEFINITION scalar examples__JSON directive @examples(values: [examples__JSON]!) on FIELD_DEFINITION | SCALAR directive @override on FIELD_DEFINITION `); function defToName(defNode) { const { kind, name } = defNode; if (name == null) { return ''; } return (kind === Kind.DIRECTIVE_DEFINITION ? '@' : '') + name.value; } const fakeDefinitionsSet = new Set( fakeDefinitionAST.definitions.map(defToName), ); const schemaWithOnlyFakedDefinitions = buildASTSchema(fakeDefinitionAST); // FIXME: mark it as valid to be able to run `validate` schemaWithOnlyFakedDefinitions['__validationErrors'] = []; export function buildWithFakeDefinitions( schemaSDL: Source, extensionSDL?: Source, options?: { skipValidation?: boolean; overrideFields?: boolean }, ): GraphQLSchema { const skipValidation = options?.skipValidation ?? false; const overrideFields = options?.overrideFields ?? false; const schemaAST = parseSDL(schemaSDL); const extensionAST = extensionSDL && parseSDL(extensionSDL); const extensionTypeDefinitions = extensionAST !== undefined && extensionAST && extensionAST.definitions.filter( (def) => def.kind === 'ObjectTypeExtension' && 'fields' in def, ); const filteredAST = { ...schemaAST, definitions: schemaAST.definitions // Remove Faker's own definitions that were added to have valid SDL for other // tools, see: https://github.com/APIs-guru/graphql-faker/issues/75 .filter((def) => { const name = defToName(def); return name === '' || !fakeDefinitionsSet.has(name); }) // map DefinitionNodes to remove fields defined in the local schema from the remote schema .map((schemaDefinition) => { if (extensionTypeDefinitions) { // looking for corresponding type definition extension in local schema const correspondingExtensionTypeDefinition = extensionTypeDefinitions.find( (extensionDef) => extensionDef.kind.slice(-9) === 'Extension' && (extensionDef as any).name.value === (schemaDefinition as any).name.value, ); // remove field existing in both schemas from remote schema to make override possible if (correspondingExtensionTypeDefinition) { (schemaDefinition as any).fields = (schemaDefinition as any).fields.filter( (fieldDef) => (correspondingExtensionTypeDefinition as any).fields.findIndex( (extensionFieldDef) => overrideFields ? // match of field name is enough extensionFieldDef.name.value === fieldDef.name.value : // check for both match of field name and `@override` directive usage extensionFieldDef.name.value === fieldDef.name.value && extensionFieldDef.directives?.findIndex( (x) => x.name.value === 'override', ) !== -1, ) === -1, ); } } return schemaDefinition; }), }; let schema = extendSchemaWithAST(schemaWithOnlyFakedDefinitions, filteredAST); const config = schema.toConfig(); schema = new GraphQLSchema({ ...config, ...(config.astNode ? {} : getDefaultRootTypes(schema)), }); if (extensionSDL != null) { schema = extendSchemaWithAST(schema, extensionAST); for (const type of Object.values(schema.getTypeMap())) { if (isObjectType(type) || isInterfaceType(type)) { for (const field of Object.values(type.getFields())) { const isExtensionField = field.astNode?.loc?.source === extensionSDL; if (field.extensions) { (field.extensions as any)['isExtensionField'] = isExtensionField; } else { field.extensions = { isExtensionField }; } } } } } if (!skipValidation) { const errors = validateSchema(schema); if (errors.length !== 0) { throw new ValidationErrors(errors); } } return schema; function extendSchemaWithAST( schema: GraphQLSchema, extensionAST?: DocumentNode, ): GraphQLSchema { if (extensionAST && !skipValidation) { const errors = [ ...validateSDL(extensionAST, schema), ...validate(schemaWithOnlyFakedDefinitions, extensionAST, [ ValuesOfCorrectTypeRule, ]), ]; if (errors.length !== 0) { throw new ValidationErrors(errors); } } return extensionAST ? extendSchema(schema, extensionAST, { assumeValid: true, commentDescriptions: true, }) : schema; } } // FIXME: move to 'graphql-js' export class ValidationErrors extends Error { subErrors: GraphQLError[]; constructor(errors) { const message = errors.map((error) => error.message).join('\n\n'); super(message); this.subErrors = errors; this.name = this.constructor.name; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error(message).stack; } } } function getDefaultRootTypes(schema) { return { query: schema.getType('Query'), mutation: schema.getType('Mutation'), subscription: schema.getType('Subscription'), }; } function parseSDL(sdl: Source) { return parse(sdl, { allowLegacySDLEmptyFields: true, allowLegacySDLImplementsInterfaces: true, }); }
<gh_stars>1-10 import { CssBaselineProps } from "@material-ui/core"; import React, { ReactElement, useRef, useState } from "react"; import ReactPlayer from "react-player"; import { genRandomNumber } from "../../src/Util"; export interface ISong { src: string; title: string; artist?: string; variant?: string; } export interface AudioState { currentlyPlaying: number; upNext: number; } interface AudioProps { onEnded: () => void; audioState: AudioState; songList: ISong[]; playing: boolean; } const Audio: React.FC<AudioProps> = ({onEnded, audioState, songList, playing}: AudioProps): ReactElement => { const style: React.CSSProperties = { width: 0, height: 0 }; return ( <ReactPlayer onEnded={onEnded} width="0" height="0" url={songList[audioState.currentlyPlaying].src} playing={playing} config={{ file: { forceAudio: true } }}/> ); }; export default Audio;
def count_unique_words(file_path, stop_words): """ Count the number of unique words in the given text file, excluding stop words. Args: file_path (str): The path to the text file. stop_words (set): A set of words to be excluded from the count. Returns: int: The number of unique words in the text file, excluding stop words. """ unique_words = set() with open(file_path, 'r', encoding='utf-8') as file: for line in file: words = line.lower().split() for word in words: word = ''.join(e for e in word if e.isalnum()) if word and word not in stop_words: unique_words.add(word) return len(unique_words)
// // TTHUDMessage.h // TT // // Created by 张福润 on 2017/3/3. // Copyright © 2017年 张福润. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> typedef NS_ENUM(NSUInteger, HUDShowTextType) { HUDShowTextTypeNone, HUDShowTextTypeText, HUDShowTextTypeDetailsText, HUDShowTextTypeRequestText, HUDShowTextTypeUploadText, HUDShowTextTypeDeleteText, HUDShowTextTypeSendText }; typedef enum : NSUInteger { /// UIActivityIndicatorView. HUDShowProgressTypeIndeterminate, /// A round, pie-chart like, progress view. HUDShowProgressTypeDeterminate, /// Horizontal progress bar. HUDShowProgressTypeDeterminateHorizontalBar, /// Ring-shaped progress view. HUDShowProgressTypeAnnularDeterminate, /// Shows a custom view. HUDShowProgressTypeCustomView, /// Shows only labels. HUDShowProgressTypeText } HUDShowProgressType; typedef enum : NSUInteger { HUDShowCompletedTypeInfo, HUDShowCompletedTypeCompleted, HUDShowCompletedTypeError, } HUDShowCompletedType; @interface TTHUDMessage : NSObject + (void)showInView:(UIView *)view; + (void)showInView:(UIView *)view showText:(NSString *)text; + (void)showInView:(UIView *)view showDetailsText:(NSString *)detailsText; + (void)showInView:(UIView *)view showRequestText:(NSString *)text; + (void)showInView:(UIView *)view showUploadText:(NSString *)text; + (void)showInView:(UIView *)view showDeleteText:(NSString *)text; + (void)showInView:(UIView *)view showSendText:(NSString *)text; + (void)showInView:(UIView *)view showText:(NSString *)text detailsText:(NSString *)detailsText; + (void)showInView:(UIView *)view showTextOnly:(NSString *)text; + (void)showInView:(UIView *)view showTextOnly:(NSString *)text completedBlock:(void(^)())completed; + (void)showInView:(UIView *)view showTextOnly:(NSString *)text detailText:(NSString *)detailText textMargin:(float)margin; + (void)showInView:(UIView *)view showTextOnly:(NSString *)text detailText:(NSString *)detailText textMargin:(float)margin completedBlock:(void(^)())completed; + (void)showCompletedText:(NSString *)text withCompletedType:(HUDShowCompletedType)completedType; + (void)showInView:(UIView *)view showCompletedText:(NSString *)text withCompletedType:(HUDShowCompletedType)completedType; + (void)showInView:(UIView *)view showCompletedText:(NSString *)text withCompletedType:(HUDShowCompletedType)completedType completedBlock:(void(^)())completed; + (void)showInView:(UIView *)view showText:(NSString *)text progress:(float)progress; + (void)showInView:(UIView *)view showText:(NSString *)text progress:(float)progress withProgressType:(HUDShowProgressType)progressType; + (void)showInView:(UIView *)view showText:(NSString *)text currentCount:(NSString *)currentCount totalCount:(NSString *)totalCount; + (void)updateShowText:(NSString *)text andDetailsText:(NSString *)detailsText inView:(UIView *)view withHUDTextType:(HUDShowTextType)hudTextType; + (void)hide; + (void)hideAllHUDInView:(UIView *)view; @end //@interface TTHUDMessage : NSObject // //@end
macro_rules! generate_mapping { (set1: { $($id1:ident),* }, set2: { $($id2:ident),* }) => { { fn create_mapping() -> std::collections::HashMap<&'static str, &'static str> { let mut mapping = std::collections::HashMap::new(); $( mapping.insert(stringify!($id1), stringify!($id2)); )* mapping } create_mapping() } }; } fn main() { let mapping = generate_mapping! { set1: { a, b, c }, set2: { x, y, z } }; assert_eq!(mapping.get("a"), Some(&"x")); assert_eq!(mapping.get("b"), Some(&"y")); assert_eq!(mapping.get("c"), Some(&"z")); }
package core import ( "bytes" "log" "path/filepath" "reflect" "sync" "sync/atomic" "time" "github.com/alikarimi999/shitcoin/core/types" "github.com/alikarimi999/shitcoin/database" ) type chainstate interface { Handler(wg *sync.WaitGroup) // if block was mined by this node local must true // if block mined by another node you must send a snapshot of block for preventing data race StateTransition(o any, local bool) GetTokens(account types.Account) []*types.UTXO GetMemTokens(account types.Account) []*types.UTXO GetStableSet() *types.UtxoSet // if miner start mining a block it will send a true to chainstate MinerIsStarting(start bool) GenesisUpdate(b *types.Block) // Load chain state from database Load() error } type stateTransmitter struct { TXs []*types.Transaction local bool } type tmpUtxo struct { time time.Duration utxo types.UTXO spendable bool } type MemSet struct { Mu *sync.Mutex Tokens map[types.Account][]*tmpUtxo } func NewMemSet() *MemSet { return &MemSet{ Mu: &sync.Mutex{}, Tokens: make(map[types.Account][]*tmpUtxo), } } type State struct { mu *sync.Mutex c *Chain memSet *MemSet // temperory chain state memSetSnapshot *MemSet stableSet *types.UtxoSet // chain state after bloack mined or remote mined block validate transportBlkCh chan *stateTransmitter transportTxCh chan *stateTransmitter minerstartingCh chan struct{} DB database.DB } func NewState(c *Chain) *State { s := &State{ mu: &sync.Mutex{}, c: c, memSet: NewMemSet(), memSetSnapshot: NewMemSet(), stableSet: types.NewUtxoSet(), transportBlkCh: make(chan *stateTransmitter), transportTxCh: make(chan *stateTransmitter), minerstartingCh: make(chan struct{}), } s.DB = database.SetupDB(filepath.Join(c.DBPath, "/chainstate")) return s } func (s *State) Handler(wg *sync.WaitGroup) { defer wg.Done() log.Println("Chain State Handler start!!!") for { select { case t := <-s.transportBlkCh: s.mu.Lock() if !t.local { for _, tx := range t.TXs { s.stableSet.UpdateUtxoSet(tx) } s.memSet = convert(s.stableSet) st := <-s.transportTxCh // recieve remaining transactions from transaction pool for _, tx := range st.TXs { s.memSet.update(tx) } } else { tx := t.TXs[0] owner := types.Account(s.c.MinerAdd) utxo := types.UTXO{ Txid: tx.TxID, Index: 0, Txout: tx.TxOutputs[0], } s.memSetSnapshot.Tokens[owner] = append(s.memSetSnapshot.Tokens[owner], &tmpUtxo{utxo: utxo, spendable: true}) s.memSet.Tokens[owner] = append(s.memSet.Tokens[owner], &tmpUtxo{utxo: utxo, spendable: true}) s.stableSet = s.memSetSnapshot.ConvertMem2Stable() } s.save() s.SyncMemSet(s.stableSet.Tokens) s.memSetSnapshot.Tokens = make(map[types.Account][]*tmpUtxo) s.mu.Unlock() case t := <-s.transportTxCh: s.mu.Lock() for _, tx := range t.TXs { s.memSet.update(tx) } s.mu.Unlock() case <-s.minerstartingCh: s.mu.Lock() s.memSetSnapshot = s.memSet.SnapShot() s.c.TxPool.ContinueHandler(true) s.mu.Unlock() } } } func (s *State) GetTokens(account types.Account) []*types.UTXO { s.mu.Lock() s.memSet.Mu.Lock() defer s.memSet.Mu.Unlock() defer s.mu.Unlock() utxos := []*types.UTXO{} for _, tu := range s.memSet.Tokens[account] { if tu.spendable { utxos = append(utxos, &tu.utxo) } } return utxos } func (s *State) GetMemTokens(account types.Account) []*types.UTXO { s.mu.Lock() s.memSet.Mu.Lock() defer s.memSet.Mu.Unlock() defer s.mu.Unlock() utxos := []*types.UTXO{} for _, tu := range s.memSet.Tokens[account] { if tu.spendable { utxos = append(utxos, &tu.utxo) } } return utxos } func (s *State) GetStableSet() *types.UtxoSet { s.mu.Lock() defer s.mu.Unlock() return s.stableSet.SnapShot() } func (s *State) StateTransition(o any, local bool) { switch t := o.(type) { case *types.Block: st := &stateTransmitter{local: local} if !local { for _, tx := range t.Transactions { st.TXs = append(st.TXs, tx) } } else { // just send minerReward transation to state handler // miner reward transaction is last one for _, tx := range t.Transactions { if tx.IsCoinbase() { st.TXs = append(st.TXs, tx) break } } } s.transportBlkCh <- st return case *types.Transaction: st := &stateTransmitter{} st.TXs = append(st.TXs, t) s.transportTxCh <- st return case []*types.Transaction: st := &stateTransmitter{} for _, tx := range t { st.TXs = append(st.TXs, tx) } s.transportTxCh <- st return default: return } } func (s *State) save() { err := s.DB.SaveState(s.stableSet.Tokens, atomic.LoadUint64(&s.c.ChainHeight), nil) if err != nil { log.Fatalln(err) } } func (s *State) MinerIsStarting(start bool) { if start { s.minerstartingCh <- struct{}{} } } func (ms *MemSet) update(tx *types.Transaction) { ms.Mu.Lock() defer ms.Mu.Unlock() var sender types.Account if !tx.IsCoinbase() { pk := tx.TxInputs[0].PublicKey account := types.Account(types.PK2Add(pk, false)) sender = account for _, in := range tx.TxInputs { for i, tu := range ms.Tokens[account] { if bytes.Equal(in.OutPoint, tu.utxo.Txid) && in.Vout == tu.utxo.Index && in.Value == tu.utxo.Txout.Value { ms.Tokens[account] = append(ms.Tokens[account][:i], ms.Tokens[account][i+1:]...) // fmt.Printf("One Token with %d Value deleted from %s in memory\n ", tu.utxo.Txout.Value, types.Pub2Address(tu.utxo.Txout.PublicKeyHash, true)) continue } } } } // add new Token var pkh []byte for index, out := range tx.TxOutputs { if out.Value == 0 { continue } pkh = out.PublicKeyHash account := types.Account(types.PK2Add(pkh, true)) tu := &tmpUtxo{ time: time.Duration(time.Now().UnixNano()), utxo: types.UTXO{ Txid: tx.TxID, Index: uint(index), Txout: out, }, } if sender == account { tu.spendable = true } ms.Tokens[account] = append(ms.Tokens[account], tu) // fmt.Printf("One Token with %d value added for %s in memory and spendable is(%v)\n", tu.utxo.Txout.Value, types.Pub2Address(tu.utxo.Txout.PublicKeyHash, true), tu.spendable) } } func (s *State) SyncMemSet(tokens map[types.Account][]*types.UTXO) { for a, tus := range s.memSet.Tokens { for _, utxo := range tokens[a] { for _, tu := range tus { if tu.time < s.c.Miner.StartTime() && reflect.DeepEqual(*utxo, tu.utxo) { tu.spendable = true } } } } } func (ms *MemSet) ConvertMem2Stable() *types.UtxoSet { us := &types.UtxoSet{ Mu: &sync.Mutex{}, Tokens: make(map[types.Account][]*types.UTXO), } for a, tu := range ms.Tokens { for _, u := range tu { us.Tokens[a] = append(us.Tokens[a], &u.utxo) } } return us } func (ms *MemSet) SnapShot() *MemSet { m := &MemSet{ Mu: &sync.Mutex{}, Tokens: make(map[types.Account][]*tmpUtxo), } for a, utxos := range ms.Tokens { for _, tu := range utxos { tmp := &tmpUtxo{ utxo: *tu.utxo.SnapShot(), spendable: tu.spendable, } m.Tokens[a] = append(m.Tokens[a], tmp) } } return m } func convert(stable *types.UtxoSet) *MemSet { ms := &MemSet{ Mu: &sync.Mutex{}, Tokens: make(map[types.Account][]*tmpUtxo), } for a, utxos := range stable.Tokens { for _, utxo := range utxos { tmp := &tmpUtxo{ utxo: *utxo, spendable: true, } ms.Tokens[a] = append(ms.Tokens[a], tmp) } } return ms } func (s *State) GenesisUpdate(b *types.Block) { for _, tx := range b.Transactions { s.memSet.update(tx) s.memSet.Tokens[types.Account(s.c.MinerAdd)][0].spendable = true s.stableSet.UpdateUtxoSet(tx) } s.save() } func (s *State) Load() error { ss, err := s.DB.ReadState() if err != nil { return err } s.stableSet.Tokens = ss s.memSet = convert(s.stableSet) return nil }
export {Environment} from './Environment'; export type {EnvironmentDefaultDict, EnvironmentDict} from './Environment'; export {getCorsOrigin} from './getCorsOrigin';
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put, Query, Res, /*ParseIntPipe*/ } from '@nestjs/common'; import { Response } from 'express'; import { ProductsService } from '../services/products.service'; import { ParseIntPipe } from 'src/common/parse-int.pipe'; import { CreateProductDto, UpdateProductDto } from 'src/dtos/products.dtos' @Controller('products') export class ProductsController { constructor(private productsService: ProductsService) { } // GET: RECIBIR PARAMETROS QUERY @Get() getProducts( @Query('limit') limit: number = 100, @Query('offset') offset: number = 0, @Query('brand') brand: string ) { return this.productsService.findAll(); } // GET : RECIBIR PARAMETROS @Get('filter') //Rutas Fijas primero antes que las rutas DINAMICAS getProductFilter() { return 'soy el filter' } @Get(':productId') @HttpCode(HttpStatus.ACCEPTED) getProduct(/*@Res() response: Response,*/ @Param('productId',ParseIntPipe ) productId: number) { /* response.status(200).send({ // Respondiendo con el motor de EXPRESS message: `product ${productId} ` }) */ return this.productsService.findOne(productId) } // POST: ENVIAR @Post() createOne(@Body() payload: CreateProductDto) { /*return { message: 'Accion de Crear', payload }*/ return this.productsService.create(payload); } // PUT: MODIFICAR @Put(':productId') update( @Param('productId') productId: string, @Body() data: UpdateProductDto ) { /*return { productId, message: `Producto Actualizado ${productId}`, data }*/ return this.productsService.update(+productId,data) } // DELETE: ELIMINAR @Delete(':productId') delete( @Param('productId') productId: string ) { return this.productsService.delete(+productId); } }
source ~/admin-openrc.sh wget -P /tmp/images http://download.cirros-cloud.net/0.3.4/cirros-0.3.4-x86_64-disk.img glance image-create \ --name "cirros" \ --file /tmp/images/cirros-0.3.4-x86_64-disk.img \ --disk-format qcow2 \ --container-format bare \ --visibility public \ --progress wget -P /tmp/images http://cloud-images.ubuntu.com/trusty/current/trusty-server-cloudimg-amd64-disk1.img glance image-create \ --name "trusty-server" \ --file /tmp/images/trusty-server-cloudimg-amd64-disk1.img \ --disk-format qcow2 \ --container-format bare \ --visibility public \ --progress glance image-list neutron net-create public \ --shared \ --provider:physical_network public \ --provider:network_type flat neutron subnet-create public 10.199.5.0/24 \ --name public \ --allocation-pool start=10.199.5.80,end=10.199.5.89 \ --dns-nameserver 8.8.8.8 \ --gateway 10.199.5.1 neutron net-update public --router:external source ~/demo-openrc.sh neutron net-create private neutron subnet-create private 172.16.1.0/24 --name private --gateway 172.16.1.1 neutron router-create router neutron router-interface-add router private neutron router-gateway-set router public ssh-keygen -q -N "" nova keypair-add --pub-key ~/.ssh/id_rsa.pub mykey nova secgroup-create ALL "ALL ingress" nova secgroup-add-rule ALL icmp -1 -1 0.0.0.0/0 nova secgroup-add-rule ALL tcp 1 65535 0.0.0.0/0 nova secgroup-add-rule ALL udp 1 65535 0.0.0.0/0 nova keypair-list nova flavor-list nova image-list # PUBLIC INSTANCE #nova boot \ #--flavor m1.tiny \ #--image cirros \ #--nic net-id=$(neutron net-show -f value -F id public) \ #--security-group ALL \ #--key-name mykey \ #public-instance # PRIVATE INSTANCE nova boot \ --flavor m1.tiny \ --image cirros \ --nic net-id=$(neutron net-show -f value -F id private) \ --security-group ALL \ --key-name mykey \ --user-data user_data_ubuntu.txt \ c1 neutron floatingip-create public #nova floating-ip-associate private-instance {FLOATING_IP} nova list # PRIVATE INSTANCE (Ubuntu) nova boot \ --flavor m1.small \ --image trusty-server \ --nic net-id=$(neutron net-show -f value -F id private) \ --security-group ALL \ --key-name mykey \ --user-data user_data_ubuntu.txt \ u1 neutron floatingip-create public #nova floating-ip-associate private-instance-u {FLOATING_IP} nova list
<reponame>lonnort/thga #include "PacPellet.hpp" #include <iostream> namespace Pacenstein { PacPellet::PacPellet(float x, float y): Item(x, y, 10) {} PacPellet::PacPellet(sf::Vector2f xy): PacPellet(xy.x, xy.y) {} void PacPellet::interact(game_data_ref_t data) { data->pacPelletsLeft--; collected = true; data->score += points; } bool PacPellet::is_collected(){ return collected; } sf::Vector2f PacPellet::getPosition(){ return this->getPos(); } }
#!/bin/bash # Copyright 2015 Crunchy Data Solutions, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ls -l / id source /opt/cpm/bin/setenv.sh initdb /pgdata
<filename>src/app/jobs/CanceledMail.js /** * @author: <NAME> <<EMAIL>> * @description: Background work for sending delivery cancellation emails */ // Import of the Lib used in this in this job import Mail from '../../lib/Mail'; class CanceledMail { get key() { return 'CanceledMail'; } async handle({ data }) { const { courier, delivery, recipient, deliveryproblem } = data; await Mail.sendMail({ to: `${courier.name} <${courier.email}>`, subject: 'Entrega cancelada!', // Subject email template: 'canceledNotification', // Template used in this email // Email's body with all data of cancellation context: { courierName: courier.name, deliveryProduct: delivery.product, recipientName: recipient.name, recipientAddress: `${recipient.street}, ${recipient.number} ${recipient.complement}`, recipientCity: recipient.city, recipientState: recipient.state, recipientZip: recipient.zipcode, deliveryProblemDescription: deliveryproblem.description } }); } } export default new CanceledMail();
#import required libraries import plotly.graph_objects as go #create data for animation frame_data = [ {'name': 'frame1', 'x': x1, 'y': y1}, {'name': 'frame2', 'x': x2, 'y': y2}, {'name': 'frame3', 'x': x3, 'y': y3} ] #create the figure fig = go.Figure( data=[go.Scatter(x=frame['x'], y=frame['y'])], frames=frame_data ) #add title, labels and other details fig.update_layout( title='Progression of Medical Condition', xaxis_title='Time (in Months)', yaxis_title='Measurement' ) #add animation fig.update_layout( updatemenus=[ dict( type = "buttons", direction = "left", buttons=list([ dict( args=[None, {"frame": {"duration": 750, "redraw": False}, "transition": {"duration": 50, "easing": "quadratic-in-out"}}], label="Play", method="animate", ) ]), ) ] ) fig.show()
package labcon import ( "net/http/httptest" "strings" "testing" "time" "github.com/dgraph-io/badger/v3" "github.com/go-chi/chi/v5" "github.com/ktnyt/labcon/cmd/labcon/app" "github.com/ktnyt/labcon/cmd/labcon/app/injectors" "github.com/ktnyt/labcon/cmd/labcon/lib" "github.com/ktnyt/labcon/driver" "github.com/ktnyt/labcon/utils" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func TestClient(t *testing.T) { r := chi.NewMux() b := &strings.Builder{} logout := zerolog.ConsoleWriter{Out: b, TimeFormat: time.RFC3339} logger := log.Output(logout).Level(zerolog.TraceLevel) opts := badger.DefaultOptions("").WithInMemory(true).WithLogger(nil) db, err := badger.Open(opts) if err != nil { t.Fatal(err) } defer db.Close() r.Use( lib.Logger(logger), lib.Badger(db), lib.DriverTokenGenerator(lib.DefaultTokenGenerator), ) a := app.NewApp(injectors.Driver) a.Setup(r) server := httptest.NewServer(r) defer server.Close() client := NewClient(server.URL) token, err := client.Register("foo", "foo") if err != nil { t.Fatal(err) } names, err := client.List() if err != nil { t.Fatal(err) } if ops := utils.ObjDiff(names, []string{"foo"}); ops != nil { t.Fatal(utils.JoinOps(ops, "\n")) } var state string if err := client.GetState("foo", &state); err != nil { t.Fatal(err) } if state != "foo" { t.Fatalf("client state = %q, want \"foo\"", state) } status, err := client.GetStatus("foo") if err != nil { t.Fatal(err) } if status != driver.Idle { t.Fatalf("client status = %q, want %q", status, driver.Idle) } op, err := client.Operation("foo", token) if err != nil { t.Fatal(err) } if op != nil { t.Fatalf("client op = %v, want nil", op) } if err := client.Dispatch("foo", driver.Op{ Name: "op", Arg: "arg", }); err != nil { t.Fatal(err) } op, err = client.Operation("foo", token) if err != nil { t.Fatal(err) } if ops := utils.ObjDiff(op, driver.Op{ Name: "op", Arg: "arg", }); ops != nil { t.Fatal(utils.JoinOps(ops, "\n")) } status, err = client.GetStatus("foo") if err != nil { t.Fatal(err) } if status != driver.Busy { t.Fatalf("client status = %q, want %q", status, driver.Busy) } if err := client.SetState("foo", token, "bar"); err != nil { t.Fatal(err) } if err := client.GetState("foo", &state); err != nil { t.Fatal(err) } if state != "bar" { t.Fatalf("client state = %q, want \"bar\"", state) } if err := client.SetStatus("foo", token, driver.Idle); err != nil { t.Fatal(err) } status, err = client.GetStatus("foo") if err != nil { t.Fatal(err) } if status != driver.Idle { t.Fatalf("client status = %q, want %q", status, driver.Idle) } op, err = client.Operation("foo", token) if err != nil { t.Fatal(err) } if op != nil { t.Fatalf("client op = %v, want nil", op) } if err := client.Disconnect("foo", token); err != nil { t.Fatal(err) } names, err = client.List() if err != nil { t.Fatal(err) } if ops := utils.ObjDiff(names, []string{}); ops != nil { t.Fatal(utils.JoinOps(ops, "\n")) } }
/** * Created by liubinbin on 15/08/2016. */ import * as _ from "lodash"; import values = require("lodash/values"); import {IArticle} from "../../definitions/storage/article"; import {Storage} from "./storagebase" export interface ISuccessCallback<TData> { (error: any, data: TData): void } export interface IHistory { id: number, articleId: string } export class History implements IHistory { id: number; articleId: string; } class HistoryStorage extends Storage<History> { Find({}:{}, callback: ISuccessCallback<History[]>): void { } tableName() { return "HISTORY" } columnList() { return "articleId"; } columnValues(model: IHistory) { var values: any[] = []; values.push(model.articleId) return values; } Add(model: IHistory, callback: ISuccessCallback<any>) { this.open().transaction((tx) => { tx.executeSql(`INSERT INTO ${this.tableName()} (${this.columnList()}) VALUES (?)`, this.columnValues(model), (transaction, results) => { if (callback)callback(null, null); }, (transation, error) => { console.log(error); }); }); } AddAsync(model: IHistory) { return new Promise((resolve, reject) => { this.Add(model, () => { resolve(model) }) }) } Init() { this.open().transaction((tx) => { tx.executeSql(`CREATE TABLE IF NOT EXISTS ${this.tableName()} (id UNIQUE, ${this.columnList()})`); console.log("<p>created </p>"); }); } AddRange(items: any[], feed_xmlurl: string, callback: any) { _(items).forEach((value) => { this.Add({title: value.title, link: value.link, feed_xmlurl: feed_xmlurl}, () => { }); }); } FindArticle({}, callback: ISuccessCallback<IArticle[]>) { this.open().transaction((tx) => { tx.executeSql(`SELECT h.id AS hId,a.* FROM ${this.tableName()} h LEFT JOIN ARTICLE3 a ON h.articleId=a.id ORDER BY rowid DESC LIMIT 100`, [], (tx, results) => { var d: IArticle[] = []; for (var i = 0; i < results.rows.length; i++) { d.push(results.rows.item(i)) } callback(null, d); }, null); }); } FindAsync() { return new Promise((resolve, reject) => { this.FindArticle({}, (error: any, data: IArticle[]) => { resolve(data) }) }) } } let historyStorage = new HistoryStorage(); historyStorage.Init(); export default historyStorage;
var worker = module.exports = function() { var appRequire = require('app-require'); var config = appRequire.requireConfig(); var restify = require('restify'); var server = restify.createServer(); var bootstrap = require('./bootstrap.js'); bootstrap.setupApp(server, __dirname); bootstrap.bootstrap(server); // change server.listen(config.http.apiPort, config.http.apiHost, function() { console.info('Server listen at port: ' + config.http.apiPort + ' host: ' + config.http.apiHost); }); return server; };
def find_pair(lst, k): pair_list = [] for i in range(len(lst)): for j in range(i+1, len(lst)): if lst[i] + lst[j] == k: pair_list.append((lst[i],lst[j])) return pair_list
<filename>src/main/java/com/common/system/entity/RcDeptExample.java package com.common.system.entity; import java.util.ArrayList; import java.util.List; public class RcDeptExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public RcDeptExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andNumIsNull() { addCriterion("num is null"); return (Criteria) this; } public Criteria andNumIsNotNull() { addCriterion("num is not null"); return (Criteria) this; } public Criteria andNumEqualTo(Integer value) { addCriterion("num =", value, "num"); return (Criteria) this; } public Criteria andNumNotEqualTo(Integer value) { addCriterion("num <>", value, "num"); return (Criteria) this; } public Criteria andNumGreaterThan(Integer value) { addCriterion("num >", value, "num"); return (Criteria) this; } public Criteria andNumGreaterThanOrEqualTo(Integer value) { addCriterion("num >=", value, "num"); return (Criteria) this; } public Criteria andNumLessThan(Integer value) { addCriterion("num <", value, "num"); return (Criteria) this; } public Criteria andNumLessThanOrEqualTo(Integer value) { addCriterion("num <=", value, "num"); return (Criteria) this; } public Criteria andNumIn(List<Integer> values) { addCriterion("num in", values, "num"); return (Criteria) this; } public Criteria andNumNotIn(List<Integer> values) { addCriterion("num not in", values, "num"); return (Criteria) this; } public Criteria andNumBetween(Integer value1, Integer value2) { addCriterion("num between", value1, value2, "num"); return (Criteria) this; } public Criteria andNumNotBetween(Integer value1, Integer value2) { addCriterion("num not between", value1, value2, "num"); return (Criteria) this; } public Criteria andPidIsNull() { addCriterion("pid is null"); return (Criteria) this; } public Criteria andPidIsNotNull() { addCriterion("pid is not null"); return (Criteria) this; } public Criteria andPidEqualTo(Integer value) { addCriterion("pid =", value, "pid"); return (Criteria) this; } public Criteria andPidNotEqualTo(Integer value) { addCriterion("pid <>", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThan(Integer value) { addCriterion("pid >", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThanOrEqualTo(Integer value) { addCriterion("pid >=", value, "pid"); return (Criteria) this; } public Criteria andPidLessThan(Integer value) { addCriterion("pid <", value, "pid"); return (Criteria) this; } public Criteria andPidLessThanOrEqualTo(Integer value) { addCriterion("pid <=", value, "pid"); return (Criteria) this; } public Criteria andPidIn(List<Integer> values) { addCriterion("pid in", values, "pid"); return (Criteria) this; } public Criteria andPidNotIn(List<Integer> values) { addCriterion("pid not in", values, "pid"); return (Criteria) this; } public Criteria andPidBetween(Integer value1, Integer value2) { addCriterion("pid between", value1, value2, "pid"); return (Criteria) this; } public Criteria andPidNotBetween(Integer value1, Integer value2) { addCriterion("pid not between", value1, value2, "pid"); return (Criteria) this; } public Criteria andSimpleNameIsNull() { addCriterion("simple_name is null"); return (Criteria) this; } public Criteria andSimpleNameIsNotNull() { addCriterion("simple_name is not null"); return (Criteria) this; } public Criteria andSimpleNameEqualTo(String value) { addCriterion("simple_name =", value, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameNotEqualTo(String value) { addCriterion("simple_name <>", value, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameGreaterThan(String value) { addCriterion("simple_name >", value, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameGreaterThanOrEqualTo(String value) { addCriterion("simple_name >=", value, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameLessThan(String value) { addCriterion("simple_name <", value, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameLessThanOrEqualTo(String value) { addCriterion("simple_name <=", value, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameLike(String value) { addCriterion("simple_name like", value, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameNotLike(String value) { addCriterion("simple_name not like", value, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameIn(List<String> values) { addCriterion("simple_name in", values, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameNotIn(List<String> values) { addCriterion("simple_name not in", values, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameBetween(String value1, String value2) { addCriterion("simple_name between", value1, value2, "simpleName"); return (Criteria) this; } public Criteria andSimpleNameNotBetween(String value1, String value2) { addCriterion("simple_name not between", value1, value2, "simpleName"); return (Criteria) this; } public Criteria andFullNameIsNull() { addCriterion("full_name is null"); return (Criteria) this; } public Criteria andFullNameIsNotNull() { addCriterion("full_name is not null"); return (Criteria) this; } public Criteria andFullNameEqualTo(String value) { addCriterion("full_name =", value, "fullName"); return (Criteria) this; } public Criteria andFullNameNotEqualTo(String value) { addCriterion("full_name <>", value, "fullName"); return (Criteria) this; } public Criteria andFullNameGreaterThan(String value) { addCriterion("full_name >", value, "fullName"); return (Criteria) this; } public Criteria andFullNameGreaterThanOrEqualTo(String value) { addCriterion("full_name >=", value, "fullName"); return (Criteria) this; } public Criteria andFullNameLessThan(String value) { addCriterion("full_name <", value, "fullName"); return (Criteria) this; } public Criteria andFullNameLessThanOrEqualTo(String value) { addCriterion("full_name <=", value, "fullName"); return (Criteria) this; } public Criteria andFullNameLike(String value) { addCriterion("full_name like", value, "fullName"); return (Criteria) this; } public Criteria andFullNameNotLike(String value) { addCriterion("full_name not like", value, "fullName"); return (Criteria) this; } public Criteria andFullNameIn(List<String> values) { addCriterion("full_name in", values, "fullName"); return (Criteria) this; } public Criteria andFullNameNotIn(List<String> values) { addCriterion("full_name not in", values, "fullName"); return (Criteria) this; } public Criteria andFullNameBetween(String value1, String value2) { addCriterion("full_name between", value1, value2, "fullName"); return (Criteria) this; } public Criteria andFullNameNotBetween(String value1, String value2) { addCriterion("full_name not between", value1, value2, "fullName"); return (Criteria) this; } public Criteria andTipsIsNull() { addCriterion("tips is null"); return (Criteria) this; } public Criteria andTipsIsNotNull() { addCriterion("tips is not null"); return (Criteria) this; } public Criteria andTipsEqualTo(String value) { addCriterion("tips =", value, "tips"); return (Criteria) this; } public Criteria andTipsNotEqualTo(String value) { addCriterion("tips <>", value, "tips"); return (Criteria) this; } public Criteria andTipsGreaterThan(String value) { addCriterion("tips >", value, "tips"); return (Criteria) this; } public Criteria andTipsGreaterThanOrEqualTo(String value) { addCriterion("tips >=", value, "tips"); return (Criteria) this; } public Criteria andTipsLessThan(String value) { addCriterion("tips <", value, "tips"); return (Criteria) this; } public Criteria andTipsLessThanOrEqualTo(String value) { addCriterion("tips <=", value, "tips"); return (Criteria) this; } public Criteria andTipsLike(String value) { addCriterion("tips like", value, "tips"); return (Criteria) this; } public Criteria andTipsNotLike(String value) { addCriterion("tips not like", value, "tips"); return (Criteria) this; } public Criteria andTipsIn(List<String> values) { addCriterion("tips in", values, "tips"); return (Criteria) this; } public Criteria andTipsNotIn(List<String> values) { addCriterion("tips not in", values, "tips"); return (Criteria) this; } public Criteria andTipsBetween(String value1, String value2) { addCriterion("tips between", value1, value2, "tips"); return (Criteria) this; } public Criteria andTipsNotBetween(String value1, String value2) { addCriterion("tips not between", value1, value2, "tips"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.github.holyloop.jencode; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.PropertySource; import com.github.holyloop.jencode.dao.BaseMapper; @SpringBootApplication @MapperScan(basePackageClasses = { BaseMapper.class }) public class MainApplication { public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } }
export enum COUNTRY_CODES { AF = 'AF', AL = 'AL', DZ = 'DZ', AS = 'AS', AD = 'AD', AO = 'AO', AI = 'AI', AG = 'AG', AR = 'AR', AM = 'AM', AW = 'AW', AU = 'AU', AT = 'AT', AZ = 'AZ', BS = 'BS', BH = 'BH', BD = 'BD', BB = 'BB', BY = 'BY', BE = 'BE', BZ = 'BZ', BJ = 'BJ', BM = 'BM', BT = 'BT', BO = 'BO', BA = 'BA', BW = 'BW', BR = 'BR', IO = 'IO', BN = 'BN', BG = 'BG', BF = 'BF', BI = 'BI', KH = 'KH', CM = 'CM', CA = 'CA', CV = 'CV', KY = 'KY', CF = 'CF', TD = 'TD', CL = 'CL', CN = 'CN', CX = 'CX', CC = 'CC', CO = 'CO', KM = 'KM', CG = 'CG', CD = 'CD', CK = 'CK', CR = 'CR', CI = 'CI', HR = 'HR', CU = 'CU', CY = 'CY', CZ = 'CZ', DK = 'DK', DJ = 'DJ', DM = 'DM', DO = 'DO', EC = 'EC', EG = 'EG', SV = 'SV', GQ = 'GQ', ER = 'ER', EE = 'EE', ET = 'ET', FK = 'FK', FO = 'FO', FJ = 'FJ', FI = 'FI', FR = 'FR', GF = 'GF', PF = 'PF', GA = 'GA', GM = 'GM', GE = 'GE', DE = 'DE', GH = 'GH', GI = 'GI', GR = 'GR', GL = 'GL', GD = 'GD', GP = 'GP', GU = 'GU', GT = 'GT', GG = 'GG', GN = 'GN', GW = 'GW', GY = 'GY', HT = 'HT', VA = 'VA', HN = 'HN', HK = 'HK', HU = 'HU', IS = 'IS', IN = 'IN', ID = 'ID', IR = 'IR', IQ = 'IQ', IE = 'IE', IM = 'IM', IL = 'IL', IT = 'IT', JM = 'JM', JP = 'JP', JE = 'JE', JO = 'JO', KZ = 'KZ', KE = 'KE', KI = 'KI', KP = 'KP', KR = 'KR', KW = 'KW', KG = 'KG', LA = 'LA', LV = 'LV', LB = 'LB', LS = 'LS', LR = 'LR', LY = 'LY', LI = 'LI', LT = 'LT', LU = 'LU', MO = 'MO', MK = 'MK', MG = 'MG', MW = 'MW', MY = 'MY', MV = 'MV', ML = 'ML', MT = 'MT', MH = 'MH', MQ = 'MQ', MR = 'MR', MU = 'MU', YT = 'YT', MX = 'MX', FM = 'FM', MD = 'MD', MC = 'MC', MN = 'MN', ME = 'ME', MS = 'MS', MA = 'MA', MZ = 'MZ', MM = 'MM', NA = 'NA', NR = 'NR', NP = 'NP', NL = 'NL', AN = 'AN', NC = 'NC', NZ = 'NZ', NI = 'NI', NE = 'NE', NG = 'NG', NU = 'NU', NF = 'NF', MP = 'MP', NO = 'NO', OM = 'OM', PK = 'PK', PW = 'PW', PS = 'PS', PA = 'PA', PG = 'PG', PY = 'PY', PE = 'PE', PH = 'PH', PN = 'PN', PL = 'PL', PT = 'PT', PR = 'PR', QA = 'QA', RO = 'RO', RU = 'RU', RW = 'RW', RE = 'RE', BL = 'BL', SH = 'SH', KN = 'KN', LC = 'LC', MF = 'MF', PM = 'PM', VC = 'VC', WS = 'WS', SM = 'SM', ST = 'ST', SA = 'SA', SN = 'SN', RS = 'RS', SC = 'SC', SL = 'SL', SG = 'SG', SK = 'SK', SI = 'SI', SB = 'SB', SO = 'SO', ZA = 'ZA', GS = 'GS', ES = 'ES', LK = 'LK', SD = 'SD', SR = 'SR', SJ = 'SJ', SZ = 'SZ', SE = 'SE', CH = 'CH', SY = 'SY', TW = 'TW', TJ = 'TJ', TZ = 'TZ', TH = 'TH', TL = 'TL', TG = 'TG', TK = 'TK', TO = 'TO', TT = 'TT', TN = 'TN', TR = 'TR', TM = 'TM', TC = 'TC', TV = 'TV', UG = 'UG', UA = 'UA', AE = 'AE', GB = 'GB', US = 'US', UY = 'UY', UZ = 'UZ', VU = 'VU', VE = 'VE', VN = 'VN', VG = 'VG', VI = 'VI', WF = 'WF', YE = 'YE', ZM = 'ZM', ZW = 'ZW', AX = 'AX', }
const sinon = require('sinon'); const expect = require('expect'); const { ObjectId } = require('mongodb'); const ActivityHistory = require('../../../src/models/ActivityHistory'); const UserCompany = require('../../../src/models/UserCompany'); const ActivityHistoryHelper = require('../../../src/helpers/activityHistories'); const SinonMongoose = require('../sinonMongoose'); describe('addActivityHistory', () => { let create; beforeEach(() => { create = sinon.stub(ActivityHistory, 'create'); }); afterEach(() => { create.restore(); }); it('should create an activityHistory', async () => { const activityId = new ObjectId(); const userId = new ObjectId(); const questionnaireAnswersList = [{ card: new ObjectId(), answerList: ['blabla'] }]; await ActivityHistoryHelper.addActivityHistory({ user: userId, activity: activityId, questionnaireAnswersList }); sinon.assert.calledOnceWithExactly( create, { user: userId, activity: activityId, questionnaireAnswersList } ); }); }); describe('list', () => { let findUserCompanies; let findHistories; beforeEach(() => { findHistories = sinon.stub(ActivityHistory, 'find'); findUserCompanies = sinon.stub(UserCompany, 'find'); }); afterEach(() => { findHistories.restore(); findUserCompanies.restore(); }); it('should return a list of histories', async () => { const companyId = new ObjectId(); const query = { startDate: '2020-12-10T23:00:00', endDate: '2021-01-10T23:00:00' }; const firstUserId = new ObjectId(); const secondUserId = new ObjectId(); const activityHistories = [ { user: firstUserId, activity: { steps: [ { subPrograms: [{ program: { name: 'une incroyable découverte' }, courses: [{ misc: 'groupe 1', format: 'strictly_e_learning', trainees: [firstUserId] }], }], }, { name: 'step without subprogram', subPrograms: [] }, ], }, }, { user: firstUserId, activity: { steps: [] } }, { user: secondUserId, activity: { steps: [{ subPrograms: [{ program: { name: 'une rencontre sensationnelle' }, courses: [{ misc: 'groupe 2', format: 'strictly_e_learning', trainees: [new ObjectId()] }], }], }], }, }]; const filteredActivityHistories = { user: firstUserId, activity: { steps: [{ subPrograms: [{ program: { name: 'une incroyable découverte' }, courses: [{ misc: 'groupe 1', format: 'strictly_e_learning', trainees: [firstUserId] }], }], }], }, }; findUserCompanies.returns( SinonMongoose.stubChainedQueries([{ user: firstUserId }, { user: secondUserId }], ['lean']) ); findHistories.returns(SinonMongoose.stubChainedQueries(activityHistories)); const result = await ActivityHistoryHelper.list(query, { company: { _id: companyId } }); expect(result).toEqual([filteredActivityHistories]); SinonMongoose.calledOnceWithExactly( findUserCompanies, [{ query: 'find', args: [{ company: companyId }, { user: 1 }] }, { query: 'lean' }] ); SinonMongoose.calledOnceWithExactly( findHistories, [ { query: 'find', args: [{ date: { $lte: new Date('2021-01-10T23:00:00'), $gte: new Date('2020-12-10T23:00:00') }, user: { $in: [firstUserId, secondUserId] }, }], }, { query: 'populate', args: [{ path: 'activity', select: '_id', populate: { path: 'steps', select: '_id', populate: { path: 'subPrograms', select: '_id', populate: [ { path: 'courses', select: 'misc format trainees', match: { format: 'strictly_e_learning' } }, { path: 'program', select: 'name' }], }, }, }], }, { query: 'populate', args: [{ path: 'user', select: '_id identity picture' }] }, { query: 'lean' }, ] ); }); });
package backend; import models.Destination; import models.DestinationGraph; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created by user on 10/28/2020. */ public class Services { /** * Get the shortest distance between a destination and all other destinations. * @param destinations - an object of DestinationGraph * @param reference - index of the source destination. * @return an array of double that signifies the shortest distance from that destination to the source destination. */ public static double[][] getShortestDistances(DestinationGraph destinations, int reference) { Dijkstra d = new Dijkstra(destinations.getDistanceAdjMatrixArray()); BellmanFord b = new BellmanFord(destinations.getDistanceRowGraphArray(), destinations.getDestinationNames().size()); return d.compute(reference); } /** * Get the lowest cost between a destination and all other destinations. * @param destinations - an object of DestinationGraph * @param reference - index of the source destination. * @return an array of double that signifies the lowest cost from that destination to the source destination. */ public static double[][] getCheapestCosts(DestinationGraph destinations, int reference) { Dijkstra d = new Dijkstra(destinations.getCostAdjMatrixArray()); BellmanFord b = new BellmanFord(destinations.getCostRowGraphArray(), destinations.getDestinationNames().size()); return d.compute(reference); } /** * Convert a 2D List to a 2D Array * @param list * @return a 2D Array */ public static double[][] convert2DListToArray(List<ArrayList<Double>> list) { int size = list.size(); double[][] arr = new double[size][size]; for (int i=0; i<size; i++) { for (int a=0; a<size; a++) { arr[i][a] = list.get(i).get(a); } } return arr; } /** * Converts adjacency matrix to row graph matrix (in 2D array format) * @param adjMatrix - a List<ArrayList<Double>> object * @return a double[][3] object */ public static double[][] convertAdjMatrixToRowGraphMatrix(List<ArrayList<Double>> adjMatrix) { int size = adjMatrix.size(); List<ArrayList<Double>> list = new ArrayList<>(); //Each connection will have 3 items: vertex 1 index, vertex 2 index, weight //Convert adjacency matrix to adjacency list for (int i=0; i<size; i++) { for (int a=0; a<size; a++) { double val = adjMatrix.get(i).get(a); if (val != 0d) { //Establish connection ArrayList<Double> subList = new ArrayList<>(); subList.add((double)i); //Vertex 1 index subList.add((double)a); //Vertex 2 index subList.add(val); //Weight //Add to list list.add(subList); } } } //Convert to primitive 2D array double[][] arr = new double[list.size()][3]; //Each connection will have 3 items: vertex 1 index, vertex 2 index, weight for (int i=0; i<list.size(); i++) { for (int a=0; a<3; a++) { arr[i][a] = list.get(i).get(a); } } return arr; } public static void main (String args[]) { DestinationGraph dg = new DestinationGraph(); dg.addDestination(new Destination("Jakarta")); dg.addDestination(new Destination("Surabaya")); dg.addDestination(new Destination("Jogja")); dg.setDistance(0, 1, 15); dg.setDistance(1, 0, 10); dg.setDistance(2, 0, 30); dg.setDistance(0, 2, 17); dg.setDistance(2, 1, 12); for (ArrayList<Double> sub : dg.getDistanceMatrix()) { for (Double d : sub) { System.out.print(d + " "); } System.out.println(); } System.out.println(); double[][] pathTable = Services.getShortestDistances(dg, 1 ); for (int i=0; i<dg.getDestinationNames().size(); i++) { System.out.println(i + " " + pathTable[0][i] + " " + pathTable[1][i]); } } }
#!/bin/sh # CYBERWATCH SAS - 2017 # # Security fix for CESA-2012:0095 # # Security announcement date: 2012-02-03 02:16:06 UTC # Script generation date: 2017-01-05 21:19:10 UTC # # Operating System: CentOS 6 # Architecture: x86_64 # # Vulnerable packages fix on version: # - ghostscript.i686:8.70-11.el6_2.6 # - ghostscript-devel.i686:8.70-11.el6_2.6 # - ghostscript.x86_64:8.70-11.el6_2.6 # - ghostscript-devel.x86_64:8.70-11.el6_2.6 # - ghostscript-doc.x86_64:8.70-11.el6_2.6 # - ghostscript-gtk.x86_64:8.70-11.el6_2.6 # # Last versions recommanded by security team: # - ghostscript.i686:8.70-21.el6_8.1 # - ghostscript-devel.i686:8.70-21.el6_8.1 # - ghostscript.x86_64:8.70-21.el6_8.1 # - ghostscript-devel.x86_64:8.70-21.el6_8.1 # - ghostscript-doc.x86_64:8.70-21.el6_8.1 # - ghostscript-gtk.x86_64:8.70-21.el6_8.1 # # CVE List: # - CVE-2009-3743 # - CVE-2010-2055 # - CVE-2010-4054 # - CVE-2010-4820 # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo yum install ghostscript.i686-8.70 -y sudo yum install ghostscript-devel.i686-8.70 -y sudo yum install ghostscript.x86_64-8.70 -y sudo yum install ghostscript-devel.x86_64-8.70 -y sudo yum install ghostscript-doc.x86_64-8.70 -y sudo yum install ghostscript-gtk.x86_64-8.70 -y
package evilcraft.render.entity; import net.minecraft.client.model.ModelBase; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import evilcraft.api.config.ExtendedConfig; import evilcraft.api.config.MobConfig; import evilcraft.api.render.ModelRenderLiving; import evilcraft.entities.monster.Werewolf; /** * Renderer for a werewolf * * @author rubensworks * */ public class RenderWerewolf extends ModelRenderLiving<ModelBase> { /** * Make a new instance * @param config The config. * @param model The model. * @param par2 No idea... */ public RenderWerewolf(ExtendedConfig<MobConfig> config, ModelBase model, float par2) { super(config, model, par2); } private void renderWerewolf(Werewolf werewolf, double x, double y, double z, float yaw, float partialTickTime) { super.doRender(werewolf, x, y, z, yaw, partialTickTime); } @Override public void doRender(EntityLiving par1EntityLiving, double x, double y, double z, float yaw, float partialTickTime) { this.renderWerewolf((Werewolf)par1EntityLiving, x, y, z, yaw, partialTickTime); } @Override public void doRender(Entity par1Entity, double x, double y, double z, float yaw, float partialTickTime) { this.renderWerewolf((Werewolf)par1Entity, x, y, z, yaw, partialTickTime); } }
#!/bin/sh BUILDDIR='build' [ ! -d "$BUILDDIR" ] && echo "build directory not found" && exit 1 cd "$BUILDDIR" ctest cd ..
#!/bin/sh # ============================================================== # Script for starting the monitoring component for ExplorViz # # Christian Zirkelbach (czi@informatik.uni-kiel.de) # ============================================================== # When this script exits (e.g. due to Ctrl-C) kill all our children as well trap "trap - TERM && kill 0" INT TERM EXIT ./kiekerSystemMonitoring/kieker-1.14-SNAPSHOT/bin/resourceMonitor.sh & java -javaagent:kieker-1.14-SNAPSHOT-aspectj.jar -Dkieker.monitoring.skipDefaultAOPConfiguration=true -Dkieker.monitoring.configuration=./META-INF/kieker.monitoring.sampleApplication.properties -Dorg.aspectj.weaver.loadtime.configuration=./META-INF/aop.sampleApplication.xml -cp . -jar sampleApplication.jar & java -javaagent:kieker-1.14-SNAPSHOT-aspectj.jar -Dkieker.monitoring.skipDefaultAOPConfiguration=true -Dkieker.monitoring.configuration=./META-INF/kieker.monitoring.remoteSampleApplicationServer.properties -Dorg.aspectj.weaver.loadtime.configuration=./META-INF/aop.remoteSampleApplicationServer.xml -cp . -jar remoteSampleApplicationServer.jar & # Allow server some time to start before starting clients sleep 3 while true; do java -javaagent:kieker-1.14-SNAPSHOT-aspectj.jar -Dkieker.monitoring.skipDefaultAOPConfiguration=true -Dkieker.monitoring.configuration=./META-INF/kieker.monitoring.remoteSampleApplicationClient.properties -Dorg.aspectj.weaver.loadtime.configuration=./META-INF/aop.remoteSampleApplicationClient.xml -cp . -jar remoteSampleApplicationClient.jar & sleep 5 done
/* #Todo API ##Todo API w/ a backend database using user token for validation to create/fetch items. ### Objective of API: ####1. POST/GET/DELETE/UPDATE a new Todo item. ####2. User login/logout with email and password (must be unique & password must be 7 chars in len) ####3. Delete/Filter/Search a Todo item. ####4. Web token access only to each unique user. ####5. Todos are private with user association id access. ##### Getting Started: 1. First run: npm install for all node modules needed. 2. Start app: node server.js 3. Use Postman to test and/or use SQlite Browser to see your database. 4. Make sure you copy/paste auth token created to use for testing in postman. 5. You can use create user then login user to start testing. */ var express = require('express'); var bodyParser = require('body-parser'); var underScore = require('underscore'); var db = require('./db.js'); var bcrypt = require('bcrypt'); var middleware = require('./middleware.js')(db); var app = express(); var PORT = process.env.PORT || 3000; var todos = []; var todoNextId = 1; app.use(bodyParser.json()); // GET /todos and/or GET/todos?completed=true and/or by GET/todos?q=work app.get('/todos', middleware.requireAuthentication, function(req, res) { // Filter for a completed Todo item with user ID association var query = req.query; var where = { userId: req.user.get('id') }; if(query.hasOwnProperty('completed') && query.completed === 'true') { where.completed = true; }else if(query.hasOwnProperty('completed') && query.completed === 'false') { where.completed = false; } if(query.hasOwnProperty('q') && query.q.length > 0) { where.description = { $like: '%' + query.q + '%' }; } db.todo.findAll({where: where}).then(function(todos) { res.json(todos); }, function(e) { res.status(500).send(); }); }); // GET /todos/:id app.get('/todos/:id', middleware.requireAuthentication, function(req, res) { var todoId = parseInt(req.params.id, 10); db.todo.findOne({ where: { id: todoId, userId: req.user.get('id') } }).then(function(todo) { if(!!todo) { res.json(todo.toJSON()); }else { res.status(404).send(); } }, function(e) { res.status(500).send(); }); }); // add todos through the Api // POST REQUEST /todos - api route app.post('/todos', middleware.requireAuthentication, function(req, res) { var body = underScore.pick(req.body, 'description', 'completed'); // Call create on db.todo db.todo.create(body).then(function(todo) { // create user association with user id req.user.addTodo(todo).then(function() { return todo.reload(); }).then(function(todo) { res.json(todo.toJSON()); }); }, function(e) { res.status(400).json(e); }); }); // DELETE /todos/:id // Delete a todo by its id app.delete('/todos/:id', middleware.requireAuthentication, function(req,res) { var todoId = parseInt(req.params.id, 10); db.todo.destroy({ // Find the todo item where: { id: todoId, userId: req.user.get('id') } }).then(function(rowsDeleted) { if(rowsDeleted === 0) { res.status(404).json({ // Error: error: 'No Todo item with that ID found!' }); }else { // Success: found a todo item to delete res.status(204).send(); } }, function() { res.status(500).send(); }); }); // PUT /todos/:id // Update/Create a Todo item app.put('/todos/:id', middleware.requireAuthentication, function(req, res) { var todoId = parseInt(req.params.id, 10); var body = underScore.pick(req.body, 'description', 'completed'); // store the values of the todos in the todos array var attributes = {}; // check if 'completed' attribute exist and if so validate it if(body.hasOwnProperty('completed')) { attributes.completed = body.completed; } // check if 'description' attribute exist and if so validate it if(body.hasOwnProperty('description')) { attributes.description = body.description; } db.todo.findOne({ where: { id: todoId, userId: req.user.get('id') } }).then(function(todo) { // If findById goes well if(todo) { // Find id with success todo.update(attributes).then(function(todo) { // Success for the todo Update res.json(todo.toJSON()); console.log('----- -----'); console.log('Succes: Your Todo item has been updated!'); console.log('----- -----'); }, function(e) { //If todo update fails res.status(400).json(e); }); }else { res.status(404).send(); console.log('----- -----'); console.log('Todo item to be updated, not found!'); console.log('----- -----'); } }, function() { // If findById fails/ goes wrong res.status(500).send(); }); }); app.post('/users', function(req, res) { var body = underScore.pick(req.body, 'email', 'password'); db.user.create(body).then(function(user) { // Success: email must be unique & password must be 7 chars in len res.json(user.toPublicJSON()); }, function(e) { // Error res.status(400).json(e); console.log('----- -----'); console.log('Error: something went wrong with email and password for user!'); console.log('----- -----'); }); }); // user login with email and password // POST /users/login app.post('/users/login', function(req, res) { var body = underScore.pick(req.body, 'email', 'password'); var userInstance; db.user.authenticate(body).then(function(user) { // success var token = user.generateToken('authentication'); userInstance = user; // save hased token in the database return db.token.create({ token: token }); }).then(function(tokenInstance) { res.header('Auth', tokenInstance.get('token')).json(userInstance.toPublicJSON()); }).catch(function() { // Error res.status(401).send(); console.log('----- -----'); console.log('User Not Found!'); console.log('----- -----'); }); }); // DELETE /users/login - logout app.delete('/users/login', middleware.requireAuthentication, function(req, res) { // trash the hased token and logout user req.token.destroy().then(function() { res.status(204).send(); console.log('User logged out'); }).catch(function() { res.status(500).send(); console.log('Error logging out'); }); }); // Sync the db and run server // force: true is to clear the database each time its ran. db.sequelize.sync({force: true}).then(function() { // DB & Server listening on port 3000 app.listen(PORT, function() { console.log('----- -----'); console.log('Server Running on http://localhost' + ':' + PORT); console.log('----- -----'); }); });
<reponame>cremalab/boilerplate-app-web import { render, screen } from "@testing-library/react" import { App } from "./App" describe("App", () => { it("renders expected text", () => { // Arrange const text = "Learn React" // Act render(<App />) const received = screen.getByText(text) // Assert expect(received).toBeDefined() }) })
pub enum FBTypeKind { Scalar, // ... other variants may exist } pub const ENUM_VALUES_FBTYPE_KIND: [FBTypeKind; 1] = [FBTypeKind::Scalar]; pub const ENUM_NAMES_FBTYPE_KIND: [&str; 1] = ["Scalar"]; pub fn enum_name_fbtype_kind(e: FBTypeKind) -> &'static str { let index = e as usize; ENUM_NAMES_FBTYPE_KIND[index] } fn main() { let scalar_name = enum_name_fbtype_kind(FBTypeKind::Scalar); println!("Name of FBTypeKind::Scalar: {}", scalar_name); }
<gh_stars>0 package org.firstinspires.ftc.teamcode.opmodes.auto.test; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import org.firstinspires.ftc.teamcode.hardware.robots.Prometheus; import org.firstinspires.ftc.teamcode.match.Alliance; import org.firstinspires.ftc.teamcode.opmodes.auto.BaseAutoOp; import org.firstinspires.ftc.teamcode.subsystem.drive.DriveSystem; import org.firstinspires.ftc.teamcode.subsystem.drive.drivecontroller.PID.PIDComplexity; import org.firstinspires.ftc.teamcode.subsystem.sensors.gyro.GyroSensorSystem; @Autonomous(name = "Sesnor Test - Simple Rotation - PASSED", group = "test") public class RotationTest extends BaseAutoOp { private Alliance alliance = Alliance.RED; private Prometheus prometheus; @Override public void initializeClass() { prometheus = new Prometheus(this); setRobot(prometheus); setGamepadConfig(null); setAlliance(Alliance.BLUE); } @Override public void runOpMode() throws InterruptedException { super.runOpMode(); telemetry.addData("Status : ", "Do NOT have Timer on"); telemetry.update(); GyroSensorSystem gyroSensorSystem = (GyroSensorSystem) prometheus.getSubsystem(GyroSensorSystem.class); waitForStart(); while (opModeIsActive()) { ((DriveSystem) prometheus.getSubsystem(DriveSystem.class)).getMovementController() .rotate(null, -90, null, PIDComplexity.NONE); sleep(2000); ((DriveSystem) prometheus.getSubsystem(DriveSystem.class)).getMovementController() .rotate(null, 90, null, PIDComplexity.NONE); sleep(2000); stop(); } } }
<gh_stars>10-100 package cloudflare import ( "encoding/json" "errors" "fmt" "io" "net/http" "golang.org/x/net/context" ) var baseURL = "https://api.cloudflare.com/client/v4" func apiURL(format string, a ...interface{}) string { return fmt.Sprintf("%s%s", baseURL, fmt.Sprintf(format, a...)) } func readResponse(r io.Reader) (result *Response, err error) { result = new(Response) err = json.NewDecoder(r).Decode(result) if err != nil { return nil, err } else if err := result.Err(); err != nil { return nil, err } return } type httpResponse struct { resp *http.Response err error } func httpDo(ctx context.Context, opts *Options, method, url string, body io.Reader) (*http.Response, error) { req, err := http.NewRequest(method, url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Auth-Email", opts.Email) req.Header.Set("X-Auth-Key", opts.Key) transport := &http.Transport{} client := &http.Client{Transport: transport} respchan := make(chan *httpResponse, 1) go func() { resp, err := client.Do(req) if err == nil { if resp.ContentLength == 0 { err = errors.New("empty response body") } } respchan <- &httpResponse{resp: resp, err: err} }() select { case <-ctx.Done(): transport.CancelRequest(req) <-respchan return nil, ctx.Err() case r := <-respchan: return r.resp, r.err } }
<gh_stars>0 package com.gzwl.demo.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.gzwl.demo.pojo.DictionaryType; import com.gzwl.demo.pojo.DictionaryTypeExample; public interface DictionaryTypeMapper { long countByExample(DictionaryTypeExample example); int deleteByExample(DictionaryTypeExample example); int deleteByPrimaryKey(Integer dtkId); int insert(DictionaryType record); /** * 新增 * @param record * @return */ int insertSelective(DictionaryType record); /** * 查询 or 条件查询 * @param example * @return */ List<DictionaryType> selectByExample(DictionaryTypeExample example); /** * * @Title: customizationSelectByExample * @Desc: 定制查询 * @param example * @return */ List<DictionaryType> customizationSelectByExample(DictionaryTypeExample example); /** * 根据id查询 * @param dtkId * @return */ DictionaryType selectByPrimaryKey(Integer dtkId); int updateByExampleSelective(@Param("record") DictionaryType record, @Param("example") DictionaryTypeExample example); int updateByExample(@Param("record") DictionaryType record, @Param("example") DictionaryTypeExample example); /** * 修改 * @param record * @return */ int updateByPrimaryKeySelective(DictionaryType record); int updateByPrimaryKey(DictionaryType record); }
<filename>pkg/nic_online.go<gh_stars>0 package pkg import ( "fmt" "path/filepath" "strings" "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" "github.com/safchain/ethtool" ) type NicOnline struct { hostNicOnline *prometheus.Desc logger log.Logger } func NewNicOnline(promLog log.Logger) *NicOnline { return &NicOnline{ hostNicOnline: prometheus.NewDesc( "host_nic_on_line", "The host nic online status", []string{"interface"}, nil, ), logger: promLog, } } func (n *NicOnline) Describe(ch chan<- *prometheus.Desc) { ch <- n.hostNicOnline } func (n *NicOnline) Collect(ch chan<- prometheus.Metric) { nicState, err := getNicStatus() if err != nil { level.Error(n.logger).Log("msg", "Get Nic status failed") return } for k, v := range nicState { ch <- prometheus.MustNewConstMetric( n.hostNicOnline, prometheus.GaugeValue, v, k, ) } level.Info(n.logger).Log("msg", "collectd nic online status success") } func getNicStatus() (map[string]float64, error) { nicStatus := map[string]float64{} nicName, err := getNicName() if err != nil { return nil, err } ethHandle, err := ethtool.NewEthtool() if err != nil { return nil, err } defer ethHandle.Close() for _, nic := range nicName { stats, err := ethHandle.LinkState(nic) if err != nil { return nil, err } nicStatus[nic] = float64(stats) } return nicStatus, nil } func getNicName() ([]string, error) { var pciNumber []string var nicNames []string res, err := Execute("/bin/sh", "-c", `lspci | grep -i Ethernet`) if err != nil { return nil, err } for _, line := range strings.Split(string(res), "\n") { pciInfo := strings.Split(line, " ") if pciInfo[0] == "" { continue } pciNumber = append(pciNumber, pciInfo[0]) } for _, pci := range pciNumber { path := fmt.Sprintf("/sys/bus/pci/devices/0000:%s/net/*/mtu", pci) paths, _ := filepath.Glob(path) if len(paths) == 0 { return nil, fmt.Errorf("get nic crad name failed") } dirName, _ := filepath.Split(paths[0]) nic := strings.Split(dirName, "net")[1] nicName := strings.Trim(nic, "/") nicNames = append(nicNames, nicName) } return nicNames, nil }
<gh_stars>0 ######################################PAPER from __future__ import annotations from sklearn.preprocessing import StandardScaler import numpy import numpy as np import pandas as pd import os import copy import seaborn as sns import matplotlib.pyplot as plt import matplotlib as mpl from partd import pandas from scipy import stats from sklearn.metrics import r2_score from scipy.optimize import curve_fit from sklearn.svm import SVR from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from sklearn.linear_model import LinearRegression import statsmodels.api as sm from statsmodels.sandbox.regression.predstd import wls_prediction_std from scipy.stats import norm from scipy import special import joblib from sklearn.metrics import mean_absolute_error from statsmodels.stats.multicomp import pairwise_tukeyhsd from statsmodels.stats.multicomp import MultiComparison import xgboost as xgb from xgboost import plot_importance from sklearn.model_selection import StratifiedKFold from sklearn.metrics import roc_curve, auc from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score, recall_score, f1_score from sklearn.metrics import roc_auc_score from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier as rfc from sklearn.linear_model import LogisticRegression as lr from sklearn.model_selection import cross_val_score from sklearn.preprocessing import normalize from sklearn.preprocessing import OneHotEncoder from sklearn import metrics from sklearn.preprocessing import label_binarize from itertools import cycle import math from sklearn.feature_selection import RFE from sklearn.svm import LinearSVC from sklearn.naive_bayes import GaussianNB # plt.rcParams['font.sans-serif']=['SimHei'] # plt.rcParams['axes.unicode_minus'] = False def remove_fliers_with_boxplot(data, col): p = data[col].boxplot(return_type='dict') # 获取异常值 for index, value in enumerate(data[col].columns): fliers_value_list = p['fliers'][index].get_ydata() # 删除异常值 for flier in fliers_value_list: data = data[data.loc[:, value] != flier] return data def ZscoreNormalization(x, mean, std): """Z-score normaliaztion""" x = (x - mean) / std return x def MinMaxNormalization(x, Max, Min): """Z-score normaliaztion""" x = (x - Min) / (Max - Min) return x def plot_regression_results(ax, y_true, y_pred, scores): # ax子图像 """Scatter plot of the predicted vs true targets.""" ax.plot([y_true.min(), y_true.max()], # y=x线,范围:实际年龄 [y_true.min(), y_true.max()], '--r', linewidth=2) ax.scatter(y_true, y_pred, alpha=0.2) #####################坐标轴设置################# ax.spines['top'].set_visible(False) # spine:脊。去掉top和right边框(隐藏坐标轴) ax.spines['right'].set_visible(False) ax.get_xaxis().tick_bottom() # 底边框作为x(自变量)轴,左边框作为y(因变量)轴(x.y轴绑定) ax.get_yaxis().tick_left() ax.spines['left'].set_position(('outward', 10)) # 将x,y轴绑定到特定位置(交点为(10,10)) ax.spines['bottom'].set_position(('outward', 10)) ax.set_xlim([y_true.min(), y_true.max()]) # 设置坐标轴刻度(范围,真实年龄的最大、最小值) ax.set_ylim([y_true.min(), y_true.max()]) # ax.set_xlabel('Measured') # #设置x、y轴名称 ax.set_ylabel('Predicted') extra = plt.Rectangle((0, 0), 0, 0, fc="w", fill=False, # 画矩形图,画图起点(0,0),矩形宽度0???????????、矩形高度0?????????????? edgecolor='none', linewidth=0) ax.legend([extra], [scores], loc='upper left', fontsize=16) def get_p(groupA, groupB): all_in = groupA.append(groupB) all_labels = [0 for i in range(len(groupA))] + [1 for i in range(len(groupB))] mc = MultiComparison(all_in, all_labels) result = mc.tukeyhsd() return result.pvalues[0] def get_spe(y_true, y_pred): # true positive TP = np.sum(np.multiply(y_true, y_pred)) ##########数组对应位置元素相乘 1→1 # false positive FP = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 1))) ############逐元素计算逻辑与 0→1 # false negative FN = np.sum(np.logical_and(np.equal(y_true, 1), np.equal(y_pred, 0))) ###########1→0 # true negative TN = np.sum(np.logical_and(np.equal(y_true, 0), np.equal(y_pred, 0))) ##########0→0 spe = TN / (TN + FP) return spe def read_source_relative_site(csv_path: str | None = "volume_sum_icv_site.csv"): """ :param csv_path: str :return: Train and test dataset of independent variables X and dependent variable y, where X is labels' relative value to ICV. """ MRI_source_df = pandas.read_csv(csv_path) MRI_source_df = MRI_source_df[MRI_source_df['sites'].isin([1])] X_df = MRI_source_df.iloc[:, 1:-8] icv_df = MRI_source_df.iloc[:, -4] y_df = MRI_source_df.iloc[:, -2] X = X_df y = y_df icv = icv_df icv = icv[:, np.newaxis] y = y[:, np.newaxis] X = X / icv # X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) return X, X, y, y # 这一部分读入你的ADNI(sites=1)相对体积数据,并进行train_test_split train = pd.read_csv('volume_sum_icv_site.csv') train = train[train['sites'].isin([1])] X_train = train.drop(columns=['name', 'age', 'sex', 'sites', 'GM', 'WM', 'CSF', 'ICV', 'sum_vol']) X_train = (X_train / train['ICV'][:, np.newaxis]).iloc[0:1155, :] y_train = (train['age']) y_train = y_train.iloc[0:1155] X_test = train.drop(columns=['name', 'age', 'sex', 'sites', 'GM', 'WM', 'CSF', 'ICV', 'sum_vol']) X_test = (X_test / train['ICV'][:, np.newaxis]).iloc[1155:-1, :] y_test = (train['age']) y_test = y_test.iloc[1155:-1] sc_X = StandardScaler() sc_y = StandardScaler() X_train_sc = sc_X.fit_transform(X_train) X_test_sc = sc_X.fit_transform(X_test) y_train_axis = y_train[:, np.newaxis] y_test_axis = y_test[:, np.newaxis] y_train_np = pd.Series.to_numpy(y_train) y_test_np = pd.Series.to_numpy(y_test) y_train_re = np.reshape(y_train_np, (-1, 1)) y_test_re = np.reshape(y_test_np, (-1, 1)) y_train_sc = sc_y.fit_transform(y_train_re) y_test_sc = sc_y.fit_transform(y_test_re) ###########训练模型 #model = xgb.XGBRegressor() #model = LinearRegression() model = SVR() # model = joblib.load(r'SVR') # model = joblib.load(r'linear') # model = joblib.load(r'xgb') model.fit(X_train_sc, y_train_sc) # y_pred_sc = model.predict(X_test_sc) # y_pred_sc_axis = y_pred_sc[:, np.newaxis] # y_pred = sc_y.inverse_transform(y_pred_sc) y_pred_sc = model.predict(X_test_sc) y_pred_2d = np.reshape(y_pred_sc, (-1, 1)) y_pred = sc_y.inverse_transform(y_pred_2d) # print("Pearson:", np.corrcoef(np.array([y_test, y_pred]))) # df = pd.DataFrame() # df['y_true'] = y_test # df['y_pred'] = y_pred # df.to_csv(r"D:\rc\毕设\CSV\prediction.csv", index=False) fig, axs = plt.subplots(1, 1, figsize=(5, 3.5), dpi=200) axs = np.ravel(axs) for ax in axs: score1 = r2_score(y_test, y_pred) score2 = mean_absolute_error(y_test, y_pred) plot_regression_results(ax, y_test, y_pred, (r'$R^2={:.2f}$' + '\n' + r'$MAE={:.2f}$').format(score1, score2)) # plt.title('模型测试结果', fontsize=16) def Fun(x, a1, a2): # 定义拟合函数形式 return a1 * x + a2 x = pd.Series.to_numpy(y_test) # 创建时间序列 a1, a2 = [1, 5] # 原始数据的参数 y = y_pred y = y.squeeze() para, pcov = curve_fit(Fun, x, y) y_fitted = Fun(x, para[0], para[1]) # 画出拟合后的曲线 plt.plot(x, y_fitted, '-g', label='Fitted curve') print(para) # plt.tight_layout() # plt.subplots_adjust(top=0.9) plt.xticks(fontsize=8) plt.yticks(fontsize=8) plt.xlabel('Chronological age', fontsize=8) plt.ylabel('Predicted age', fontsize=8) # plt.savefig(r"D:\rc\paper\fig\model.png", dpi=400) plt.show()
public void optimizeSchedulingAlgorithm(int numProcesses, int[] arrivalTime, int[] burstTime) { int[] priority_queue = new int[numProcesses]; int[] waitQueue = new int[numProcesses]; // calculate turnaround time int[] tat = new int[numProcesses]; for (int i = 0; i < numProcesses; i++) tat[i] = burstTime[i] + waitQueue[i]; // Calculate total waiting time int totalWaitingTime = 0; for (int i=0; i<numProcesses; i++) totalWaitingTime += waitQueue[i]; // Calculate average waiting time double avgWaitingTime = (float)totalWaitingTime / (float)numProcesses; // Calculate average turn around time double avgTAT = (float)totalWaitingTime / (float)numProcesses; // Print the optimized scheduling System.out.println("Optimized CPU Scheduling"); System.out.println("Arrival time \t Burst time \t Priority queue \t Waiting time \t Turn around time"); for (int i = 0; i < numProcesses; i++) { System.out.println(arrivalTime[i] + "\t\t" + burstTime[i] + "\t\t" + priority_queue[i] + "\t\t" + waitQueue[i] + "\t\t" + tat[i]); } System.out.println("Average waiting time = " +avgWaitingTime); System.out.println("Average turn around time = " +avgTAT); }
import { FindAllQueryDTO } from '../../shared'; import { USER_ALLOWED_RELATIONS, USER_ALLOWED_SELECT_FIELDS, USER_ALLOWED_SORT_FIELDS } from '../constants/user-fields'; import { UpdateUserDTO } from './update-user-dto'; // Assuming the correct path for UpdateUserDTO export class FindUsersQueryDTO extends IntersectionType( FindAllQueryDTO(USER_ALLOWED_SELECT_FIELDS, USER_ALLOWED_SORT_FIELDS, USER_ALLOWED_RELATIONS), UpdateUserDTO ) { // Additional customizations can be added here if needed }
/* import { Server, Faker, uid } from 'react-mock'; const activitySchema = { title: Faker.lorem.words(), notes: Faker.lorem.text(), contact: Faker.name.findName(), dueDate: Faker.date.future(1), type: Faker.random.arrayElement(["interview", "meeting", "event", "application", "correspondance"]) } const fakeActivities = Array(5).fill(activitySchema) */ const randomDate = function (start, end) { return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); }; const randomType = function(arr) { return arr[Math.floor(Math.random() * arr.length)]; }; // Activities Data Generator let fakeActivities = []; for (let i = 0; i < 5; i++) { let activity = { title: `Activity ${i}`, notes: `Lorem Ipsum Act ${i}`, contact: `<NAME> ${i}`, dueDate: randomDate(new Date(), new Date(2019, 6, 1)), type: randomType(["interview", "meeting", "event", "application", "correspondance"]) } fakeActivities.push(activity) } //Contacts Data Generator let fakeContacts = []; for (let i = 0; i < 5; i++) { let contact = { name: `<NAME> ${i}`, title: `Position ${i}`, notes: `Lorem Ipsum Act ${i}`, lastContact: randomDate(new Date(), new Date(2019, 6, 1)), type: randomType(["recruiter", "hiring manager", "industry professional", "other"]), organization: `Some Org ${i}` } fakeContacts.push(contact) } export { fakeActivities, fakeContacts };
<filename>ROS_Eploration/nav2d_karto/OpenKarto/source/OpenKarto/Meta.h /* * Copyright (C) 2006-2011, SRI International (R) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #ifndef __OpenKarto_Meta_h__ #define __OpenKarto_Meta_h__ #include <OpenKarto/MetaType.h> #include <OpenKarto/MetaClass.h> #include <OpenKarto/MetaClassManager.h> #include <OpenKarto/MetaEnum.h> #include <OpenKarto/MetaEnumManager.h> namespace karto { ///** \addtogroup OpenKarto */ //@{ //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// /** * Gets the number of MetaClass's registered. * @return number of MetClass's registered */ inline kt_size_t GetRegisteredMetaClassSize() { return MetaClassManager::GetInstance().GetSize(); } /** * Gets a registered MetaClass by index. Use GetRegisteredMetaClassSize to get index range. * @param index * @return reference to registered MetaClass * @throws Exception if index is out of range */ inline const MetaClass& GetMetaClassByIndex(kt_size_t index) { return MetaClassManager::GetInstance()[index]; } /** * Gets a registered MetaClass by name. * @param rName Class name * @return reference to registered MetaClass * @throws Exception if there is no registered MetaClass by specified name */ inline const MetaClass& GetMetaClassByName(const karto::String& rName) { return MetaClassManager::GetInstance().GetByName(rName); } /** * Gets a registered MetaClass by object. * @param rObject object * @return reference to registered MetaClass * @throws Exception if there is no registered MetaClass by object */ template <typename T> const MetaClass& GetMetaClassByObject(const T& rObject) { return MetaClassManager::GetInstance().GetById(GetTypeId(rObject)); } /** * Gets a registered MetaClass by type. * @return reference to registered MetaClass * @throws Exception if there is no registered MetaClass by type T */ template <typename T> const MetaClass& GetMetaClassByType() { return MetaClassManager::GetInstance().GetById(GetTypeId<T>()); } //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// /** * Gets the number of MetaEnum's registered. * @return number of MetaEnum's registered */ inline kt_size_t GetRegisteredMetaEnumSize() { return MetaEnumManager::GetInstance().GetSize(); } /** * Gets a registered MetaEnum by index. Use GetRegisteredMetaClassSize to get index range. * @param index * @return reference to registered MetaEnum * @throws Exception if index is out of range */ inline const MetaEnum& GetMetaEnumByIndex(kt_size_t index) { return MetaEnumManager::GetInstance()[index]; } /** * Gets a registered MetaEnum by name. * @param rName enum name * @return reference to registered MetaEnum * @throws Exception if there is no registered MetaEnum by specified name */ inline const MetaEnum& GetMetaEnumByName(const karto::String& rName) { return MetaEnumManager::GetInstance().GetByName(rName); } /** * Gets a registered MetaEnum by object. * @param rObject object * @return reference to registered MetaEnum * @throws Exception if there is no registered MetaEnum by object */ template <typename T> const MetaEnum& GetMetaEnumByObject(const T& rObject) { return MetaEnumManager::GetInstance().GetById(GetTypeId<T>(rObject)); } /** * Gets a registered MetaEnum by type. * @return reference to registered MetaEnum * @throws Exception if there is no registered MetaEnum by type T */ template <typename T> const MetaEnum& GetMetaEnumByType() { return MetaEnumManager::GetInstance().GetById(GetTypeId<T>()); } //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //@cond EXCLUDE /** * Check that meta type is registered. * Internal method. Please don't call. */ KARTO_EXPORT void CheckTypeRegistered(const char* pName, void (*registerFunc)()); // @endcond //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// /** * Macro for adding a C++ class to the Meta system. */ #define KARTO_TYPE(type) \ template <> struct KartoTypeId<type> \ { \ static const char* Get(kt_bool = true) {return #type;} \ }; \ /** * Macro for adding a C++ class to the Meta system with a registration function as a callback. * The registration function will be call the first time the provided class is accessed. */ #define KARTO_AUTO_TYPE(type, registerFunc) \ template <> struct KartoTypeId<type> \ { \ static const char* Get(kt_bool checkRegister = true) \ { \ if (checkRegister) \ CheckTypeRegistered(#type, registerFunc); \ return #type; \ } \ }; \ //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// /** * Macro for getting the right runtime type info. */ #define KARTO_RTTI() \ public: virtual const char* GetKartoClassId() const {return GetKartoTypeIdTemplate(this);} \ private: //@} } #endif // __OpenKarto_Meta_h__
public IEnumerable<Element> RetrieveWorstElementsByHits(IEnumerable<Element> elements, int top) { return elements.OrderBy(e => e.Hits).Take(top); }
func setupUserAvatar(avatarImageView: UIImageView, avatarURLString: String) { // Set the corner radius to make the avatar circular avatarImageView.layer.cornerRadius = avatarImageView.bounds.width / 2.0 avatarImageView.layer.masksToBounds = true // Adjust the bottom constraint to position the avatar at 30% of the screen height let screenHeight = UIScreen.main.bounds.height avatarImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -0.3 * screenHeight).isActive = true // Load the user's avatar image from the provided URL string if let url = URL(string: avatarURLString) { URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data { DispatchQueue.main.async { avatarImageView.image = UIImage(data: data) } } }.resume() } }
def count_chars(s): result = {} for c in s: if c in result: result[c] += 1 else: result[c] = 1 return result
/* * Copyright (c) 2020. <NAME>, Partners Healthcare and members of Forome Association * * Developed by <NAME> and <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.forome.astorage.core.source; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.forome.astorage.core.Metadata; import org.forome.astorage.core.record.Record; import org.forome.core.struct.Position; import java.util.Optional; public class CacheSource implements Source { private Source source; private final Cache<Position, Optional<Record>> cacheRecords; public CacheSource(Source source) { this.source = source; this.cacheRecords = CacheBuilder.newBuilder() .maximumSize(100) .build(); } @Override public Metadata getMetadata() { return source.getMetadata(); } @Override public Record getRecord(Position position) { try { Optional<Record> oRecord = cacheRecords.get(position, () -> Optional.ofNullable(source.getRecord(position))); return oRecord.orElse(null); } catch (Throwable e) { throw new RuntimeException(e); } } }
<filename>vendor/github.com/docker/libcompose/integration/stop_test.go package integration import ( "fmt" . "gopkg.in/check.v1" ) func (s *CliSuite) TestStop(c *C) { p := s.ProjectFromText(c, "up", SimpleTemplate) name := fmt.Sprintf("%s_%s_1", p, "hello") cn := s.GetContainerByName(c, name) c.Assert(cn, NotNil) c.Assert(cn.State.Running, Equals, true) s.FromText(c, p, "stop", SimpleTemplate) cn = s.GetContainerByName(c, name) c.Assert(cn, NotNil) c.Assert(cn.State.Running, Equals, false) }
#!/usr/bin/env bash set -euo pipefail # A command to run after creating the container. # # This command is run after "updateContentCommand" # and before "postStartCommand". # # see: https://code.visualstudio.com/docs/remote/devcontainerjson-reference#_lifecycle-scripts exec task onboard
# Sample usage of the ObjectFilter class objects = [Object(10), Object(15, session='A', idx=5), Object(20, session='B', idx=8), Object(25, session='C', idx=12)] filtered_objects = ObjectFilter.filter_objects({'time': 12, 'session': 'B', 'idx': 8}, {'time': 22}, objects) for obj in filtered_objects: print(obj.time, obj.session, obj.idx) # Output: 15 A 5
# frozen_string_literal: true require 'erb_lint/all'
package com.tabeldata.oauth.models; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import java.io.Serializable; import java.sql.Timestamp; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor @ToString(exclude = {"redirectUrls", "oauthGrantTypes", "oauthScopes", "applications", "authorities"}) public class OauthClientDetails implements Serializable { private String id; private String name; private String password; private boolean autoApprove; private Integer expiredInSecond; private String createdBy; private Timestamp createdDate; private String lastUpdateBy; private Timestamp lastUpdateDate; private List<String> redirectUrls; private List<String> authorities; private List<OauthGrantType> oauthGrantTypes; private List<OauthScope> oauthScopes; private List<OauthApplication> applications; }
import { StateDirectory } from './state/state-directory'; import { StateRepository } from './state/state-repository'; import { StateSession } from './state/state-session'; export declare class Plotter { stateDirectoryName: string; private myStateDirectory; stateDirectory: StateDirectory; private myStateRepository; stateRepository: StateRepository; private myStateSession; stateSession: StateSession; }
#!/bin/python # *-* encoding=utf-8 *-* ''' Image Priting Program Based on Haftoning ''' import sys import numpy, scipy from scipy import ndimage from scipy import misc import scipy.fftpack as fftpack import matplotlib.pyplot as plt sys.path.append('../Proj04-01') from DFT import DFT_2D, IDFT_2D def en_padding(img): M, N = img.shape P, Q = 2 * M, 2 * N _img = numpy.zeros(P*Q).reshape((P, Q)) for x in range(M): for y in range(N): _img[x][y] = img[x][y] return _img def de_padding(img): P, Q = img.shape M, N = P/2, Q/2 _img = numpy.zeros(M*N).reshape((M, N)) for x in range(M): for y in range(N): _img[x][y] = img[x][y] return _img def shift(img): M, N = img.shape _img = img.copy() for x in range(M): for y in range(N): _img[x][y] = img[x][y] * numpy.power(-1.0, (x+y)) return _img def sqdistance(p1, p2): return ((p1[0]-p2[0])*(p1[0]-p2[0])) + \ ((p1[1]-p2[1])*(p1[1]-p2[1])) def lowpass_mask(P, Q, cuf_off_frequency): center = (P/2.0, Q/2.0) mask = numpy.zeros(P * Q).reshape(P, Q) for u in range(P): for v in range(Q): mask[u][v] = numpy.exp(-1*sqdistance(center, (u, v)) / (2*(cuf_off_frequency*cuf_off_frequency))) return mask def highpass_mask(P, Q, cuf_off_frequency): return 1.0 - lowpass_mask(P, Q, cuf_off_frequency) # center = (P/2.0, Q/2.0) # mask = numpy.zeros(P * Q).reshape(P, Q) # for u in range(P): # for v in range(Q): # mask[u][v] = 1.0-numpy.exp(-1*sqdistance(center, (u, v)) / (2*(cuf_off_frequency*cuf_off_frequency))) # return mask def main(): img_file = 'Fig0441(a)(characters_test_pattern).tif' img = misc.imread(img_file) padding_img = en_padding(img) padding_img = shift(padding_img) dft_img = DFT_2D(padding_img) for cut_off_frequency in [30, 60, 160]: print cut_off_frequency hp_mask = highpass_mask(dft_img.shape[0], dft_img.shape[1], cut_off_frequency) misc.imsave('%s_hpmask_%d.tif' % (img_file, cut_off_frequency), 255 * hp_mask) hp_img = numpy.multiply(dft_img, hp_mask) misc.imsave('%s_fft_%d.tif' % (img_file, cut_off_frequency), numpy.log(1+numpy.abs(hp_img))) hp_idtft_img = shift(IDFT_2D(hp_img).real) hp_idtft_img = de_padding(hp_idtft_img) print hp_idtft_img.shape misc.imsave('%s_hp_%d.tif' % (img_file, cut_off_frequency), hp_idtft_img) if __name__ == '__main__': main()
package flux import ( "fmt" "sync" ) //Collector defines a typ of map string type Collector map[string]interface{} //Eachfunc defines the type of the Mappable.Each rule type Eachfunc func(interface{}, interface{}, func()) //StringEachfunc defines the type of the Mappable.Each rule type StringEachfunc func(interface{}, string, func()) //StringMappable defines member function rules for securemap type StringMappable interface { Clear() HasMatch(k string, v interface{}) bool Each(f StringEachfunc) Keys() []string Copy(map[string]interface{}) Has(string) bool Get(string) interface{} Remove(string) Set(k string, v interface{}) Clone() StringMappable } //NewCollector returns a new collector instance func NewCollector() Collector { return make(Collector) } //Clone makes a new clone of this collector func (c Collector) Clone() Collector { col := make(Collector) col.Copy(c) return col } //Remove deletes a key:value pair func (c Collector) Remove(k string) { if c.Has(k) { delete(c, k) } } //Keys return the keys of the Collector func (c Collector) Keys() []string { var keys []string c.Each(func(_ interface{}, k string, _ func()) { keys = append(keys, k) }) return keys } //Get returns the value with the key func (c Collector) Get(k string) interface{} { return c[k] } //Has returns if a key exists func (c Collector) Has(k string) bool { _, ok := c[k] return ok } //HasMatch checks if key and value exists and are matching func (c Collector) HasMatch(k string, v interface{}) bool { if c.Has(k) { return c.Get(k) == v } return false } //Set puts a specific key:value into the collector func (c Collector) Set(k string, v interface{}) { c[k] = v } //Copy copies the map into the collector func (c Collector) Copy(m map[string]interface{}) { for v, k := range m { c.Set(v, k) } } //Each iterates through all items in the collector func (c Collector) Each(fx StringEachfunc) { var state bool for k, v := range c { if state { break } fx(v, k, func() { state = true }) } } //Clear clears the collector func (c Collector) Clear() { for k := range c { delete(c, k) } } // SyncCollector provides a mutex controlled map type SyncCollector struct { c Collector rw sync.RWMutex } //NewSyncCollector returns a new collector instance func NewSyncCollector() *SyncCollector { so := SyncCollector{c: make(Collector)} return &so } //Clone makes a new clone of this collector func (c *SyncCollector) Clone() *SyncCollector { var co Collector c.rw.RLock() co = c.c.Clone() c.rw.RUnlock() so := SyncCollector{c: co} return &so } //Remove deletes a key:value pair func (c *SyncCollector) Remove(k string) { c.rw.Lock() c.c.Remove(k) c.rw.Unlock() } //Set puts a specific key:value into the collector func (c *SyncCollector) Set(k string, v interface{}) { c.rw.Lock() c.c.Set(k, v) c.rw.Unlock() } //Copy copies the map into the collector func (c *SyncCollector) Copy(m map[string]interface{}) { for v, k := range m { c.Set(v, k) } } //Each iterates through all items in the collector func (c *SyncCollector) Each(fx StringEachfunc) { var state bool c.rw.RLock() for k, v := range c.c { if state { break } fx(v, k, func() { state = true }) } c.rw.RUnlock() } //Keys return the keys of the Collector func (c *SyncCollector) Keys() []string { var keys []string c.Each(func(_ interface{}, k string, _ func()) { keys = append(keys, k) }) return keys } //Get returns the value with the key func (c *SyncCollector) Get(k string) interface{} { var v interface{} c.rw.RLock() v = c.c.Get(k) c.rw.RUnlock() return v } //Has returns if a key exists func (c *SyncCollector) Has(k string) bool { var ok bool c.rw.RLock() _, ok = c.c[k] c.rw.RUnlock() return ok } //HasMatch checks if key and value exists and are matching func (c *SyncCollector) HasMatch(k string, v interface{}) bool { // c.rw.RLock() // defer c.rw.RUnlock() if c.Has(k) { return c.Get(k) == v } return false } //Clear clears the collector func (c *SyncCollector) Clear() { for k := range c.c { c.rw.Lock() delete(c.c, k) c.rw.Unlock() } } //Mappable defines member function rules for securemap type Mappable interface { Clear() HasMatch(k, v interface{}) bool Each(f Eachfunc) Keys() []interface{} Copy(map[interface{}]interface{}) CopySecureMap(Mappable) Has(interface{}) bool Get(interface{}) interface{} Remove(interface{}) Set(k, v interface{}) Clone() Mappable } //SecureMap simple represents a map with a rwmutex locked in type SecureMap struct { data map[interface{}]interface{} lock *sync.RWMutex } //Clear unlinks the previous map func (m *SecureMap) Clear() { m.lock.Lock() m.data = make(map[interface{}]interface{}) m.lock.Unlock() } //HasMatch checks if a key exists and if the value matches func (m *SecureMap) HasMatch(key, value interface{}) bool { m.lock.RLock() k, ok := m.data[key] m.lock.RUnlock() if ok { return k == value } return false } //Each interates through the map func (m *SecureMap) Each(fn Eachfunc) { stop := false m.lock.RLock() for k, v := range m.data { if stop { break } fn(v, k, func() { stop = true }) } m.lock.RUnlock() } //Keys return the keys of the map func (m *SecureMap) Keys() []interface{} { m.lock.RLock() keys := make([]interface{}, len(m.data)) count := 0 for k := range m.data { keys[count] = k count++ } m.lock.RUnlock() return keys } //Clone makes a clone for this securemap func (m *SecureMap) Clone() Mappable { sm := NewSecureMap() m.lock.RLock() for k, v := range m.data { sm.Set(k, v) } m.lock.RUnlock() return sm } //CopySecureMap Copies a into the map func (m *SecureMap) CopySecureMap(src Mappable) { src.Each(func(k, v interface{}, _ func()) { m.Set(k, v) }) } //Copy Copies a map[interface{}]interface{} into the map func (m *SecureMap) Copy(src map[interface{}]interface{}) { for k, v := range src { m.Set(k, v) } } //Has returns true/false if value exists by key func (m *SecureMap) Has(key interface{}) bool { m.lock.RLock() _, ok := m.data[key] m.lock.RUnlock() return ok } //Get a key's value func (m *SecureMap) Get(key interface{}) interface{} { m.lock.RLock() k := m.data[key] m.lock.RUnlock() return k } //Set a key with value func (m *SecureMap) Set(key, value interface{}) { if _, ok := m.data[key]; ok { return } m.lock.Lock() m.data[key] = value m.lock.Unlock() } //Remove a value by its key func (m *SecureMap) Remove(key interface{}) { m.lock.Lock() delete(m.data, key) m.lock.Unlock() } //NewSecureMap returns a new securemap func NewSecureMap() *SecureMap { return &SecureMap{make(map[interface{}]interface{}), new(sync.RWMutex)} } //SecureMapFrom returns a new securemap func SecureMapFrom(core map[interface{}]interface{}) *SecureMap { return &SecureMap{core, new(sync.RWMutex)} } //SecureStack provides addition of functions into a stack type SecureStack struct { listeners []interface{} lock *sync.RWMutex } //Splice returns a new splice from the list func (f *SecureStack) Splice(begin, end int) []interface{} { size := f.Size() if end > size { end = size } f.lock.RLock() ms := f.listeners[begin:end] f.lock.RUnlock() var dup []interface{} dup = append(dup, ms...) return dup } //Set lets you retrieve an item in the list func (f *SecureStack) Set(ind int, d interface{}) { sz := f.Size() if ind >= sz { return } if ind < 0 { ind = sz - ind if ind < 0 { return } } f.lock.Lock() f.listeners[ind] = d f.lock.Unlock() } //Get lets you retrieve an item in the list func (f *SecureStack) Get(ind int) interface{} { sz := f.Size() if ind >= sz { ind = sz - 1 } if ind < 0 { ind = sz - ind if ind < 0 { return nil } } f.lock.RLock() r := f.listeners[ind] f.lock.RUnlock() return r } //Strings return the stringified version of the internal list func (f *SecureStack) String() string { f.lock.RLock() sz := fmt.Sprintf("%+v", f.listeners) f.lock.RUnlock() return sz } //Clear flushes the stack listener func (f *SecureStack) Clear() { f.lock.Lock() f.listeners = f.listeners[0:0] f.lock.Unlock() } //Size returns the total number of listeners func (f *SecureStack) Size() int { f.lock.RLock() sz := len(f.listeners) f.lock.RUnlock() return sz } //Add adds a function into the stack func (f *SecureStack) Add(fx interface{}) int { f.lock.Lock() ind := len(f.listeners) f.listeners = append(f.listeners, fx) f.lock.Unlock() return ind } //Delete removes the function at the provided index func (f *SecureStack) Delete(ind int) { if ind <= 0 && len(f.listeners) <= 0 { return } f.lock.RLock() copy(f.listeners[ind:], f.listeners[ind+1:]) f.listeners[len(f.listeners)-1] = nil f.listeners = f.listeners[:len(f.listeners)-1] f.lock.RUnlock() } //Each runs through the function lists and executing with args func (f *SecureStack) Each(fx func(interface{})) { if f.Size() <= 0 { return } f.lock.RLock() for _, d := range f.listeners { fx(d) } f.lock.RUnlock() } //FunctionStack provides addition of functions into a stack type FunctionStack struct { listeners []func(...interface{}) lock *sync.RWMutex } //Clear flushes the stack listener func (f *FunctionStack) Clear() { f.lock.Lock() f.listeners = f.listeners[0:0] f.lock.Unlock() } //Size returns the total number of listeners func (f *FunctionStack) Size() int { f.lock.RLock() sz := len(f.listeners) f.lock.RUnlock() return sz } //Add adds a function into the stack func (f *FunctionStack) Add(fx func(...interface{})) int { f.lock.Lock() ind := len(f.listeners) f.listeners = append(f.listeners, fx) f.lock.Unlock() return ind } //Delete removes the function at the provided index func (f *FunctionStack) Delete(ind int) { if ind <= 0 && len(f.listeners) <= 0 { return } f.lock.RLock() copy(f.listeners[ind:], f.listeners[ind+1:]) f.listeners[len(f.listeners)-1] = nil f.listeners = f.listeners[:len(f.listeners)-1] f.lock.RUnlock() } //Each runs through the function lists and executing with args func (f *FunctionStack) Each(d ...interface{}) { if f.Size() <= 0 { return } f.lock.RLock() for _, fx := range f.listeners { fx(d...) } f.lock.RUnlock() } //SingleStack provides a function stack fro single argument //functions type SingleStack struct { *FunctionStack } //Add adds a function into the stack func (s *SingleStack) Add(fx func(interface{})) int { return s.FunctionStack.Add(func(f ...interface{}) { fx(f[0]) }) } //NewSecureStack returns a new functionstack instance func NewSecureStack() *SecureStack { return &SecureStack{ make([]interface{}, 0), new(sync.RWMutex), } } //NewFunctionStack returns a new functionstack instance func NewFunctionStack() *FunctionStack { return &FunctionStack{ make([]func(...interface{}), 0), new(sync.RWMutex), } } //NewSingleStack returns a singlestack instance func NewSingleStack() *SingleStack { return &SingleStack{ NewFunctionStack(), } }
package main import ( "context" "os" "github.com/rancher/system-agent/pkg/localplan" "github.com/mattn/go-colorable" "github.com/rancher/system-agent/pkg/applyinator" "github.com/rancher/system-agent/pkg/config" "github.com/rancher/system-agent/pkg/image" "github.com/rancher/system-agent/pkg/k8splan" "github.com/rancher/system-agent/pkg/version" "github.com/rancher/wrangler/pkg/signals" "github.com/sirupsen/logrus" ) const ( cattleLogLevelEnv = "CATTLE_LOGLEVEL" cattleAgentConfigEnv = "CATTLE_AGENT_CONFIG" defaultConfigFile = "/etc/rancher/agent/config.yaml" ) func main() { logrus.SetOutput(colorable.NewColorableStdout()) if os.Getuid() != 0 { logrus.Fatalf("Must be run as root.") } rawLevel := os.Getenv(cattleLogLevelEnv) if rawLevel != "" { if lvl, err := logrus.ParseLevel(os.Getenv(cattleLogLevelEnv)); err != nil { logrus.Fatal(err) } else { logrus.SetLevel(lvl) } } run() } func run() { topContext := signals.SetupSignalHandler(context.Background()) logrus.Infof("Rancher System Agent version %s is starting", version.FriendlyVersion()) configFile := os.Getenv(cattleAgentConfigEnv) if configFile == "" { configFile = defaultConfigFile } var cf config.AgentConfig err := config.Parse(configFile, &cf) if err != nil { logrus.Fatalf("Unable to parse config file %v", err) } if !cf.LocalEnabled && !cf.RemoteEnabled { logrus.Fatalf("Local and remote were both not enabled. Exiting, as one must be enabled.") } logrus.Infof("Using directory %s for work", cf.WorkDir) imageUtil := image.NewUtility(cf.ImagesDir, cf.ImageCredentialProviderConfig, cf.ImageCredentialProviderBinDir, cf.AgentRegistriesFile) applyinator := applyinator.NewApplyinator(cf.WorkDir, cf.PreserveWorkDir, cf.AppliedPlanDir, imageUtil) if cf.RemoteEnabled { logrus.Infof("Starting remote watch of plans") var connInfo config.ConnectionInfo if err := config.Parse(cf.ConnectionInfoFile, &connInfo); err != nil { logrus.Fatalf("Unable to parse connection info file %v", err) } k8splan.Watch(topContext, *applyinator, connInfo) } if cf.LocalEnabled { logrus.Infof("Starting local watch of plans in %s", cf.LocalPlanDir) localplan.WatchFiles(topContext, *applyinator, cf.LocalPlanDir) } <-topContext.Done() }
#!bin/bash gcd() { let "m=$1%$2" if [[ $m == 0 ]]; then let "ans=$2" else gcd $2 $m fi } ans=0 while [[ true ]]; do read a b if [[ -z $a || -z $b ]]; then break fi gcd $a $b echo "GCD is $ans" done echo "bye"
package disjoint_set; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * * @author exponential-e * 백준 3830번: 교수님은 기다리지 않는다. * * @see https://www.acmicpc.net/problem/3830/ * */ public class Boj3830 { private static int[] parent; private static long[] weight; private static final String NEW_LINE = "\n"; private static final String U = "UNKNOWN"; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); while (true) { StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); if (N + M == 0) break; parent = new int[N]; weight = new long[N]; Arrays.fill(parent, -1); while (M-- > 0) { st = new StringTokenizer(br.readLine()); String cmd = st.nextToken(); int a = Integer.parseInt(st.nextToken()) - 1; int b = Integer.parseInt(st.nextToken()) - 1; if (cmd.equals("!")) { long w = Long.parseLong(st.nextToken()); merge(a, b, w); } else { sb.append(find(a) != find(b) ? U : weight[b] - weight[a]).append(NEW_LINE); } } } System.out.println(sb.toString()); } private static int find(int x) { if (parent[x] < 0) return x; int p = find(parent[x]); weight[x] += weight[parent[x]]; // value update return parent[x] = p; } private static void merge(int x, int y, long w) { int[] prev = {x , y}; x = find(x); y = find(y); if(x == y) return; long cal = w - weight[prev[1]] + weight[prev[0]]; // difference if(parent[x] < parent[y]) { parent[x] += parent[y]; parent[y] = x; weight[y] += cal; } else{ parent[y] += parent[x]; parent[x] = y; weight[x] -= cal; } } }
#!/bin/bash key=$1 event=$2 url="https://maker.ifttt.com/trigger/${event}/with/key/${key}" curl -s -X POST "${url}" -d "value1=$3" -d "value2=$4" -d "value3=$5" #
package seoul.democracy.issue.domain; public enum IssueType { P, // 제안, proposal D, // 토론, debate A // 실행, action }