text
stringlengths
1
1.05M
<filename>src/core/interceptors/transform.interceptor.ts import { NestInterceptor, Injectable, ExecutionContext, CallHandler, } from '@nestjs/common'; import { PaginateResult } from 'mongoose'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { Reflector } from '@nestjs/core'; import { THttpSuccessResponse, EHttpStatus, IHttpResultPaginate, TMessage, } from '../interfaces/http.interface'; import * as META from '../constants/meta.constants'; export function transformDataToPaginate<T>( data: PaginateResult<T>, request?: any, ): IHttpResultPaginate<T[]> { return { data: data.docs, params: request ? request.query : null, pagination: { total: data.total, current_page: data.page, total_page: data.pages, per_page: data.limit, }, }; } @Injectable() export class TransformInterceptor<T> implements NestInterceptor<T, THttpSuccessResponse<T>> { constructor(private readonly reflecor: Reflector) {} intercept( context: ExecutionContext, next: CallHandler<T>, ): Observable<THttpSuccessResponse<T>> { const call$ = next.handle(); const target = context.getHandler(); const request = context.switchToHttp().getRequest(); const message = this.reflecor.get<TMessage>(META.HTTP_SUCCESS_MESSAGE, target) || '成功'; const usePaginate = this.reflecor.get<boolean>( META.HTTP_RES_TRANSFORM_PAGINATE, target, ); return call$.pipe( map((data: any) => { const result = !usePaginate ? data : transformDataToPaginate<T>(data, request); return { status: EHttpStatus.SUCCESS, message, result }; }), ); } }
#!/bin/bash # From https://github.com/kivy/kivy-ios # Set up build locations export RENIOSDEPROOT="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )/../" && pwd )" export TMPROOT="$RENIOSDEPROOT/tmp" export CACHEROOT="$RENIOSDEPROOT/cache" # Set up path to include our gas-preprocessor.pl export $PATH="$RENIOSDEPROOT/scripts:$PATH" # create build directories if not found try mkdir -p $CACHEROOT try mkdir -p $TMPROOT # Versions export PYTHON_VERSION=2.7.3 export RENPY_VERSION=6.14.1 export PYGAME_VERSION=1.9.1 export FREETYPE_VERSION=2.3.12 export FRIBIDI_VERSION=0.19.2 export SDL_REVISION=45187a87d35b export SDL2_TTF_REVISION=15fdede47c58 export SDL2_IMAGE_REVISION=4a8d59cbf927 export LIBAV_VERSION=0.7.6
class Card: def __init__(self, rarity): valid_rarities = {"UR", "SSR", "SR"} if rarity not in valid_rarities: raise ValueError("Invalid rarity level") self._rarity = rarity def get_rarity(self): return self._rarity def set_rarity(self, new_rarity): valid_rarities = {"UR", "SSR", "SR"} if new_rarity not in valid_rarities: raise ValueError("Invalid rarity level") self._rarity = new_rarity
#!/bin/bash # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. FLAGS_HELP=" usage: ./bin/concat.sh -i FILE [-o FILE] [-f] This script concatenates a list of files into a single file. The list of files is supplied via text file, using the -i|--input_from argument. The filenames can be relative to the working directory or located in a directory listed in LIBDOT_SEARCH_PATH. Absolute paths also work, but should be avoided when the input file is intended to be used by others. If the -f|--forever argument is provided, then the script will monitor the list of input files and recreate the output when it detects a change. The environment variable LIBDOT_SEARCH_PATH can be used to define a search path. It's consulted when resolving input files, and lets you specify relative paths in the input file without imposing a parent directory structure. Multiple paths can be separated by the colon character. There are a few directives that can be specified in the input file. They are... @include FILE This can be used to include an additional list of files. It's useful when you want to include a list of files specified by a separate project, or any time you want to compose lists of dependencies. The included FILE must be relative to the LIBDOT_SEARCH_PATH. If an included file specifies a file that is already part of the result it will not be duplicated. When an included file is being processed this script will change the current directory to the LIBDOT_SEARCH_PATH entry where the FILE was found. This is to make certain that any scripts executed by an included @resource directive happen relative to a known location. @resource NAME TYPE SOURCE NAME - The resource NAME is that name that you'd use to fetch the resource with lib.resource.get(name) TYPE - If the resource type is 'raw' then the resource will be included without any munging. Otherwise, the resource will be wrapped in a JavaScript string. If you specify the type as a valid mimetype then you'll be able to get the resource as a 'data:' url easily from lib.resource.getDataUrl(...). SOURCE - When specified as '< FILENAME' it is interpreted as a file from the LIBDOT_SEARCH_PATH search path. When specified as '\$ shell command' then the output of the shell command is used as the value of the resource. This includes a resource in the output. A resource can be a file on disk or the output of a shell command. Resources are output as JavaScript strings by default but can also be the raw file contents or script output, which is useful when you want to include a JSON resource. The resource directive depends on libdot/js/lib_resource.js, but the dependency is not automatically injected. It's up to your input file to include it. @echo DATA Echo's a static string to the output file. " source "$(dirname "$0")/common.sh" DEFINE_boolean forever "$FLAGS_FALSE" \ "Recreate the output file whenever one of the inputs changes. " f DEFINE_string input_from '' \ "A file containing the list of files to concatenate." i DEFINE_string output '' \ "The output file." o DEFINE_boolean echo_inotify "$FLAGS_FALSE" \ "Echo the inotify list to stdout." I COMMAND_LINE="$(readlink -f $0) $@" FLAGS "$@" || exit $? eval set -- "${FLAGS_ARGV}" NEWLINE=$'\n' # Maximum file descriptor used. CONCAT_MAX_FD=2 # List of files (absolute paths) we need to include in the inotify watch list. # This may include files not in the output, like other concat files referenced # with the @include directive. CONCAT_INOTIFY_FILES="" # List of files we've included in the output to be included in the header of # the output. These paths should be as specified in the concat source list # so they're short and relative to the LIBDOT_SEARCH_PATH. CONCAT_HEADER_FILES="" # Output we've generated so far. CONCAT_OUTPUT="" # Echo the results to the FLAGS_output file or stdout if the flag is not # provided. function echo_results() { local saved_output="$CONCAT_OUTPUT" CONCAT_OUTPUT="" append_comment "This file was generated by libdot/bin/concat.sh." append_comment "It has been marked read-only for your safety. Rather" append_comment "than edit it directly, please modify one of these source" append_comment "files..." append_comment for f in $CONCAT_HEADER_FILES; do append_comment "$f" done append_comment CONCAT_OUTPUT="$CONCAT_OUTPUT$NEWLINE$saved_output" if [ -z "$FLAGS_output" ]; then echo "${CONCAT_OUTPUT}" else rm -rf "$FLAGS_output" echo "${CONCAT_OUTPUT}" >> "$FLAGS_output" fi } # Append to the pending output. # # This also adds a trailing newline. function append_output() { CONCAT_OUTPUT="${CONCAT_OUTPUT}$@$NEWLINE" } # Append a comment to the pending output. # # The output is wrapped to 79 columns, with each line (including the first) # prefixed with "// ". function append_comment() { local str=$* if [ -z "$str" ]; then append_output "//" return fi append_output "$(echo -n "${str}" | awk -v WIDTH=76 ' { while (length>WIDTH) { print "// " substr($0,1,WIDTH); $0=substr($0,WIDTH+1); } print "// " $0; }' )" } # Append a JavaScript string to the pending output. # # The output is surrounded in single quote ("'") characters and wrapped to 79 # columns. Wrapped lines are joined with a plus ("+"). # # Single quotes found in the input are escaped. function append_string() { local str=$* append_output "$(echo "${str//\'/\'}" | awk -v WIDTH=76 ' { while (length>WIDTH) { print "\047" substr($0,1,WIDTH) "\047 +"; $0=substr($0,WIDTH+1); } print "\047" $0 "\047 +"; } END { print "\047\047"; }' )" } # Convert data into a format that can be included in JavaScript and append it to # the output. # # This makes the resource available via lib.resource.get(...), and depends # on libdot/js/lib_resource.js. # # You can append the contents of a file or the output of a shell command. # # Resources are included in the list of files watched by inotify. function append_resource() { local name="$1" local type="$2" local source="$3" local data if [ "${source:0:2}" == "\$ " ]; then # Resource generated by a command line. data=$(eval "${source:2}") insist elif [ "${source:0:2}" == "< " ]; then # Resource is the contents of an existing file. source="$(echo "${source:2}" | sed -e 's/[:space:]*//')" local abspath if [ "${source:0:1}" != '/' -a "${source:0:1}" != '.' ]; then abspath="$(search_file "${source}")" if [ -z "$abspath" ]; then echo_err "Can't find resource file: ${source}" return 1 fi else abspath="$(readlink -f "$source")" fi CONCAT_HEADER_FILES="${CONCAT_HEADER_FILES} ${source}" CONCAT_INOTIFY_FILES="${CONCAT_INOTIFY_FILES}$NEWLINE$abspath" data="$(cat "$abspath")" else echo_err "Not sure how to interpret resource: $name $type $source" return 1 fi append_output "lib.resource.add('$name', '$type'," if [ "$type" = "raw" ]; then # The resource should be the raw contents of the file or command output. # Great for json data. append_outout "${data}" else # Resource should be wrapped in a JS string. append_string "${data}" fi append_output ");" append_output } # Process a single line from a concat file. function process_concat_line() { local line="$1" if [ "${line:0:1}" != "@" ]; then line="@file $line" fi echo_err "$line" if [ "${line:0:6}" = "@file " ]; then # Input line doesn't start with an "@", it's just a file to include # in the output. line="${line:6}" local abspath="$(search_file "$line")" if [ -z "$abspath" ]; then echo_err "File not found: $line" return 1 fi if (echo -e "${CONCAT_INOTIFY_FILES}" | grep -xq "$abspath"); then echo_err "Skipping duplicate file." return 0 fi CONCAT_HEADER_FILES="$CONCAT_HEADER_FILES $line" CONCAT_INOTIFY_FILES="$CONCAT_INOTIFY_FILES$NEWLINE$abspath" append_comment "SOURCE FILE: $line" append_output "$(cat "$abspath")" elif [ "${line:0:6}" = "@echo " ]; then append_output "${line:6}" elif [ "${line:0:6}" = "@eval " ]; then line=$(eval "${line:6}") insist append_output "$line" elif [ "${line:0:10}" = "@resource " ]; then local name="$(echo "${line:10}" | cut -d' ' -f1)" local type="$(echo "${line:10}" | cut -d' ' -f2)" local path="$(echo "${line:10}" | cut -d' ' -f3-)" insist append_resource "$name" "$type" "$path" else echo_err "Unknown directive: $line" return 1 fi } # Process a concat file opened at a given file descriptor. function process_concat_fd() { local fd=$1 while read -r 0<&$fd READ_LINE; do local line="" READ_LINE=${READ_LINE##} # Strip leading spaces. # Handle trailing escape as line continuation. while [ $(expr "$READ_LINE" : ".*\\\\$") != 0 ]; do READ_LINE=${READ_LINE%\\} # Strip trailing escape. line="$line$READ_LINE" insist read -r 0<&$fd READ_LINE done line="$line$READ_LINE" if [ -z "$line" -o "${line:0:1}" = '#' ]; then # Skip blank lines and comments. continue fi if [ "${line:0:9}" = "@include " ]; then echo_err "$line" local relative_path="${line:9}" local absolute_path=$(search_file "$relative_path") insist process_concat_file "$absolute_path" else insist process_concat_line "$line" fi done } # Process a concat file specified by absolute path. function process_concat_file { local absolute_path="$1" CONCAT_INOTIFY_FILES="$CONCAT_INOTIFY_FILES$NEWLINE$absolute_path" CONCAT_MAX_FD=$(($CONCAT_MAX_FD + 1)) local fd=$CONCAT_MAX_FD eval "exec $fd< $absolute_path" insist pushd "$(dirname "$absolute_path")" > /dev/null insist process_concat_fd $fd popd > /dev/null eval "exec $fd>&-" } function main() { local input="" if [ -z "$FLAGS_input_from" ]; then echo_err "Missing argument: --input" exit 1 fi if [ ! -z "$FLAGS_output" ]; then echo_err $(date "+%H:%M:%S") "- Re-creating: $FLAGS_output" fi insist process_concat_file "$FLAGS_input_from" echo_results if [ "$FLAGS_forever" = "$FLAGS_TRUE" ]; then echo -e '\a' inotifywait -qqe modify $0 $FLAGS_input_from $CONCAT_INOTIFY_FILES local err=$? if [[ $err != 0 && $err != 1 ]]; then echo_err "inotify exited with status code: $err" exit $err fi exec $COMMAND_LINE fi if [ "$FLAGS_echo_inotify" = "$FLAGS_TRUE" ]; then echo $FLAGS_input_from $CONCAT_INOTIFY_FILES fi return 0 } main "$@"
import { Player, uuid } from "@cph-scorer/model"; import { ApiProperty } from "@nestjs/swagger"; import { IsBoolean, IsNotEmpty, IsUUID } from "class-validator"; export class PlayerDTO extends Player { @ApiProperty() @IsNotEmpty() @IsUUID("4") public id: uuid; @ApiProperty() @IsNotEmpty() public firstName: string; @ApiProperty() @IsNotEmpty() public lastName: string; @ApiProperty() @IsBoolean() public register: boolean; }
<reponame>luisdiasdev/simple-social-network package br.com.agateownz.foodsocial.modules.user.controller; import br.com.agateownz.foodsocial.config.ApplicationProfiles; import br.com.agateownz.foodsocial.modules.shared.annotations.MockMvcContextConfiguration; import br.com.agateownz.foodsocial.modules.shared.controller.AbstractControllerTest; import br.com.agateownz.foodsocial.modules.user.UserProfileMockBuilders.*; import br.com.agateownz.foodsocial.modules.user.dto.request.ModifyUserProfileRequest; import br.com.agateownz.foodsocial.modules.user.dto.response.UserProfileResponse; import br.com.agateownz.foodsocial.modules.user.service.UserProfileService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ActiveProfiles; import static br.com.agateownz.foodsocial.modules.user.UserProfileMockBuilders.*; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ActiveProfiles(ApplicationProfiles.TEST) @WebMvcTest(UserProfileController.class) @MockMvcContextConfiguration class UserProfileControllerTest extends AbstractControllerTest { private static final String ENDPOINT = "/users/profile"; @MockBean private UserProfileService userProfileService; @BeforeEach public void setup() { when(userProfileService.getFromAuthenticatedUser()) .thenReturn(UserProfileWithPictureResponseMock.valid()); doAnswer(invocationOnMock -> { var request = invocationOnMock.<ModifyUserProfileRequest>getArgument(0); return UserProfileResponse.builder() .displayName(request.getDisplayName().orElseThrow()) .bio(request.getBio().orElseThrow()) .website(request.getWebsite().orElseThrow()) .build(); }).when(userProfileService).save(any()); doReturn(profilePictureResponse()) .when(userProfileService).saveProfilePicture(any()); } @DisplayName("GET /users/profile") @Nested @WithMockUser class GetUserProfileTest { @DisplayName("should return user profile if authenticated") @Test public void success() throws Exception { mockMvc.perform(get(ENDPOINT)) .andExpect(status().isOk()); } @DisplayName("should return 403 if not authenticated") @Test @WithAnonymousUser public void fail() throws Exception { mockMvc.perform(get(ENDPOINT)) .andExpect(status().isForbidden()); } } @DisplayName("POST /users/profile") @Nested @WithMockUser class PostUserProfileTest { @DisplayName("should return the new user profile if authenticated") @Test public void successPost() throws Exception { mockMvc.perform(post(ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .content(toJsonString(ModifyUserProfileRequestMock.valid()))) .andExpect(status().isOk()) .andExpect(jsonPath("$.displayName", is(VALID_CHANGED_DISPLAY_NAME))) .andExpect(jsonPath("$.website", is(VALID_CHANGED_WEBSITE))) .andExpect(jsonPath("$.bio", is(VALID_CHANGED_BIO))); } @DisplayName("should return 400 if displayName size is not valid") @Test public void displayNameFail() throws Exception { mockMvc.perform(post(ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .content(toJsonString(ModifyUserProfileRequestMock.invalidDisplayName()))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$[0].message", is("displayName size must be between 0 and 60"))); } @DisplayName("should return 400 if website size is not valid") @Test public void websiteFail() throws Exception { mockMvc.perform(post(ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .content(toJsonString(ModifyUserProfileRequestMock.invalidWebsite()))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$[0].message", is("website size must be between 0 and 100"))); } @DisplayName("should return 400 if bio size is not valid") @Test public void bioFail() throws Exception { mockMvc.perform(post(ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .content(toJsonString(ModifyUserProfileRequestMock.invalidBio()))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$[0].message", is("bio size must be between 0 and 200"))); } @DisplayName("should return 403 if not authenticated") @Test @WithAnonymousUser public void fail() throws Exception { mockMvc.perform(post(ENDPOINT)) .andExpect(status().isForbidden()); } } @DisplayName("PUT /users/profile") @Nested @WithMockUser class PutUserProfileTest { @DisplayName("should return the updated user profile if authenticated") @Test public void successPut() throws Exception { mockMvc.perform(put(ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .content(toJsonString(ModifyUserProfileRequestMock.valid()))) .andExpect(status().isOk()) .andExpect(jsonPath("$.displayName", is(VALID_CHANGED_DISPLAY_NAME))) .andExpect(jsonPath("$.website", is(VALID_CHANGED_WEBSITE))) .andExpect(jsonPath("$.bio", is(VALID_CHANGED_BIO))); } @DisplayName("should return 400 if displayName size is not valid") @Test public void displayNameFail() throws Exception { mockMvc.perform(put(ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .content(toJsonString(ModifyUserProfileRequestMock.invalidDisplayName()))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$[0].message", is("displayName size must be between 0 and 60"))); } @DisplayName("should return 400 if website size is not valid") @Test public void websiteFail() throws Exception { mockMvc.perform(put(ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .content(toJsonString(ModifyUserProfileRequestMock.invalidWebsite()))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$[0].message", is("website size must be between 0 and 100"))); } @DisplayName("should return 400 if bio size is not valid") @Test public void bioFail() throws Exception { mockMvc.perform(put(ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .content(toJsonString(ModifyUserProfileRequestMock.invalidBio()))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$[0].message", is("bio size must be between 0 and 200"))); } @DisplayName("should return 403 if not authenticated") @Test @WithAnonymousUser public void fail() throws Exception { mockMvc.perform(put(ENDPOINT)) .andExpect(status().isForbidden()); } } @DisplayName("POST /users/profile/picture") @Nested @WithMockUser class PostUserProfilePictureTest { @DisplayName("should return content uri if authenticated") @Test public void success() throws Exception { mockMvc.perform(multipart(ENDPOINT + "/picture") .file(profilePictureMultipartFile()) .contentType(MediaType.MULTIPART_FORM_DATA)) .andExpect(status().isOk()) .andExpect(jsonPath("$.uuid", is(VALID_PROFILE_PICTURE_UUID))) .andExpect(jsonPath("$.contentUri", is(VALID_PROFILE_PICTURE_URI))); } @DisplayName("should return 403 if not authenticated") @Test @WithAnonymousUser public void fail() throws Exception { mockMvc.perform(multipart(ENDPOINT + "/picture") .file(profilePictureMultipartFile()) .contentType(MediaType.MULTIPART_FORM_DATA)) .andExpect(status().isForbidden()); } } @DisplayName("DELETE /users/profile/picture") @Nested @WithMockUser class DeleteUserProfilePictureTest { @DisplayName("should return 204 if image deleted") @Test public void success() throws Exception { mockMvc.perform(delete(ENDPOINT + "/picture")) .andExpect(status().isNoContent()); } @DisplayName("should return 403 if not authenticated") @Test @WithAnonymousUser public void fail() throws Exception { mockMvc.perform(post(ENDPOINT + "/picture")) .andExpect(status().isForbidden()); } } }
<gh_stars>10-100 package com.github.robindevilliers.welcometohell.ui.renderers; import com.github.robindevilliers.welcometohell.ui.RendererUtilities; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.springframework.stereotype.Component; import com.github.robindevilliers.welcometohell.ui.Renderer; import com.github.robindevilliers.welcometohell.wizard.domain.Option; import java.io.StringWriter; import java.util.Map; import java.util.UUID; import static com.github.robindevilliers.welcometohell.wizard.type.Serialization.serialize; @Component public class OptionRenderer implements Renderer<Option> { @Override public boolean accepts(Class<?> clz) { return Option.class.equals(clz); } @Override public void render(VelocityEngine velocityEngine, String wizardSessionId, String pageId, Option element, StringWriter content, Map<String, Object> data) { VelocityContext context = new VelocityContext(); RendererUtilities.generateClasses(element, context, "", "bg"); RendererUtilities.generateStyles(element, context); RendererUtilities.generateContent(velocityEngine, element, data, context); context.put("name", element.getData()); context.put("value", serialize(element.getType(), element.getValue())); context.put("checked" , element.getValue().equals(data.get(element.getData()))); context.put("id", UUID.randomUUID().toString()); velocityEngine.getTemplate("views/option.html").merge(context, content); } }
package cyclops.container.immutable; import cyclops.container.relational.Contains; import cyclops.container.control.Try; import cyclops.container.immutable.impl.Seq; import cyclops.container.immutable.impl.Vector; import cyclops.container.immutable.tuple.Tuple2; import cyclops.container.immutable.tuple.Tuple3; import cyclops.container.immutable.tuple.Tuple4; import cyclops.container.persistent.PersistentCollection; import cyclops.container.persistent.PersistentSet; import cyclops.container.recoverable.OnEmptyError; import cyclops.container.recoverable.OnEmptySwitch; import cyclops.container.traversable.IterableX; import cyclops.container.traversable.Traversable; import cyclops.function.combiner.Monoid; import cyclops.function.enhanced.Function3; import cyclops.function.enhanced.Function4; import cyclops.reactive.ReactiveSeq; import java.util.Comparator; import java.util.Random; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import org.reactivestreams.Publisher; public interface ImmutableSet<T> extends OnEmptySwitch<ImmutableSet<T>, ImmutableSet<T>>, PersistentSet<T>, OnEmptyError<T, ImmutableSet<T>>, Contains<T>, IterableX<T> { <R> ImmutableSet<R> unitIterable(Iterable<R> it); @Override default ReactiveSeq<T> stream() { return IterableX.super.stream(); } @Override default ImmutableSet<T> plus(T e) { return append(e); } @Override default ImmutableSet<T> plusAll(Iterable<? extends T> list) { ImmutableSet<T> set = this; for (T next : list) { set = set.plus(next); } return set; } @Override default <U> ImmutableSet<U> ofType(Class<? extends U> type) { return (ImmutableSet<U>) IterableX.super.ofType(type); } @Override default ImmutableSet<T> filterNot(Predicate<? super T> predicate) { return (ImmutableSet<T>) IterableX.super.filterNot(predicate); } @Override default ImmutableSet<T> notNull() { return (ImmutableSet<T>) IterableX.super.notNull(); } @Override default ImmutableSet<T> peek(Consumer<? super T> c) { return (ImmutableSet<T>) IterableX.super.peek(c); } boolean containsValue(T value); int size(); ImmutableSet<T> add(T value); ImmutableSet<T> removeValue(T value); boolean isEmpty(); <R> ImmutableSet<R> map(Function<? super T, ? extends R> fn); <R> ImmutableSet<R> flatMap(Function<? super T, ? extends ImmutableSet<? extends R>> fn); <R> ImmutableSet<R> concatMap(Function<? super T, ? extends Iterable<? extends R>> fn); @Override <R> ImmutableSet<R> mergeMap(Function<? super T, ? extends Publisher<? extends R>> fn); @Override <R> ImmutableSet<R> mergeMap(int maxConcurecy, Function<? super T, ? extends Publisher<? extends R>> fn); ImmutableSet<T> filter(Predicate<? super T> predicate); default <R1, R2, R3, R> ImmutableSet<R> forEach4(Function<? super T, ? extends Iterable<R1>> iterable1, BiFunction<? super T, ? super R1, ? extends Iterable<R2>> iterable2, Function3<? super T, ? super R1, ? super R2, ? extends Iterable<R3>> iterable3, Function4<? super T, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction) { return this.concatMap(in -> { ReactiveSeq<R1> a = ReactiveSeq.fromIterable(iterable1.apply(in)); return a.flatMap(ina -> { ReactiveSeq<R2> b = ReactiveSeq.fromIterable(iterable2.apply(in, ina)); return b.flatMap(inb -> { ReactiveSeq<R3> c = ReactiveSeq.fromIterable(iterable3.apply(in, ina, inb)); return c.map(in2 -> yieldingFunction.apply(in, ina, inb, in2)); }); }); }); } default <R1, R2, R3, R> ImmutableSet<R> forEach4(Function<? super T, ? extends Iterable<R1>> iterable1, BiFunction<? super T, ? super R1, ? extends Iterable<R2>> iterable2, Function3<? super T, ? super R1, ? super R2, ? extends Iterable<R3>> iterable3, Function4<? super T, ? super R1, ? super R2, ? super R3, Boolean> filterFunction, Function4<? super T, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction) { return this.concatMap(in -> { ReactiveSeq<R1> a = ReactiveSeq.fromIterable(iterable1.apply(in)); return a.flatMap(ina -> { ReactiveSeq<R2> b = ReactiveSeq.fromIterable(iterable2.apply(in, ina)); return b.flatMap(inb -> { ReactiveSeq<R3> c = ReactiveSeq.fromIterable(iterable3.apply(in, ina, inb)); return c.filter(in2 -> filterFunction.apply(in, ina, inb, in2)) .map(in2 -> yieldingFunction.apply(in, ina, inb, in2)); }); }); }); } default <R1, R2, R> ImmutableSet<R> forEach3(Function<? super T, ? extends Iterable<R1>> iterable1, BiFunction<? super T, ? super R1, ? extends Iterable<R2>> iterable2, Function3<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction) { return this.concatMap(in -> { Iterable<R1> a = iterable1.apply(in); return ReactiveSeq.fromIterable(a) .flatMap(ina -> { ReactiveSeq<R2> b = ReactiveSeq.fromIterable(iterable2.apply(in, ina)); return b.map(in2 -> yieldingFunction.apply(in, ina, in2)); }); }); } default <R1, R2, R> ImmutableSet<R> forEach3(Function<? super T, ? extends Iterable<R1>> iterable1, BiFunction<? super T, ? super R1, ? extends Iterable<R2>> iterable2, Function3<? super T, ? super R1, ? super R2, Boolean> filterFunction, Function3<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction) { return this.concatMap(in -> { Iterable<R1> a = iterable1.apply(in); return ReactiveSeq.fromIterable(a) .flatMap(ina -> { ReactiveSeq<R2> b = ReactiveSeq.fromIterable(iterable2.apply(in, ina)); return b.filter(in2 -> filterFunction.apply(in, ina, in2)) .map(in2 -> yieldingFunction.apply(in, ina, in2)); }); }); } default <R1, R> ImmutableSet<R> forEach2(Function<? super T, ? extends Iterable<R1>> iterable1, BiFunction<? super T, ? super R1, ? extends R> yieldingFunction) { return this.concatMap(in -> { Iterable<? extends R1> b = iterable1.apply(in); return ReactiveSeq.fromIterable(b) .map(in2 -> yieldingFunction.apply(in, in2)); }); } default <R1, R> ImmutableSet<R> forEach2(Function<? super T, ? extends Iterable<R1>> iterable1, BiFunction<? super T, ? super R1, Boolean> filterFunction, BiFunction<? super T, ? super R1, ? extends R> yieldingFunction) { return this.concatMap(in -> { Iterable<? extends R1> b = iterable1.apply(in); return ReactiveSeq.fromIterable(b) .filter(in2 -> filterFunction.apply(in, in2)) .map(in2 -> yieldingFunction.apply(in, in2)); }); } @Override default ImmutableSet<T> onEmpty(T value) { if (size() == 0) { return add(value); } return this; } @Override default ImmutableSet<T> onEmptyGet(Supplier<? extends T> supplier) { return onEmpty(supplier.get()); } @Override default <X extends Throwable> Try<ImmutableSet<T>, X> onEmptyTry(Supplier<? extends X> supplier) { return isEmpty() ? Try.failure(supplier.get()) : Try.success(this); } @Override default ImmutableSet<T> onEmptySwitch(Supplier<? extends ImmutableSet<T>> supplier) { if (size() == 0) { return supplier.get(); } return this; } <R> ImmutableSet<R> unitStream(Stream<R> stream); @Override default ImmutableSet<T> removeStream(Stream<? extends T> stream) { return unitStream(stream().removeStream(stream)); } default ImmutableSet<T> removeAll(Iterable<? extends T> it) { return unitStream(stream().removeAll(it)); } @Override default ImmutableSet<T> removeAll(T... values) { return unitStream(stream().removeAll(values)); } @Override default ImmutableSet<T> retainAll(Iterable<? extends T> it) { return unitStream(stream().retainAll(it)); } @Override default ImmutableSet<T> retainStream(Stream<? extends T> stream) { return unitStream(stream().retainStream(stream)); } @Override default ImmutableSet<T> retainAll(T... values) { return unitStream(stream().retainAll(values)); } @Override default <T2, R> ImmutableSet<R> zip(BiFunction<? super T, ? super T2, ? extends R> fn, Publisher<? extends T2> publisher) { return unitStream(stream().zip(fn, publisher)); } default <U, R> ImmutableSet<R> zipWithStream(Stream<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) { return unitStream(stream().zipWithStream(other, zipper)); } @Override default <U> ImmutableSet<Tuple2<T, U>> zipWithPublisher(Publisher<? extends U> other) { return unitStream(stream().zipWithPublisher(other)); } @Override default <U> ImmutableSet<Tuple2<T, U>> zip(Iterable<? extends U> other) { return unitStream(stream().zip(other)); } @Override default <S, U, R> ImmutableSet<R> zip3(Iterable<? extends S> second, Iterable<? extends U> third, Function3<? super T, ? super S, ? super U, ? extends R> fn3) { return unitStream(stream().zip3(second, third, fn3)); } @Override default <T2, T3, T4, R> ImmutableSet<R> zip4(Iterable<? extends T2> second, Iterable<? extends T3> third, Iterable<? extends T4> fourth, Function4<? super T, ? super T2, ? super T3, ? super T4, ? extends R> fn) { return unitStream(stream().zip4(second, third, fourth, fn)); } @Override default ImmutableSet<T> combine(BiPredicate<? super T, ? super T> predicate, BinaryOperator<T> op) { return unitStream(stream().combine(predicate, op)); } @Override default ImmutableSet<T> combine(Monoid<T> op, BiPredicate<? super T, ? super T> predicate) { return unitStream(stream().combine(op, predicate)); } @Override default ImmutableSet<T> cycle(long times) { return unitStream(stream().cycle(times)); } @Override default ImmutableSet<T> cycle(Monoid<T> m, long times) { return unitStream(stream().cycle(m, times)); } @Override default ImmutableSet<T> cycleWhile(Predicate<? super T> predicate) { return unitStream(stream().cycleWhile(predicate)); } @Override default ImmutableSet<T> cycleUntil(Predicate<? super T> predicate) { return unitStream(stream().cycleUntil(predicate)); } @Override default <U, R> ImmutableSet<R> zip(Iterable<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) { return unitStream(stream().zip(other, zipper)); } @Override default <S, U> ImmutableSet<Tuple3<T, S, U>> zip3(Iterable<? extends S> second, Iterable<? extends U> third) { return unitStream(stream().zip3(second, third)); } @Override default <T2, T3, T4> ImmutableSet<Tuple4<T, T2, T3, T4>> zip4(Iterable<? extends T2> second, Iterable<? extends T3> third, Iterable<? extends T4> fourth) { return unitStream(stream().zip4(second, third, fourth)); } @Override default ImmutableSet<Tuple2<T, Long>> zipWithIndex() { return unitStream(stream().zipWithIndex()); } @Override default ImmutableSet<Seq<T>> sliding(int windowSize) { return unitStream(stream().sliding(windowSize)); } @Override default ImmutableSet<Seq<T>> sliding(int windowSize, int increment) { return unitStream(stream().sliding(windowSize, increment)); } @Override default <C extends PersistentCollection<? super T>> ImmutableSet<C> grouped(int size, Supplier<C> supplier) { return unitStream(stream().grouped(size, supplier)); } @Override default IterableX<Vector<T>> groupedUntil(Predicate<? super T> predicate) { return unitStream(stream().groupedUntil(predicate)); } @Override default ImmutableSet<Vector<T>> groupedUntil(BiPredicate<Vector<? super T>, ? super T> predicate) { return unitStream(stream().groupedUntil(predicate)); } default <U> ImmutableSet<Tuple2<T, U>> zipWithStream(Stream<? extends U> other) { return unitStream(stream().zipWithStream(other)); } @Override default ImmutableSet<Vector<T>> groupedWhile(Predicate<? super T> predicate) { return unitStream(stream().groupedWhile(predicate)); } @Override default <C extends PersistentCollection<? super T>> ImmutableSet<C> groupedWhile(Predicate<? super T> predicate, Supplier<C> factory) { return unitStream(stream().groupedWhile(predicate, factory)); } @Override default <C extends PersistentCollection<? super T>> ImmutableSet<C> groupedUntil(Predicate<? super T> predicate, Supplier<C> factory) { return unitStream(stream().groupedUntil(predicate, factory)); } @Override default ImmutableSet<Vector<T>> grouped(int groupSize) { return unitStream(stream().grouped(groupSize)); } @Override default ImmutableSet<T> distinct() { return unitStream(stream().distinct()); } @Override default ImmutableSet<T> scanLeft(Monoid<T> monoid) { return unitStream(stream().scanLeft(monoid)); } @Override default <U> ImmutableSet<U> scanLeft(U seed, BiFunction<? super U, ? super T, ? extends U> function) { return unitStream(stream().scanLeft(seed, function)); } @Override default ImmutableSet<T> scanRight(Monoid<T> monoid) { return unitStream(stream().scanRight(monoid)); } @Override default <U> ImmutableSet<U> scanRight(U identity, BiFunction<? super T, ? super U, ? extends U> combiner) { return unitStream(stream().scanRight(identity, combiner)); } @Override default ImmutableSet<T> sorted() { return unitStream(stream().sorted()); } @Override default ImmutableSet<T> sorted(Comparator<? super T> c) { return unitStream(stream().sorted(c)); } @Override default ImmutableSet<T> takeWhile(Predicate<? super T> p) { return unitStream(stream().takeWhile(p)); } @Override default ImmutableSet<T> dropWhile(Predicate<? super T> p) { return unitStream(stream().dropWhile(p)); } @Override default ImmutableSet<T> takeUntil(Predicate<? super T> p) { return unitStream(stream().takeUntil(p)); } @Override default ImmutableSet<T> dropUntil(Predicate<? super T> p) { return unitStream(stream().dropUntil(p)); } @Override default ImmutableSet<T> dropRight(int num) { return unitStream(stream().dropRight(num)); } @Override default ImmutableSet<T> takeRight(int num) { return unitStream(stream().takeRight(num)); } @Override default ImmutableSet<T> drop(long num) { return unitStream(stream().drop(num)); } @Override default ImmutableSet<T> take(long num) { return unitStream(stream().take(num)); } @Override default ImmutableSet<T> intersperse(T value) { return unitStream(stream().intersperse(value)); } @Override default ImmutableSet<T> reverse() { return unitStream(stream().reverse()); } @Override default ImmutableSet<T> shuffle() { return unitStream(stream().shuffle()); } @Override default ImmutableSet<T> shuffle(Random random) { return unitStream(stream().shuffle(random)); } @Override default ImmutableSet<T> slice(long from, long to) { return unitStream(stream().slice(from, to)); } @Override default <U extends Comparable<? super U>> ImmutableSet<T> sorted(Function<? super T, ? extends U> function) { return unitStream(stream().sorted(function)); } @Override default Traversable<T> traversable() { return stream(); } @Override default ImmutableSet<T> prependStream(Stream<? extends T> stream) { return unitStream(stream().prependStream(stream)); } @Override default ImmutableSet<T> appendAll(T... values) { return unitStream(stream().appendAll(values)); } @Override default ImmutableSet<T> append(T value) { return unitStream(stream().append(value)); } @Override default ImmutableSet<T> prepend(T value) { return unitStream(stream().prepend(value)); } @Override default ImmutableSet<T> prependAll(T... values) { return unitStream(stream().prependAll(values)); } @Override default ImmutableSet<T> deleteBetween(int start, int end) { return unitStream(stream().deleteBetween(start, end)); } @Override default ImmutableSet<T> insertStreamAt(int pos, Stream<T> stream) { return unitStream(stream().insertStreamAt(pos, stream)); } @Override default ImmutableSet<ReactiveSeq<T>> permutations() { return unitStream(stream().permutations()); } @Override default ImmutableSet<ReactiveSeq<T>> combinations(int size) { return unitStream(stream().combinations(size)); } @Override default ImmutableSet<ReactiveSeq<T>> combinations() { return unitStream(stream().combinations()); } @Override default ImmutableSet<T> removeAt(long pos) { return unitStream(stream().removeAt(pos)); } @Override default ImmutableSet<T> removeFirst(Predicate<? super T> pred) { return unitStream(stream().removeFirst(pred)); } @Override default ImmutableSet<T> appendAll(Iterable<? extends T> value) { return unitStream(stream().appendAll(value)); } @Override default ImmutableSet<T> prependAll(Iterable<? extends T> value) { return unitStream(stream().prependAll(value)); } @Override default ImmutableSet<T> updateAt(int pos, T value) { return unitStream(stream().updateAt(pos, value)); } @Override default ImmutableSet<T> insertAt(int pos, Iterable<? extends T> values) { return plusAll(values); } @Override default ImmutableSet<T> insertAt(int i, T value) { return plus(value); } @Override default ImmutableSet<T> insertAt(int pos, T... values) { ImmutableSet<T> res = this; for (T next : values) { res = res.plus(next); } return res; } }
<filename>open-sphere-plugins/csv-common/src/main/java/io/opensphere/csvcommon/format/factory/CellFormatterFactory.java<gh_stars>10-100 package io.opensphere.csvcommon.format.factory; import java.util.Map; import io.opensphere.core.preferences.PreferencesRegistry; import io.opensphere.core.util.collections.New; import io.opensphere.csvcommon.format.CellFormatter; import io.opensphere.csvcommon.format.color.ColorFormatter; import io.opensphere.csvcommon.format.datetime.DateFormatter; import io.opensphere.csvcommon.format.datetime.DateTimeFormatter; import io.opensphere.csvcommon.format.datetime.TimeFormatter; import io.opensphere.csvcommon.format.position.LatitudeFormatter; import io.opensphere.csvcommon.format.position.LongitudeFormatter; import io.opensphere.csvcommon.format.position.PositionFormatter; import io.opensphere.importer.config.ColumnType; /** * Gets the formatters for a given type. * */ public final class CellFormatterFactory { /** The map of column type to cell formatter. */ private final Map<ColumnType, CellFormatter> myFormatterMap = New.map(); /** The map of column type to system format. */ private final Map<ColumnType, String> mySystemFormatMap = New.map(); /** * Gets the formatter based on the column result. * * @param columnType The column type. * @param preferencesRegistry The preferences registry. * @return The cell formatter. */ public CellFormatter getFormatter(ColumnType columnType, PreferencesRegistry preferencesRegistry) { CellFormatter formatter = myFormatterMap.get(columnType); if (formatter == null) { if (columnType == ColumnType.DOWN_TIMESTAMP || columnType == ColumnType.TIMESTAMP) { formatter = new DateTimeFormatter(preferencesRegistry); } else if (columnType == ColumnType.DATE || columnType == ColumnType.DOWN_DATE) { formatter = new DateFormatter(preferencesRegistry); } else if (columnType == ColumnType.TIME || columnType == ColumnType.DOWN_TIME) { formatter = new TimeFormatter(preferencesRegistry); } else if (columnType == ColumnType.LAT) { formatter = new LatitudeFormatter(preferencesRegistry); } else if (columnType == ColumnType.LON) { formatter = new LongitudeFormatter(preferencesRegistry); } else if (columnType == ColumnType.POSITION) { formatter = new PositionFormatter(preferencesRegistry); } else if (columnType == ColumnType.COLOR) { formatter = new ColorFormatter(); } if (formatter != null) { myFormatterMap.put(columnType, formatter); } } return formatter; } /** * Gets the system format for the given column type. * * @param columnType The column type. * @param preferencesRegistry The preferences registry. * @return The system format. */ public String getSystemFormat(ColumnType columnType, PreferencesRegistry preferencesRegistry) { String systemFormat = mySystemFormatMap.get(columnType); if (systemFormat == null) { CellFormatter formatter = getFormatter(columnType, preferencesRegistry); if (formatter != null) { systemFormat = formatter.getSystemFormat(); mySystemFormatMap.put(columnType, systemFormat); } } return systemFormat; } }
import { getLogger } from '../logger.ts'; import { pair, Pair } from '../types/mod.ts'; import { next_async } from '../lib/iterable/mod.ts'; import { scan } from './scan.ts'; const logger = await getLogger('methods/enumerate'); async function* _enumerate_impl_fn<T>(iter: AsyncIterable<T>): AsyncIterable<Pair<number, T>> { logger.trace('enumerate()'); const { done, value } = await next_async(iter); if (done) { return; } yield* scan(([current], elem) => pair(current + 1, elem), pair(0, value), iter); } export function enumerate<T>(iter: AsyncIterable<T>): AsyncIterable<Pair<number, T>> { return _enumerate_impl_fn(iter); }
<filename>blingfirecompile.library/inc/FAPrintUtils.h /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_PRINT_UTILS_H_ #define _FA_PRINT_UTILS_H_ #include "FAConfig.h" #include <iostream> namespace BlingFire { class FARegexpTree; class FARegexpTree2Funcs; class FAToken; class FAWREToken; class FATagSet; /// template function for printing of arrays /// array elements must support << operator template <class Ty> void FAPrintArray (std::ostream& os, const Ty * pA, const int Size) { if (NULL != pA) { os << "["; for (int i = 0; i < Size; ++i) { os << " " << (int) pA [i]; } os << " ]"; } else { os << "NULL"; } } /// template function for reversed printing of arrays /// array elements must support << operator template <class Ty> void FAPrintArray_rev (std::ostream& os, const Ty * pA, const int Size) { if (NULL != pA) { os << "["; for (int i = Size - 1; i >= 0; --i) { os << " " << (int) pA [i]; } os << " ]"; } else { os << "NULL"; } } template<> void FAPrintArray (std::ostream& os, const FAToken * pA, const int Size); template<> void FAPrintArray (std::ostream& os, const FAWREToken * pA, const int Size); template<> void FAPrintArray (std::ostream& os, const float * pA, const int Size); /// prints out RegexpTree in dotty format void FAPrintRegexpTree ( std::ostream& os, const FARegexpTree * pTree, const char * pRegexp ); /// prints regexp functions in dotty format void FAPrintRegexpFuncs ( std::ostream& os, const FARegexpTree2Funcs * pFuncs, const FARegexpTree * pTree ); /// FAToken << operator std::ostream& operator <<(std::ostream& os, const FAToken& Token); /// FAWREToken << operator std::ostream& operator <<(std::ostream& os, const FAWREToken& Token); /// prints 0-separated list of words (in UTF-8) void FAPrintWordList ( std::ostream& os, const int * pWordList, const int Count, const char Delim = ' ' ); /// prints splitted chain (in UTF-8) void FAPrintSplitting ( std::ostream& os, const int * pChain, const int ChainSize, const int * pEnds, const int EndsCount, const char Delim = ' ' ); /// print a list of tags (in ASCII) void FAPrintTagList ( std::ostream& os, const FATagSet * pTagSet, const int * pTags, const int Count, const char Delim = ' ' ); /// prints word (in UTF-8) void FAPrintWord ( std::ostream& os, const int * pWord, const int WordLen ); /// prints tagged word (in UTF-8) void FAPrintTaggedWord ( std::ostream& os, const FATagSet * pTagSet, const int * pWord, const int WordLen, const int Tag ); /// prints a single value (in ASCII) void FAPrintValue ( std::ostream& os, const int Value, const int Width, const bool Hex ); /// prints a chain of digitis (in ASCII) void FAPrintChain ( std::ostream& os, const int * pChain, const int ChainSize, const int Dir, const int Width, const bool Hex ); /// prints hyphenated word in UTF-8 void FAPrintHyphWord ( std::ostream& os, const int * pWord, const int * pHyphs, const int WordLen ); } #endif
<filename>e2e/cypress/integration/ui/settings/data-feed/data-feed-create.spec.ts describe('chef datafeed', () => { const name = 'cytest', url = 'http://test.com', username = 'admin', password = 'password', tokenType = 'TestType', token = '<PASSWORD>=', endpoint = 'https://test.com', bucketName = 'bucket', accessKey = 'access_key', secretKey = 'secret_key'; const minioBucket = 'mybucket', minioSecret = 'minioadmin', minioAccess = 'minioadmin', minioUrl = 'http://127.0.0.1:9000'; before(() => { cy.adminLogin('/settings').then(() => { const admin = JSON.parse(<string>localStorage.getItem('chef-automate-user')); cy.get('app-welcome-modal').invoke('hide'); cy.restoreStorage(); cy.get('body').type('feat'); cy.get('.title').contains('Chef Automate Data Feed').parent().parent() .find('.onoffswitch').click(); cy.get('chef-button').contains('Close').click(); cy.reload(); cy.contains('know').click(); cy.contains('Data Feeds').click(); // cy.get('app-notification.error chef-icon').click({ multiple: true }); }); }); beforeEach(() => { cy.restoreStorage(); }); afterEach(() => { cy.saveStorage(); }); describe ('chef data feed page', () => { const reusableDate = Date.now(); it('check if clicking on new integration button opens up the slider', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=interation-menu]').should('be.visible'); cy.get('[data-cy=close-feed-button]').click(); }); it('check if clicking on a interation opens the form', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=ServiceNow]').click(); cy.get('[data-cy=data-feed-create-form]').should('be.visible'); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed service now', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=ServiceNow]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=select-auth-type]').click(); cy.get('[data-cy=select-username-password]').click(); cy.get('[data-cy=add-username]').type(username); cy.get('[data-cy=add-password]').type(password); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('create data feed splunk', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Splunk]').click(); cy.get('[data-cy=add-name]').type(name + reusableDate); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + reusableDate).should('exist'); }); it('create data feed ELK', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=ELK]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=select-auth-type]').click(); cy.get('[data-cy=select-username-password]').click(); cy.get('[data-cy=add-username]').type(username); cy.get('[data-cy=add-password]').type(password); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('create data feed error splunk', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Splunk]').click(); cy.get('[data-cy=add-name]').type(name + reusableDate); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=add-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed error ELK', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=ELK]').click(); cy.get('[data-cy=add-name]').type(name + reusableDate); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=select-auth-type]').click(); cy.get('[data-cy=select-username-password]').click(); cy.get('[data-cy=add-username]').type(username); cy.get('[data-cy=add-password]').type(password); cy.get('[data-cy=add-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed with changed token type Splunk', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Splunk]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=toggle-type]').click(); cy.get('[data-cy=add-token-type]').clear(); cy.get('[data-cy=add-token-type]').type(tokenType); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('create data feed with changed token type ELK', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=ELK]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=select-auth-type]').click(); cy.get('[data-cy=select-access-token]').click(); cy.get('[data-cy=toggle-type]').click(); cy.get('[data-cy=add-token-type]').clear(); cy.get('[data-cy=add-token-type]').type(tokenType); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('test error in data feed Splunk', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Splunk]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed Custom with token', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Custom]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=add-token-type]').type(tokenType); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('test connection in data feed Custom', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Custom]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=select-auth-type]').click(); cy.get('[data-cy=select-username-password]').click(); cy.get('[data-cy=add-username]').type(username); cy.get('[data-cy=add-password]').type(password); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed Custom with username', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Custom]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=select-auth-type]').click(); cy.get('[data-cy=select-username-password]').click(); cy.get('[data-cy=add-username]').type(username); cy.get('[data-cy=add-password]').type(password); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('create data feed error custom', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Custom]').click(); cy.get('[data-cy=add-name]').type(name + reusableDate); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=add-token-type]').type(tokenType); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=add-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('test error in data feed ELK for Token', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=ELK]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=select-auth-type]').click(); cy.get('[data-cy=select-access-token]').click(); cy.get('[data-cy=toggle-type]').click(); cy.get('[data-cy=add-token-type]').clear(); cy.get('[data-cy=add-token-type]').type(tokenType); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('test error in data feed ELK for username and password', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=ELK]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=select-auth-type]').click(); cy.get('[data-cy=select-username-password]').click(); cy.get('[data-cy=add-username]').type(username); cy.get('[data-cy=add-password]').type(password); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed minio', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Minio]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-endpoint]').type(endpoint); cy.get('[data-cy=add-bucket-name]').type(bucketName); cy.get('[data-cy=add-access-key]').type(accessKey); cy.get('[data-cy=add-secret-key]').type(secretKey); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('test error in data feed minio failure', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Minio]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-endpoint]').type(endpoint); cy.get('[data-cy=add-bucket-name]').type(bucketName); cy.get('[data-cy=add-access-key]').type(accessKey); cy.get('[data-cy=add-secret-key]').type(secretKey); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('test connection in data feed minio success', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Minio]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-endpoint]').type(minioUrl); cy.get('[data-cy=add-bucket-name]').type(minioBucket); cy.get('[data-cy=add-access-key]').type(minioAccess); cy.get('[data-cy=add-secret-key]').type(minioSecret); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.info').should('be.visible'); cy.get('.data-feed-slider app-notification.info chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed for S3', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy="Amazon S3"]').click(); cy.get('[data-cy=add-name]').type(name + reusableDate); cy.get('[data-cy=add-bucket-name]').type(bucketName); cy.get('[data-cy=add-access-key]').type(accessKey); cy.get('[data-cy=add-secret-key]').type(secretKey); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + reusableDate).should('exist'); }); it('error in creating data feed for S3', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy="Amazon S3"]').click(); cy.get('[data-cy=add-name]').type(name + reusableDate); cy.get('[data-cy=add-bucket-name]').type(bucketName); cy.get('[data-cy=add-access-key]').type(accessKey); cy.get('[data-cy=add-secret-key]').type(secretKey); cy.get('[data-cy=add-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('test faliure in data feed S3', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('app-data-feed-create').scrollTo('bottom'); cy.get('[data-cy="Amazon S3"]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-bucket-name]').type(bucketName); cy.get('[data-cy=add-access-key]').type(accessKey); cy.get('[data-cy=add-secret-key]').type(secretKey); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); }); describe ('chef data feed page', () => { const reusableDate = Date.now(); it('check if clicking on new integration button opens up the slider', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=interation-menu]').should('be.visible'); cy.get('[data-cy=close-feed-button]').click(); }); it('check if clicking on a interation opens the form', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=ServiceNow]').click(); cy.get('[data-cy=data-feed-create-form]').should('be.visible'); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed service now', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=ServiceNow]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=select-auth-type]').click(); cy.get('[data-cy=select-username-password]').click(); cy.get('[data-cy=add-username]').type(username); cy.get('[data-cy=add-password]').type(password); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('create data feed splunk', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Splunk]').click(); cy.get('[data-cy=add-name]').type(name + reusableDate); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + reusableDate).should('exist'); }); it('create data feed error', () => { cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Splunk]').click(); cy.get('[data-cy=add-name]').type(name + reusableDate); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=add-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed with changed token type', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Splunk]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=toggle-type]').click(); cy.get('[data-cy=add-token-type]').clear(); cy.get('[data-cy=add-token-type]').type(tokenType); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('test error in data feed', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Splunk]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-url]').type(url); cy.get('[data-cy=add-token]').type(token); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('create data feed minio', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Minio]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-endpoint]').type(endpoint); cy.get('[data-cy=add-bucket-name]').type(bucketName); cy.get('[data-cy=add-access-key]').type(accessKey); cy.get('[data-cy=add-secret-key]').type(secretKey); cy.get('[data-cy=add-button]').click(); cy.get('app-notification.info').should('be.visible'); cy.get('app-notification.info chef-icon').click(); cy.contains('Data Feeds').click(); cy.get('chef-table chef-tbody chef-td').contains('cytest' + date).should('exist'); }); it('test error in data feed minio failure', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Minio]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-endpoint]').type(endpoint); cy.get('[data-cy=add-bucket-name]').type(bucketName); cy.get('[data-cy=add-access-key]').type(accessKey); cy.get('[data-cy=add-secret-key]').type(secretKey); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.error').should('be.visible'); cy.get('.data-feed-slider app-notification.error chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); it('test connection in data feed minio success', () => { const date = Date.now(); cy.get('[data-cy=create-data-feed]').click(); cy.get('[data-cy=Minio]').click(); cy.get('[data-cy=add-name]').type(name + date); cy.get('[data-cy=add-endpoint]').type(minioUrl); cy.get('[data-cy=add-bucket-name]').type(minioBucket); cy.get('[data-cy=add-access-key]').type(minioAccess); cy.get('[data-cy=add-secret-key]').type(minioSecret); cy.get('[data-cy=test-button]').click(); cy.get('app-data-feed-create').scrollTo('top'); cy.get('.data-feed-slider app-notification.info').should('be.visible'); cy.get('.data-feed-slider app-notification.info chef-icon').click(); cy.get('[data-cy=close-feed-button]').click(); }); }); });
def find_primes(n): primes = [] for i in range(2, n+1): is_prime = True for j in range(2, i): if i % j == 0: is_prime = False break if is_prime: primes.append(i) return primes print(find_primes(10)) # prints [2, 3, 5, 7]
<reponame>cyberdevnet/mer-hacker import React from "react"; import Dialog from '@material-ui/core/Dialog'; import "../../styles/CreateTemplateModal.css"; export default function GetAllClientsModal(ac) { let ClientList = Number(ac.dc.clientListID) const Cancel = () => { ac.dc.setshowclientModal(false); }; const handleClientUp = () => { if (ClientList < ac.dc.allClients.length && ac.dc.clientListID !== ac.dc.allClients.length - 1) { ac.dc.setsingleClient(ac.dc.allClients[ClientList + 1]) ac.dc.setclientListID(ClientList + 1) } }; const handleClientDown = () => { if (ClientList > 0) { ac.dc.setsingleClient(ac.dc.allClients[ClientList - 1]) ac.dc.setclientListID(ClientList - 1) } }; return ( <Dialog open={true} fullWidth > <div > <div className="modal-dialog-summary modal-confirm-summary"> <div > <div style={{ borderBottom: 'none' }} className="modal-header"> <button onClick={Cancel} type="button" className="close" data-dismiss="modal" aria-hidden="true" style={{ top: '0px', right: '-55px', outline: 'none' }} > <span>&times;</span> </button> <button onClick={handleClientUp} type="button" className="close" data-dismiss="modal" aria-hidden="true" style={{ top: '65px', right: '-45px', fontSize: '23px', color: 'black', outline: 'none' }} > <span className="glyphicon glyphicon-circle-arrow-right"></span> </button> <button onClick={handleClientDown} type="button" className="close" data-dismiss="modal" aria-hidden="true" style={{ top: '65px', left: '-45px', fontSize: '23px', color: 'black', outline: 'none' }} > <span className="glyphicon glyphicon-circle-arrow-left" ></span> </button> </div> <div className="modal-body text-center" style={{ fontSize: '11px', color: 'darkslategray' }}> <h4>Client Details</h4> <table className="table table-striped table-bordered" id="table1"> <tbody key='1'> <tr> <th style={{ width: '100%', float: 'left' }}> description </th> <td> {ac.dc.singleClient.description} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> firstSeen </th> <td> {ac.dc.singleClient.firstSeen} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> groupPolicy8021x </th> <td> {ac.dc.singleClient.groupPolicy8021x} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> id </th> <td> {ac.dc.singleClient.id} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> ip </th> <td> {ac.dc.singleClient.ipEnabled} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> ip6 </th> <td> {ac.dc.singleClient.ip6} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> ip6local </th> <td> {ac.dc.singleClient.ip6Local} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> lastSeen </th> <td> {ac.dc.singleClient.lastSeen} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> mac </th> <td> {ac.dc.singleClient.mac} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> manufacturer </th> <td> {ac.dc.singleClient.manufacturer} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> notes </th> <td> {ac.dc.singleClient.notes} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> os </th> <td> {ac.dc.singleClient.os} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> recentDeviceName </th> <td> {ac.dc.singleClient.recentDeviceName} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> recentDeviceSerial </th> <td> {ac.dc.singleClient.recentDeviceSerial} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> smInstalled </th> <td> {ac.dc.singleClient.smInstalled} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> ssid </th> <td> {ac.dc.singleClient.ssid} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> status </th> <td> {ac.dc.singleClient.status} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> switchport </th> <td> {ac.dc.singleClient.switchport} </td> </tr> {/* <tr> <th style={{ width: '100%',float: 'left' }}> usage </th> <td> {ac.dc.singleClient.usage} </td> </tr> */} <tr> <th style={{ width: '100%', float: 'left' }}> user </th> <td> {ac.dc.singleClient.user} </td> </tr> <tr> <th style={{ width: '100%', float: 'left' }}> vlan </th> <td> {ac.dc.singleClient.vlan} </td> </tr> </tbody> </table> </div> </div> </div> </div> </Dialog> ); }
<filename>stardog/js/load.js var loadState = { preload: function() { //logo game.load.image('logo', 'assets/stardog.png'); game.load.spritesheet('bg', 'assets/titlescreen.png', 1200, 600); //music game.load.audio('music1', 'assets/audio/logoMusic.mp3'); game.load.audio('music2', 'assets/audio/level1music.wav'); game.load.audio('music3', 'assets/audio/labMusic.wav'); game.load.audio('music4', 'assets/audio/bossMusic.wav'); //credit screen game.load.image('credits', 'assets/credits.png'); //intro slides game.load.image('screen', 'assets/screen.jpg'); game.load.spritesheet('intro1', 'assets/incoming.png', 1000, 500); game.load.image('intro2', 'assets/incomingmessage.png'); game.load.image('start1', 'assets/spaceStart.png'); game.load.image('start2', 'assets/spaceAccept.png'); //pause screen game.load.image('pause', 'assets/menu1.jpg'); //player sprite sheet game.load.spritesheet('dog', 'assets/dog.png', 200, 100); //astrid sprite sheet game.load.spritesheet('astrid', 'assets/astrid.png', 83, 200); //enemy sprite sheets game.load.spritesheet('guard1', 'assets/guard1.png', 110, 199); game.load.spritesheet('guard2', 'assets/guard2.png', 111, 200); game.load.spritesheet('guard3', 'assets/guard3.png', 113, 199); game.load.spritesheet('scientist1', 'assets/scientist1.png', 114, 205); game.load.spritesheet('nox', 'assets/tenebris.png', 160, 256); //level backgrounds + grounds game.load.image('sky', 'assets/sky.png'); game.load.image('ground1', 'assets/ground1.png'); game.load.image('platform', 'assets/platform.png'); game.load.image('tower', 'assets/tower.png'); game.load.image('smallTower', 'assets/smallTower.png'); game.load.image('elevator', 'assets/elevator.png'); game.load.image('lab', 'assets/lab.png'); game.load.image('ground2', 'assets/ground2.png'); game.load.image('platform2', 'assets/platform2.png'); game.load.image('elevator2', 'assets/elevator2.png'); game.load.image('bossBG', 'assets/bossBG.png'); game.load.image('cage', 'assets/cage.png'); game.load.image('arrow', 'assets/arrow.png'); game.load.image('door', 'assets/door.png'); game.load.image('exit', 'assets/exit.png'); game.load.image('ground3', 'assets/ground3.png'); game.load.image('platform3', 'assets/platform3.png'); game.load.image('laser', 'assets/laser.png'); game.load.image('laser2', 'assets/laser2.png'); //dog related items game.load.image('bark1', 'assets/barkwaves.png'); game.load.image('bark2', 'assets/barkwaves2.png'); game.load.image('shield', 'assets/shield.png'); game.load.image('dogbone', 'assets/dogbone.png'); game.load.image('capsule', 'assets/capsule.png'); //feedback bars game.load.image('hb1', 'assets/healthBar.png'); game.load.image('hb2', 'assets/healthFrame.png'); game.load.image('bb1', 'assets/barkBar.png'); game.load.image('bb2', 'assets/barkFrame.png'); //enemy related items game.load.image('bullet', 'assets/bullet.png'); game.load.image('bullet2', 'assets/bullet2.png'); game.load.image('crate', 'assets/crate.png'); //switch and shield game.load.spritesheet('switch', 'assets/switch.png', 52, 91); game.load.spritesheet('switch2', 'assets/switch2.png', 52, 91); game.load.image('corpshield', 'assets/corpshield.png'); game.load.image('corp', 'assets/corp.png'); //speech blocks game.load.image('chat1', 'assets/chat3.png'); game.load.image('chat2', 'assets/chat4.png'); game.load.image('noxtext1', 'assets/noxtext1.png'); game.load.image('noxtext2', 'assets/noxtext2.png'); game.load.image('astridtext1', 'assets/astridtext1.png'); game.load.image('astridtext2', 'assets/astridtext2.png'); //sound effects game.load.audio('barkSound', 'assets/audio/bark.wav'); game.load.audio('superBarkSound', 'assets/audio/superbark.wav'); game.load.audio('superMegaBarkSound', 'assets/audio/supermegabark.wav'); game.load.audio('shootSound', 'assets/audio/enemyShootSound.wav'); game.load.audio('shieldFuzz', 'assets/audio/shield.wav'); game.load.audio('shieldOn', 'assets/audio/shieldOn.wav'); game.load.audio('shieldOff', 'assets/audio/shieldOff.wav'); game.load.audio('damageSound', 'assets/audio/damage.wav'); game.load.audio('healthSound', 'assets/audio/health.wav'); game.load.audio('powerSound', 'assets/audio/powerUp.wav'); game.load.audio('deathSound', 'assets/audio/dogHit.wav'); game.load.audio('destroySound', 'assets/audio/objectDestroyed.wav'); game.load.audio('destroyShield', 'assets/audio/shieldDestroyed.wav'); game.load.audio('jump', 'assets/audio/jump.wav'); }, create: function() { //start the menu state game.state.start('menu'); } }
conda list -p $PREFIX --canonical # Test the build string. Should contain NumPy, but not the version conda list -p $PREFIX --canonical | grep "conda-build-test-numpy-build-run-1\.0-py..h......._0"
<reponame>ArcheSpace/Arche.js<gh_stars>1000+ import { ColorSpace } from "./enums/ColorSpace"; /** * Render settings. */ export interface EngineSettings { /** Color space.*/ colorSpace?: ColorSpace; }
// Autogenerated from library/channels.i package ideal.library.channels; import ideal.library.elements.*; public interface readonly_output<element> extends readonly_closeable, readonly_syncable, any_output<element> { }
#!/bin/sh #################### ## Jib and deploy ## #################### # Tool for building Docker container with Gradle and jib, and deploying to AWS ECS # # Requirements: # * aws-cli # * amazon-ecr-credential-helper # # Usage: # $ ./jib-aws-deploy needToLogin serviceANR clusterANR checkPeriod [buildParams] # * needToLogin: contains yes if need to login before push into Docker registry # * serviceANR: anr link to the service # * clusterANR: anr link to the cluster # * checkPeriod: health check grace period in seconds for the service # * buildParams: comma-separated build options if [ "$1" = "yes" ]; then $(aws ecr get-login --no-include-email --region eu-central-1) if [ $? -eq 1 ]; then echo "An error occurred while logging in to aws" exit 1 fi fi if [ -z "$5" ]; then ./gradlew jib else ./gradlew -P$5 jib fi if [ $? -eq 1 ]; then echo "An error occurred while building the Docker image" exit 2 fi if ! aws ecs update-service --cluster "$2" --service "$3" --health-check-grace-period-seconds "$4" --force-new-deployment; then echo "An error occurred while restarting the service" exit 3 fi
from __future__ import absolute_import, division, print_function, unicode_literals import json import requests import urllib3 import traceback # main URL to connect to MAIN_URL = 'https://us-central1-yuce-8-v1.cloudfunctions.net/yuce_8_api_client' # supported intervals by YUCE-8 INTERVAL_1D = '1d' INTERVAL_1HOUR = '1hour' INTERVAL_4HOURS = '4hour' INTERVAL_30MIN = '30min' INTERVAL_15MIN = '15min' INTERVAL_5MIN = '5min' INTERVAL_1MIN = '1min' ACTION_GET_VERSION = 'get_version' ACTION_GET_SUPPORTED_SYMBOLS = 'get_symbols' ACTION_GET_LATEST_FORECAST = 'get_latest_forecast' ACTION_GET_HISTORICAL_FORECAST = 'get_historical_forecast' ACTION_SAVE_CURRENT_SUBSCRIBERS = 'save_current_subscribers' ACTION_GET_HISTORICAL_DATA = 'get_historical_data' PARAMETER_HISTORY = 'history' PARAMETER_MSG = 'msg' PARAMETER_ACTION = 'action' PARAMETER_VERSION = 'version' PARAMETER_SYMBOLS = 'symbols' PARAMETER_SYMBOL = 'symbol' PARAMETER_INTERVAL = 'interval' PARAMETER_F_0 = 'f_0' PARAMETER_MAX_RECORDS = 'max_records' PARAMETER_RESULT = 'result' # main client class Y8_API_Client(): # initialize the client def __init__(self, user_name): global MAIN_URL self.user_name = user_name print('Y8_API_Client initialized | connecting to ', MAIN_URL, ' with user ', user_name) # internally used to post a json object to the YUCE-8 service def post_json(self, json_obj): global MAIN_URL json_obj['user_name'] = self.user_name print(json_obj) print(MAIN_URL) return requests.post(MAIN_URL, json=json_obj) # get the current backend version def get_backend_version(self): global PARAMETER_ACTION global ACTION_GET_VERSION global PARAMETER_VERSION global PARAMETER_MSG try: req = self.post_json({PARAMETER_ACTION: ACTION_GET_VERSION}) if req.status_code == 200: msg = req.json()[PARAMETER_MSG] version = msg[PARAMETER_VERSION] return version else: raise(req.text) except Exception as E: print('ERROR@get_backend_version: ', E) traceback.print_exc() return None # get the list of supported symbols and intervals def get_supported_symbols(self): global PARAMETER_ACTION global ACTION_GET_SUPPORTED_SYMBOLS global PARAMETER_MSG global PARAMETER_SYMBOLS try: req = self.post_json({PARAMETER_ACTION: ACTION_GET_SUPPORTED_SYMBOLS}) if req.status_code == 200: msg = req.json()[PARAMETER_MSG] symbols = msg[PARAMETER_SYMBOLS] return symbols else: raise(req.text) except Exception as E: print('ERROR@get_supported_symbols: ', E) traceback.print_exc() return None # get the the current forecast for symbol and interval def get_latest_forecast(self, symbol, interval): global PARAMETER_ACTION global ACTION_GET_LATEST_FORECAST global PARAMETER_MSG global PARAMETER_F_0 try: req = self.post_json({ PARAMETER_ACTION: ACTION_GET_LATEST_FORECAST, PARAMETER_SYMBOL: symbol, PARAMETER_INTERVAL: interval }) if req.status_code == 200: msg = req.json()[PARAMETER_MSG] f_0 = msg[PARAMETER_F_0] return f_0 else: raise(req.text) except Exception as E: print('ERROR@get_latest_forecast: ', E) traceback.print_exc() return None # get the the historical forecast for symbol and interval (in steps +1, +2, +3...) def get_historical_forecast(self, symbol, interval, history): global PARAMETER_ACTION global ACTION_GET_LATEST_FORECAST global PARAMETER_MSG global PARAMETER_F_0 if history < 1: print('history must be >= 1') return None else: try: req = self.post_json({ PARAMETER_ACTION: ACTION_GET_HISTORICAL_FORECAST, PARAMETER_SYMBOL: symbol, PARAMETER_INTERVAL: interval, PARAMETER_HISTORY: history }) if req.status_code == 200: msg = req.json()[PARAMETER_MSG] f_0 = msg[PARAMETER_F_0] return f_0 else: raise(req.text) except Exception as E: print('ERROR@get_historical_forecast: ', E) traceback.print_exc() return None # get the historical data of a certain asset (only BTCUSD is allowed) def get_historical_data(self, symbol, interval, max_records): global PARAMETER_ACTION global ACTION_GET_LATEST_FORECAST global PARAMETER_MSG global PARAMETER_MAX_RECORDS if symbol != 'BTCUSD': print('only BTCUSD is allowed') return None else: try: req = self.post_json({ PARAMETER_ACTION: ACTION_GET_HISTORICAL_DATA, PARAMETER_SYMBOL: symbol, PARAMETER_INTERVAL: interval, PARAMETER_MAX_RECORDS: max_records }) if req.status_code == 200: msg = req.json()[PARAMETER_MSG] data = msg[PARAMETER_RESULT] return data else: raise(req.text) except Exception as E: print('ERROR@get_historical_data: ', E) traceback.print_exc() return None
// // CreateOrderServiceCell.h // allrichstore // // Created by zhaozhe on 16/11/16. // Copyright © 2016年 allrich88. All rights reserved. // #import "BaseTableViewCell.h" @class CreateOrderServiceModel; @interface CreateOrderServiceCell : BaseTableViewCell /** model */ @property(nonatomic,strong) CreateOrderServiceModel * model; @end
package com.infamous.framework.http.core; import com.infamous.framework.converter.ObjectMapper; import com.infamous.framework.http.HttpMethod; import java.util.Collection; import java.util.Map; import java.util.Optional; public interface HttpRequest<R extends HttpRequest> { R queryParam(String key, Collection<?> list, boolean encoded); default R queryParam(String key, Collection<?> list) { return queryParam(key, list, false); } R queryParam(String key, Object value, boolean encoded); default R queryParam(String key, Object value) { return queryParam(key, value, false); } R pathParam(String key, String value, boolean encoded); default R pathParam(String key, String value) { return pathParam(key, value, false); } R header(String key, String value); R headers(Map<String, String> headerMap); R appendUrl(String url); R useUrl(String url); R withObjectMapper(ObjectMapper objectMapper); String getUrl(); HttpMethod getMethod(); Map<String, String> getHeaders(); default R contentType(String contentType) { return header("Content-Type", contentType); } default Optional<RequestBody> getBody() { return Optional.empty(); } default boolean hasBody() { return getBody().isPresent(); } }
#!/bin/bash # Attaches another terminal to an existing terminal docker exec -i -t gazelle-front-end bash
<reponame>lananh265/social-network<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.alignCenter = void 0; var alignCenter = { "viewBox": "0 0 8 8", "children": [{ "name": "path", "attribs": { "d": "M.09 0c-.06 0-.09.04-.09.09v1.91h2v-1.91c0-.06-.04-.09-.09-.09h-1.81zm6 0c-.05 0-.09.04-.09.09v1.91h2v-1.91c0-.06-.04-.09-.09-.09h-1.81zm-3 1c-.06 0-.09.04-.09.09v.91h2v-.91c0-.05-.04-.09-.09-.09h-1.81zm-3.09 2v1h8v-1h-8zm0 2v1.91c0 .05.04.09.09.09h1.81c.05 0 .09-.04.09-.09v-1.91h-2zm3 0v.91c0 .05.04.09.09.09h1.81c.05 0 .09-.04.09-.09v-.91h-2zm3 0v1.91c0 .05.04.09.09.09h1.81c.05 0 .09-.04.09-.09v-1.91h-2z" } }] }; exports.alignCenter = alignCenter;
#!/bin/bash . "$(dirname $(readlink -f "$0"))/filenames.sh" echo "Filename for app zip file will be: $FILENAME_APP" (cd ./dist && zip -r $FILENAME_APP *) (zip ./dist/$FILENAME_APP Staticfile)
#!/usr/bin/env bash if [ -n "$DEBUG_DRUPALPOD" ]; then set -x fi # Load env vars during prebuild using `gp env` command if [ -n "$GITPOD_HEADLESS" ]; then eval "$(gp env -e | grep DP_GOOGLE_ACCESS_KEY)" eval "$(gp env -e | grep DP_GOOGLE_SECRET)" fi # Establish connection with Google Cloud through Minio client mc config host add gcs https://storage.googleapis.com "$DP_GOOGLE_ACCESS_KEY" "$DP_GOOGLE_SECRET" # Check if ready-made envs file exist if mc find gcs/drupalpod/ready-made-envs.tar.gz; then # Download the ready-made envs file echo "*** Downloading all the environments" mc cp gcs/drupalpod/ready-made-envs.tar.gz /workspace/ready-made-envs.tar.gz # Extact the file echo "*** Extracting the environments (less than 1 minute)" cd /workspace && time tar zxf ready-made-envs.tar.gz --checkpoint=.10000 else # If it's not ready - rebuild environment from scratch cd "$GITPOD_REPO_ROOT" && time .gitpod/drupal/envs-prep/create-environments.sh fi
const isMtrxLike = require('../src/isMtrxLike') const assert = require('assert') describe('isMtrxLike', function() { it('return a bool', function() { let a = [[1, 2, 3], [2, 3, 5]] assert.strictEqual(isMtrxLike(a), true) let b = [[1, 2, 4], [3, 2]] assert.strictEqual(isMtrxLike(b), false) let c = [[undefined, 1, 3], [2, 3, 4]] assert.strictEqual(isMtrxLike(c), false) let d = [['a', 2, 3], [3, 2, 4]] assert.strictEqual(isMtrxLike(d), false) }) })
import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router'; import { UserLoginService } from '../user/user-login/user-login.service'; @Injectable() export class AuthGuard implements CanActivate { constructor( private router: Router, public userLoginService: UserLoginService) { } canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean { //这里可以调用真实的服务进行验证 // this.userLoginService.currentUser // .subscribe( // data => { // }, // error => console.error(error) // ); return true; } }
// // KunAppDelegate.h // CatogaryDemo // // Created by kunkunGit on 10/26/2018. // Copyright (c) 2018 kunkunGit. All rights reserved. // @import UIKit; @interface KunAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
import axios, { AxiosRequestConfig } from "axios"; import { useContext, useEffect, useRef } from "react"; import { useHistory } from "react-router-dom"; import { AuthTokenContext } from "../authorization/AuthTokenProvider"; import { isIDPEnabled, isLoginDisabled } from "../environment"; export const useApiUnauthorized = <T>( requestConfig: Partial<AxiosRequestConfig> = {}, ) => { return (finalRequestConfig: Partial<AxiosRequestConfig> = {}): Promise<T> => fetchJsonUnauthorized({ ...requestConfig, ...finalRequestConfig, }); }; export const useApi = <T>(requestConfig: Partial<AxiosRequestConfig> = {}) => { const history = useHistory(); const { authToken } = useContext(AuthTokenContext); // In order to always have the up to date token, // especially when polling for a long time within nested loops const authTokenRef = useRef<string>(authToken); useEffect( function updateRef() { authTokenRef.current = authToken; }, [authToken], ); return async ( finalRequestConfig: Partial<AxiosRequestConfig> = {}, ): Promise<T> => { try { const response = await fetchJson(authTokenRef.current, { ...requestConfig, ...finalRequestConfig, }); return response; } catch (error) { if ( !isIDPEnabled && !isLoginDisabled && error.status && error.status === 401 ) { history.push("/login"); } throw error; } }; }; export async function fetchJsonUnauthorized( request?: Partial<AxiosRequestConfig>, rawBody: boolean = false, ) { const finalRequest: AxiosRequestConfig = request ? { ...request, data: rawBody ? request.data : JSON.stringify(request.data), headers: { Accept: "application/json", "Content-Type": "application/json", ...request.headers, }, } : { method: "GET", headers: { Accept: "application/json", }, }; try { const response = await axios({ ...finalRequest, validateStatus: () => true, // Don't ever reject the promise for special status codes }); if ( response.status >= 200 && response.status < 300 && // Also handle empty responses (!response.data || (!!response.data && !response.data.error)) ) { return response.data; } else { // Reject other status try { return Promise.reject({ status: response.status, ...response.data }); } catch (e) { return Promise.reject({ status: response.status }); } } } catch (e) { return Promise.reject(e); // Network or connection failure } } function fetchJson(authToken: string, request?: Partial<AxiosRequestConfig>) { const finalRequest = { ...(request || {}), headers: { Authorization: `Bearer ${authToken}`, ...((request && request.headers) || {}), }, }; return fetchJsonUnauthorized(finalRequest); }
<reponame>jieyouxu/Functional-JavaScript-Snippets /** * Given: * - An `options` object * - A nullable `key` * - A `defaultOption` * Returns the associated value of `options[key]`, or if `options[key]` is * falsy or undefined, return the `defaultOption` otherwise. */ const optionOrDefault = (defaultOption, options, key) => { return options[key] || defaultOption; }; export { optionOrDefault };
def check_solution_satisfiability(solution_precs, specs_to_add, specs_to_remove): # Create a set of all package dependencies after adding and removing updated_solution = solution_precs.union(specs_to_add).difference(specs_to_remove) # Check if the updated solution is satisfiable satisfiable = is_satisfiable(updated_solution) if not satisfiable: print("Warning: The resulting solution is not satisfiable") return satisfiable
module.exports = function toReadable(number) { let num = number.toString().split(""); function switcherOne(num) { let phrase = ""; switch (num[0]) { case "0": phrase = "zero"; break; case "1": phrase = "one"; break; case "2": phrase = "two"; break; case "3": phrase = "three"; break; case "4": phrase = "four"; break; case "5": phrase = "five"; break; case "6": phrase = "six"; break; case "7": phrase = "seven"; break; case "8": phrase = "eight"; break; case "9": phrase = "nine"; break; } return phrase; } function switcherTen(num) { let tens = ""; switch (num[0]) { case "1": tens = "ten"; break; case "2": tens = "twenty"; break; case "3": tens = "thirty"; break; case "4": tens = "forty"; break; case "5": tens = "fifty"; break; case "6": tens = "sixty"; break; case "7": tens = "seventy"; break; case "8": tens = "eighty"; break; case "9": tens = "ninety"; break; } if (num[1] != 0 && num[0] >= 2) { return tens + " " + switcherOne(num[1]); } else if (num[1] == 0 && num[0] != 1) { return tens; } else { switch (num[0] + num[1]) { case "11": tens = "eleven"; break; case "12": tens = "twelve"; break; case "13": tens = "thirteen"; break; case "14": tens = "fourteen"; break; case "15": tens = "fifteen"; break; case "16": tens = "sixteen"; break; case "17": tens = "seventeen"; break; case "18": tens = "eighteen"; break; case "19": tens = "nineteen"; break; } return tens; } } if (num.length == 1) { return switcherOne(num); } if (num.length == 2) { return switcherTen(num); } if (num.length == 3) { if (num[1] == 0 && num[2] == 0) { return switcherOne(num[0]) + " hundred"; } else if (num[1] == 0) { return switcherOne(num[0]) + " hundred " + switcherOne(num[2]); } else { return ( switcherOne(num[0]) + " hundred " + switcherTen(num.slice(1)) ); } } };
/** * Copyright 2021 <NAME> and the Contributors - https://github.com/ArnabXD/TGVCBot/graphs/contributors * * 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 */ export interface QueueData { link: string; title: string; image: string; artist: string; duration: string; requestedBy: { id: number; first_name: string; }; mp3_link: string; provider: 'jiosaavn' | 'youtube' | 'telegram'; } class Queues { queues: Map<number, QueueData[]>; constructor() { this.queues = new Map<number, QueueData[]>(); } push(chatId: number, item: QueueData) { let queue = this.queues.get(chatId); if (queue) { return queue.push(item); } else { this.queues.set(chatId, [item]); return 1; } } get(chatId: number) { let queue = this.queues.get(chatId); if (queue) return queue.shift(); } has(chatId: number) { return !!this.queues.get(chatId); } getAll(chatId: number) { return this.queues.get(chatId); } delete(chatId: number, position: number) { let queue = this.queues.get(chatId); if (queue && position <= queue.length) { return queue.splice(position - 1, 1); } } clear(chatId: number) { return this.queues.delete(chatId); } } export const queue = new Queues();
#!/bin/bash # Install jq apt-get update apt-get install -y jq # Install Pip Packages pip install captum torchvision matplotlib pillow pytorch-lightning flask flask-compress ipywidgets minio # Install Yarn npm install npm npm install yarn # Install Jupyter Notebook Widgets jupyter nbextension install --py --symlink --sys-prefix captum.insights.attr_vis.widget # Enable Jupyter Notebook Extensions jupyter nbextension enable --py widgetsnbextension jupyter nbextension enable captum.insights.attr_vis.widget --py --sys-prefix
<filename>node_modules/@nivo/colors/dist/types/schemes/categorical.d.ts export declare const categoricalColorSchemes: { nivo: string[]; category10: readonly string[]; accent: readonly string[]; dark2: readonly string[]; paired: readonly string[]; pastel1: readonly string[]; pastel2: readonly string[]; set1: readonly string[]; set2: readonly string[]; set3: readonly string[]; }; export declare type CategoricalColorSchemeId = keyof typeof categoricalColorSchemes; export declare const categoricalColorSchemeIds: ("nivo" | "category10" | "accent" | "dark2" | "paired" | "pastel1" | "pastel2" | "set1" | "set2" | "set3")[]; //# sourceMappingURL=categorical.d.ts.map
#! /bin/sh # Copyright (C) 2001-2013 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Test for PR 203. # See also automake bug#11030. # # == Original Report for PR/203 == # Some standard targets are missing '-local' hooks. For instance, # installdirs is missing this. Ideally this would be an automatic # feature of any exported target. . test-init.sh echo AC_OUTPUT >> configure.ac cat > Makefile.am << 'END' foodir = $(datadir)/$(distdir) installdirs-local: $(MKDIR_P) $(DESTDIR)$(foodir) install-data-hook: installdirs-local END $ACLOCAL $AUTOMAKE test $(grep -c installdirs-local Makefile.in) -eq 4 cwd=$(pwd) || fatal_ "getting current working directory" $AUTOCONF ./configure --prefix="$cwd/inst" $MAKE installdirs test -d inst/share/$me-1.0 rm -rf inst $MAKE install test -d inst/share/$me-1.0 rm -rf inst ./configure --prefix=/foo $MAKE installdirs DESTDIR="$cwd/dest" test -d dest/foo/share/$me-1.0 rm -rf dest $MAKE install DESTDIR="$cwd/dest" test -d dest/foo/share/$me-1.0 rm -rf dest :
#!/bin/bash # Check if Ubuntu 18.04 or 16.04 if [ "$(lsb_release -r -s)" != "18.04" ] && [ "$(lsb_release -r -s)" != "16.04" ]; then echo "WARNING: This operating system may not be supported by this script." echo "Continue? (y/n)" read PROMPT if [ "$PROMPT" == "n" -o "$PROMPT" == "N" ] then exit fi fi ufw allow https ufw allow http ufw allow ssh ufw allow 3000 ufw allow 10000 while true; do echo "WARNING: If SSH port (22) is incorrect you may lock yourself out." echo "Do you want to enable UFW? (y/n) " read UFW if [ "$UFW" == "y" -o "$UFW" == "Y" ] then ufw enable ufw status break elif [ "$UFW" == "n" -o "$UFW" == "N" ] then ufw disable echo "UFW configured but disabled." echo "Please correct and verify firewall rules before enabling UFW with:" echo " sudo ufw enable" break fi done
<filename>app/core/CoreOfWallet/control/profile.js let facade = require('gamecloud'); /** * 个人中心 * Create by gamegold Fuzhou on 2018-11-27 */ class profile extends facade.Control { /** * 提取VIP福利 * @param {*} user * @param {*} params * * @todo 可以将提取日志写入邮件系统,记录诸如TXID等信息备查 */ async VipDraw(user, params) { let draw_count = params.draw_count; if( draw_count < 10 * 100000) { return {code: -1, msg: 'draw is not enouth'}; } user.baseMgr.info.getData(true); //强制刷新下 let vip_usable_count = user.baseMgr.info.getAttr('vcur'); if(draw_count > vip_usable_count) { return {code: -2, msg: 'draw beyond'}; } //以管理员账户为指定用户转账,这需要管理员账户上余额充足,未来还需要考虑一定的风控机制 let ret = await this.core.service.gamegoldHelper.execute('tx.send', [ user.baseMgr.info.getAttr('acaddr'), draw_count, ]); if(!ret) { return {code: -3, msg: 'txsend fail'}; } else { user.baseMgr.info.subVipCur(draw_count); return {code: 0}; } } } exports = module.exports = profile;
<reponame>ryurock/shizoo /// <reference path="../../node_modules/electron/electron.d.ts" /> const electron = require('electron'); const ipcMain: typeof Electron.ipcMain = electron.ipcMain; const BrowserWindow: typeof Electron.BrowserWindow = electron.BrowserWindow; const app: Electron.App = electron.app; import {OAuthGithub} from './oauth/github'; class MyApplication { mainWindow: Electron.BrowserWindow = null; oAuthGithub: OAuthGithub = null; constructor(public app: Electron.App){ this.app.on('window-all-closed', this.onWindowAllClosed); this.app.on('ready', this.onReady); } onWindowAllClosed(){ if(process.platform != 'darwin'){ this.app.quit(); } } onReady(){ this.mainWindow = new BrowserWindow({ width: 1024, height: 600, minWidth: 500, minHeight: 200, acceptFirstMouse: true }); this.mainWindow.loadURL('file://' + __dirname + '/../../index.html'); this.mainWindow.webContents.openDevTools(); ipcMain.on('asynchronous-message', (event: Electron.Event, arg: string) => { if (arg == "oauth-github") { let oAuthGithub = new OAuthGithub(); oAuthGithub.authorization(event); } }) this.mainWindow.on('closed', () => { this.mainWindow = null; }); } } const myapp = new MyApplication(app);
#!/bin/bash set -e node_modules/.bin/rimraf dist mkdir dist node_modules/.bin/tsc -p . node_modules/.bin/rimraf dist-es6 mkdir dist-es6 node_modules/.bin/tsc -p . -t esnext -m commonjs --outDir dist-es6 node_modules/.bin/rollup dist-es6/browser.js --format cjs --output dist-browser.js node_modules/.bin/rollup dist-es6/node.js --format cjs --output dist-node.js
<gh_stars>0 const banco = require('../helper/conection'); const playerRepository = require('../repository/PlayerRepository'); const { hash } = require('bcryptjs'); class CreateUserService{ async execute({ email,senha,nome,idade,sexo }){ const player = new playerRepository(); await player.playerExist(email); const passwordHash = await hash(senha,8); await player.createPlayer({ email,passwordHash,nome,idade,sexo }); return { email,nome } } } module.exports = CreateUserService;
/* * Copyright 2019 Wultra s.r.o. * * 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 io.getlime.security.powerauth.lib.webflow.authentication.repository.model.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.Objects; /** * Entity which stores configuration of anti-fraud system. * * @author <NAME>, <EMAIL> */ @Entity @Table(name = "wf_afs_config") public class AfsConfigEntity implements Serializable { private static final long serialVersionUID = -3077689235187445743L; @Id @Column(name = "config_id") private String afsConfigId; @Column(name = "js_snippet_url") private String jsSnippetUrl; @Column(name = "parameters") private String parameters; /** * Default constructor. */ public AfsConfigEntity() { } /** * Entity constructor. * @param afsConfigId AFS configuration ID. * @param jsSnippetUrl JavaScript snipped for integration of AFS into Web Flow. * @param parameters Parameters which should be sent together with the AFS request. */ public AfsConfigEntity(String afsConfigId, String jsSnippetUrl, String parameters) { this.afsConfigId = afsConfigId; this.jsSnippetUrl = jsSnippetUrl; this.parameters = parameters; } public String getAfsConfigId() { return afsConfigId; } public void setAfsConfigId(String afsConfigId) { this.afsConfigId = afsConfigId; } public String getJsSnippetUrl() { return jsSnippetUrl; } public void setJsSnippetUrl(String jsSnippetUrl) { this.jsSnippetUrl = jsSnippetUrl; } public String getParameters() { return parameters; } public void setParameters(String parameters) { this.parameters = parameters; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AfsConfigEntity that = (AfsConfigEntity) o; return afsConfigId.equals(that.afsConfigId) && jsSnippetUrl.equals(that.jsSnippetUrl) && Objects.equals(parameters, that.parameters); } @Override public int hashCode() { return Objects.hash(afsConfigId, jsSnippetUrl, parameters); } }
#!/bin/sh # # Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 only, as # published by the Free Software Foundation. # # This code is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # version 2 for more details (a copy is included in the LICENSE file that # accompanied this code). # # You should have received a copy of the GNU General Public License version # 2 along with this work; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. # # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA # or visit www.oracle.com if you need additional information or have any # questions. # # Shell script for generating an IDEA project from a given list of modules usage() { echo "usage: $0 [-h|--help] [-v|--verbose] [-o|--output <path>] [modules]+" exit 1 } SCRIPT_DIR=`dirname $0` #assume TOP is the dir from which the script has been called TOP=`pwd` cd $SCRIPT_DIR; SCRIPT_DIR=`pwd` cd $TOP; IDEA_OUTPUT=$TOP/.idea VERBOSE="false" while [ $# -gt 0 ] do case $1 in -h | --help ) usage ;; -v | --vebose ) VERBOSE="true" ;; -o | --output ) IDEA_OUTPUT=$2 shift ;; -*) # bad option usage ;; * ) # non option break ;; esac shift done mkdir $IDEA_OUTPUT || exit 1 cd $IDEA_OUTPUT; IDEA_OUTPUT=`pwd` MAKE_DIR="$SCRIPT_DIR/../make" IDEA_MAKE="$MAKE_DIR/idea" IDEA_TEMPLATE="$IDEA_MAKE/template" cp -r "$IDEA_TEMPLATE"/* "$IDEA_OUTPUT" #init template variables for file in `ls -p $IDEA_TEMPLATE | grep -v /`; do VAR_SUFFIX=`echo $file | cut -d'.' -f1 | tr [:lower:] [:upper:]` eval "$VAR_SUFFIX"_TEMPLATE="$IDEA_TEMPLATE"/$file eval IDEA_"$VAR_SUFFIX"="$IDEA_OUTPUT"/$file done #override template variables if [ -d "$TEMPLATES_OVERRIDE" ] ; then for file in `ls -p "$TEMPLATES_OVERRIDE" | grep -v /`; do cp "$TEMPLATES_OVERRIDE"/$file "$IDEA_OUTPUT"/ VAR_SUFFIX=`echo $file | cut -d'.' -f1 | tr [:lower:] [:upper:]` eval "$VAR_SUFFIX"_TEMPLATE="$TEMPLATES_OVERRIDE"/$file done fi if [ "$VERBOSE" = "true" ] ; then echo "output dir: $IDEA_OUTPUT" echo "idea template dir: $IDEA_TEMPLATE" fi if [ ! -f "$JDK_TEMPLATE" ] ; then echo "FATAL: cannot find $JDK_TEMPLATE" >&2; exit 1 fi if [ ! -f "$ANT_TEMPLATE" ] ; then echo "FATAL: cannot find $ANT_TEMPLATE" >&2; exit 1 fi cd $TOP ; make -f "$IDEA_MAKE/idea.gmk" -I $MAKE_DIR/.. idea MAKEOVERRIDES= OUT=$IDEA_OUTPUT/env.cfg MODULES="$*" || exit 1 cd $SCRIPT_DIR . $IDEA_OUTPUT/env.cfg # Expect MODULE_ROOTS, MODULE_NAMES, BOOT_JDK & SPEC to be set if [ "x$MODULE_ROOTS" = "x" ] ; then echo "FATAL: MODULE_ROOTS is empty" >&2; exit 1 fi if [ "x$MODULE_NAMES" = "x" ] ; then echo "FATAL: MODULE_NAMES is empty" >&2; exit 1 fi if [ "x$BOOT_JDK" = "x" ] ; then echo "FATAL: BOOT_JDK is empty" >&2; exit 1 fi if [ "x$SPEC" = "x" ] ; then echo "FATAL: SPEC is empty" >&2; exit 1 fi SOURCE_FOLDER=" <sourceFolder url=\"file://\$MODULE_DIR\$/####\" isTestSource=\"false\" />" SOURCE_FOLDERS_DONE="false" addSourceFolder() { root=$@ relativePath="`echo "$root" | sed -e s@"$TOP/\(.*$\)"@"\1"@`" folder="`echo "$SOURCE_FOLDER" | sed -e s@"\(.*/\)####\(.*\)"@"\1$relativePath\2"@`" printf "%s\n" "$folder" >> $IDEA_JDK } ### Generate project iml rm -f $IDEA_JDK while IFS= read -r line do if echo "$line" | egrep "^ .* <sourceFolder.*####" > /dev/null ; then if [ "$SOURCE_FOLDERS_DONE" = "false" ] ; then SOURCE_FOLDERS_DONE="true" for root in $MODULE_ROOTS; do addSourceFolder $root done fi else printf "%s\n" "$line" >> $IDEA_JDK fi done < "$JDK_TEMPLATE" MODULE_NAME=" <property name=\"module.name\" value=\"####\" />" addModuleName() { mn="`echo "$MODULE_NAME" | sed -e s@"\(.*\)####\(.*\)"@"\1$MODULE_NAMES\2"@`" printf "%s\n" "$mn" >> $IDEA_ANT } BUILD_DIR=" <property name=\"build.target.dir\" value=\"####\" />" addBuildDir() { DIR=`dirname $SPEC` mn="`echo "$BUILD_DIR" | sed -e s@"\(.*\)####\(.*\)"@"\1$DIR\2"@`" printf "%s\n" "$mn" >> $IDEA_ANT } ### Generate ant.xml rm -f $IDEA_ANT while IFS= read -r line do if echo "$line" | egrep "^ .* <property name=\"module.name\"" > /dev/null ; then addModuleName elif echo "$line" | egrep "^ .* <property name=\"build.target.dir\"" > /dev/null ; then addBuildDir else printf "%s\n" "$line" >> $IDEA_ANT fi done < "$ANT_TEMPLATE" ### Generate misc.xml rm -f $IDEA_MISC JTREG_HOME=" <path>####</path>" IMAGES_DIR=" <jre alt=\"true\" value=\"####\" />" addImagesDir() { DIR=`dirname $SPEC`/images/jdk mn="`echo "$IMAGES_DIR" | sed -e s@"\(.*\)####\(.*\)"@"\1$DIR\2"@`" printf "%s\n" "$mn" >> $IDEA_MISC } addJtregHome() { DIR=`dirname $SPEC` mn="`echo "$JTREG_HOME" | sed -e s@"\(.*\)####\(.*\)"@"\1$JT_HOME\2"@`" printf "%s\n" "$mn" >> $IDEA_MISC } rm -f $MISC_ANT while IFS= read -r line do if echo "$line" | egrep "^ .*<path>jtreg_home</path>" > /dev/null ; then addJtregHome elif echo "$line" | egrep "^ .*<jre alt=\"true\" value=\"images_jdk\"" > /dev/null ; then addImagesDir else printf "%s\n" "$line" >> $IDEA_MISC fi done < "$MISC_TEMPLATE" ### Compile the custom Logger CLASSES=$IDEA_OUTPUT/classes if [ "x$ANT_HOME" = "x" ] ; then # try some common locations, before giving up if [ -f "/usr/share/ant/lib/ant.jar" ] ; then ANT_HOME="/usr/share/ant" elif [ -f "/usr/local/Cellar/ant/1.9.4/libexec/lib/ant.jar" ] ; then ANT_HOME="/usr/local/Cellar/ant/1.9.4/libexec" else echo "FATAL: cannot find ant. Try setting ANT_HOME." >&2; exit 1 fi fi CP=$ANT_HOME/lib/ant.jar rm -rf $CLASSES; mkdir $CLASSES if [ "x$CYGPATH" = "x" ] ; then ## CYGPATH may be set in env.cfg JAVAC_SOURCE_FILE=$IDEA_OUTPUT/src/idea/JdkIdeaAntLogger.java JAVAC_CLASSES=$CLASSES JAVAC_CP=$CP else JAVAC_SOURCE_FILE=`cygpath -am $IDEA_OUTPUT/src/idea/JdkIdeaAntLogger.java` JAVAC_CLASSES=`cygpath -am $CLASSES` JAVAC_CP=`cygpath -am $CP` fi $BOOT_JDK/bin/javac -d $JAVAC_CLASSES -cp $JAVAC_CP $JAVAC_SOURCE_FILE
let scalarProduct = (2 * 4) + (-1 * 8) + (7 * -3); scalarProduct = -26;
<gh_stars>10-100 import Head from "next/head"; import debounce from "debounce"; import { useEffect } from "react"; import { ObjectId } from "mongodb"; import { GetServerSideProps } from "next"; import { withPageAuthRequired, getSession } from "@auth0/nextjs-auth0"; import { Grid, GridItem } from "@chakra-ui/react"; import PresentationModel from "model/presentation"; import PresentationType from "model/interfaces/presentation"; import { EditorPanel, EditorNavbar, PreviewSpace, SlideNavigator, FullScreenPresentation, } from "components"; import { getDb } from "lib/db/getDb"; import { Slide } from "model/slide"; import { useStore } from "lib/stores/presentation"; import { keyListeners } from "lib/setupKeyListeners"; import { mapUnderscoreIdToId } from "@lib/utils/mapUnderscoreId"; interface EditorPageProps { presentation: PresentationType; pid: string; } export function EditorPage(props: EditorPageProps) { const { presentation } = props; const store = useStore(); const slides = useStore((state) => state.presentation.slides); const currentSlide = slides[store.currentSlideIdx]; const getUpdateCurrentSlideFn = ( field: keyof Slide, shouldDebounce = false ) => { const updateFn = (value: string) => store.updateCurrentSlide(() => ({ [field]: value })); if (shouldDebounce) { return debounce(updateFn, 300); } return updateFn; }; const updateBgColor = getUpdateCurrentSlideFn("bgColor", true); const updateFontColor = getUpdateCurrentSlideFn("fontColor", true); const updateMdContent = getUpdateCurrentSlideFn("mdContent"); const updateFontFamily = getUpdateCurrentSlideFn("fontFamily"); useEffect(() => { store.setPresentation(presentation); const { cleanUp, setUpKeyListener } = keyListeners(); setUpKeyListener(); return cleanUp; }, []); return ( <> <Head> <title>{presentation.title}</title> </Head> {!store.isPresentationMode ? ( <> <EditorNavbar /> <Grid height={"calc(100vh - 70px)"} templateRows="repeat(12, 1fr)" templateColumns="repeat(3, 1fr)" as="main" > <GridItem rowSpan={12} colSpan={1}> <EditorPanel value={currentSlide.mdContent} bgColor={currentSlide.bgColor} setBgColor={updateBgColor} fontColor={currentSlide.fontColor} setFontColor={updateFontColor} setValue={updateMdContent} fontFamily={currentSlide.fontFamily} setFontFamily={updateFontFamily} /> </GridItem> <GridItem rowSpan={11} colSpan={2}> <PreviewSpace fontFamily={currentSlide.fontFamily} bgColor={currentSlide.bgColor} fontColor={currentSlide.fontColor} mdContent={currentSlide.mdContent} /> </GridItem> <GridItem rowSpan={1} colSpan={2}> <SlideNavigator onClickSlide={store.goToSlide} /> </GridItem> </Grid>{" "} </> ) : ( <FullScreenPresentation /> )} </> ); } export const getServerSideProps: GetServerSideProps<{}> = withPageAuthRequired({ async getServerSideProps(ctx) { const { req, res, params } = ctx; const pid = params["pid"]; const { user } = getSession(req, res); const db = await getDb(); const collection = db.getCollection(PresentationModel); const presentation = await collection.findOne<PresentationModel>({ userEmail: user.email, _id: new ObjectId(pid as string), }); if (!presentation) { return { redirect: { destination: "/not-found", permanent: false, }, }; } const { _id, ...payload } = presentation as PresentationModel & { _id: ObjectId; }; const props: EditorPageProps = { presentation: { ...payload, id: _id.toHexString(), slides: payload.slides.map(mapUnderscoreIdToId), }, pid: pid as string, }; return { props, }; }, }); export default EditorPage;
SELECT product_name FROM products ORDER BY product_name DESC;
#!/bin/bash set -e export OMPI_MCA_plm=isolated export OMPI_MCA_btl_vader_single_copy_mechanism=none export OMPI_MCA_rmaps_base_oversubscribe=yes python -c 'import shenfun'
/* * Copyright 2019 <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 io.openvalidation.common.unittesting.astassertion; import io.openvalidation.common.ast.ASTModel; import io.openvalidation.common.ast.operand.ASTOperandStaticNumber; public class StaticNumberAssertion extends StaticAssertion<ASTOperandStaticNumber> { public StaticNumberAssertion(ASTOperandStaticNumber item, ASTModel ast, ASTAssertionBase parent) { super(item, ast, parent); } public StaticNumberAssertion hasValue(Double value) { shouldEquals(model.getNumberValue(), value, "Double Value"); return this; } public ArithmeticOperandAssertion parentArithmeticOperand() { shouldBeInstanceOf(this.parent(), ArithmeticOperandAssertion.class, "ARITHMETIC NUMBER ITEM"); return (ArithmeticOperandAssertion) this.parent(); } // public ArithmeticAssertion parentArithmetic() { // return this.parentArithmeticOperand().parentList(); // } public OperandAssertion parentOperand() { shouldBeInstanceOf(this.parent(), OperandAssertion.class, "PARENT OPERAND"); return (OperandAssertion) this.parent(); } public ConditionAssertion parentCondition() { return parentOperand().parentCondition(); } public RuleAssertion parentRule() { return parentCondition().parentRule(); } }
<filename>demo22.solon_dubbo_provider/src/main/java/webapp/server/HelloServiceImpl.java<gh_stars>1-10 package webapp.server; import org.apache.dubbo.config.annotation.Service; import webapp.protocol.HelloService; @Service(group = "hello") public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { System.out.println("from client :" + name); return "hello, " + name; } @Override public String sayHello2(String name) { return "hello2, " + name; } @Override public String sayHello3(String name) { return "hello3, " + name; } }
<filename>back/routes/error.js<gh_stars>0 const express = require("express"); const router = express.Router(); router.get("/role", (req, res) => { console.log("Error route role"); return res.json({ error: "You need permisions" }); }); module.exports = router;
/* * Copyright (c) 2021 - <NAME> - https://www.yupiik.com * 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 io.yupiik.bundlebee.core.command.impl; import io.yupiik.bundlebee.core.BundleBee; import io.yupiik.bundlebee.core.test.BundleBeeExtension; import io.yupiik.bundlebee.core.test.CommandExecutor; import io.yupiik.bundlebee.core.test.http.SpyingResponseLocator; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.extension.RegisterExtension; import org.talend.sdk.component.junit.http.api.HttpApiHandler; import org.talend.sdk.component.junit.http.api.Request; import org.talend.sdk.component.junit.http.api.Response; import org.talend.sdk.component.junit.http.internal.impl.ResponseImpl; import org.talend.sdk.component.junit.http.junit5.HttpApi; import org.talend.sdk.component.junit.http.junit5.HttpApiInject; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import static java.util.logging.Level.INFO; import static org.junit.jupiter.api.Assertions.assertEquals; @HttpApi(useSsl = true) class DeleteCommandTest { @RegisterExtension BundleBeeExtension extension = new BundleBeeExtension(); @HttpApiInject private HttpApiHandler<?> handler; @Test void deleteMaven(final CommandExecutor executor, final TestInfo info) { { final var spyingResponseLocator = newSpyingHandler(info, false); handler.setResponseLocator(spyingResponseLocator); final var logs = executor.wrap(INFO, () -> new BundleBee() .launch("delete", "--alveolus", "DeleteCommandTest.deleteMaven")); assertEquals("" + "Deleting 'DeleteCommandTest.deleteMaven'\n" + "Deleting 'ApplyCommandTest.apply'\n" + "Deleting 's2' (kind=services) for namespace 'default'\n" + "Deleting 's' (kind=services) for namespace 'default'\n" + "", logs); assertEquals(2, spyingResponseLocator.getFound().size()); } { final var spyingResponseLocator = newSpyingHandler(info, true); handler.setResponseLocator(spyingResponseLocator); final var logs = executor.wrap(INFO, () -> new BundleBee() .launch("delete", "--alveolus", "DeleteCommandTest.deleteMaven")); assertEquals("" + "Deleting 'DeleteCommandTest.deleteMaven'\n" + "Deleting 'ApplyCommandTest.apply'\n" + "Deleting 's2' (kind=services) for namespace 'default'\n" + "Deleting 's' (kind=services) for namespace 'default'\n" + "", logs); assertEquals(2, spyingResponseLocator.getFound().size()); } } private SpyingResponseLocator newSpyingHandler(final TestInfo info, final boolean fail) { return new SpyingResponseLocator( info.getTestClass().orElseThrow().getName() + "_" + info.getTestMethod().orElseThrow().getName()) { @Override protected Optional<Response> doFind(final Request request, final String pref, final ClassLoader loader, final Predicate<String> headerFilter, final boolean exactMatching) { switch (request.method()) { case "CONNECT": return Optional.empty(); case "DELETE": case "GET": if (fail) { return Optional.of(new ResponseImpl(Map.of(), 404, "{}".getBytes(StandardCharsets.UTF_8))); } return Optional.of(new ResponseImpl(Map.of(), 200, "{}".getBytes(StandardCharsets.UTF_8))); default: return Optional.of(new ResponseImpl(Map.of(), 500, "{}".getBytes(StandardCharsets.UTF_8))); } } }; } }
#!/bin/sh cnf_file="${1:-configs/openssl-server.cnf}" openssl req -batch -config "${cnf_file}" -newkey rsa:2048 -sha256 -out csr/servercert.csr -outform PEM
def is_power_of_2(n): if n == 0: return False else: while n % 2 == 0: n = n // 2 return n == 1 print(is_power_of_2(128))
<filename>guacamole-common-js/src/main/webapp/modules/StringReader.js /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var Guacamole = Guacamole || {}; /** * A reader which automatically handles the given input stream, returning * strictly text data. Note that this object will overwrite any installed event * handlers on the given Guacamole.InputStream. * * @constructor * @param {!Guacamole.InputStream} stream * The stream that data will be read from. */ Guacamole.StringReader = function(stream) { /** * Reference to this Guacamole.InputStream. * * @private * @type {!Guacamole.StringReader} */ var guac_reader = this; /** * Parser for received UTF-8 data. * * @type {!Guacamole.UTF8Parser} */ var utf8Parser = new Guacamole.UTF8Parser(); /** * Wrapped Guacamole.ArrayBufferReader. * * @private * @type {!Guacamole.ArrayBufferReader} */ var array_reader = new Guacamole.ArrayBufferReader(stream); // Receive blobs as strings array_reader.ondata = function(buffer) { // Decode UTF-8 var text = utf8Parser.decode(buffer); // Call handler, if present if (guac_reader.ontext) guac_reader.ontext(text); }; // Simply call onend when end received array_reader.onend = function() { if (guac_reader.onend) guac_reader.onend(); }; /** * Fired once for every blob of text data received. * * @event * @param {!string} text * The data packet received. */ this.ontext = null; /** * Fired once this stream is finished and no further data will be written. * @event */ this.onend = null; };
#!/usr/bin/env bash # Preprocess video dataset before training sound event detection model export PYTHONPATH=/root/workspace/drama-graph export PYTHONIOENCODING=utf-8 #evaluate sound event detection model python sound_event_detection/src/evaluate.py
#! /bin/bash ########################################### # ########################################### # constants export JAVA_HOME=/usr/lib/jvm/java-1.8.0-amazon-corretto export PATH=$PATH:$JAVA_HOME/bin baseDir=$(cd `dirname "$0"`;pwd) MVNNAME=maven.tgz # functions # main [ -z "${BASH_SOURCE[0]}" -o "${BASH_SOURCE[0]}" = "$0" ] || return cd /opt && wget -O $MVNNAME https://www-us.apache.org/dist/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz tar xzf $MVNNAME mv apache-maven-* maven rm $MVNNAME export MAVEN_HOME=/opt/maven export PATH=$PATH:$MAVEN_HOME/bin rm -rf $0
. $TESTSUITE/common.sh OUTPUT=$(dub test -b unittest-cov --root=$(dirname "${BASH_SOURCE[0]}") --skip-registry=all --nodeps -q -- --no-colours --verbose 2>&1 || true) echo "$OUTPUT" | grep -cE "✓ verbose 1 \(100[0-9]\.[0-9]{3} ms\)" > /dev/null echo "$OUTPUT" | grep -cE "✓ verbose 2 \(50[0-9]\.[0-9]{3} ms\)" > /dev/null echo "$OUTPUT" | grep -cE "✓ verbose 3 \(25[0-9]\.[0-9]{3} ms\)" > /dev/null echo "$OUTPUT" | grep -c "✗ verbose 4" > /dev/null echo "$OUTPUT" | grep -c "Summary: 3 passed, 1 failed" > /dev/null echo "$OUTPUT" | grep -cv "this UDA should be ignored" > /dev/null echo "$OUTPUT" | grep -c "[verbose/verbose.d:22:1]" > /dev/null echo "$OUTPUT" | grep -c "[verbose/verbose.d:17:1]" > /dev/null echo "$OUTPUT" | grep -c "[verbose/verbose.d:12:1]" > /dev/null echo "$OUTPUT" | grep -c "[verbose/verbose.d:7:1]" > /dev/null echo "$OUTPUT" | grep -c "core\.exception\.AssertError thrown from .*verbose\.d on line 23:"> /dev/null echo "$OUTPUT" | grep -cE "\s+(unittest failure|Assertion failure)" > /dev/null echo "$OUTPUT" | grep -cE "silly.d" > /dev/null rm -r $(dirname "${BASH_SOURCE[0]}")/.dub $(dirname "${BASH_SOURCE[0]}")/verbose-test-unittest
<gh_stars>0 /******************************************************************************* * Copyright 2019 <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. * * Contributors: * <NAME> - Initial contribution and API ******************************************************************************/ package com.sa.security.config; import java.util.Optional; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import org.springframework.security.web.header.writers.StaticHeadersWriter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import com.sa.security.JsonAuthHandler; import com.sa.security.RestAuthenticationEntryPoint; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private RestAuthenticationEntryPoint restAuthenticationEntryPoint; @Autowired private UserDetailsService userDetailsService; @Autowired private JsonAuthHandler jsonAuthsHandler; @Autowired private DataSource dataSource; @Value("${rememberme.key}") private String rememberMeKey; @Bean public DaoAuthenticationProvider authenticationProvider(PasswordEncoder encoder) { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setPasswordEncoder(encoder); daoAuthenticationProvider.setUserDetailsService(userDetailsService); return daoAuthenticationProvider; } private PersistentTokenRepository persistentTokenRepository() { JdbcTokenRepositoryImpl repo = new JdbcTokenRepositoryImpl(); repo.setDataSource(dataSource); return repo; } @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(11); } @Bean public AuditorAware<String> auditorProvider() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); final String user = (auth != null) ? auth.getName() : "system"; return () -> Optional.of(user); } @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() // .addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class) .exceptionHandling() .authenticationEntryPoint(restAuthenticationEntryPoint) .and() .authorizeRequests() .antMatchers("/", "/*").permitAll() .antMatchers("/api/**").authenticated() .and() .formLogin() .loginPage("/api/login") .usernameParameter("username") .passwordParameter("password") .successHandler(jsonAuthsHandler) .failureHandler(jsonAuthsHandler) .permitAll() .and() .logout() .logoutUrl("/api/logout") .logoutSuccessUrl("/") .logoutSuccessHandler(jsonAuthsHandler) .deleteCookies("remember-me", "JSESSIONID") .permitAll() .and() .rememberMe() .userDetailsService(userDetailsService) .tokenRepository(persistentTokenRepository()) .rememberMeCookieName("REMEMBER_ME") .rememberMeParameter("remember_me") .tokenValiditySeconds(1209600) // default 2 weeks. in sec .useSecureCookie(false) .key(rememberMeKey) .and() .headers() // .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin", "http://localhost:3001")) // .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")) // .addHeaderWriter(new StaticHeadersWriter("Access-Control-Max-Age", "3600")) // .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Credentials", "true")) // .addHeaderWriter(new StaticHeadersWriter("Access-Control-Expose-Headers", "X-CSRF-TOKEN,X-CSRF-HEADER,X-CSRF-PARAM,JSESSIONID,REMEMBER_ME")) // .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Headers", "origin, accept, content-type, X-Requested-With, Access-Control-Request-Method, Access-Control-Allow-Credentials, Access-Control-Request-Headers")) // .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Headers", "*")) ; } @Bean CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); return source; } }
<reponame>havocp/hwf // |trace-test| TMFLAGS: full,fragprofile,treevis; valgrind function testRegExpTest() { var r = /abc/; var flag = false; for (var i = 0; i < 10; ++i) flag = r.test("abc"); return flag; } assertEq(testRegExpTest(), true);
<gh_stars>1-10 import React, { useState } from 'react' import { useRouter } from 'next/router' import { Modal, Button, Row, Col, Alert } from 'react-bootstrap' import PropTypes from 'prop-types' import SearchUsers from '../../common/SearchUsers' import MiniLoader from '../../common/MiniLoader' import baseUrl from '../../../shared/baseUrl' function InviteMemberModal (props) { const { showModal, toggleModal, groupId, memberUsernames, moderatorUsernames, user } = props const router = useRouter() const { access_token: accessToken } = user const [invitedMembers, setInvitedMembers] = useState([]) const [error, setError] = useState('') const [isLoading, setIsLoading] = useState(false) const alreadyMembers = [...memberUsernames, ...moderatorUsernames] const addMembers = () => { if (!invitedMembers.length) { return setError('Please select the users to be added') } setIsLoading(true) setError('') const reqHeaders = new Headers() reqHeaders.append('access_token', accessToken) reqHeaders.append('Content-Type', 'application/json') const body = { members: invitedMembers } const requestOptions = { method: 'POST', headers: reqHeaders, body: JSON.stringify(body) } fetch(`${baseUrl}/groups/${groupId}/members`, requestOptions) .then((res) => res.json()) .then((res) => { const { success, error, results } = res if (success) { const { invalidUsernames } = results if (invalidUsernames && invalidUsernames.length) { setError( `Following usernames couldn't be added : ${invalidUsernames.join( ', ' )}` ) } router.reload() } else { setError(error.sqlMessage || error) } setIsLoading(false) }) .catch((error) => { setError(error.message) setIsLoading(false) }) } return <Modal size={'lg'} show={showModal} onHide={toggleModal}> <Modal.Body> <h5>Add members to group </h5> <div className="container"> <Row> <Col> <SearchUsers selectedUsers={invitedMembers} setSelectedUsers={setInvitedMembers} user={user} limit={5} alreadySelected={alreadyMembers} /> </Col> </Row> {error && <Alert variant="danger">{error}</Alert>} </div> </Modal.Body> <Modal.Footer> <Button variant={'danger'} onClick={toggleModal}> Cancel </Button> <Button variant={'success'} onClick={addMembers} disabled={isLoading}> Add members&nbsp; {isLoading && <MiniLoader />} </Button> </Modal.Footer> </Modal> } InviteMemberModal.propTypes = { toggleModal: PropTypes.func.isRequired, showModal: PropTypes.bool, groupId: PropTypes.number.isRequired, user: PropTypes.shape({ username: PropTypes.string, access_token: PropTypes.string, isAdmin: PropTypes.number }), memberUsernames: PropTypes.arrayOf(PropTypes.string), moderatorUsernames: PropTypes.arrayOf(PropTypes.string) } export default InviteMemberModal
<reponame>rsuite/rsuite-icons // Generated by script, don't edit it please. import createSvgIcon from '../../createSvgIcon'; import ExclamationTriangleSvg from '@rsuite/icon-font/lib/legacy/ExclamationTriangle'; const ExclamationTriangle = createSvgIcon({ as: ExclamationTriangleSvg, ariaLabel: 'exclamation triangle', category: 'legacy', displayName: 'ExclamationTriangle' }); export default ExclamationTriangle;
<gh_stars>1000+ /* Copyright (c) 2020-2021 Intel Corporation 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. */ #if __INTEL_COMPILER && _MSC_VER #pragma warning(disable : 2586) // decorated name length exceeded, name was truncated #endif #define CONFORMANCE_INPUT_NODE #include "conformance_flowgraph.h" //! \file conformance_input_node.cpp //! \brief Test for [flow_graph.input_node] specification using output_msg = conformance::message<true, true, true>; #if __TBB_CPP17_DEDUCTION_GUIDES_PRESENT int input_body_f(tbb::flow_control&) { return 42; } void test_deduction_guides() { using namespace tbb::flow; graph g; auto lambda = [](tbb::flow_control&) { return 42; }; auto non_const_lambda = [](tbb::flow_control&) mutable { return 42; }; // Tests for input_node(graph&, Body) input_node s1(g, lambda); static_assert(std::is_same_v<decltype(s1), input_node<int>>); input_node s2(g, non_const_lambda); static_assert(std::is_same_v<decltype(s2), input_node<int>>); input_node s3(g, input_body_f); static_assert(std::is_same_v<decltype(s3), input_node<int>>); input_node s4(s3); static_assert(std::is_same_v<decltype(s4), input_node<int>>); #if __TBB_PREVIEW_FLOW_GRAPH_NODE_SET broadcast_node<int> bc(g); // Tests for input_node(const node_set<Args...>&, Body) input_node s5(precedes(bc), lambda); static_assert(std::is_same_v<decltype(s5), input_node<int>>); input_node s6(precedes(bc), non_const_lambda); static_assert(std::is_same_v<decltype(s6), input_node<int>>); input_node s7(precedes(bc), input_body_f); static_assert(std::is_same_v<decltype(s7), input_node<int>>); #endif g.wait_for_all(); } #endif // __TBB_CPP17_DEDUCTION_GUIDES_PRESENT template<typename O> void test_inheritance(){ using namespace oneapi::tbb::flow; CHECK_MESSAGE((std::is_base_of<graph_node, input_node<O>>::value), "input_node should be derived from graph_node"); CHECK_MESSAGE((std::is_base_of<sender<O>, input_node<O>>::value), "input_node should be derived from sender<Output>"); CHECK_MESSAGE((!std::is_base_of<receiver<O>, input_node<O>>::value), "input_node cannot have predecessors"); } //! Test the body object passed to a node is copied //! \brief \ref interface TEST_CASE("input_node and body copying"){ conformance::test_copy_body_function<oneapi::tbb::flow::input_node<int>, conformance::copy_counting_object<int>>(); } //! The node that is constructed has a reference to the same graph object as src, //! has a copy of the initial body used by src. //! The successors of src are not copied. //! \brief \ref requirement TEST_CASE("input_node copy constructor"){ using namespace oneapi::tbb::flow; graph g; conformance::copy_counting_object<output_msg> fun2; input_node<output_msg> node1(g, fun2); conformance::test_push_receiver<output_msg> node2(g); conformance::test_push_receiver<output_msg> node3(g); oneapi::tbb::flow::make_edge(node1, node2); input_node<output_msg> node_copy(node1); conformance::copy_counting_object<output_msg> b2 = copy_body<conformance::copy_counting_object<output_msg>, input_node<output_msg>>(node_copy); CHECK_MESSAGE((fun2.copy_count + 1 < b2.copy_count), "constructor should copy bodies"); oneapi::tbb::flow::make_edge(node_copy, node3); node_copy.activate(); g.wait_for_all(); CHECK_MESSAGE((conformance::get_values(node2).size() == 0 && conformance::get_values(node3).size() == 1), "Copied node doesn`t copy successor"); node1.activate(); g.wait_for_all(); CHECK_MESSAGE((conformance::get_values(node2).size() == 1 && conformance::get_values(node3).size() == 0), "Copied node doesn`t copy successor"); } //! Test inheritance relations //! \brief \ref interface TEST_CASE("input_node superclasses"){ test_inheritance<int>(); test_inheritance<void*>(); test_inheritance<output_msg>(); } //! Test input_node forwarding //! \brief \ref requirement TEST_CASE("input_node forwarding"){ conformance::counting_functor<output_msg> fun(conformance::expected); conformance::test_forwarding<oneapi::tbb::flow::input_node<output_msg>, void, output_msg>(5, fun); } //! Test input_node buffering //! \brief \ref requirement TEST_CASE("input_node buffering"){ conformance::dummy_functor<int> fun; conformance::test_buffering<oneapi::tbb::flow::input_node<int>, int>(fun); } //! Test calling input_node body //! \brief \ref interface \ref requirement TEST_CASE("input_node body") { oneapi::tbb::flow::graph g; constexpr std::size_t counting_threshold = 10; conformance::counting_functor<output_msg> fun(counting_threshold); oneapi::tbb::flow::input_node<output_msg> node1(g, fun); conformance::test_push_receiver<output_msg> node2(g); oneapi::tbb::flow::make_edge(node1, node2); node1.activate(); g.wait_for_all(); CHECK_MESSAGE((conformance::get_values(node2).size() == counting_threshold), "Descendant of the node needs to be receive N messages"); CHECK_MESSAGE((fun.execute_count == counting_threshold + 1), "Body of the node needs to be executed N + 1 times"); } //! Test deduction guides //! \brief \ref interface \ref requirement TEST_CASE("Deduction guides"){ #if __TBB_CPP17_DEDUCTION_GUIDES_PRESENT test_deduction_guides(); #endif } //! Test that measured concurrency respects set limits //! \brief \ref requirement TEST_CASE("concurrency follows set limits"){ oneapi::tbb::global_control c(oneapi::tbb::global_control::max_allowed_parallelism, oneapi::tbb::this_task_arena::max_concurrency()); utils::ConcurrencyTracker::Reset(); oneapi::tbb::flow::graph g; conformance::concurrency_peak_checker_body counter(1); oneapi::tbb::flow::input_node<int> testing_node(g, counter); conformance::test_push_receiver<int> sink(g); make_edge(testing_node, sink); testing_node.activate(); g.wait_for_all(); } //! Test node Output class meet the CopyConstructible requirements. //! \brief \ref interface \ref requirement TEST_CASE("Test input_node Output class") { conformance::test_output_class<oneapi::tbb::flow::input_node<conformance::copy_counting_object<int>>>(); } struct input_node_counter{ static int count; int N; input_node_counter(int n) : N(n){}; int operator()( oneapi::tbb::flow_control & fc ) { ++count; if(count > N){ fc.stop(); return N; } return N; } }; struct function_node_counter{ static int count; int operator()( int ) { ++count; utils::doDummyWork(1000000); CHECK_MESSAGE((input_node_counter::count <= function_node_counter::count + 1), "input_node `try_get()' call testing: a call to body is made only when the internal buffer is empty"); return 1; } }; int input_node_counter::count = 0; int function_node_counter::count = 0; //! Test input_node `try_get()' call testing: a call to body is made only when the internal buffer is empty. //! \brief \ref requirement TEST_CASE("input_node `try_get()' call testing: a call to body is made only when the internal buffer is empty.") { oneapi::tbb::global_control control(oneapi::tbb::global_control::max_allowed_parallelism, 1); oneapi::tbb::flow::graph g; input_node_counter fun1(500); function_node_counter fun2; oneapi::tbb::flow::function_node <int, int, oneapi::tbb::flow::rejecting> fnode(g, oneapi::tbb::flow::serial, fun2); oneapi::tbb::flow::input_node<int> testing_node(g, fun1); make_edge(testing_node, fnode); testing_node.activate(); g.wait_for_all(); }
<filename>elog/elog.go // Copyright 2018 Cobaro Pty Ltd. All Rights Reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAx1MAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package elog import ( "fmt" "io" "os" "time" ) const ( LogLevelEmerg = iota LogLevelError LogLevelWarning LogLevelInfo1 LogLevelInfo2 LogLevelDebug1 LogLevelDebug2 LogLevelDebug3 ) const ( LogDateLocaltime = iota LogDateUTC LogDateEpochSecond LogDateEpochMilli LogDateEpochMicro LogDateEpochNano LogDateNone ) type Elog struct { writer io.Writer level int dateFormat int logger func(io.Writer, string, ...interface{}) (int, error) } // Set the logfile to an open file // By defult we use stderr, set to io.Discard to disable func (log *Elog) SetLogFile(w io.Writer) { log.writer = w } // Get the current logfile func (log *Elog) LogFile() (w io.Writer) { return log.writer } // Set the log level func (log *Elog) SetLogLevel(level int) { log.level = level } // Get the log level func (log *Elog) LogLevel() (level int) { return log.level } // Set the log format func (log *Elog) SetLogDateFormat(format int) { log.dateFormat = format } // Get the log format func (log *Elog) LogDateFormat() (format int) { return log.dateFormat } // Set the log function // If set, then we will call this function instead of our internal // function. This allows for unification of application and client library // logging. func (log *Elog) SetLogFunc(logger func(io.Writer, string, ...interface{}) (int, error)) { log.logger = logger } // Get the current log function (which may be used) func (log *Elog) LogFunc() func(io.Writer, string, ...interface{}) (int, error) { return log.logger } // Actually Log func (log *Elog) Logf(level int, format string, a ...interface{}) (int, error) { if level > log.level { return 0, nil } if log.writer == nil { log.writer = os.Stderr } if log.logger == nil { log.logger = fmt.Fprintf } var t = time.Now() var stime string = "" var msg string = fmt.Sprintf(format, a...) switch log.dateFormat { case LogDateLocaltime: stime = t.Format(time.UnixDate) case LogDateUTC: stime = t.UTC().Format(time.UnixDate) case LogDateEpochSecond: stime = fmt.Sprintf("%d", t.Unix()) case LogDateEpochMilli: seconds := t.Unix() millis := (t.UnixNano() - seconds*1000*1000*1000) / (1000 * 1000) stime = fmt.Sprintf("%d.%d", seconds, millis) case LogDateEpochMicro: seconds := t.Unix() micros := (t.UnixNano() - seconds*1000*1000*1000) / 1000 stime = fmt.Sprintf("%d.%d", seconds, micros) case LogDateEpochNano: seconds := t.Unix() nanos := t.UnixNano() - seconds*1000*1000*1000 stime = fmt.Sprintf("%d.%d", seconds, nanos) case LogDateNone: return log.logger(log.writer, "%s\n", msg) } return log.logger(log.writer, "%s %s\n", stime, msg) }
require('./check-versions')(); const config = require('./config'); const path = require('path'); const express = require('express'); const webpack = require('webpack'); const webpackConfig = require('./webpack.dev.conf'); // default port where dev server listens for incoming traffic const { port } = config.dev; const app = express(); const compiler = webpack(webpackConfig); const devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, quiet: false, }); const hotMiddleware = require('webpack-hot-middleware')(compiler, { log: false, heartbeat: 2000, }); // force page reload when html-webpack-plugin template changes compiler.plugin('compilation', (compilation) => { compilation.plugin('html-webpack-plugin-after-emit', (data, cb) => { hotMiddleware.publish({ action: 'reload' }); cb(); }); }); // handle fallback for HTML5 history API app.use(require('connect-history-api-fallback')()); // serve webpack bundle output app.use(devMiddleware); // enable hot-reload and state-preserving // compilation error display app.use(hotMiddleware); // serve pure static assets const staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory); app.use(staticPath, express.static(path.resolve('./app/static'))); const uri = `http://localhost:${port}`; let resolveProm; const readyPromise = new Promise((resolve) => { resolveProm = resolve; }); console.log('> Starting dev server...'); devMiddleware.waitUntilValid(() => { console.log(`> Listening at ${uri}\n`); // when env resolveProm(); }); const server = app.listen(port); module.exports = { ready: readyPromise, close: () => { server.close(); }, };
// Copyright (c) 2015-2016, ETH Zurich, <NAME>, Zurich Eye // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the ETH Zurich, Wyss Zurich, Zurich Eye nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL ETH Zurich, Wyss Zurich, Zurich Eye BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <memory> #include <algorithm> #include <ze/common/types.hpp> #include <ze/common/macros.hpp> #include <imp/core/image.hpp> #include <imp/core/memory_storage.hpp> namespace ze { /** * @brief The ImageRaw class is an image (surprise) holding raw memory * * The ImageRaw memory can be used to allocate raw memory of a given size, or * take external memory and hold a reference to that. Note that when external * memory is given to the class, the memory won't be managed! You have to take * care about the memory deletion. Instead when you let the class itself allocate * the memory it will take care of freeing the memory again. In addition the allocation * takes care about memory address alignment (default: 32-byte) for the beginning of * every row. * * The template parameters are as follows: * - Pixel: The pixel's memory representation (e.g. imp::Pixel8uC1 for single-channel unsigned 8-bit images) * - pixel_type: The internal enum for specifying the pixel's type more specificly */ template<typename Pixel> class ImageRaw : public ze::Image<Pixel> { public: ZE_POINTER_TYPEDEFS(ImageRaw); using Base = Image<Pixel>; using Memory = ze::MemoryStorage<Pixel>; using Deallocator = ze::MemoryDeallocator<Pixel>; public: ImageRaw() = default; virtual ~ImageRaw() = default; /** * @brief ImageRaw construcs an image of given \a size */ ImageRaw(const ze::Size2u& size, PixelOrder pixel_order = ze::PixelOrder::undefined); /** * @brief ImageRaw construcs an image of given size \a width x \a height */ ImageRaw(uint32_t width, uint32_t height, PixelOrder pixel_order = ze::PixelOrder::undefined) : ImageRaw({width, height}, pixel_order) { } /** * @brief ImageRaw copy constructs an image from the given image \a from */ ImageRaw(const ImageRaw& from); /** * @brief ImageRaw copy constructs an arbitrary base image \a from (not necessarily am \a ImageRaw) */ ImageRaw(const Base& from); /** * @brief ImageRaw constructs an image with the given data (copied or refererenced!) * @param data Pointer to the image data. * @param width Image width. * @param height Image height. * @param pitch Length of a row in bytes (including padding). * @param use_ext_data_pointer Flag controlling whether the image should be copied (false) or if the data is just referenced (true) */ ImageRaw(Pixel* data, uint32_t width, uint32_t height, uint32_t pitch, bool use_ext_data_pointer = false, PixelOrder pixel_order = ze::PixelOrder::undefined); /** * @brief ImageRaw constructs an image with the given data shared with the given tracked object * @param data Pointer to the image data. * @param width Image width. * @param height Image height. * @param pitch Length of a row in bytes (including padding). * @param tracked Tracked object that shares the given image data * @note we assume that the tracked object takes care about memory deallocations */ ImageRaw(Pixel* data, uint32_t width, uint32_t height, uint32_t pitch, const std::shared_ptr<void const>& tracked, PixelOrder pixel_order = ze::PixelOrder::undefined); /** Returns a pointer to the pixel data. * The pointer can be offset to position \a (ox/oy). * @param[in] ox Horizontal/Column offset of the pointer array. * @param[in] oy Vertical/Row offset of the pointer array. * @return Pointer to the pixel array. */ virtual Pixel* data(uint32_t ox = 0, uint32_t oy = 0) override; virtual const Pixel* data(uint32_t ox = 0, uint32_t oy = 0) const override; protected: std::unique_ptr<Pixel, Deallocator> data_; //!< the actual image data std::shared_ptr<void const> tracked_ = nullptr; //!< tracked object to share memory }; //----------------------------------------------------------------------------- // convenience typedefs // (sync with explicit template class instantiations at the end of the cpp file) typedef ImageRaw<ze::Pixel8uC1> ImageRaw8uC1; typedef ImageRaw<ze::Pixel8uC2> ImageRaw8uC2; typedef ImageRaw<ze::Pixel8uC3> ImageRaw8uC3; typedef ImageRaw<ze::Pixel8uC4> ImageRaw8uC4; typedef ImageRaw<ze::Pixel16sC1> ImageRaw16sC1; typedef ImageRaw<ze::Pixel16sC2> ImageRaw16sC2; typedef ImageRaw<ze::Pixel16sC3> ImageRaw16sC3; typedef ImageRaw<ze::Pixel16sC4> ImageRaw16sC4; typedef ImageRaw<ze::Pixel16uC1> ImageRaw16uC1; typedef ImageRaw<ze::Pixel16uC2> ImageRaw16uC2; typedef ImageRaw<ze::Pixel16uC3> ImageRaw16uC3; typedef ImageRaw<ze::Pixel16uC4> ImageRaw16uC4; typedef ImageRaw<ze::Pixel32sC1> ImageRaw32sC1; typedef ImageRaw<ze::Pixel32sC2> ImageRaw32sC2; typedef ImageRaw<ze::Pixel32sC3> ImageRaw32sC3; typedef ImageRaw<ze::Pixel32sC4> ImageRaw32sC4; typedef ImageRaw<ze::Pixel32fC1> ImageRaw32fC1; typedef ImageRaw<ze::Pixel32fC2> ImageRaw32fC2; typedef ImageRaw<ze::Pixel32fC3> ImageRaw32fC3; typedef ImageRaw<ze::Pixel32fC4> ImageRaw32fC4; // shared pointers template <typename Pixel> using ImageRawPtr = typename ImageRaw<Pixel>::Ptr; template <typename Pixel> using ImageRawConstPtr = typename ImageRaw<Pixel>::ConstPtr; } // namespace ze
#!/bin/bash #SBATCH --exclude=hermes[1-4],trillian[1-3],artemis[1-7],qdata[1-8],nibbler[1-4],slurm[1-5] #SBATCH --output=granger/80_nodes/script_23_72_75.out #SBATCH --error=granger/80_nodes/script_23_72_75.err #SBATCH --job-name="72-75" hostname date +%s%N time blender -t 1 -b Star-collapse-ntsc.blend -s 72 -e 75 -a &> /dev/null date +%s%N
package com.tchocolat.kaanyagci.chocolat.Activities; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.tchocolat.kaanyagci.chocolat.R; import com.tchocolat.kaanyagci.chocolat.Structures.AddNoeud; import com.tchocolat.kaanyagci.chocolat.Structures.DivNoeud; import com.tchocolat.kaanyagci.chocolat.Structures.EqNoeud; import com.tchocolat.kaanyagci.chocolat.Structures.Feuille; import com.tchocolat.kaanyagci.chocolat.Structures.Noeud; import com.tchocolat.kaanyagci.chocolat.Structures.NoeudBinaire; import com.tchocolat.kaanyagci.chocolat.Structures.NoeudUnaire; import com.tchocolat.kaanyagci.chocolat.Structures.SubsNoeud; public class Main extends Activity { private static Noeud res; private boolean start,first; private TextView ecran,clear_button,point_button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); res = null; getActionBar().hide(); start=true; first=true; setContentView(R.layout.activity_main); ecran = ((TextView)findViewById(R.id.ecran)); clear_button = ((TextView)findViewById(R.id.clean_button)); point_button = ((TextView)findViewById(R.id.point_button)); } private boolean checkZero() { return ecran.getText().toString().equals("0"); } private double getEcran() { return Double.parseDouble(ecran.getText().toString()); } private int getButtonValue(View v) { return Integer.parseInt(((TextView) v).getText().toString()); } //Private functions public void showNumber (View v) { if (res != null) { clear_button.setText("AC"); } if (first) { //Si l'écran est 0 ecran.setText("" + getButtonValue(v)); if (res == null) { //Si ce n'est pas le 1er chiffre clear_button.setText("C"); } } else { ecran.setText(""+ecran.getText().toString()+getButtonValue(v)); } first=false; } public void showPoint(View v) { ecran.setText(ecran.getText().toString()+"."); first=false; point_button.setClickable(false); } public void addition(View v) { if (res == null) { //Si il n'y a pas de noeud d'avant ça //On stocke le numéro affiche sur l'écran dans une feuille res = new Feuille(getEcran()); //On crée un noeud d'addition AddNoeud an = new AddNoeud(); //On met la feuille à noeud gauche an.setNg(res); //On change le res avec le noeud d'addition res = an; } else { //Si il y a déjà un noeud if (res.hasPlace()) { //Si il y a encore la place dans res //On met la feuille de l'écran dans res if (res instanceof NoeudBinaire) { ((NoeudBinaire)res).setNd(new Feuille(getEcran())); } else { ((NoeudUnaire)res).setFils(new Feuille(getEcran())); } //On le calcul double resultat = res.calcul(); //On met ce numéro sur l'écran ecran.setText(""+resultat); //On crée un nouveau noeud d'addition AddNoeud an = new AddNoeud(); //On met le res comme son noeud gauche an.setNg(new Feuille(resultat)); //On change le res avec ce noeud d'addition res = an; } } first = true; } public void division(View v) { if (res == null) { //Si il n'y a pas de noeud d'avant ça //On stocke le numéro affiche sur l'écran dans une feuille res = new Feuille(getEcran()); //On crée un noeud d'addition DivNoeud an = new DivNoeud(); //On met la feuille à noeud gauche an.setNg(res); //On change le res avec le noeud d'addition res = an; } else { //Si il y a déjà un noeud if (res.hasPlace()) { //Si il y a encore la place dans res //On met la feuille de l'écran dans res if (res instanceof NoeudBinaire) { ((NoeudBinaire)res).setNd(new Feuille(getEcran())); } else { ((NoeudUnaire)res).setFils(new Feuille(getEcran())); } //On le calcul double resultat = res.calcul(); //On met ce numéro sur l'écran ecran.setText(""+resultat); //On crée un nouveau noeud d'addition DivNoeud an = new DivNoeud(); //On met le res comme son noeud gauche an.setNg(new Feuille(resultat)); //On change le res avec ce noeud d'addition res = an; } } first = true; } public void minus(View v) { if (res == null) { //Si il n'y a pas de noeud d'avant ça //On stocke le numéro affiche sur l'écran dans une feuille res = new Feuille(getEcran()); //On crée un noeud d'addition SubsNoeud an = new SubsNoeud(); //On met la feuille à noeud gauche an.setNg(res); //On change le res avec le noeud d'addition res = an; } else { //Si il y a déjà un noeud if (res.hasPlace()) { //Si il y a encore la place dans res //On met la feuille de l'écran dans res if (res instanceof NoeudBinaire) { ((NoeudBinaire)res).setNd(new Feuille(getEcran())); } else { ((NoeudUnaire)res).setFils(new Feuille(getEcran())); } //On le calcul double resultat = res.calcul(); //On met ce numéro sur l'écran ecran.setText(""+resultat); //On crée un nouveau noeud d'addition SubsNoeud an = new SubsNoeud(); //On met le res comme son noeud gauche an.setNg(new Feuille(resultat)); //On change le res avec ce noeud d'addition res = an; } } first = true; } public void equals(View v) { if (res == null) { //Si il n'y a pas de noeud d'avant ça //On stocke le numéro affiche sur l'écran dans une feuille res = new Feuille(getEcran()); //On crée un noeud d'addition EqNoeud an = new EqNoeud(); //On met la feuille à noeud gauche an.setFils(res); //On change le res avec le noeud d'addition res = an; } else { //Si il y a déjà un noeud if (res.hasPlace()) { //Si il y a encore la place dans res //On met la feuille de l'écran dans res if (res instanceof NoeudBinaire) { ((NoeudBinaire)res).setNd(new Feuille(getEcran())); } else { ((NoeudUnaire)res).setFils(new Feuille(getEcran())); } //On le calcul double resultat = res.calcul(); //On met ce numéro sur l'écran ecran.setText(""+resultat); //On crée un nouveau noeud d'addition EqNoeud an = new EqNoeud() ; //On met le res comme son noeud gauche an.setFils(new Feuille(resultat)); //On change le res avec ce noeud d'addition res = an; } } first = true; } public void clear(View v) { if (((TextView)v).getText().toString().equals("C")) { ecran.setText("0"); } else { res = null; first = true; clear_button.setText("C"); } } }
#!/usr/bin/env bash set -Eeuxo pipefail here="$(dirname "${BASH_SOURCE[0]}")" client_dir="$(git -C "$here" rev-parse --show-toplevel)" source_commit="$(git -C "$here" log -1 --pretty=format:%h)" tag="$(echo "$1" | tr "+" "-")" # Clear the directory used for temporary, just in case a previous build failed rm -r "$client_dir/.docker" || true mkdir -p "$client_dir/.docker" code_signing_fingerprint="$("$here/../fingerprint.sh")" gpg_tempfile="$client_dir/.docker/code_signing_key" gpg --export-secret-key --armor "$code_signing_fingerprint" > "$gpg_tempfile" # Don't store any secrets in the repo dir trap "rm -r ""$client_dir/.docker"" || true" ERR # Load up all the config we need now, the rest will be resolved as needed config_file="$client_dir/packaging/linux/docker/config.json" image_name="$(jq -r '.image_name' "$config_file")" readarray -t variants <<< "$(jq -r '.variants | keys | .[]' "$config_file")" # We assume that the JSON file is correctly ordered for variant in "${variants[@]}"; do base_variant="$(jq -r ".variants.\"$variant\".base" "$config_file")" dockerfile="$(jq -r ".variants.\"$variant\".dockerfile" "$config_file")" if [ "$base_variant" = "null" ]; then docker build \ --pull \ --build-arg SOURCE_COMMIT="$source_commit" \ --build-arg SIGNING_FINGERPRINT="$code_signing_fingerprint" \ -f "$client_dir/$dockerfile" \ -t "$image_name:$tag$variant" \ "$client_dir" else docker build \ --build-arg BASE_IMAGE="$image_name:$tag$base_variant" \ -f "$client_dir/$dockerfile" \ -t "$image_name:$tag$variant" \ "$client_dir" fi done
def permutation(elements): if len(elements) == 1: yield elements else: for perm in permutation(elements[1:]): for i in range(len(elements)): yield perm[:i] + elements[0:1] + perm[i:] permutation = list(permutation([1,2,3])) for p in permutation: print(p)
<gh_stars>0 import ReactModal from "react-modal"; import React from "react"; import { Form, Button } from 'react-bootstrap' import "../../../assests/sass/editVolunteerProfile.scss"; // import { Form, Button } from "react-bootstrap"; class ConsumerSignOffModal extends React.Component { constructor (props) { super(props); this.state = { id: this.props.allPostsByUser.id, newUser: '', agreedUponPrice:'' }; this.producerSignOff=this.producerSignOff.bind(this); } producerSignOff(){ this.props.memberdashboardactions.updatePostOnAgreedPrice(this.props.session.id,this.props.allPostsByUser.id, this.props.allPostsByUser.offerPrice,'CONSUMER_SIGNOFF'); this.props.handleCloseModal(); } render () { const customStyles = { content : { top : '5%', left : '20%', right : '20%', bottom : 'auto', height: 'auto', overlfow: 'scroll' } }; return ( <ReactModal isOpen={this.props.allPostsByUser && (this.props.allPostsByUser.status === 'ACCEPTED' || this.props.allPostsByUser.status === 'PENDING_CONSUMER_SIGNOFF') ? this.props.showModal : false} contentLabel="Minimal Modal Example" style={customStyles} > <h4 id="contained-modal-title" className="modal-title">Details :</h4> {(this.props.allPostsByUser.status === 'PENDING_CONSUMER_SIGNOFF') && <div> <label className="control-label signOffLabel">Post Status :</label> <div> <p>Signed-Off By Requester, Please Sign-Off From Your End.</p> <label className="control-label signOffLabel">Amount Agreed:{ this.props.allPostsByUser.offerPrice}</label> </div> <button className="btn btn-defa ult signOffButton" type="button" onClick={this.producerSignOff}>Sign off</button> </div> } {(this.props.allPostsByUser.status === 'ACCEPTED') && <div> <label className="control-label signOffLabel">Post Status :</label> <div>Payment Pending</div> <label className="control-label signOffLabel">Amount Agreed: { this.props.allPostsByUser.offerPrice}</label> </div> } <button className="btn btn-default goodsAndServicesButton" onClick={this.props.handleCloseModal}>Close </button> </ReactModal> ); } } export default ConsumerSignOffModal ;
<gh_stars>10-100 package testsubjects; import testannotations.KindaInject; import testinterfaces.ValueGetter; public class ProtectedFieldCollaborator { @KindaInject ProtectedField delegate; public String getProtectedValue() { return delegate.protectedValue; } public void setProtectedValue(String newValue) { delegate.protectedValue = newValue; } public ValueGetter getValueGetter() { return new ValueGetter() { @Override public String getValue() { return delegate.protectedValue; } }; } }
import React, { Component } from 'react' import { Alert, Nav, NavItem, NavLink, TabContent, TabPane } from 'reactstrap' import { translations } from '../../utils/_translations' import PaymentModel from '../../models/PaymentModel' import Refund from '../edit/Refund' import BottomNavigationButtons from '../../common/BottomNavigationButtons' import GatewayModel from '../../models/GatewayModel' import Overview from './Overview' export default class Payment extends Component { constructor (props) { super(props) this.state = { entity: this.props.entity, activeTab: '1', show_success: false, gateways: [] } this.gatewayModel = new GatewayModel() this.paymentModel = new PaymentModel(this.state.entity.invoices, this.state.entity, this.state.entity.credits) this.triggerAction = this.triggerAction.bind(this) this.toggleTab = this.toggleTab.bind(this) this.refresh = this.refresh.bind(this) } componentDidMount () { this.getGateways() } refresh (entity) { this.paymentModel = new PaymentModel(this.state.entity.invoices, entity, this.state.entity.credits) this.setState({ entity: entity }) } getGateways () { this.gatewayModel.getGateways().then(response => { if (!response) { alert('error') } this.setState({ gateways: response }, () => { console.log('gateways', this.state.gateways) }) }) } toggleTab (tab) { if (this.state.activeTab !== tab) { this.setState({ activeTab: tab }) } } triggerAction (action) { this.paymentModel.completeAction(this.state.entity, action).then(response => { this.setState({ show_success: true }, () => { this.props.updateState(response, this.refresh) }) setTimeout( function () { this.setState({ show_success: false }) } .bind(this), 2000 ) }) } render () { return ( <React.Fragment> <Nav tabs className="nav-justified disable-scrollbars"> <NavItem> <NavLink className={this.state.activeTab === '1' ? 'active' : ''} onClick={() => { this.toggleTab('1') }} > {translations.overview} </NavLink> </NavItem> </Nav> <TabContent activeTab={this.state.activeTab}> <TabPane tabId="1"> <Overview model={this.paymentModel} customers={this.props.customers} entity={this.state.entity} gateways={this.state.gateways} gatewayModel={this.gatewayModel}/> </TabPane> <TabPane tabId="2"> <Refund customers={this.props.customer} payment={this.state.entity} modal={false} allInvoices={[]} allCredits={[]} invoices={null} credits={null} paymentables={this.state.entity.paymentables} /> </TabPane> </TabContent> {this.state.show_success && <Alert color="primary"> {translations.action_completed} </Alert> } <BottomNavigationButtons button1_click={(e) => this.toggleTab('2')} button1={{ label: translations.refund }} button2_click={(e) => this.triggerAction('archive')} button2={{ label: translations.archive }}/> </React.Fragment> ) } }
import { Injectable } from '@angular/core'; import { constants } from 'src/constants'; import { BigQueryService } from '../big-query/big-query.service'; import { FormQueryResponse, FormQueryResultStats } from '../../home.models'; @Injectable({ providedIn: 'root' }) export class HomeHelperService { constructor(private bigQueryService: BigQueryService) { } /** * Runs the query using the bigquery service and reformats * the response into understandable format * @param query The query obtained from side panel form */ public async runFormQuery(query: string): Promise<FormQueryResponse> { const request = await this.bigQueryService.runQuery(query); const formattedResult = this.bigQueryService.convertResult(request.result)[0]; if (!this.validateFormattedResult(formattedResult)) { throw new Error('Invalid Query'); } /** * Get other stats from response */ const formQueryResultStats: FormQueryResultStats = { projectId: request.result.jobReference.projectId, jobId: request.result.jobReference.jobId, totalBytesProcessed: request.result.totalBytesProcessed, jobComplete: request.result.jobComplete, cacheHit: request.result.cacheHit }; return { formQueryResult: formattedResult, formQueryResultStats: formQueryResultStats }; } private validateFormattedResult(formattedResult) { /** * Check if upstream is present */ if ('upstream' in formattedResult) { /** * Check if it is an array */ if (!(formattedResult.upstream instanceof Array)) { return false; } /** * Check if all properties exist */ if (formattedResult.upstream.length > 0) { for (const prop of Object.values(constants.bigQuery.datasets.route.tables.UPSTREAM.columns)) { if (!(prop in formattedResult.upstream[0])) { return false; } } } } /** * Check if upstream is present */ if (!('cm' in formattedResult)) { return false; } /** * Check if it is an array */ if (!(formattedResult.cm instanceof Array)) { return false; } /** * Check if all properties exist */ if (formattedResult.cm.length > 0) { for (const prop of Object.values(constants.bigQuery.datasets.route.tables.CM.columns)) { if (!(prop in formattedResult.cm[0])) { return false; } } } /** * Check if downstream is present */ if ('downstream' in formattedResult) { /** * Check if it is an array */ if (!(formattedResult.downstream instanceof Array)) { return false; } /** * Check if all properties exist */ if (formattedResult.downstream.length > 0) { for (const prop of Object.values(constants.bigQuery.datasets.route.tables.DOWNSTREAM.columns)) { if (!(prop in formattedResult.downstream[0])) { return false; } } } } return true; } }
set :ssh_options, { user: 'deploy', auth_methods: %w(publickey) } server '<ip/domain>', user: 'deploy', roles: %w{app web}
#!/usr/bin/env bash #SBATCH --job-name extract_metadata #SBATCH -N 1 #SBATCH -p opteron # Use modules to set the software environment java -jar target/code-1.0-SNAPSHOT-jar-with-dependencies.jar extract_metadata IntroClassJava
import random import string def generate_password(length): password_characters = string.ascii_letters + string.digits return ''.join(random.choice(password_characters) for i in range(length)) password = generate_password(8) print("Password is:", password)
<reponame>w-zengtao/ruby-rsa-verify require "rsa/tools/version" require "rsa/tools/utility" require "rsa/tools/generator" module Rsa::Tools # 验签 & 用对方的公钥验签 def self.verify(public_key, data, original_data) Utility.verify(public_key, data, original_data) end # 签名 & 用自己私钥签名 & RSAWithSha256 的签名 def self.sign(private_key, data) Utility.sign(private_key, data) end # TO C的业务 & 私钥加密 公钥解密 def self.encrypt(private_key, data) Utility.encrypt(private_key, data) end def self.decrypt(public_key, encrypted) Utility.decrypt(public_key, encrypted) end # TO B的业务 & 公钥加密 私钥解密 def self.pub_encrypt(public_key, data) Utility.pub_encrypt(public_key, data) end def self.pri_decrypt(private_key, encrypted) Utility.pri_decrypt(private_key, encrypted) end def self.key_pairs return Generator.key_pairs end def self.pem_pairs(pri_path = nil, pub_path = nil) return Generator.pem_pairs(pri_path, pub_path) end end
import { SET_ERROR, TOGGLE_DETAILS } from '~/actions/errors'; import { LOCATION_CHANGE } from 'react-router-redux'; const defaultState = { json: null, status: null, statusText: null, details: false, }; export default function errors(state = defaultState, action) { switch (action.type) { case SET_ERROR: { const { json, status, statusText } = action; return { ...state, json, status, statusText }; } case TOGGLE_DETAILS: return { ...state, details: !state.details }; case LOCATION_CHANGE: return { ...state, json: null, status: null, statusText: null }; default: return state; } }
<reponame>gloriamutie/ColorApp package com.gloria.GameKids.ui; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentPagerAdapter; import androidx.viewpager.widget.ViewPager; import android.os.Bundle; import com.gloria.GameKids.R; import com.gloria.GameKids.adapters.PlaylistPagerAdapter; import com.gloria.GameKids.models.Item; import org.parceler.Parcels; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class DetailsActivity extends AppCompatActivity { @BindView(R.id.viewPager) ViewPager mViewPager; private PlaylistPagerAdapter adapterViewPager; private List<Item> mitemlist; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); ButterKnife.bind(this); mitemlist= Parcels.unwrap(getIntent().getParcelableExtra("itemlist")); int startingPosition = getIntent().getIntExtra("position",0); adapterViewPager = new PlaylistPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,mitemlist); mViewPager.setAdapter(adapterViewPager); mViewPager.setCurrentItem(startingPosition); } }
budget -f 138 -l 171 -n MinistryofAgricultureAnimalIndustryFisheries 2014-15.pdf budget -o -f 138 -l 139 -n MinistryofAgricultureAnimalIndustryFisheries-2 2014-15.pdf budget -f 172 -l 175 -n DairyDevelopmentAuthority 2014-15.pdf budget -o -f 172 -l 173 -n DairyDevelopmentAuthority-2 2014-15.pdf budget -f 176 -l 179 -n KampalaCityCouncilAuthority 2014-15.pdf budget -o -f 176 -l 177 -n KampalaCityCouncilAuthority-2 2014-15.pdf budget -f 180 -l 185 -n NationalAnimalGeneticResourceCentreandDataBank 2014-15.pdf budget -o -f 180 -l 181 -n NationalAnimalGeneticResourceCentreandDataBank-2 2014-15.pdf budget -f 186 -l 191 -n NationalAgriculturalResearchOrganisation 2014-15.pdf budget -o -f 186 -l 187 -n NationalAgriculturalResearchOrganisation-2 2014-15.pdf budget -f 192 -l 201 -n NAADSSecretariat 2014-15.pdf budget -o -f 192 -l 193 -n NAADSSecretariat-2 2014-15.pdf budget -f 202 -l 206 -n UgandaCottonDevelopmentOrganisation 2014-15.pdf budget -o -f 202 -l 203 -n UgandaCottonDevelopmentOrganisation-2 2014-15.pdf budget -f 207 -l 213 -n UgandaCoffeeDevelopmentAuthority 2014-15.pdf budget -o -f 207 -l 208 -n UgandaCoffeeDevelopmentAuthority-2 2014-15.pdf budget -f 214 -l 222 -n MinistryofLandsHousingUrbanDevelopment 2014-15.pdf budget -o -f 214 -l 215 -n MinistryofLandsHousingUrbanDevelopment-2 2014-15.pdf budget -f 223 -l 224 -n KampalaCityCouncilAuthority 2014-15.pdf budget -o -f 223 -l 224 -n KampalaCityCouncilAuthority-2 2014-15.pdf budget -f 225 -l 228 -n UgandaLandCommission 2014-15.pdf budget -o -f 225 -l 226 -n UgandaLandCommission-2 2014-15.pdf budget -f 229 -l 243 -n MinistryofEnergyandMineralDevelopment 2014-15.pdf budget -o -f 229 -l 230 -n MinistryofEnergyandMineralDevelopment-2 2014-15.pdf budget -f 244 -l 246 -n RuralElectrificationAgency 2014-15.pdf budget -o -f 244 -l 245 -n RuralElectrificationAgency-2 2014-15.pdf budget -f 247 -l 262 -n MinistryofWorksandTransport 2014-15.pdf budget -o -f 247 -l 248 -n MinistryofWorksandTransport-2 2014-15.pdf budget -f 263 -l 268 -n UgandaNationalRoadAuthority 2014-15.pdf budget -o -f 263 -l 264 -n UgandaNationalRoadAuthority-2 2014-15.pdf budget -f 269 -l 273 -n UgandaRoadFund 2014-15.pdf budget -o -f 269 -l 270 -n UgandaRoadFund-2 2014-15.pdf budget -f 274 -l 278 -n KampalaCityCouncilAuthority 2014-15.pdf budget -o -f 274 -l 275 -n KampalaCityCouncilAuthority-2 2014-15.pdf budget -f 279 -l 285 -n MinistryofInformationCommunicationsTechnology 2014-15.pdf budget -o -f 279 -l 280 -n MinistryofInformationCommunicationsTechnology-2 2014-15.pdf budget -f 286 -l 290 -n NationalInformationTechnologyAuthority 2014-15.pdf budget -o -f 286 -l 287 -n NationalInformationTechnologyAuthority-2 2014-15.pdf budget -f 291 -l 339 -n MinistryofTradeIndustryandCooperatives 2014-15.pdf budget -o -f 291 -l 292 -n MinistryofTradeIndustryandCooperatives-2 2014-15.pdf budget -f 340 -l 346 -n MinistryofTourismWildlifeandAntiquities 2014-15.pdf budget -o -f 340 -l 341 -n MinistryofTourismWildlifeandAntiquities-2 2014-15.pdf budget -f 347 -l 354 -n UgandaIndustrialResearchInstitute 2014-15.pdf budget -o -f 347 -l 348 -n UgandaIndustrialResearchInstitute-2 2014-15.pdf budget -f 355 -l 358 -n UgandaTourismBoard 2014-15.pdf budget -o -f 355 -l 356 -n UgandaTourismBoard-2 2014-15.pdf budget -f 359 -l 362 -n UgandaNationalBureauofStandards 2014-15.pdf budget -o -f 359 -l 360 -n UgandaNationalBureauofStandards-2 2014-15.pdf budget -f 363 -l 387 -n MinistryofEducationandSports 2014-15.pdf budget -o -f 363 -l 364 -n MinistryofEducationandSports-2 2014-15.pdf budget -f 388 -l 393 -n BusitemaUniversity 2014-15.pdf budget -o -f 388 -l 389 -n BusitemaUniversity-2 2014-15.pdf budget -f 394 -l 399 -n KampalaCityCouncilAuthority 2014-15.pdf budget -o -f 394 -l 395 -n KampalaCityCouncilAuthority-2 2014-15.pdf budget -f 400 -l 403 -n MuniUniversity 2014-15.pdf budget -o -f 400 -l 401 -n MuniUniversity-2 2014-15.pdf budget -f 404 -l 407 -n EducationServiceCommission 2014-15.pdf budget -o -f 404 -l 405 -n EducationServiceCommission-2 2014-15.pdf budget -f 408 -l 412 -n MakerereUniversity 2014-15.pdf budget -o -f 408 -l 409 -n MakerereUniversity-2 2014-15.pdf budget -f 413 -l 417 -n MbararaUniversity 2014-15.pdf budget -o -f 413 -l 414 -n MbararaUniversity-2 2014-15.pdf budget -f 418 -l 421 -n MakerereUniversityBusinessSchool 2014-15.pdf budget -o -f 418 -l 419 -n MakerereUniversityBusinessSchool-2 2014-15.pdf budget -f 422 -l 425 -n KyambogoUniversity 2014-15.pdf budget -o -f 422 -l 423 -n KyambogoUniversity-2 2014-15.pdf budget -f 426 -l 428 -n UgandaManagementInstitute 2014-15.pdf budget -o -f 426 -l 427 -n UgandaManagementInstitute-2 2014-15.pdf budget -f 429 -l 436 -n GuluUniversity 2014-15.pdf budget -o -f 429 -l 430 -n GuluUniversity-2 2014-15.pdf budget -f 437 -l 447 -n MinistryofHealth 2014-15.pdf budget -o -f 437 -l 438 -n MinistryofHealth-2 2014-15.pdf budget -f 448 -l 458 -n UgandaAIDSCommission 2014-15.pdf budget -o -f 448 -l 449 -n UgandaAIDSCommission-2 2014-15.pdf budget -f 459 -l 465 -n UgandaCancerInstitute 2014-15.pdf budget -o -f 459 -l 460 -n UgandaCancerInstitute-2 2014-15.pdf budget -f 466 -l 470 -n UgandaHeartInstitute 2014-15.pdf budget -o -f 466 -l 467 -n UgandaHeartInstitute-2 2014-15.pdf budget -f 471 -l 474 -n NationalMedicalStores 2014-15.pdf budget -o -f 471 -l 472 -n NationalMedicalStores-2 2014-15.pdf budget -f 475 -l 479 -n KampalaCityCouncilAuthority 2014-15.pdf budget -o -f 475 -l 476 -n KampalaCityCouncilAuthority-2 2014-15.pdf budget -f 480 -l 484 -n HealthServiceCommission 2014-15.pdf budget -o -f 480 -l 481 -n HealthServiceCommission-2 2014-15.pdf budget -f 485 -l 488 -n UgandaBloodTransfusionService 2014-15.pdf budget -o -f 485 -l 486 -n UgandaBloodTransfusionService-2 2014-15.pdf budget -f 489 -l 494 -n MulagoHospitalComplex 2014-15.pdf budget -o -f 489 -l 490 -n MulagoHospitalComplex-2 2014-15.pdf budget -f 495 -l 500 -n ButabikaHospital 2014-15.pdf budget -o -f 495 -l 496 -n ButabikaHospital-2 2014-15.pdf budget -f 501 -l 578 -n ReferralHospitals 2014-15.pdf budget -o -f 501 -l 502 -n ReferralHospitals-2 2014-15.pdf budget -f 579 -l 602 -n MinistryofWaterandEnvironment 2014-15.pdf budget -o -f 579 -l 580 -n MinistryofWaterandEnvironment-2 2014-15.pdf budget -f 603 -l 605 -n KampalaCityCouncilAuthority 2014-15.pdf budget -o -f 603 -l 604 -n KampalaCityCouncilAuthority-2 2014-15.pdf budget -f 606 -l 614 -n NationalEnvironmentManagementAuthority 2014-15.pdf budget -o -f 606 -l 607 -n NationalEnvironmentManagementAuthority-2 2014-15.pdf budget -f 615 -l 620 -n NationalForestryAuthority 2014-15.pdf budget -o -f 615 -l 616 -n NationalForestryAuthority-2 2014-15.pdf budget -f 621 -l 651 -n MinistryofGenderLabourandSocialDevelopment 2014-15.pdf budget -o -f 621 -l 622 -n MinistryofGenderLabourandSocialDevelopment-2 2014-15.pdf budget -f 652 -l 654 -n KampalaCityCouncilAuthority 2014-15.pdf budget -o -f 652 -l 653 -n KampalaCityCouncilAuthority-2 2014-15.pdf budget -f 655 -l 657 -n EqualOpportunitiesCommission 2014-15.pdf budget -o -f 655 -l 656 -n EqualOpportunitiesCommission-2 2014-15.pdf budget -f 658 -l 660 -n OfficeofthePresident 2014-15.pdf budget -o -f 658 -l 659 -n OfficeofthePresident-2 2014-15.pdf budget -f 661 -l 667 -n MinistryofDefence 2014-15.pdf budget -o -f 661 -l 662 -n MinistryofDefence-2 2014-15.pdf budget -f 668 -l 670 -n ExternalSecurityOrganisation 2014-15.pdf budget -o -f 668 -l 669 -n ExternalSecurityOrganisation-2 2014-15.pdf budget -f 671 -l 688 -n MinistryofJusticeandConstitutionalAffairs 2014-15.pdf budget -o -f 671 -l 672 -n MinistryofJusticeandConstitutionalAffairs-2 2014-15.pdf budget -f 689 -l 700 -n MinistryofInternalAffairs 2014-15.pdf budget -o -f 689 -l 690 -n MinistryofInternalAffairs-2 2014-15.pdf budget -f 701 -l 706 -n Judiciary 2014-15.pdf budget -o -f 701 -l 702 -n Judiciary-2 2014-15.pdf budget -f 707 -l 710 -n LawReformCommission 2014-15.pdf budget -o -f 707 -l 708 -n LawReformCommission-2 2014-15.pdf budget -f 711 -l 714 -n UgandaHumanRightsCommission 2014-15.pdf budget -o -f 711 -l 712 -n UgandaHumanRightsCommission-2 2014-15.pdf budget -f 715 -l 717 -n LawDevelopmentCentre 2014-15.pdf budget -o -f 715 -l 716 -n LawDevelopmentCentre-2 2014-15.pdf budget -f 718 -l 721 -n UgandaRegistrationServicesBureau 2014-15.pdf budget -o -f 718 -l 719 -n UgandaRegistrationServicesBureau-2 2014-15.pdf budget -f 722 -l 727 -n NationalCitizenshipandImmigrationControl 2014-15.pdf budget -o -f 722 -l 723 -n NationalCitizenshipandImmigrationControl-2 2014-15.pdf budget -f 728 -l 731 -n DirectorateofPublicProsecutions 2014-15.pdf budget -o -f 728 -l 729 -n DirectorateofPublicProsecutions-2 2014-15.pdf budget -f 732 -l 743 -n UgandaPoliceinclLDUs 2014-15.pdf budget -o -f 732 -l 733 -n UgandaPoliceinclLDUs-2 2014-15.pdf budget -f 744 -l 751 -n UgandaPrisons 2014-15.pdf budget -o -f 744 -l 745 -n UgandaPrisons-2 2014-15.pdf budget -f 752 -l 756 -n JudicialServiceCommission 2014-15.pdf budget -o -f 752 -l 753 -n JudicialServiceCommission-2 2014-15.pdf budget -f 757 -l 765 -n OfficeofthePrimeMinister 2014-15.pdf budget -o -f 757 -l 758 -n OfficeofthePrimeMinister-2 2014-15.pdf budget -f 766 -l 773 -n MinistryofPublicService 2014-15.pdf budget -o -f 766 -l 767 -n MinistryofPublicService-2 2014-15.pdf budget -f 774 -l 780 -n MinistryofLocalGovernment 2014-15.pdf budget -o -f 774 -l 775 -n MinistryofLocalGovernment-2 2014-15.pdf budget -f 781 -l 788 -n EastAfricanCommunity 2014-15.pdf budget -o -f 781 -l 782 -n EastAfricanCommunity-2 2014-15.pdf budget -f 789 -l 792 -n NationalPlanningAuthority 2014-15.pdf budget -o -f 789 -l 790 -n NationalPlanningAuthority-2 2014-15.pdf budget -f 793 -l 800 -n KampalaCityCouncilAuthority 2014-15.pdf budget -o -f 793 -l 794 -n KampalaCityCouncilAuthority-2 2014-15.pdf budget -f 801 -l 805 -n PublicServiceCommission 2014-15.pdf budget -o -f 801 -l 802 -n PublicServiceCommission-2 2014-15.pdf budget -f 806 -l 810 -n LocalGovernmentFinanceCommission 2014-15.pdf budget -o -f 806 -l 807 -n LocalGovernmentFinanceCommission-2 2014-15.pdf budget -f 811 -l 860 -n MinistryofFinancePlanningEconomicDevelopment 2014-15.pdf budget -o -f 811 -l 812 -n MinistryofFinancePlanningEconomicDevelopment-2 2014-15.pdf budget -f 861 -l 866 -n InspectorateofGovernment 2014-15.pdf budget -o -f 861 -l 862 -n InspectorateofGovernment-2 2014-15.pdf budget -f 867 -l 869 -n EthicsandIntegrity 2014-15.pdf budget -o -f 867 -l 868 -n EthicsandIntegrity-2 2014-15.pdf budget -f 870 -l 871 -n KampalaCityCouncilAuthority 2014-15.pdf budget -o -f 870 -l 871 -n KampalaCityCouncilAuthority-2 2014-15.pdf budget -f 872 -l 876 -n AuditorGeneral 2014-15.pdf budget -o -f 872 -l 873 -n AuditorGeneral-2 2014-15.pdf budget -f 877 -l 882 -n UgandaRevenueAuthority 2014-15.pdf budget -o -f 877 -l 878 -n UgandaRevenueAuthority-2 2014-15.pdf budget -f 883 -l 889 -n UgandaBureauofStatistics 2014-15.pdf budget -o -f 883 -l 884 -n UgandaBureauofStatistics-2 2014-15.pdf budget -f 890 -l 895 -n PublicProcurementandDisposalofAssets 2014-15.pdf budget -o -f 890 -l 891 -n PublicProcurementandDisposalofAssets-2 2014-15.pdf budget -f 896 -l 900 -n ParliamentaryCommission 2014-15.pdf budget -o -f 896 -l 897 -n ParliamentaryCommission-2 2014-15.pdf budget -f 901 -l 911 -n OfficeofthePresident 2014-15.pdf budget -o -f 901 -l 902 -n OfficeofthePresident-2 2014-15.pdf budget -f 912 -l 914 -n StateHouse 2014-15.pdf budget -o -f 912 -l 913 -n StateHouse-2 2014-15.pdf budget -f 915 -l 932 -n MinistryofForeignAffairs 2014-15.pdf budget -o -f 915 -l 916 -n MinistryofForeignAffairs-2 2014-15.pdf budget -f 933 -l 937 -n ElectoralCommission 2014-15.pdf budget -o -f 933 -l 934 -n ElectoralCommission-2 2014-15.pdf
def binaryToDecimal(binary): decimal = 0 for i in range(0, len(binary)): decimal += int(binary[i]) * 2**(len(binary)-1-i) return decimal testBinary = '1011' result = binaryToDecimal(testBinary) print(result)
class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def sumOfNode(self, node): if node is None: return 0 return node.value + self.sumOfNode(node.left) + self.sumOfNode(node.right) # Modify the given code snippet as follows: # Assuming 'root' is the root of the binary tree root = TreeNode(1, TreeNode(2), TreeNode(3)) ans = root.sumOfNode(root) return ans
// Copyright 2009 The Apache Software Foundation // // 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.apache.tapestry5.ioc.services; import org.apache.tapestry5.ioc.Invokable; import java.util.concurrent.Future; /** * A service that allows work to occur in parallel using a thread pool. The thread pool is started lazily, and is * shutdown when the Registry is shutdown. * * @see org.apache.tapestry5.ioc.IOCSymbols * @since 5.1.0.1 */ public interface ParallelExecutor { /** * Submits the invocable object to be executed in a pooled thread. Returns a Future object representing the eventual * result of the invocable's operation. The actual operation will be wrapped such that {@link * PerthreadManager#cleanup()} is invoked after the operation completes. * * @param invocable to execute in a thread * @param <T> * @return Future result of that invocation */ <T> Future<T> invoke(Invokable<T> invocable); /** * As with {@link #invoke(org.apache.tapestry5.ioc.Invokable)}, but the result is wrapped inside a {@linkplain * org.apache.tapestry5.ioc.services.ThunkCreator thunk}. Invoking methods on the thunk will block until the value * is available. * * @param proxyType return type, used to create the thunk * @param invocable object that will eventually execute and return a value * @param <T> * @return the thunk */ <T> T invoke(Class<T> proxyType, Invokable<T> invocable); }
<reponame>chohra-med/mentorList<filename>src/Components/ListView.js<gh_stars>1-10 import React, {Component} from 'react'; import { View, ScrollView, Image, TouchableOpacity, TextInput, Text, RefreshControl, Switch, I18nManager, } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import styles from './ListViewStyle'; //we import Loadach to filter Items import _ from 'lodash'; import I18n from '../locales/i18n'; // Data that will be showed first const firstData = [ {"id": 1, "helps": "Software engineer", "name": "<NAME>"}, {"id": 2, "helps": "Junior Mobile Developer", "name": "<NAME>"}, {"id": 3, "helps": "Junior Data Science", "name": "<NAME>"}, {"id": 4, "helps": "Senior Data Science", "name": "<NAME>"}, {"id": 5, "helps": "Junior Mobile Developer", "name": "<NAME>"}, {"id": 6, "helps": "Senior FullStack Developer", "name": "<NAME>"}, {"id": 7, "helps": "Lead Fronted Developer", "name": "<NAME>"}, {"id": 8, "helps": "Senior Backend Developer", "name": "<NAME>"}, {"id": 9, "helps": "Senior Supply chain Specialist", "name": "<NAME>"}, {"id": 10, "helps": "Junior Digital Marketing", "name": "<NAME>"} ]; // Data that will be showed after const secondData = [ {"id": 412, "helps": "Junior Devops Developer", "name": "<NAME>"}, {"id": 323, "helps": "Senior Blockchain Developer", "name": "<NAME>"}, {"id": 512, "helps": "Senior Blockchain Developer", "name": "<NAME>"}, {"id": 47, "helps": "Junior Web Developer", "name": "<NAME> "}, {"id": 58, "helps": "CEO", "name": "<NAME>"}, {"id": 69, "helps": "Business developer", "name": "<NAME>"}, {"id": 610, "helps": "Junior Ui/Ux Designer", "name": "<NAME>"} ]; //this function return if ScrollView reached the buttom or not const isCloseToBottom = ({layoutMeasurement, contentOffset, contentSize}) => { const paddingToBottom = 20; return layoutMeasurement.height + contentOffset.y >= contentSize.height - paddingToBottom; }; export default class ListView extends Component { constructor(props) { super(props); this.state = { loadMore: false, ourData: [], generalData: [], nameFiltered: '', refreshing: false, isRTL: true, currentLanguage: 'en' }; this.filterBy = this.filterBy.bind(this); this.orderBy = this.orderBy.bind(this); }; //to filter our data by NAME filterBy() { let { generalData, nameFiltered } = this.state; let data = generalData; data = data.filter(x => String(x.name.toUpperCase()).includes(nameFiltered.toUpperCase())); this.setState({ourData: data}) } //to order our data by NAME orderBy() { let data = this.state.ourData; data = _.sortBy(data, ['name', 'id']); this.setState({ourData: data}) } //We recupere our data and put it in our State, And we set the language componentWillMount() { this.setState({ourData: firstData}); this.setState({generalData: firstData}); this.setState({isRTL: !I18nManager.isRTL}); if (I18nManager.isRTL) { this.setState({currentLanguage: 'ar'}); } else { this.setState({currentLanguage: 'en'}); } } // this is called when we want to add the second data // When scrollView reached its end updateList() { if (!this.state.loadMore) { let data = this.state.ourData; data = data.concat(secondData); this.setState({generalData: data}); this.setState({ourData: data}); this.setState({loadMore: true}); this.setState({nameFiltered: ''}) } } //This enable us to control the direction for different language _onDirectionChange = () => { I18nManager.forceRTL(this.state.isRTL); this.setState({isRTL: !this.state.isRTL}); if (this.state.isRTL) { this.setState({currentLanguage: 'ar'}); } else { this.setState({currentLanguage: 'en'}); } }; //This function enable us to MAP our Data in the our form showList() { return ( this.state.ourData.map(data => { return ( <TouchableOpacity key={data.id}> <View style={styles.listViewContainer}> <Image style={styles.image} source={require('../assets/Images/profile.jpg')} /> <View style={styles.textContainer}> <Text style={styles.name}>{data.name}</Text> <Text style={styles.helps}> {data.helps}</Text> </View> <Icon name="arrow-right" style={styles.button} color='black' size={32} onPress={() => { }} > </Icon> </View> <View style={{ borderBottomColor: 'black', borderBottomWidth: 0.5, width: '90%', marginLeft: '5%' }} /> </TouchableOpacity> ) }) ); } //this is called when we refresh our scroll view _onRefresh = () => { this.setState({refreshing: true}); this.setState({ourData: this.state.generalData}); this.setState({refreshing: false}); this.setState({nameFiltered: ''}) }; render() { let {currentLanguage, nameFiltered, refreshing} = this.state; I18n.locale = currentLanguage; I18n.fallbacks = true; return ( <View> <View style={{ flexDirection: 'row', justifyContent: 'center' }}> <TextInput style={{height: 40, borderWidth: 2, margin: 5, width: '60%'}} placeholder={I18n.t('filtering')} value={nameFiltered} onChangeText={(nameFiltered) => { this.setState({nameFiltered}); this.filterBy; }} /> <TouchableOpacity style={{width: 30, justifyContent: 'center', borderRadius: 20, borderColor: 'grey', margin: 6}} onPress={this.filterBy} > <Icon color='black' size={20} name="search"/> </TouchableOpacity> <TouchableOpacity style={{ justifyContent: 'center', borderRadius: 4, borderColor: 'grey', borderWidth: 1, marginLeft: 20, margin: 6 }} onPress={this.orderBy} > <Text style={{fontSize: 14, color: 'black'}}> {I18n.t('sortElement')}</Text> </TouchableOpacity> </View> <View title={'Quickly Test RTL Layout'}> <View style={{flexDirection: 'row', justifyContent: 'center'}}> <Text style={[styles.name, {margin: 1}]}> {I18n.t('changeLanguage')}</Text> <View style={styles.switchRowSwitchView}> <Switch onValueChange={this._onDirectionChange} style={styles.rightAlignStyle} value={this.state.isRTL} /> </View> </View> </View> <ScrollView refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={this._onRefresh} />} contentContainerStyle={{flexGrow: 1, borderWidth: 1, paddingBottom: 80}} onScroll={({nativeEvent}) => { if (isCloseToBottom(nativeEvent)) { this.updateList() } }} > <View> { this.showList() } </View> </ScrollView> </View> ); } }
from TestFxns import * tester=PyTester("Testing the EnergyMethod module base type") class FakeEnergyMethod(psr.EnergyMethod): def __init__(self,myid): """Registers this module with ModuleManager. Internal use only!!!""" super(FakeEnergyMethod,self).__init__(myid) def deriv_(self,Order,wfn): Mol=wfn.system egy=[0.0] for Ai in Mol: egy[0]+=0.5*(Ai[0]*Ai[0]+Ai[1]*Ai[1]+Ai[2]*Ai[2]) return wfn,egy def insert_supermodule(): cf = ModuleCreationFuncs() cf.add_py_creator("FakeEnergyMethod",FakeEnergyMethod) return cf def run(mm,tester): om=psr.OptionMap() om.add_option("MAX_DERIV",psr.OptionType.Int,False,None,"",0) om.add_option("FDIFF_DISPLACEMENT",psr.OptionType.Float,False,None,"",0.005) om.add_option("FDIFF_STENCIL_SIZE",psr.OptionType.Int,False,None,"",3) minfo=psr.ModuleInfo() minfo.name="FakeEnergyMethod" minfo.type="c_module" minfo.base="EnergyMethod" minfo.path="./TestEnergyMethod.so" minfo.version="1.0" minfo.description="A 3*Natoms H.O." minfo.options=om mm.load_module_from_minfo(minfo,"Test the H.O.") egy_mod=mm.get_module("Test the H.O.",0) wfn=psr.Wavefunction() H,H1=psr.create_atom([0.0,0.0,0.0],1),psr.create_atom([0.0,0.0,0.89],1) MyU=psr.AtomSetUniverse() MyU.insert(H); MyU.insert(H1); wfn.system=psr.System(MyU,True) #The right answers egy=[0.39605] grad=[0.0 for i in range(6)] grad[5]=0.89 hess=[0.0 for i in range(36)] for i in range(0,36,7):hess[i]=1.0; deriv=egy_mod.deriv(0,wfn) tester.test_value("Energy works",egy,deriv[1]) deriv=egy_mod.deriv(1,wfn) tester.test_value("Grad has right dimensions",len(grad),len(deriv[1])) for i in range(len(grad)): tester.test_value("FDiff grad comp "+str(i),grad[i],deriv[1][i]) deriv=egy_mod.deriv(2,wfn) tester.test_value("Hessian has right dimensions",len(hess),len(deriv[1])) for i in range(len(hess)): tester.test_value("FDiff Hessian comp "+str(i),hess[i],deriv[1][i]) with psr.ModuleAdministrator() as mm: run(mm,tester) psr.finalize() tester.print_results()
<filename>packages/core/decorator/interface/discord-pipe-transform.ts import { ClientEvents } from 'discord.js'; import { ConstructorType } from '../../util/type/constructor-type'; /** * Base pipe interface */ export interface DiscordPipeTransform<T = any, D = any> { transform( event: keyof ClientEvents, context: T, content?: D, type?: ConstructorType<D> ): any | Promise<any>; }
#!/usr/bin/env bash # # filter_fastq_by_length.sh - Select reads to keep based on size range # # Version 1.0.0 (September 20, 2015) # # Copyright (c) 2015 Andrew Krohn # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. # # This script was inspired by discussion at the following link: # https://www.biostars.org/p/62678/ set -e scriptdir="$( cd "$( dirname "$0" )" && pwd )" ## Check whether user had supplied -h or --help. If yes display help if [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]; then less $scriptdir/docs/filter_fastq_by_length.help exit 0 fi ## Read script mode and display usage if incorrect number of arguments supplied input=($1) minlength=($2) maxlength=($3) usage=`printf " Usage (order is important!): filter_fasta_by_length.sh <input_fasta> <min_length> <max_length> Input fasta must have valid extension (.fasta, .fa, .fas, .fna). "` if [[ -z $input ]]; then echo "$usage" exit 1 fi if [[ ! -s $input ]]; then echo " Check if supplied input is a valid file. $usage" exit 1 fi if [[ "$#" -ne "3" ]]; then echo " Incorrect number of arguments supplied. $usage" exit 1 fi ## Parse input filename and count reads fastaext="${input##*.}" inputbase=$(basename $input .$fastaext) ## If other than fastq supplied as input, display usage if [[ "$fastaext" != "fasta" ]] && [[ "$fastaext" != "fa" ]] && [[ "$fastaext" != "fas" ]] && [[ "$fastaext" != "fna" ]]; then echo " Input file does not have correct fasta extension (.fasta, .fa, .fas, or .fna). If you supplied a valid fasta file, change the extension and try again. $usage File supplied as input: $input " exit 1 fi ## Report that script is starting echo " Starting filtering process. Please be patient." ## Count input reads inputlines=$(cat $input | wc -l) inputseqs=$(echo "$inputlines/2" | bc) ## Define directories filedir=$(dirname $input) ## Filter input echo " Filtering file to retain reads ${minlength}bp-${maxlength}bp. Input: $filedir/$input ($inputseqs reads). Output: $filedir/$inputbase.$minlength-$maxlength.$fastaext" cat $input | awk -v high=$maxlength -v low=$minlength '{y= i++ % 2 ; L[y]=$0; if(y==1 && length(L[1])<=high) if(y==1 && length(L[1])>=low) {printf("%s\n%s\n",L[0],L[1]);}}' > $filedir/$inputbase.$minlength-$maxlength.$fastaext outlines=$(cat $filedir/$inputbase.$minlength-$maxlength.$fastaext | wc -l) outseqs=$(echo "$outlines/2" | bc) echo "Retained $outseqs reads. " exit 0
#!/bin/bash echo "" >> salida.dat NUM=1 while [ $NUM -le 42 ]; do ./hanoi $NUM >> salida.dat NUM=`expr $NUM + 1` done
import React, { useEffect } from "react"; import { withStyles, makeStyles } from "@material-ui/core/styles"; import Paper from "@material-ui/core/Paper"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableContainer from "@material-ui/core/TableContainer"; import TableHead from "@material-ui/core/TableHead"; import TablePagination from "@material-ui/core/TablePagination"; import TableRow from "@material-ui/core/TableRow"; import { connect } from "react-redux"; import { withRouter } from "react-router-dom"; import { getListRide } from "../../store/actions/bookingActions/bookingActions"; const StyledTableCell = withStyles((theme) => ({ body: { fontSize: 14, height: 10, }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ root: { "&:nth-of-type(even)": { backgroundColor: "#e1f5fe", }, }, }))(TableRow); const columns = [ { id: "booking", label: "Booking" }, { id: "pickUpDate", label: "Pick up date" }, { id: "pickUpHour", label: "Pick up hour", }, { id: "PickUpAddress", label: "Pick up address", }, { id: "dropOffDate", label: "Drop off date", }, { id: "requestedDropOffZipcode", align: "center", label: "Requested zipcode", }, { id: "status", align: "center", label: "Status", }, { id: "paymentStatus", label: "Payment status", }, { id: "customer", label: "Customer", }, { id: "standardPrice", label: "Standard price", format: (value) => value.toFixed(2), }, { id: "price", label: "Price", format: (value) => value.toFixed(2), }, ]; const useStyles = makeStyles({ root: { width: "100%", height: "100%", }, head: { backgroundColor: "#00ACC1", }, stateCancelled: { backgroundColor: "red", padding: "5px", color: "white" }, //red stateAccepted: { backgroundColor: "#4caf50", padding: "5px", color: "white" }, //green stateStarted: { backgroundColor: "#03a9f4", padding: "5px", color: "white" }, //blue stateFinished: { backgroundColor: "#e0e0e0", padding: "5px", color: "black" }, //gray stateOperationalCancelled: { backgroundColor: "#ff8a65", padding: "5px", color: "white", }, //orange state: { backgroundColor: "#fff9c4", padding: "5px", color: "black" }, //yellow }); function Booking(props) { const classes = useStyles(); const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(10); const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(+event.target.value); setPage(0); }; const { listRide } = props.booking; useEffect(() => { // if (user.id != null) { props.getListRide(11469); // } }, []); return ( <Paper className={classes.root}> <TableContainer> <Table aria-label="sticky table"> <TableHead className={classes.head}> <TableRow> {columns.map((column) => ( <TableCell key={column.id} align={column.align} style={{ minWidth: column.minWidth }} > {column.label} </TableCell> ))} </TableRow> </TableHead> <TableBody> {listRide.length > 0 && listRide .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((row) => { let pickUp = new Date(row.Request.EstimatePickUpDate); let pickUpMonth = pickUp.getMonth() + 1; let pickUpYear = pickUp.getFullYear(); let pickUpDay = pickUp.getDate(); let pickUpHour = pickUp.getHours() + 1; let pickUpMin = pickUp.getMinutes(); let dropOff = new Date(row.Request.EstimateDropOffDate); let dropOffMonth = dropOff.getMonth() + 1; let dropOffYear = dropOff.getFullYear(); let dropOffDay = dropOff.getDate(); let driverPrice = (row.Request.DriverPrice / 100).toFixed(2); let optionPrice = ( (row.Request.DriverPrice + row.Request.OptionsPrice) / 100 ).toFixed(2); console.log("Reporting -> optionPrice", optionPrice); return ( <StyledTableRow> <StyledTableCell> {row.Request.ReservationCode} </StyledTableCell> <StyledTableCell align="left"> {pickUpMonth + "/" + pickUpDay + "/" + pickUpYear} </StyledTableCell> <StyledTableCell> {pickUpHour + ":" + pickUpMin} </StyledTableCell> <StyledTableCell align="left"> {row.Request.AddressPickUp} </StyledTableCell> <StyledTableCell> {dropOffMonth + "/" + dropOffDay + "/" + dropOffYear} </StyledTableCell> <StyledTableCell width="20px" align="center"> {row.Request.AddressDropOffPostalCode || "--"} </StyledTableCell> <StyledTableCell width="30px" align="center"> <span className={ row.Request.State === "started" ? classes.stateStarted : row.Request.State === "cancelled" ? classes.stateCancelled : row.Request.State === "finished" ? classes.stateFinished : row.Request.State === "operational_cancelled" ? classes.stateOperationalCancelled : row.Request.State === "accepted" ? classes.stateAccepted : classes.state } > {row.Request.State} </span> </StyledTableCell> <StyledTableCell> {row.Request.PaymentType} </StyledTableCell> <StyledTableCell align="left"> {row.FrontEndUser.FirstName} {row.FrontEndUser.LastName} </StyledTableCell> <StyledTableCell>{driverPrice || "--"} €</StyledTableCell> <StyledTableCell align="left"> {optionPrice} € </StyledTableCell> </StyledTableRow> ); })} </TableBody> </Table> </TableContainer> <TablePagination rowsPerPageOptions={[10, 25, 100]} component="div" count={listRide.length} rowsPerPage={rowsPerPage} page={page} onChangePage={handleChangePage} onChangeRowsPerPage={handleChangeRowsPerPage} /> </Paper> ); } const mapStateToProps = (state) => ({ auth: state.auth, booking: state.booking, }); export default connect(mapStateToProps, { getListRide, })(withRouter(Booking));
// Custom exception class for insufficient funds class InsufficientFundsException extends Exception { public InsufficientFundsException(String message) { super(message); } } // BankAccount class class BankAccount { private double balance; // Constructor public BankAccount(double initialBalance) { this.balance = initialBalance; } // Withdraw method public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException("Insufficient funds in the account"); } else { balance -= amount; System.out.println("Withdrawal of " + amount + " successful. Remaining balance: " + balance); } } } // Main program to demonstrate the BankAccount class public class Main { public static void main(String[] args) { // Create a BankAccount instance with initial balance of 1000 BankAccount account = new BankAccount(1000); try { // Attempt to withdraw an amount greater than the balance account.withdraw(1500); } catch (InsufficientFundsException e) { System.out.println("Exception caught: " + e.getMessage()); } } }
#!/bin/sh cd src javac com/merjapp/*.java jar cmf ../MANIFEST.MF ../merjapp.jar com/merjapp/*.class ../libs/*.jar
<filename>src/components/shared/MappedStakeholderForm.js<gh_stars>0 import Grid from '@material-ui/core/Grid' import { makeStyles } from '@material-ui/core/styles' import TextField from '@material-ui/core/TextField' import Typography from '@material-ui/core/Typography' import { Formik } from 'formik' import PropTypes from 'prop-types' import React from 'react' import * as Yup from 'yup' import { MESSAGES, STAKEHOLDER_SECTORS, STAKEHOLDER_STATUSES } from '../../constants' import Button from '../shared/Button' import DropdownField from '../shared/DropdownField' const useStyles = makeStyles(theme => ({ button: { marginRight: theme.spacing(2) }, formHelpText: { display: 'block', marginBottom: theme.spacing(2) }, formSection: { marginBottom: theme.spacing(3) } })) const schema = Yup.object().shape({ firstName: Yup .string() .required('Please enter a first name'), id: Yup .string(), influence: Yup .number() .typeError('Please enter a number from 1 to 10') .min(1, 'Please enter a number from 1 to 10') .max(10, 'Please enter a number from 1 to 10') .required('Please enter a number from 1 to 10'), interest: Yup .number() .typeError('Please enter a number from 1 to 10') .min(1, 'Please enter a number from 1 to 10') .max(10, 'Please enter a number from 1 to 10') .required('Please enter a number from 1 to 10'), organisation: Yup .string() .required('Please enter an organisation'), position: Yup .string(), relationshipOwner: Yup .string(), relationshipStatus: Yup .string() .required('Please choose a relationship status'), sector: Yup .string() .required('Please choose a sector'), surname: Yup .string() .required('Please enter a surname') }) const sectorOptions = [ { labelText: '', value: '' }, ...Object.keys(STAKEHOLDER_SECTORS).map(key => { return { labelText: STAKEHOLDER_SECTORS[key], value: key } }) ] const relationshipStatusOptions = [ { labelText: '', value: '' }, ...Object.keys(STAKEHOLDER_STATUSES).map(key => { return { labelText: STAKEHOLDER_STATUSES[key], value: key } }) ] export const stakeholderInitialValues = { firstName: '', id: '', organisation: '', position: '', sector: '', surname: '' } export const mappedStakeholderInitialValues = { influence: '', interest: '', relationshipOwner: '', relationshipStatus: '' } export const initialValues = { ...stakeholderInitialValues, ...mappedStakeholderInitialValues } const MappedStakeholderForm = props => { const classes = useStyles() const handleFieldChange = formikHandleChange => { return event => { formikHandleChange(event) props.onChange(event) } } return ( <Formik enableReinitialize initialValues={props.initialValues} onSubmit={props.onSubmit} validationSchema={schema} render={({ errors, handleChange, handleSubmit, isSubmitting, touched, values }) => ( <form onSubmit={handleSubmit}> <Typography className={classes.formHelpText} variant='caption' > {MESSAGES.FORM_HELP_TEXT} </Typography> <input id='id' type='hidden' value={values.id} /> <div className={classes.formSection}> <Typography variant='h5' component='h2' gutterBottom > Who </Typography> <Grid container spacing={3} > <Grid item xs={12} sm={6} > <DropdownField id='sector' labelText='Sector*' onChange={handleFieldChange(handleChange)} options={sectorOptions} value={values.sector} disabled={props.disabledFields.indexOf('sector') !== -1} error={errors.sector && touched.sector} helperText={errors.sector && touched.sector ? errors.sector : ''} /> </Grid> <Grid item xs={12} sm={6} > <TextField fullWidth id='organisation' label='Organisation*' onChange={handleFieldChange(handleChange)} value={values.organisation} disabled={props.disabledFields.indexOf('organisation') !== -1} variant='outlined' error={errors.organisation && touched.organisation} helperText={errors.organisation && touched.organisation ? errors.organisation : ''} /> </Grid> </Grid> <Grid container spacing={3} > <Grid item xs={12} sm={6} > <TextField fullWidth id='firstName' label='First name*' onChange={handleFieldChange(handleChange)} value={values.firstName} disabled={props.disabledFields.indexOf('firstName') !== -1} variant='outlined' error={errors.firstName && touched.firstName} helperText={errors.firstName && touched.firstName ? errors.firstName : ''} /> </Grid> <Grid item xs={12} sm={6} > <TextField fullWidth id='surname' label='Surname*' onChange={handleFieldChange(handleChange)} value={values.surname} disabled={props.disabledFields.indexOf('surname') !== -1} variant='outlined' error={errors.surname && touched.surname} helperText={errors.surname && touched.surname ? errors.surname : ''} /> </Grid> </Grid> <Grid container spacing={3} > <Grid item xs={12} sm={6} > <TextField fullWidth id='position' label='Position' onChange={handleFieldChange(handleChange)} value={values.position} disabled={props.disabledFields.indexOf('position') !== -1} variant='outlined' error={errors.position && touched.position} helperText={errors.position && touched.position ? errors.position : ''} /> </Grid> </Grid> </div> <div className={classes.formSection}> <Typography variant='h5' component='h2' gutterBottom > Interest and influence </Typography> <Grid container spacing={3} > <Grid item xs={12} sm={6} > <TextField fullWidth id='interest' label='Interest*' onChange={handleFieldChange(handleChange)} type='number' value={values.interest} disabled={props.disabledFields.indexOf('interest') !== -1} variant='outlined' error={errors.interest && touched.interest} helperText={errors.interest && touched.interest ? errors.interest : 'From 1 to 10 (Uninterested — extremely interested)'} /> </Grid> <Grid item xs={12} sm={6} > <TextField fullWidth id='influence' label='Influence*' onChange={handleFieldChange(handleChange)} type='number' value={values.influence} disabled={props.disabledFields.indexOf('influence') !== -1} variant='outlined' error={errors.influence && touched.influence} helperText={errors.influence && touched.influence ? errors.influence : 'From 1 to 10 (uninfluential — extremely influential)'} /> </Grid> </Grid> </div> <div className={classes.formSection}> <Typography variant='h5' component='h2' gutterBottom > Relationship </Typography> <Grid container spacing={3} > <Grid item xs={12} sm={6} > <DropdownField id='relationshipStatus' labelText='Status*' onChange={handleFieldChange(handleChange)} options={relationshipStatusOptions} value={values.relationshipStatus} disabled={props.disabledFields.indexOf('relationshipStatus') !== -1} error={errors.relationshipStatus && touched.relationshipStatus} helperText={errors.relationshipStatus && touched.relationshipStatus ? errors.relationshipStatus : ''} /> </Grid> <Grid item xs={12} sm={6} > <TextField fullWidth id='relationshipOwner' label='Owner' onChange={handleFieldChange(handleChange)} value={values.relationshipOwner} disabled={props.disabledFields.indexOf('relationshipOwner') !== -1} variant='outlined' error={errors.relationshipOwner && touched.relationshipOwner} helperText={errors.relationshipOwner && touched.relationshipOwner ? errors.relationshipOwner : ''} /> </Grid> </Grid> </div> <div> <Button className={classes.button} disabled={isSubmitting} onClick={props.onCancel} variant='contained' > Cancel </Button> <Button color='primary' disabled={isSubmitting} type='submit' variant='contained' > {props.submitButtonLabel} </Button> </div> </form> )} /> ) } MappedStakeholderForm.propTypes = { disabledFields: PropTypes.array, initialValues: PropTypes.object, onCancel: PropTypes.func.isRequired, onChange: PropTypes.func, onSubmit: PropTypes.func.isRequired, submitButtonLabel: PropTypes.string } MappedStakeholderForm.defaultProps = { disabledFields: [], initialValues, onChange: () => {}, submitButtonLabel: 'Save' } export default MappedStakeholderForm
#!/bin/bash $DOTS/unquoted_error
package serial import ( "errors" "fmt" flatbuffers "github.com/google/flatbuffers/go" "github.com/peterwilliams97/pdf-search/serial/pdf_index" "github.com/unidoc/unidoc/common" ) // table PdfIndex { // num_files: uint32; // num_pages: uint32; // index : [byte]; // hipd: [HashIndexPathDoc]; // } type SerialPdfIndex struct { NumFiles uint32 NumPages uint32 BleveMem []byte HIPDs []HashIndexPathDoc } // WriteSerialPdfIndex func WriteSerialPdfIndex(spi SerialPdfIndex) []byte { b := flatbuffers.NewBuilder(0) buf := MakeSerialPdfIndex(b, spi) return buf } // func ReadSerialPdfIndex(buf []byte) (SerialPdfIndex, error) { // return ReadSerialPdfIndex(buf) // } // func WWriteSerialPdfIndex(f *os.File, spi SerialPdfIndex) error { // b := flatbuffers.NewBuilder(0) // buf := MakeSerialPdfIndex(b, spi) // check := crc32.ChecksumIEEE(buf) // uint32 // size := uint64(len(buf)) // if err := binary.Write(f, binary.LittleEndian, size); err != nil { // return err // } // if err := binary.Write(f, binary.LittleEndian, check); err != nil { // return err // } // _, err := f.Write(buf) // return err // } // func RReadSerialPdfIndex(f *os.File) (SerialPdfIndex, error) { // var size uint64 // var check uint32 // if err := binary.Read(f, binary.LittleEndian, &size); err != nil { // return SerialPdfIndex{}, err // } // if err := binary.Read(f, binary.LittleEndian, &check); err != nil { // return SerialPdfIndex{}, err // } // buf := make([]byte, size) // if _, err := f.Read(buf); err != nil { // return SerialPdfIndex{}, err // } // if crc32.ChecksumIEEE(buf) != check { // panic(errors.New("bad checksum")) // return SerialPdfIndex{}, errors.New("bad checksum") // } // return ReadSerialPdfIndex(buf) // } func MakeSerialPdfIndex(b *flatbuffers.Builder, spi SerialPdfIndex) []byte { b.Reset() var locOffsets []flatbuffers.UOffsetT for _, hipd := range spi.HIPDs { locOfs := addHashIndexPathDoc(b, hipd) locOffsets = append(locOffsets, locOfs) } pdf_index.PdfIndexStartHipdVector(b, len(spi.HIPDs)) // Prepend TextLocations in reverse order. for i := len(locOffsets) - 1; i >= 0; i-- { b.PrependUOffsetT(locOffsets[i]) } locationsOfs := b.EndVector(len(spi.HIPDs)) // Write the SerialPdfIndex object. pdf_index.PdfIndexStart(b) pdf_index.PdfIndexAddNumFiles(b, spi.NumFiles) pdf_index.PdfIndexAddNumPages(b, spi.NumPages) pdf_index.PdfIndexAddHipd(b, locationsOfs) dplOfs := pdf_index.PdfIndexEnd(b) // Finish the write operations by our SerialPdfIndex the root object. b.Finish(dplOfs) // return the byte slice containing encoded data: return b.Bytes[b.Head():] } func ReadSerialPdfIndex(buf []byte) (SerialPdfIndex, error) { // Initialize a SerialPdfIndex reader from `buf`. spi := pdf_index.GetRootAsPdfIndex(buf, 0) // Vectors, such as `Hipd`, have a method suffixed with 'Length' that can be used // to query the length of the vector. You can index the vector by passing an index value // into the accessor. var hipds []HashIndexPathDoc for i := 0; i < spi.HipdLength(); i++ { var loc pdf_index.HashIndexPathDoc ok := spi.Hipd(&loc, i) if !ok { return SerialPdfIndex{}, errors.New("bad HashIndexPathDoc") } hipds = append(hipds, getHashIndexPathDoc(&loc)) } common.Log.Info("ReadSerialPdfIndex: NumFiles=%d NumPages=%d HIPDs=%d", spi.NumFiles(), spi.NumPages(), len(hipds)) for i := 0; i < len(hipds) && i < 2; i++ { common.Log.Info("ReadSerialPdfIndex: hipds[%d]=%s", i, hipds[i]) } return SerialPdfIndex{ NumFiles: spi.NumFiles(), NumPages: spi.NumPages(), // Index []byte HIPDs: hipds, }, nil } // func RReadPdfIndex(f *os.File) (SerialPdfIndex, error) { // var size uint64 // var check uint32 // if err := binary.Read(f, binary.LittleEndian, &size); err != nil { // return SerialPdfIndex{}, err // } // if err := binary.Read(f, binary.LittleEndian, &check); err != nil { // return SerialPdfIndex{}, err // } // buf := make([]byte, size) // if _, err := f.Read(buf); err != nil { // return SerialPdfIndex{}, err // } // if crc32.ChecksumIEEE(buf) != check { // panic(errors.New("bad checksum")) // return SerialPdfIndex{}, errors.New("bad checksum") // } // return ReadSerialPdfIndex(buf) // } // table HashIndexPathDoc { // hash: string; // index: uint64; // path: string; // doc: DocPositions; // } type HashIndexPathDoc struct { Hash string Index uint64 Path string Doc DocPositions } // addHashIndexPathDoc writes HashIndexPathDoc `hipd` to builder `b`. func addHashIndexPathDoc(b *flatbuffers.Builder, hipd HashIndexPathDoc) flatbuffers.UOffsetT { hash := b.CreateString(hipd.Hash) path := b.CreateString(hipd.Path) doc := addDocPositions(b, hipd.Doc) // Write the HashIndexPathDoc object. pdf_index.HashIndexPathDocStart(b) pdf_index.HashIndexPathDocAddHash(b, hash) pdf_index.HashIndexPathDocAddIndex(b, hipd.Index) pdf_index.HashIndexPathDocAddPath(b, path) pdf_index.HashIndexPathDocAddDoc(b, doc) return pdf_index.HashIndexPathDocEnd(b) } // getHashIndexPathDoc reads a HashIndexPathDoc. func getHashIndexPathDoc(loc *pdf_index.HashIndexPathDoc) HashIndexPathDoc { // Copy the HashIndexPathDoc's fields (since these are numbers). var pos pdf_index.DocPositions sdoc := loc.Doc(&pos) // doc := getDocPositions(sdoc) numPageNums := sdoc.PageNumsLength() numPageTexts := sdoc.PageTextsLength() common.Log.Info("numPageNums=%d", numPageNums) common.Log.Info("numPageTexts=%d", numPageTexts) var pageNums []uint32 for i := 0; i < sdoc.PageNumsLength(); i++ { num := sdoc.PageNums(i) pageNums = append(pageNums, num) } var pageTexts []string for i := 0; i < sdoc.PageTextsLength(); i++ { text := string(sdoc.PageTexts(i)) pageTexts = append(pageTexts, text) } doc := DocPositions{ Path: string(sdoc.Path()), DocIdx: sdoc.DocIdx(), PageNums: pageNums, PageTexts: pageTexts, } common.Log.Info("Hash=%q", string(loc.Hash())) common.Log.Info("Path=%#q", string(loc.Path())) hipd := HashIndexPathDoc{ Hash: string(loc.Hash()), Path: string(loc.Path()), Index: loc.Index(), Doc: doc, } // common.Log.Info("getHashIndexPathDoc: hipd=%#v", hipd) return hipd } // // DocPositions tracks the data that is used to index a PDF file. // table DocPositions { // path: string; // Path of input PDF file. // doc_idx: uint64; // Index into lState.fileList. // page_nums: [uint32]; // page_texts: [string]; // } type DocPositions struct { Path string // Path of input PDF file. DocIdx uint64 // Index into lState.fileList. PageNums []uint32 PageTexts []string } func (doc DocPositions) String() string { return fmt.Sprintf("{DocPositions: DocIdx=%d PageNums=%d PageTexts=%d %q}", doc.DocIdx, len(doc.PageNums), len(doc.PageTexts), doc.Path) } func MakeDocPositions(b *flatbuffers.Builder, doc DocPositions) []byte { common.Log.Info("MakeDocPositions: doc=%s", doc) b.Reset() dplOfs := addDocPositions(b, doc) // Finish the write operations by our SerialPdfIndex the root object. b.Finish(dplOfs) // return the byte slice containing encoded data: return b.Bytes[b.Head():] } func addDocPositions(b *flatbuffers.Builder, doc DocPositions) flatbuffers.UOffsetT { path := b.CreateString(doc.Path) var pageOffsets []flatbuffers.UOffsetT for _, pageNum := range doc.PageNums { b.StartObject(1) // common.Log.Info("i=%d pageNum=%d", i, pageNum) b.PrependUint32Slot(0, pageNum, 0) locOfs := b.EndObject() pageOffsets = append(pageOffsets, locOfs) } pdf_index.DocPositionsStartPageNumsVector(b, len(doc.PageNums)) // Prepend TextLocations in reverse order. for i := len(pageOffsets) - 1; i >= 0; i-- { b.PrependUOffsetT(pageOffsets[i]) } pageOfs := b.EndVector(len(doc.PageNums)) var textOffsets []flatbuffers.UOffsetT for _, text := range doc.PageTexts { textOfs := b.CreateString(text) textOffsets = append(textOffsets, textOfs) } pdf_index.DocPositionsStartPageTextsVector(b, len(doc.PageTexts)) // Prepend TextLocations in reverse order. for i := len(textOffsets) - 1; i >= 0; i-- { b.PrependUOffsetT(textOffsets[i]) } textOfs := b.EndVector(len(doc.PageTexts)) // Write the SerialPdfIndex object. pdf_index.DocPositionsStart(b) pdf_index.DocPositionsAddPath(b, path) pdf_index.DocPositionsAddDocIdx(b, doc.DocIdx) pdf_index.DocPositionsAddPageNums(b, pageOfs) pdf_index.DocPositionsAddPageTexts(b, textOfs) return pdf_index.DocPositionsEnd(b) } func ReadDocPositions(buf []byte) (DocPositions, error) { // Initialize a SerialPdfIndex reader from `buf`. sdoc := pdf_index.GetRootAsDocPositions(buf, 0) // Vectors, such as `PageNums`, have a method suffixed with 'Length' that can be used // to query the length of the vector. You can index the vector by passing an index value // into the accessor. var pageNums []uint32 for i := 0; i < sdoc.PageNumsLength(); i++ { page := sdoc.PageNums(i) pageNums = append(pageNums, page) } var pageTexts []string for i := 0; i < sdoc.PageTextsLength(); i++ { text := string(sdoc.PageTexts(i)) pageTexts = append(pageTexts, text) } doc := DocPositions{ Path: string(sdoc.Path()), DocIdx: sdoc.DocIdx(), PageNums: pageNums, PageTexts: pageTexts, } // common.Log.Info("ReadDocPositions: doc=%s", doc) return doc, nil }
# Create a LogFileInfo object log_file1 = LogFileInfo("log1.txt", 1024, "2022-01-01 12:00:00") log_file2 = LogFileInfo("log2.txt", 2048, "2022-01-02 09:30:00") # Create a LogFileStorage instance log_file_storage = LogFileStorage() # Store log files log_file_storage.store_log_file(log_file1) log_file_storage.store_log_file(log_file2) # Retrieve a log file retrieved_log_file = log_file_storage.get_log_file("log1.txt") print(retrieved_log_file.file_name) # Output: log1.txt # List all log files all_log_files = log_file_storage.list_log_files() print(all_log_files) # Output: ['log1.txt', 'log2.txt']
def remove_duplicates(string): non_duplicate = "" for char in string: if char not in non_duplicate: non_duplicate += char return non_duplicate res = remove_duplicates(string) print(res) # Outputs "abrcd"
import java.util.*; public class FrequencySort { // Function to print the frequency of words static void frequencySort(String str) { HashMap<String, Integer> wordFreq = new HashMap<>(); String[] words = str.split(" "); // Counting word frequency for (String word : words) { wordFreq.put(word, wordFreq.getOrDefault(word, 0) + 1); } // Sorting words by its frequency List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(wordFreq.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o2.getValue()).compareTo(o1.getValue()); } }); // Printing the sorted words for (Map.Entry<String, Integer> entry : list) System.out.print(entry.getKey() + " "); } public static void main(String[] args) { String str = "This is a sample sentence for the task"; frequencySort(str); } }
const error = require('../../error')('/server/options', { url: ({ id }) => `https://serverjs.io/documentation/errors/#${id}` }); error.notobject = ` Your options must be an object as required by the options definition. If you are a developer and want to accept a single option, make sure to use the '__root' property. `; error.noarg = ({ name }) => ` The option '${name}' cannot be passed through the arguments of server. This might be because it's sensitive and it has to be set in the environment. Please read the documentation for '${name}' and make sure to set it correctly. `; error.noenv = ({ name }) => ` The option '${name}' cannot be passed through the environment of server. Please read the documentation for '${name}' and make sure to set it correctly. `; error.cannotextend = ({ type, name }) => ` The option "${name}" must be an object but it received "${type}". Please check your options to make sure you are passing an object. ${type === 'undefined' ? ` If you are the creator of the plugin and you are receiving 'undefined', you could allow for the default behaviour to be an empty object 'default: {}' ` : ''} `; error.required = ({ name }) => ` The option '${name}' is required but it was not set neither as an argument nor in the environment. Please make sure to set it. `; error.type = ({ name, expected, received, value }) => ` The option '${name}' should be a '[${typeof expected}]' but you passed a '${received}': ${JSON.stringify(value)} `; error.enum = ({ name, value, possible }) => ` The option '${name}' has a value of '${value}' but it should have one of these values: ${JSON.stringify(possible)} `; error.validate = ({ name, value }) => ` Failed to validate the option '${name}' with the value '${value}'. Please consult this option documentation for more information. `; error.secretexample = ` It looks like you are trying to use 'your-random-string-here' as the secret, just as in the documentation. Please don't do this! Create a strong secret and store it in your '.env'. `; error.secretgenerated = ` Please change the secret in your environment configuration. The default one is not recommended and should be changed. More info in https://serverjs.io/errors#defaultSecret `; module.exports = error;
package acmd_test import ( "bytes" "context" "flag" "fmt" "net/http" "os" "time" "github.com/cristalhq/acmd" ) var ( nopFunc = func(context.Context, []string) error { return nil } nopUsage = func(cfg acmd.Config, cmds []acmd.Command) {} ) func ExampleRunner() { testOut := os.Stdout testArgs := []string{"someapp", "now", "--times", "3"} const format = "15:04:05" now, _ := time.Parse(format, "10:20:30") cmds := []acmd.Command{ { Name: "now", Description: "prints current time", Do: func(ctx context.Context, args []string) error { fs := flag.NewFlagSet("some name for help", flag.ContinueOnError) times := fs.Int("times", 1, "how many times to print time") if err := fs.Parse(args); err != nil { return err } for i := 0; i < *times; i++ { fmt.Printf("now: %s\n", now.Format(format)) } return nil }, }, { Name: "status", Description: "prints status of the system", Do: func(ctx context.Context, args []string) error { req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://www.githubstatus.com/", http.NoBody) resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() // TODO: parse response, I don't know return nil }, }, } r := acmd.RunnerOf(cmds, acmd.Config{ AppName: "acmd-example", AppDescription: "Example of acmd package", PostDescription: "Best place to add examples", Version: "the best v0.x.y", Output: testOut, Args: testArgs, Usage: nopUsage, }) if err := r.Run(); err != nil { panic(err) } // Output: // now: 10:20:30 // now: 10:20:30 // now: 10:20:30 } func ExampleHelp() { testOut := os.Stdout testArgs := []string{"someapp", "help"} cmds := []acmd.Command{ { Name: "now", Description: "prints current time", Do: nopFunc, }, { Name: "status", Description: "prints status of the system", Do: nopFunc, }, { Name: "boom", Do: nopFunc, }, } r := acmd.RunnerOf(cmds, acmd.Config{ AppName: "acmd-example", AppDescription: "Example of acmd package", PostDescription: "Best place to add examples.", Version: "the best v0.x.y", Output: testOut, Args: testArgs, }) if err := r.Run(); err != nil { panic(err) } // Output: Example of acmd package // // Usage: // // acmd-example <command> [arguments...] // // The commands are: // // boom <no description> // help shows help message // now prints current time // status prints status of the system // version shows version of the application // // Best place to add examples. // // Version: the best v0.x.y } func ExampleVersion() { testOut := os.Stdout testArgs := []string{"someapp", "version"} cmds := []acmd.Command{ {Name: "foo", Do: nopFunc}, {Name: "bar", Do: nopFunc}, } r := acmd.RunnerOf(cmds, acmd.Config{ AppName: "acmd-example", AppDescription: "Example of acmd package", Version: "the best v0.x.y", Output: testOut, Args: testArgs, Usage: nopUsage, }) if err := r.Run(); err != nil { panic(err) } // Output: acmd-example version: the best v0.x.y } func ExampleAlias() { testOut := os.Stdout testArgs := []string{"someapp", "f"} cmds := []acmd.Command{ { Name: "foo", Alias: "f", Do: func(ctx context.Context, args []string) error { fmt.Fprint(testOut, "foo") return nil }, }, { Name: "bar", Alias: "b", Do: func(ctx context.Context, args []string) error { fmt.Fprint(testOut, "bar") return nil }, }, } r := acmd.RunnerOf(cmds, acmd.Config{ AppName: "acmd-example", AppDescription: "Example of acmd package", Version: "the best v0.x.y", Output: testOut, Args: testArgs, Usage: nopUsage, }) if err := r.Run(); err != nil { panic(err) } // Output: foo } func ExampleAutosuggestion() { testOut := os.Stdout testArgs := []string{"someapp", "baz"} cmds := []acmd.Command{ {Name: "foo", Do: nopFunc}, {Name: "bar", Do: nopFunc}, } r := acmd.RunnerOf(cmds, acmd.Config{ AppName: "acmd-example", AppDescription: "Example of acmd package", Version: "the best v0.x.y", Output: testOut, Args: testArgs, Usage: nopUsage, }) if err := r.Run(); err == nil { panic("must fail with command not found") } // Output: // "baz" unknown command, did you mean "bar"? // Run "acmd-example help" for usage. } func ExampleNestedCommands() { testOut := os.Stdout testArgs := []string{"someapp", "foo", "qux"} cmds := []acmd.Command{ { Name: "foo", Subcommands: []acmd.Command{ {Name: "bar", Do: nopFunc}, {Name: "baz", Do: nopFunc}, { Name: "qux", Do: func(ctx context.Context, args []string) error { fmt.Fprint(testOut, "qux") return nil }, }, }, }, {Name: "boom", Do: nopFunc}, } r := acmd.RunnerOf(cmds, acmd.Config{ AppName: "acmd-example", AppDescription: "Example of acmd package", Version: "the best v0.x.y", Output: testOut, Args: testArgs, }) if err := r.Run(); err != nil { panic(err) } // Output: qux } func ExamplePropagateFlags() { testOut := os.Stdout testArgs := []string{"someapp", "foo", "-dir=test-dir", "--verbose"} buf := &bytes.Buffer{} cmds := []acmd.Command{ { Name: "foo", Do: func(ctx context.Context, args []string) error { fs := flag.NewFlagSet("foo", flag.ContinueOnError) isRecursive := fs.Bool("r", false, "should file list be recursive") common := withCommonFlags(fs) if err := fs.Parse(args); err != nil { return err } if common.IsVerbose { fmt.Fprintf(buf, "TODO: dir %q, is recursive = %v\n", common.Dir, *isRecursive) } return nil }, }, { Name: "bar", Do: func(ctx context.Context, args []string) error { fs := flag.NewFlagSet("bar", flag.ContinueOnError) common := withCommonFlags(fs) if err := fs.Parse(args); err != nil { return err } if common.IsVerbose { fmt.Fprintf(buf, "TODO: dir %q\n", common.Dir) } return nil }, }, } r := acmd.RunnerOf(cmds, acmd.Config{ AppName: "acmd-example", AppDescription: "Example of acmd package", Version: "the best v0.x.y", Output: testOut, Args: testArgs, }) if err := r.Run(); err != nil { panic(err) } fmt.Println(buf.String()) // Output: TODO: dir "test-dir", is recursive = false } type commonFlags struct { IsVerbose bool Dir string } // NOTE: should be added before flag.FlagSet method Parse(). func withCommonFlags(fs *flag.FlagSet) *commonFlags { c := &commonFlags{} fs.BoolVar(&c.IsVerbose, "verbose", false, "should app be verbose") fs.StringVar(&c.Dir, "dir", ".", "directory to process") return c }