text
stringlengths
1
1.05M
<gh_stars>0 export const INDEX = '/'; export const NEW_CHAPTER = '/new-chapter'; export const EDIT_CHAPTER = '/edit-chapter/:chapterId'; export const QUIZ = '/quiz/:chapterId';
import re def check_valid_phone_number(string): pattern = r"^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$" if re.match(pattern, string): return True else: return False
addSbtPlugin("io.github.davidgregory084" % "sbt-tpolecat" % "0.1.4") addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.8")
<reponame>tollesonpdx/Last_Minute_Camping_With_C // <NAME> Copyright (c) 2019 // New Beginnings - Capstone Project // filename: f_campTreeTravPrint.c #include "headers.h" int campTreeTravPrint(struct campground* node, int p) { // go left if (node->left != NULL) { campTreeTravPrint(node->left, p); } // process current if (p) { campTreePrintNode(node); } // go right if (node->right != NULL) { campTreeTravPrint(node->right, p); } return 0; }
/* * Copyright 2018-2021 Elyra Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React, { useMemo } from "react"; import { DeepPartial } from "redux"; import { ThemeProvider as StyledThemeProvider } from "styled-components"; import { Theme } from "../types"; import { CanvasOverrides } from "./styles"; import useSystemInfo from "./useSystemInfo"; import { deepmerge } from "./utils"; const defaultTheme: Omit<Theme, "mode" | "platform"> = { palette: { focus: "#528bff", border: "#181a1f", divider: "rgba(128, 128, 128, 0.35)", hover: "#2c313a", active: "rgba(255, 255, 255, 0.18)", tabBorder: "#e7e7e7", inputBorder: "transparent", sash: "transparent", primary: { main: "#4d78cc", hover: "#6087cf", contrastText: "#fff", }, secondary: { main: "#353b45", contrastText: "#f0f0f0", }, error: { main: "#be1100", contrastText: "#fff", }, errorMessage: { main: "#be1100", contrastText: "#fff", errorBorder: "#be1100", }, text: { icon: "#c5c5c5", primary: "#cccccc", secondary: "#abb2bf", bold: "#e7e7e7", inactive: "rgba(231, 231, 231, 0.6)", disabled: "rgba(215, 218, 224, 0.25)", link: "#3794ff", error: "#f48771", }, background: { default: "#282c34", secondary: "#21252b", input: "#1b1d23", }, highlight: { border: "rgba(255, 255, 255, 0.12)", hover: "rgba(128, 128, 128, 0.07)", focus: "rgba(128, 128, 128, 0.14)", }, }, shape: { borderRadius: "0px", }, typography: { fontFamily: "-apple-system, system-ui, sans-serif", fontWeight: "normal", fontSize: "13px", }, }; function mergeThemes(systemInfo: { mode: "dark" | "light"; platform: "mac" | "win" | "other"; }) { return (overides: Partial<Theme>): Theme => { return deepmerge<Theme>( { ...defaultTheme, ...systemInfo }, overides as DeepPartial<Theme> ); }; } const ThemeProvider: React.FC<{ theme: DeepPartial<Theme> }> = ({ theme, children, }) => { return ( <StyledThemeProvider theme={theme as any}>{children}</StyledThemeProvider> ); }; export const InternalThemeProvider: React.FC = ({ children }) => { const systemInfo = useSystemInfo(); const theme = useMemo(() => mergeThemes(systemInfo), [systemInfo]); return ( <StyledThemeProvider theme={theme}> <CanvasOverrides /> {children} </StyledThemeProvider> ); }; export function createTheme(theme: DeepPartial<Theme>) { return theme; } export default ThemeProvider;
#!/bin/sh # Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. SPARSE=${SPARSE:-sparse} SPARSE_FLAGS=${SPARSE_FLAGS:-" -D__POSIX__ -Wsparse-all -Wno-do-while -Wno-transparent-union -Iinclude -Iinclude/uv-private -Isrc "} SOURCES=" include/uv-private/tree.h include/uv-private/uv-unix.h include/uv.h src/fs-poll.c src/inet.c src/queue.h src/unix/async.c src/unix/core.c src/unix/dl.c src/unix/error.c src/unix/fs.c src/unix/getaddrinfo.c src/unix/internal.h src/unix/loop-watcher.c src/unix/loop.c src/unix/pipe.c src/unix/poll.c src/unix/process.c src/unix/signal.c src/unix/stream.c src/unix/tcp.c src/unix/thread.c src/unix/threadpool.c src/unix/timer.c src/unix/tty.c src/unix/udp.c src/uv-common.c src/uv-common.h " TESTS=" test/benchmark-async-pummel.c test/benchmark-async.c test/benchmark-fs-stat.c test/benchmark-getaddrinfo.c test/benchmark-loop-count.c test/benchmark-million-async.c test/benchmark-million-timers.c test/benchmark-multi-accept.c test/benchmark-ping-pongs.c test/benchmark-pound.c test/benchmark-pump.c test/benchmark-sizes.c test/benchmark-spawn.c test/benchmark-tcp-write-batch.c test/benchmark-thread.c test/benchmark-udp-pummel.c test/blackhole-server.c test/dns-server.c test/echo-server.c test/run-benchmarks.c test/run-tests.c test/runner-unix.c test/runner-unix.h test/runner.c test/runner.h test/task.h test/test-active.c test/test-async.c test/test-barrier.c test/test-callback-order.c test/test-callback-stack.c test/test-condvar.c test/test-connection-fail.c test/test-cwd-and-chdir.c test/test-delayed-accept.c test/test-dlerror.c test/test-embed.c test/test-error.c test/test-fail-always.c test/test-fs-event.c test/test-fs-poll.c test/test-fs.c test/test-get-currentexe.c test/test-get-loadavg.c test/test-get-memory.c test/test-getaddrinfo.c test/test-getsockname.c test/test-hrtime.c test/test-idle.c test/test-ipc-send-recv.c test/test-ipc.c test/test-loop-handles.c test/test-multiple-listen.c test/test-mutexes.c test/test-pass-always.c test/test-ping-pong.c test/test-pipe-bind-error.c test/test-pipe-connect-error.c test/test-platform-output.c test/test-poll-close.c test/test-poll.c test/test-process-title.c test/test-ref.c test/test-run-nowait.c test/test-run-once.c test/test-semaphore.c test/test-shutdown-close.c test/test-shutdown-eof.c test/test-signal-multiple-loops.c test/test-signal.c test/test-spawn.c test/test-stdio-over-pipes.c test/test-tcp-bind-error.c test/test-tcp-bind6-error.c test/test-tcp-close-while-connecting.c test/test-tcp-close.c test/test-tcp-connect-error-after-write.c test/test-tcp-connect-error.c test/test-tcp-connect-timeout.c test/test-tcp-connect6-error.c test/test-tcp-flags.c test/test-tcp-open.c test/test-tcp-read-stop.c test/test-tcp-shutdown-after-write.c test/test-tcp-unexpected-read.c test/test-tcp-write-error.c test/test-tcp-write-to-half-open-connection.c test/test-tcp-writealot.c test/test-thread.c test/test-threadpool-cancel.c test/test-threadpool.c test/test-timer-again.c test/test-timer.c test/test-tty.c test/test-udp-dgram-too-big.c test/test-udp-ipv6.c test/test-udp-multicast-join.c test/test-udp-multicast-ttl.c test/test-udp-open.c test/test-udp-options.c test/test-udp-send-and-recv.c test/test-util.c test/test-walk-handles.c " case `uname -s` in AIX) SPARSE_FLAGS="$SPARSE_FLAGS -D_AIX=1" SOURCES="$SOURCES src/unix/aix.c" ;; Darwin) SPARSE_FLAGS="$SPARSE_FLAGS -D__APPLE__=1" SOURCES="$SOURCES include/uv-private/uv-bsd.h src/unix/darwin.c src/unix/kqueue.c src/unix/fsevents.c" ;; DragonFly) SPARSE_FLAGS="$SPARSE_FLAGS -D__DragonFly__=1" SOURCES="$SOURCES include/uv-private/uv-bsd.h src/unix/kqueue.c src/unix/freebsd.c" ;; FreeBSD) SPARSE_FLAGS="$SPARSE_FLAGS -D__FreeBSD__=1" SOURCES="$SOURCES include/uv-private/uv-bsd.h src/unix/kqueue.c src/unix/freebsd.c" ;; Linux) SPARSE_FLAGS="$SPARSE_FLAGS -D__linux__=1" SOURCES="$SOURCES include/uv-private/uv-linux.h src/unix/linux-inotify.c src/unix/linux-core.c src/unix/linux-syscalls.c src/unix/linux-syscalls.h" ;; NetBSD) SPARSE_FLAGS="$SPARSE_FLAGS -D__NetBSD__=1" SOURCES="$SOURCES include/uv-private/uv-bsd.h src/unix/kqueue.c src/unix/netbsd.c" ;; OpenBSD) SPARSE_FLAGS="$SPARSE_FLAGS -D__OpenBSD__=1" SOURCES="$SOURCES include/uv-private/uv-bsd.h src/unix/kqueue.c src/unix/openbsd.c" ;; SunOS) SPARSE_FLAGS="$SPARSE_FLAGS -D__sun=1" SOURCES="$SOURCES include/uv-private/uv-sunos.h src/unix/sunos.c" ;; esac for ARCH in __i386__ __x86_64__ __arm__; do $SPARSE $SPARSE_FLAGS -D$ARCH=1 $SOURCES done # Tests are architecture independent. $SPARSE $SPARSE_FLAGS -Itest $TESTS
<style> .dashboard { border: solid 2px #000; padding: 10px; border-radius: 20px; } </style> <div class="dashboard"></div>
module.exports = { 'Wat is je oogkleur?': 'eyeColor', 'Welke kleur kledingstukken heb je aan vandaag? (Meerdere antwoorden mogelijk natuurlijk...)': 'clothesWearingToday', };
<reponame>AriusX7/godfather<gh_stars>10-100 import NightActionsManager, { NightActionPriority } from '@mafia/managers/NightActionsManager'; import SingleTarget from '@mafia/mixins/SingleTarget'; import Townie from '@mafia/mixins/Townie'; import type Player from '@mafia/structures/Player'; class Retributionist extends SingleTarget { public name = 'Retributionist'; public action = 'revive'; public priority = NightActionPriority.RETRIBUTIONIST; public flags = { canTransport: false, canVisit: false, canWitch: false }; // whether the Ret has already revived a player private hasRevived = false; public constructor(player: Player) { super(player); this.description = this.game.t('roles/town:retributionistDescription'); this.actionText = this.game.t('roles/actions:retributionistText'); this.actionGerund = this.game.t('roles/actions:retributionistGerund'); } public async tearDown(actions: NightActionsManager, target: Player) { target.isAlive = true; target.deathReason = ''; target.flags.isRevived = true; target.flags.revivedOn = this.game.cycle; this.hasRevived = true; await this.game.channel.send(this.game.t('roles/town:retributionistAnnouncement', { player: target })); target.queueMessage(this.game.t('roles/town:retributionistMessage')); if (target.role.name === 'Vigilante') { Reflect.set(target.role, 'guilty', false); } if (this.game.canOverwritePermissions) { const overwrite = this.game.channel.permissionOverwrites.find( (permission) => permission.type === 'member' && permission.id === target.user.id ); if (overwrite) await overwrite.update({ SEND_MESSAGES: true, ADD_REACTIONS: true }); } } public canUseAction() { if (this.hasRevived) return { check: false, reason: this.game.t('roles/town:retributionistAlreadyRevived') }; const validTargets = this.game.players.filter((target) => this.canTarget(target).check); if (validTargets.length === 0) return { check: false, reason: this.game.t('roles/global:noTargets') }; return { check: true, reason: '' }; } public canTarget(target: Player) { if (target.isAlive || target.role.faction.name !== 'Town') return { check: false, reason: this.game.t('roles/town:retributionistDeadTownies') }; if (target.cleaned) return { check: false, reason: this.game.t('roles/town:retributionistNoCleaned') }; // @ts-ignore tsc cannot detect static properties if (target.role.constructor.unique) return { check: false, reason: this.game.t('roles/town:retributionistNoUnique') }; return { check: true, reason: '' }; } public static unique = true; } Retributionist.categories = [...Retributionist.categories, 'Town Support']; Retributionist.aliases = ['Ret', 'Retri']; export default Townie(Retributionist);
<gh_stars>0 from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from .solid import SolidDefinition from .resource import ResourceDefinition class VersionStrategy(ABC): """Abstract class for defining a strategy to version solids and resources. When subclassing, `get_solid_version` must be implemented, and `get_resource_version` can be optionally implemented. `get_solid_version` should ingest a SolidDefinition, and `get_resource_version` should ingest a ResourceDefinition. From that, each synthesize a unique string called a `version`, which will be tagged to outputs of that solid in the pipeline. Providing a `VersionStrategy` instance to a job will enable memoization on that job, such that only steps whose outputs do not have an up-to-date version will run. """ @abstractmethod def get_solid_version(self, solid_def: "SolidDefinition") -> str: pass def get_resource_version( self, resource_def: "ResourceDefinition" # pylint: disable=unused-argument ) -> Optional[str]: return None
<gh_stars>0 import { PassportStrategy } from '@nestjs/passport'; import { Strategy, VerifyCallback } from 'passport-google-oauth20'; import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { InjectModel } from '@nestjs/mongoose'; import { User, UserDocument } from 'src/user/schemas/user.schema'; import { Model } from 'mongoose'; import { AuthService } from '../auth.service'; @Injectable() export class GoogleStrategy extends PassportStrategy(Strategy, 'google') { constructor( @InjectModel(User.name) private readonly UserModel: Model<UserDocument>, private readonly ConfigService: ConfigService, private readonly authService: AuthService, ) { super({ clientID: ConfigService.get<string>('GOOGLE_CLIENT_ID'), clientSecret: ConfigService.get<string>('GOOGLE_SECRET'), callbackURL: 'https://petshion-dev.herokuapp.com/auth/google/PetshionOauth', scope: ['email', 'profile'], }); } async validate( accessToken: string, refreshToken: string, profile: any, done: VerifyCallback, ) { const { displayName, id, _json } = profile; const user = { googleid: id, userName: displayName, userImage: _json.picture, }; if (!(await this.UserModel.findOne({ googleId: user.googleid }))) { const userData = await this.UserModel.create({ googleId: user.googleid, username: user.userName, image: user.userImage, }); await userData.save(); } const savedUserData = await this.UserModel.findOne({ googleId: user.googleid, }); const Token = await this.authService.createToken(savedUserData); const UserData = { username: savedUserData.username, image: savedUserData.image, token: Token, }; console.log(JSON.stringify(UserData)); done(null, UserData); } }
export class ConsentReviewStep { results: Array<any>; saveable: boolean; identifier: string; constructor(identifier: string, givenName: string, familyName: string) { this.results = [{ identifier: "consentDocumentParticipantSignature", consented: true, saveable: false, signature: { signatureImage: "", requiresName: true, givenName, requiresSignatureImage: false, title: "Participant", familyName, signatureDate: new Date().toUTCString(), identifier: "consentDocumentParticipantSignature" } }]; this.saveable = false; this.identifier = identifier; } }
const dot = (color = '#ccc', outline = false) => ({ alignItems: 'center', display: 'flex', ':before': { backgroundColor: outline ? null : color, border: outline ? `1px solid ${color}` : null, borderRadius: 10, content: '" "', display: 'block', marginRight: 8, height: 10, width: 10, }, }); // Curious blue // Waterloo // Flamingo const BASE_THEME_COLOR = '51,163,220';//'123,130,150';//'240,100,40'; // Blue bayeux const BASE_FONT_COLOR = '81,105,133'; export default function (props) { const { colorMap, creatable } = props; return { // Don't show the separator clearIndicator: (styles) => ({ ...styles, display: creatable ? null : 'none' }), menu: styles => ({ ...styles, marginTop: 0, maxHeight: '30vh', borderRadius: '0 0 5px' }), menuList: styles => ({ ...styles, paddingTop: 0, maxHeight: '30vh' }), control: (styles, { hasValue, getValue, isDisabled, isFocused }) => { const commonStyles = { ...styles, width: '100%', opacity: isDisabled ? 0.6 : null, cursor: isDisabled ? 'not-allowed' : null, boxShadow: 'none', border: `1px solid rgba(133,141,162, ${isFocused ? 1 : 0.5}) !important`, }; // If provided a color map, use that to code everything if (colorMap) { const data = hasValue ? getValue()[0] : {}; const color = data && data.value in colorMap ? colorMap[data.value] : colorMap['default']; return { ...commonStyles, border: hasValue ? `1px solid rgba(${color}, 0.4) !important` : commonStyles.border, backgroundColor: hasValue ? `rgba(${color}, 0.05) !important` : styles.backgroundColor } } else { return commonStyles; } }, indicator: (styles, { data }) => { const commonStyles = { ...styles, }; if (colorMap) { const color = data && data.value in colorMap ? colorMap[data.value] : colorMap['default'] return { ...commonStyles, borderColor: `rgb(${color}) transparent transparent` } } else { return commonStyles; } }, option: (styles, { data, isDisabled, isFocused, isSelected }) => { const commonStyles = { ...styles, backgroundColor: isFocused ? `rgba(${BASE_THEME_COLOR}, 0.05) !important` : null, color: isFocused ? `rgba(${BASE_FONT_COLOR}, 1)` : isSelected ? `rgba(${BASE_FONT_COLOR}, 0.7)` : `rgba(${BASE_FONT_COLOR}, 0.6)` }; if (colorMap) { const color = data && data.value in colorMap ? colorMap[data.value] : colorMap['default'] return { ...commonStyles, backgroundColor: isFocused || isSelected ? `rgba(${color}, 0.05) !important` : null, color: isFocused || isSelected ? `rgb(${color}) !important` : null, cursor: isDisabled ? 'not-allowed' : 'default', '::before': { ...styles['::before'], backgroundColor: color, }, ...dot(`rgb(${color})`) } } else { return commonStyles; } }, placeholder: styles => { const commonStyles = { ...styles, color: `rgba(${BASE_FONT_COLOR}, 0.5) !important`, }; if (colorMap) { const color = colorMap['default'] return { ...commonStyles, color: `rgb(${color}) !important`, ...dot(`rgb(${color})`, true) } } else { return commonStyles; } }, singleValue: (styles, { data }) => { const commonStyles = { ...styles, color: `rgba(${BASE_FONT_COLOR}, 0.8) !important`, }; if (colorMap) { const color = data && data.value in colorMap ? colorMap[data.value] : colorMap['default'] return { ...commonStyles, color: `rgb(${color}) !important`, ...dot(`rgb(${color})`) } } else { return commonStyles; } }, } }
#!/usr/bin/env bash #set -x # Generates diff patches between MegaCarPack and current one source ../setEnv.sh CURRENT_DB_PATH=${TDUCP_PATH}/database/reference/Civicmanvtec-Milli-CarMegapack REFERENCE_DB_PATH=${TDUCP_PATH}/database/current echo "Getting diffs between current database and Civicmanvtec-Milli one, please wait..." ../tduf/databaseTool.sh diff-patches -n -j ${CURRENT_DB_PATH} -J ${REFERENCE_DB_PATH} -p ${DIFF_PATCHES_CARPACK_PATH} echo "Deleting diff on ACHIEVEMENTS topic..." rm ${DIFF_PATCHES_CARPACK_PATH}/ACHIEVEMENTS.mini.json echo "Deleting diff on PNJ topic..." rm ${DIFF_PATCHES_CARPACK_PATH}/PNJ.mini.json echo "All done!"
def bal_brackets(string): open_bracket = set('{[(') close_bracket = set('}])') matching_bracket = {('}', '{'), (')', '('), (']', '[')} stack = [] for i in string: if i in open_bracket: stack.append(i) elif i in close_bracket: if len(stack) == 0: return False elif (i, stack[-1]) not in matching_bracket: return False stack.pop() if len(stack) == 0: return True else: return False print(bal_brackets(string))
function signup(){ $("#signupModal").modal(); } function reload(){ window.location.href = site_url+"/home"; } function load_signup_form(type){ $("#chose_type").empty(); var html = '<div class="form-group">' +'Họ tên: <input type="text" id="first_name" name="first_name" class="form-control" placeholder="<NAME>" required autofocus>' +'</div>'+'<div id="error5" style="color: red;">'+'</div>' +'<div class="form-group">' +'Email: <input type="email" id="inputEmail" name="email" class="form-control" placeholder="Email" required>' +'</div>'+'<div id="error1" style="color: red;">'+'</div>' +'<div class="form-group">' +'Mật khẩu: <input type="password" id="input<PASSWORD>" name="password" class="form-control" placeholder="<NAME>" required >' +'</div>'+'<div id="error2" style="color: red;">'+'</div>' +'<div class="form-group">' +'Xác nhận mật khẩu: <input type="password" id="inputPassword<PASSWORD>" name="password<PASSWORD>" class="form-control" placeholder="<NAME>ậ<NAME>" required >' +'</div>'+'<div id="error3" style="color: red;">'+'</div>' +'<div id="error4" style="color: red;">'+'</div>' +'<input type="number" id="su" name="su" class="form-control" value="'+type+'" style="display:none">'; $("#chose_type").append(html); $("#captcha").attr("style","display:block"); $("#btn_sm").attr("style","display:block"); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bft.util; import bftsmart.tom.util.KeyLoader; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; /** * * @author joao */ public class ECDSAKeyLoader implements KeyLoader { private String path; private int myId; private String sigAlgorithm; public ECDSAKeyLoader(int myId, String configHome, String sigAlgorithm) { this.myId = myId; this.path = configHome + "keys" + System.getProperty("file.separator"); this.sigAlgorithm = sigAlgorithm; } public X509Certificate loadCertificate() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { return loadCertificate(this.myId); } public X509Certificate loadCertificate(int id) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { return BFTCommon.getCertificate(path + "cert" + id + ".pem"); } @Override public PublicKey loadPublicKey(int id) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { return loadCertificate(id).getPublicKey(); } @Override public PublicKey loadPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { return loadCertificate(this.myId).getPublicKey(); } @Override public PrivateKey loadPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { return BFTCommon.getPemPrivateKey(path + "keystore.pem"); } @Override public String getSignatureAlgorithm() { return this.sigAlgorithm; } }
#!/bin/bash set -e # Environment variables: # VANTA_KEY (the Vanta per-domain secret key) # VANTA_OWNER_EMAIL (the email of the person who owns this computer. Ignored if VANTA_KEY is missing.) PKG_URL="https://vanta-agent.s3.amazonaws.com/v1.5.9/vanta.pkg" # Checksum needs to be updated when PKG_URL is updated. CHECKSUM="77c23d5e9d9bc18191faef2d4ba532ed325861d5052ef48d07b7433ae376a744" PKG_PATH="/tmp/vanta.pkg" ## # Vanta needs to be installed as root; use sudo if not already uid 0 ## if [ $(echo "$UID") = "0" ]; then SUDO='' else SUDO='sudo -E' fi if [ -z "$VANTA_KEY" ]; then printf "\033[31m You must specify the VANTA_KEY environment variable in order to install the agent. \n\033[0m\n" exit 1 fi function onerror() { printf "\033[31m$ERROR_MESSAGE Something went wrong while installing the Vanta agent. If you're having trouble installing, please send an email to support@vanta.com, and we'll help you fix it! \n\033[0m\n" $SUDO launchctl unsetenv VANTA_KEY $SUDO launchctl unsetenv VANTA_OWNER_EMAIL } trap onerror ERR ## # Download the agent ## printf "\033[34m\n* Downloading the Vanta Agent\n\033[0m" rm -f $PKG_PATH curl --progress-bar $PKG_URL > $PKG_PATH ## # Checksum ## printf "\033[34m\n* Ensuring checksums match\n\033[0m" downloaded_checksum=$(shasum -a256 $PKG_PATH | cut -d" " -f1) if [ $downloaded_checksum = $CHECKSUM ]; then printf "\033[34mChecksums match.\n\033[0m" else printf "\033[31m Checksums do not match. Please contact support@vanta.com \033[0m\n" exit 1 fi ## # Install the agent ## printf "\033[34m\n* Installing the Vanta Agent. You might be asked for your password...\n\033[0m" $SUDO launchctl setenv VANTA_KEY "$VANTA_KEY" $SUDO launchctl setenv VANTA_OWNER_EMAIL "$VANTA_OWNER_EMAIL" $SUDO /usr/sbin/installer -pkg $PKG_PATH -target / >/dev/null $SUDO launchctl unsetenv VANTA_KEY $SUDO launchctl unsetenv VANTA_OWNER_EMAIL rm -f $PKG_PATH ## # check if the agent is running # return val 0 means running, # return val 2 means running but needs to register ## $SUDO /usr/local/vanta/vanta-cli status || [ $? == 2 ] printf "\033[32m Your Agent is running properly. It will continue to run in the background and submit data to Vanta. You can check the agent status using the \"vanta-cli status\" command. If you ever want to stop the agent, please use the toolbar icon or the vanta-cli command. It will restart automatically at login. To register this device to a new user, run \"vanta-cli register\" or click on \"Register Vanta Agent\" on the toolbar. \033[0m"
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _ReactHigherEventTypes = require("./ReactHigherEventTypes"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ReactHigherEventContainer = function (_Component) { _inherits(ReactHigherEventContainer, _Component); function ReactHigherEventContainer(props) { _classCallCheck(this, ReactHigherEventContainer); var _this = _possibleConstructorReturn(this, (ReactHigherEventContainer.__proto__ || Object.getPrototypeOf(ReactHigherEventContainer)).call(this, props)); _this.events = new Map(); _this.proxySubscribers = new Set(); _this.state = {}; _this.lastNativeEvent = null; _this.subscribe = _this.subscribe.bind(_this); _this.handleEvent = _this.handleEvent.bind(_this); _this.proxySubscribe = _this.proxySubscribe.bind(_this); return _this; } _createClass(ReactHigherEventContainer, [{ key: "componentWillUpdate", value: function componentWillUpdate(nextProps, nextState) { if (this.state !== nextState) { this.proxySubscribers.forEach(function (subscriber) { return subscriber(nextState); }); } } }, { key: "subscribe", value: function subscribe(eventType, handler) { var _this2 = this; var eventSubscribers = this.events.get(eventType); if (!eventSubscribers) { eventSubscribers = new Set(); this.events.set(eventType, eventSubscribers); this.updateEventProp({ eventType: eventType, create: true }); } eventSubscribers.add(handler); return function () { var eventSubscribers = _this2.events.get(eventType); if (eventSubscribers) { eventSubscribers.delete(handler); if (eventSubscribers.size === 0) { _this2.events.delete(eventType); _this2.updateEventProp({ eventType: eventType, create: false }); } } }; } }, { key: "proxySubscribe", value: function proxySubscribe(handler) { var _this3 = this; this.proxySubscribers.add(handler); handler(this.state); return function () { _this3.proxySubscribers.delete(handler); }; } }, { key: "updateEventProp", value: function updateEventProp(_ref) { var _this4 = this; var eventType = _ref.eventType, create = _ref.create; this.setState(function (state) { if (!!state[eventType] === create) { return state; } return _extends({}, state, _defineProperty({}, eventType, create ? _this4.handleEvent.bind(null, eventType) : null)); }); } }, { key: "handleEvent", value: function handleEvent(eventType, event) { if (!this.events.has(eventType) || event.nativeEvent === this.lastNativeEvent) { return; } this.lastNativeEvent = event.nativeEvent; var subscribers = this.events.get(eventType); if (subscribers) { subscribers.forEach(function (func) { return func(event); }); } } }, { key: "getChildContext", value: function getChildContext() { return { higherEvent: { subscribe: this.subscribe }, higherEventProxy: { subscribe: this.proxySubscribe } }; } }, { key: "render", value: function render() { var _props = this.props, children = _props.children, component = _props.component, props = _objectWithoutProperties(_props, ["children", "component"]); var Component = component || "div"; return _react2.default.createElement( Component, _extends({}, props, this.state), children ); } }]); return ReactHigherEventContainer; }(_react.Component); ReactHigherEventContainer.childContextTypes = _extends({}, _ReactHigherEventTypes.ContextTypes, _ReactHigherEventTypes.ProxyContextTypes); exports.default = ReactHigherEventContainer;
<reponame>peterobrien/edge-react-gui // @flow import { connect } from 'react-redux' import type { Dispatch, State } from '../../../../../ReduxTypes.js' // $FlowFixMe import UI_SELECTORS from '../../../../selectors' // $FlowFixMe import { updateRenameWalletInput } from '../../action' import WalletListRowOptions from './WalletListRowOptions.ui' const mapStateToProps = (state: State) => ({ wallets: UI_SELECTORS.getWallets(state), // $FlowFixMe archives: state.ui.wallets.archives }) const mapDispatchToProps = (dispatch: Dispatch) => ({ updateRenameWalletInput: input => dispatch(updateRenameWalletInput(input)) }) export default connect( mapStateToProps, mapDispatchToProps )(WalletListRowOptions)
#!/bin/sh set -e sudo mv /etc/apt/sources.list.d/pgdg* /tmp sudo apt-get update sudo apt-get install -y software-properties-common python-software-properties sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable sudo apt-get update # Disable postgresql since it draws ssl-cert that doesn't install cleanly # postgis postgresql-9.1 postgresql-client-9.1 postgresql-9.1-postgis-2.1 postgresql-9.1-postgis-2.1-scripts libpq-dev sudo apt-get install -y --allow-unauthenticated python-numpy libpng12-dev libjpeg-dev libgif-dev liblzma-dev libgeos-dev libcurl4-gnutls-dev libproj-dev libxml2-dev libexpat-dev libxerces-c-dev libnetcdf-dev netcdf-bin libpoppler-dev libpoppler-private-dev libsqlite3-dev gpsbabel swig libhdf4-alt-dev libhdf5-serial-dev libpodofo-dev poppler-utils libfreexl-dev unixodbc-dev libwebp-dev libepsilon-dev liblcms2-2 libpcre3-dev libcrypto++-dev libfyba-dev libmysqlclient-dev libogdi3.2-dev libcfitsio-dev openjdk-8-jdk libzstd1-dev ccache curl autoconf automake sqlite3 libspatialite-dev sudo apt-get install -y doxygen texlive-latex-base sudo apt-get install -y make sudo apt-get install -y python-dev python-pip sudo apt-get install -y g++ sudo apt-get install -y libssl-dev sudo apt-get install -y --allow-unauthenticated libsfcgal-dev sudo apt-get install -y --allow-unauthenticated fossil libgeotiff-dev libopenjp2-7-dev libcairo2-dev wget https://github.com/Esri/file-geodatabase-api/raw/master/FileGDB_API_1.5/FileGDB_API_1_5_64gcc51.tar.gz tar xzf FileGDB_API_1_5_64gcc51.tar.gz sudo cp FileGDB_API-64gcc51/lib/* /usr/lib sudo ldconfig FILE=clang+llvm-9.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz URL_ROOT=https://github.com/rouault/gdal_ci_tools/raw/master/${FILE} curl -Ls ${URL_ROOT}aa ${URL_ROOT}ab ${URL_ROOT}ac ${URL_ROOT}ad ${URL_ROOT}ae | tar xJf -
interface NotifyOptions { color?: string; zIndex?: number; message: string; context?: any; duration?: number; selector?: string; background?: string; safeAreaInsetTop?: boolean; } export default function Notify(options: NotifyOptions | string): void; export {};
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ListFamilyComponent } from './list-family.component'; describe('ListFamilyComponent', () => { let component: ListFamilyComponent; let fixture: ComponentFixture<ListFamilyComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ListFamilyComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ListFamilyComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
<filename>src/app/popups/book-options/book-options.component.ts<gh_stars>0 import { Component, Input, OnInit } from '@angular/core'; import { DataService } from 'src/app/services/data.service'; import { PopoverController } from '@ionic/angular'; import { ModalController } from '@ionic/angular'; import { AddBookPage } from 'src/app/pages/add-book/add-book.page'; @Component({ selector: 'app-book-options', templateUrl: './book-options.component.html', styleUrls: ['./book-options.component.scss'], }) export class BookOptionsComponent implements OnInit { @Input() book_id :string; constructor( private data : DataService, private popover : PopoverController, private modalController: ModalController, ) { } ngOnInit() { console.log(this.book_id) } async edit() { const modal = await this.modalController.create({ component: AddBookPage, componentProps: { 'data': { type : 'edit', book_id:this.book_id, } }, initialBreakpoint: 0.5, breakpoints: [0, 0.5, 1] }); this.popover.dismiss(); return await modal.present(); } delete(){ this.data.deleteBook(this.book_id).then(res => { console.log(res); this.popover.dismiss(); }).catch(error => { this.popover.dismiss(); console.log(error); }) } }
<reponame>openeuler-mirror/radiaTest import configparser from pathlib import Path from kombu import Exchange, Queue ini_path = "/etc/radiaTest/messenger.ini" def loads_config_ini(section, option): config_ini = Path(ini_path) cfg = configparser.ConfigParser() cfg.read(config_ini) if not cfg.get(section, option): return None return cfg.get(section, option) # Broker settings broker_url = loads_config_ini("celery", "BROKER_URL") broker_pool_limit = 10 imports = ('manage', ) worker_state_db = 'celeryservice/celerymain/celery_revokes_state_db' # Task结果储存配置 task_ignore_result = False # Using mysql to store state and results result_backend = loads_config_ini("celery", "RESULT_BACKEND") # 频次限制配置 worker_disable_rate_limits = True # task_default_rate_limit = '10000/m' (10000 times per minute) # 一般配置 task_serializer = 'json' result_serializer = 'json' accept_content = ['json'] timezone = 'Asia/Shanghai' enable_utc = True # task_compression = 'gzip' # 默认log配置 celeryd_log_file = 'celeryservice/celerymain/celery.log' # beat配置 beat_max_loop_interval = 3600 # rabbitMQ routing配置 # 队列属性定义 task_queues = ( Queue( 'queue_run_suite', exchange=Exchange( 'messenger_exchange', type='direct' ), routing_key='run_suite', ), Queue( 'queue_run_template', exchange=Exchange( 'messenger_exchange', type='direct' ), routing_key='run_template', ), Queue( 'queue_run_case', exchange=Exchange( 'messenger_exchange', type='direct' ), routing_key='run_case', ), Queue( 'queue_job_callback', exchange=Exchange( 'messenger_exchange', type='direct' ), routing_key='job_callback', ), Queue( 'queue_check_alive', exchange=Exchange( 'messenger_exchange', type='direct' ), routing_key='check_alive', ), ) task_default_exchange_type = 'direct' # server confg server_addr = loads_config_ini("server", "SERVER_ADDR") ca_verify = loads_config_ini("server", "CA_VERIFY") # messenger config messenger_ip = loads_config_ini("messenger", "MESSENGER_IP") messenger_listen = loads_config_ini("messenger", "MESSENGER_LISTEN") # pxe config pxe_ip = loads_config_ini("pxe", "PXE_IP") pxe_ssh_user = loads_config_ini("pxe", "PXE_SSH_USER") pxe_ssh_port = loads_config_ini("pxe", "PXE_SSH_PORT") pxe_pkey = loads_config_ini("pxe", "PRIVATE_KEY") # dhcp config dhcp_ip = loads_config_ini("dhcp", "DHCP_IP") # SSL file path(Warning: if you modify this item, # you need to change the corresponding build and deployment files) messenger_cert_path = loads_config_ini("messenger", "MESSENGER_CERT_PATH") server_cert_path = loads_config_ini("server", "SERVER_CERT_PATH")
let person = { name: 'John Doe', address: '123 Main St.', occupation: 'Software Engineer' };
#!/bin/sh # 20210217 takeru nakazato, hiromasaono # SPARQL query QUERY="PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX oboInOwl: <http://www.geneontology.org/formats/oboInOwl#> SELECT DISTINCT ?go ?rhea WHERE { FILTER(regex(?go, 'GO_')) ?go oboInOwl:hasDbXref ?rhea . FILTER(regex(?rhea, 'RHEA')) }" # curl -> format -> delete header curl -s -H "Accept: text/csv" --data-urlencode "query=$QUERY" https://integbio.jp/rdf/sparql | sed -e 's/\"//g; s/http:\/\/purl.obolibrary.org\/obo\///g; s/RHEA://g; s/,/\t/g' | sed -e '1d'
#include "virgl_vk.h" int toto() { }
import React from 'react' import { Row, Button, Autocomplete } from 'react-materialize' import { connect } from 'react-redux' import { clearArticles } from '../../store/articles' import { clearVideos } from '../../store/videos' import { fetchArtistAutocompletions, clearCompletions } from "../../store/autocomplete" const Follow = props => { const userId = auth.currentUser.uid const onSubmit = () => { const artistName = document.getElementById('artistName').value; clearAll(); }; const onAutocomplete = (value) => { clearAll(); }; const autocompleteArtists = (e, v) => { props.fetchArtistAutocompletions(v); }; const clearAll = () => { props.clearArticles(); props.clearVideos(); props.clearCompletions() }; return ( <div> <Row> <Row style={{marginBottom: 0}}> <h2 className="chune-feed-title">Follow an Artist</h2></Row> </Row> <Row className="chune-follow-element"> <Autocomplete title="Artist Name" id="artistName" onChange={autocompleteArtists} data={props.artistAutocompletions} limit={5} onAutocomplete={onAutocomplete} /> <Button onClick={onSubmit} className="chune-follow-button"> Follow </Button> </Row> </div> ) } const mapState = ({ artistAutocompletions }) => ({ artistAutocompletions }) const mapDispatch = dispatch => ({ clearArticles: () => dispatch(clearArticles()), clearVideos: () => dispatch(clearVideos()), fetchArtistAutocompletions: (name) => dispatch(fetchArtistAutocompletions(name)), clearCompletions: () => dispatch(clearCompletions()) }); export default connect(mapState, mapDispatch)(Follow)
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <hr> * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * This file has been modified by the OpenOLAT community. Changes are licensed * under the Apache 2.0 license as the original file. * <p> */ package org.olat.core.gui.control.winmgr; import org.json.JSONException; import org.json.JSONObject; import org.olat.core.logging.AssertException; /** * Description:<br> * Initial Date: 28.03.2006 <br> * * @author <NAME> */ public class CommandFactory { /** * tells the ajax-command interpreter to reload the main (=ajax's parent) window * @param redirectURL e.g. /olat/m/10001/ * @return the generated command */ public static Command createParentRedirectTo(String redirectURL) { JSONObject root = new JSONObject(); try { root.put("rurl", redirectURL); } catch (JSONException e) { throw new AssertException("wrong data put into json object", e); } Command c = new Command(3); c.setSubJSON(root); return c; } public static Command createNewWindowRedirectTo(String redirectURL) { JSONObject root = new JSONObject(); try { root.put("nwrurl", redirectURL); } catch (JSONException e) { throw new AssertException("wrong data put into json object", e); } Command c = new Command(8); c.setSubJSON(root); return c; } public static Command createNewWindowCancelRedirectTo() { JSONObject root = new JSONObject(); try { root.put("nwrurl", "close-window"); } catch (JSONException e) { throw new AssertException("wrong data put into json object", e); } Command c = new Command(8); c.setSubJSON(root); return c; } /** * command to replace sub tree of the dom with html-fragments and execute the script-tags of the fragments * @return */ public static Command createDirtyComponentsCommand() { return new Command(2); } /** * command to calculate the needed js lib to add, the needed css to include, and the needed css to hide/remove * @return */ public static Command createJSCSSCommand() { return new Command(7); } /** * - resets the js flag which is set when the user changes form data and is checked when an other link is clicked.(to prevent form data loss).<br> * @return the command */ public static Command createPrepareClientCommand(String businessControlPath) { JSONObject root = new JSONObject(); try { root.put("bc", businessControlPath==null? "":businessControlPath); } catch (JSONException e) { throw new AssertException("wrong data put into json object", e); } Command c = new Command(6); c.setSubJSON(root); return c; } /** * @param res * @return */ public static Command createParentRedirectForExternalResource(String redirectMapperURL) { JSONObject root = new JSONObject(); try { root.put("rurl", redirectMapperURL); } catch (JSONException e) { throw new AssertException("wrong data put into json object", e); } Command c = new Command(5); c.setSubJSON(root); return c; } public static Command reloadWindow() { String script = "try { window.location.reload(); } catch(e) { if(window.console) console.log(e) }"; return new JSCommand(script); } }
#!/usr/bin/env bash # Create a temp dir and clean it up on exit TEMPDIR=`mktemp -d -t consul-test.XXX` trap "rm -rf $TEMPDIR" EXIT HUP INT QUIT TERM # Build the Consul binary for the API tests echo "--> Building consul" go build -o $TEMPDIR/consul || exit 1 # Run the tests echo "--> Running tests" go list ./... | PATH=$TEMPDIR:$PATH xargs -n1 go test
#!/bin/sh eval $* exit 0
<filename>src/Jimdo/JimFlow/PrintTicketBundle/Resources/public/js/backend/PrinterForm.js $(function() { var $printerForm = $('#printer_edit_form'), $stateInput = $('#printer_edit_form').find('input[type=hidden].is-active'), state; $('#deactivate').on('click', function() { state = $stateInput.val(); $stateInput.val(state == 1 ? 0 : 1); $('#printer_edit_form').submit(); }); });
import asyncio import aioredis from ..config.app import Config from ..types import IO def init_pool(loop: asyncio.AbstractEventLoop, config: Config) -> IO[aioredis.commands.Redis]: c = config.redis address = (c.host, c.port) pool = aioredis.create_redis_pool( address=address, db=c.db, password=<PASSWORD>, ssl=None, encoding=None, minsize=c.min_connections, maxsize=c.max_connections, loop=loop ) return pool
<filename>SampleBackend/src/main/java/test/backend/www/model/hotelbeds/basic/annotation/validators/ValidReviewFilterValidator.java /** * Autogenerated code by SdkModelGenerator. * Do not edit. Any modification on this file will be removed automatically after project build * */ package test.backend.www.model.hotelbeds.basic.annotation.validators; import java.util.List; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import test.backend.www.model.hotelbeds.basic.model.ReviewFilter; public class ValidReviewFilterValidator implements ConstraintValidator<ValidReviewFilter, List<ReviewFilter>> { @Override public void initialize(ValidReviewFilter constraintAnnotation) { // TODO Auto-generated method stub } @Override public boolean isValid(List<ReviewFilter> value, ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); boolean result = true; if (value != null) { for (ReviewFilter review : value) { if (review.getMaxRate() == null && review.getMinRate() == null) { context.buildConstraintViolationWithTemplate( "{com.hotelbeds.distribution.hotel_api_webapp.webapp.api.model.ReviewFilter.rates.null.message}").addConstraintViolation(); result = false; } else if (result && review.getMaxRate() != null && review.getMinRate() != null && (review.getMaxRate().compareTo(review.getMinRate()) < 0)) { context.buildConstraintViolationWithTemplate( "{com.hotelbeds.distribution.hotel_api_webapp.webapp.api.model.ReviewFilter.rates.value.message}").addConstraintViolation(); result = false; } if (review.getMinReviewCount() != null && review.getMinReviewCount() == 0) { context.buildConstraintViolationWithTemplate( "{com.hotelbeds.distribution.hotel_api_webapp.webapp.api.model.ReviewFilter.reviewCounts.zero.message}") .addConstraintViolation(); result = false; } } } return result; } }
from flask_script import Manager from flask import Flask from models import Task, TaskManager app = Flask(__name__) manager = Manager(app) @manager.command def list_tasks(): task_manager = TaskManager() # Assuming TaskManager class exists tasks = task_manager.get_all_tasks() # Assuming get_all_tasks() method returns all tasks for task in tasks: print(f"Task ID: {task.id}, Title: {task.title}, Status: {task.status}")
def find_second_smallest(arr): smallest = arr[0] second_smallest = None for i in range(1, len(arr)): if arr[i] < smallest: second_smallest = smallest smallest = arr[i] return second_smallest arr = [9, 7, 4, 8, 2] second_smallest = find_second_smallest(arr) print("Second smallest number is:", second_smallest) # Output is 7
package bluegrass.blues.config.definition; /** * * @author gcaseres */ public class RootNode extends CompositeNode { public RootNode() { } @Override public String getPath() { return "root"; } /* @Override protected void validateName(ConfigurationNode configNode) throws NodeValidationException { Root nodes have not name validation. } */ }
<reponame>Mac15001900/almuCards let SceneGallery = new Phaser.Class({ Extends: Phaser.Scene, initialize: function SceneGallery() { Phaser.Scene.call(this, { key: 'SceneGallery' }); }, preload: function () { console.log("Preload in gallery"); //ładowanie obrazków tła this.load.image('cardFire', 'assets/card_fire.png'); this.load.image('cardForest', 'assets/card_forest.png'); this.load.image('cardWater', 'assets/card_water.png'); this.cards = []; //tworzenie listy wszystkich kart w grze for (let card in cardData) this.cards = this.cards.concat(DeckBank.createCardsFromPrototype(cardData[card])); let imagesToLoad = DeckBank.getImages(this.cards); for (let image in imagesToLoad) //ładowanie obrazków kart { this.load.image(imagesToLoad[image], 'assets/cardImages/' + imagesToLoad[image] + '.png'); } this.load.image('cardReverse', 'assets/card_reverse.png'); this.load.image('buttonLeft', 'assets/button_left.png'); //obrazki przycisków this.load.image('buttonRight', 'assets/button_right.png'); this.page = 0; }, layout: { FIRST_CARD_X: 175, FIRST_CARD_Y: 120, CARD_SCALE: 0.15, CARDS_H_SPACING: 120, CARDS_V_SPACING: 200, CARDS_PER_PAGE: 32, BUTTON_LEFT_X: 50, BUTTOR_LEFT_Y: 430, BUTTON_RIGHT_X: 1125, BUTTOR_RIGHT_Y: 430, BIG_CARD_X: 600, BIG_CARD_Y: 400, }, create: function () { console.log('Gallery open'); this.buttonLeft = new Button(this, "galleryLeft", this.layout.BUTTON_LEFT_X, this.layout.BUTTOR_LEFT_Y, 0.8, "buttonLeft", null); this.buttonRight = new Button(this, "galleryRight", this.layout.BUTTON_RIGHT_X, this.layout.BUTTOR_RIGHT_Y, 0.8, "buttonRight", null); this.createPage(); }, createPage: function () { for (let card in this.currentCards) this.currentCards[card].visual.removeAll(true); this.currentCards = []; for (let i = this.page * this.layout.CARDS_PER_PAGE; i < Math.min(this.cards.length, (this.page + 1) * this.layout.CARDS_PER_PAGE); i++) { let j = i - this.page * this.layout.CARDS_PER_PAGE; let newCard = new Card(this, this.cards[i], this.layout.FIRST_CARD_X + (j % 8) * this.layout.CARDS_H_SPACING, this.layout.FIRST_CARD_Y + Math.floor(j / 8) * this.layout.CARDS_V_SPACING, this.layout.CARD_SCALE, null); newCard.reverseCard(true, false); this.currentCards.push(newCard); } if (this.page === 0) this.buttonLeft.visual.setVisible(false); else this.buttonLeft.visual.setVisible(true); if ((this.page + 1) * this.layout.CARDS_PER_PAGE >= this.cards.length) this.buttonRight.visual.setVisible(false); else this.buttonRight.visual.setVisible(true); } });
public static List<List<Integer>> getSubsetsWithSum(int[] arr, int sum) { // list to hold the subsets List<List<Integer>> subsets = new ArrayList<>(); // compute subsets using backtracking recursion getSubsetsWithSum(arr, sum, 0, 0, new ArrayList<>(), subsets); return subsets; } public static void getSubsetsWithSum(int[] arr, int sum, int startIndex, int currSum, List<Integer> currSubset, List<List<Integer>> allSubsets) { if (currSum == sum) { allSubsets.add(new ArrayList<Integer>(currSubset)); return; } // loop over elements starting from startIndex for (int i = startIndex; i < arr.length; i++) { // subsets should not have duplicates, // so use arr[i - 1] to avoid adding duplicate elements if (i > 0 && arr[i] == arr[i - 1]) { continue; } currSubset.add(arr[i]); getSubsetsWithSum(arr, sum, i + 1, currSum + arr[i], currSubset, allSubsets); currSubset.remove(currSubset.size() - 1); } }
package org.insightcentre.nlp.saffron.authors; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.insightcentre.nlp.saffron.DefaultSaffronListener; import org.insightcentre.nlp.saffron.SaffronListener; import org.insightcentre.nlp.saffron.data.Author; import org.insightcentre.nlp.saffron.data.CollectionCorpus; import org.insightcentre.nlp.saffron.data.Corpus; import org.insightcentre.nlp.saffron.data.Document; /** * * @author <NAME> &lt;<EMAIL>&gt; */ public class Consolidate { private static void badOptions(OptionParser p, String message) throws IOException { System.err.println("Error: " + message); p.printHelpOn(System.err); System.exit(-1); } public static void main(String[] args) { try { // Parse command line arguments final OptionParser p = new OptionParser() {{ accepts("t", "The input text corpus").withRequiredArg().ofType(File.class); accepts("o", "The new output corpus").withRequiredArg().ofType(File.class); }}; final OptionSet os; try { os = p.parse(args); } catch(Exception x) { badOptions(p, x.getMessage()); return; } final File corpusFile = (File)os.valueOf("t"); if(corpusFile == null || !corpusFile.exists()) { badOptions(p, "Corpus does not exist"); } File output = (File)os.valueOf("o"); if(output == null) { output = corpusFile; } ObjectMapper mapper = new ObjectMapper(); Corpus corpus = mapper.readValue(corpusFile, CollectionCorpus.class); Set<Author> authors = extractAuthors(corpus); Map<Author, Set<Author>> consolidation = new ConsolidateAuthors().consolidate(authors); Corpus newCorpus = applyConsolidation(corpus, consolidation, new DefaultSaffronListener()); mapper.writerWithDefaultPrettyPrinter().writeValue(output, corpus); } catch(Throwable t) { t.printStackTrace(); System.exit(-1); } } public static Set<Author> extractAuthors(Corpus corpus) { return extractAuthors(corpus, new DefaultSaffronListener()); } public static Set<Author> extractAuthors(Corpus corpus, SaffronListener log) { Set<Author> authors = new HashSet<Author>(); for(Document doc : corpus.getDocuments()) { for(Author author : doc.getAuthors()) { authors.add(author); } } return authors; } /** * Apply the consolidation * @param corpus The corpus to consolidate over * @param consolidation The author consolidation map (i.e., a map from a canonical author to all the variants in the corpus) * @param log The logger * @return The consolidated corpus */ public static Corpus applyConsolidation(Corpus corpus, Map<Author, Set<Author>> consolidation, SaffronListener log) { Map<Author, Author> rmap = new HashMap<>(); for(Map.Entry<Author, Set<Author>> e1 : consolidation.entrySet()) { for(Author a1 : e1.getValue()) { rmap.put(a1, e1.getKey()); } } Collection<Document> updateDocuments = new AbstractCollection<Document>() { final Iterator<Document> iter = corpus.getDocuments().iterator(); @Override public Iterator<Document> iterator() { return new Iterator<Document>() { @Override public Document next() { Document document = iter.next(); List<Author> authors2 = new ArrayList<>(); for (Author a : document.authors) { if(!rmap.containsKey(a)) throw new RuntimeException("Author not found in consolidation"); authors2.add(rmap.get(a)); } Document doc2 = new Document(document.file, document.id, document.url, document.name, document.mimeType, authors2, document.metadata, document.getContents(), document.date); return doc2; } @Override public boolean hasNext() { return iter.hasNext(); } }; } @Override public int size() { return corpus.size(); } }; return new CollectionCorpus(new ArrayList<>(updateDocuments)); } }
#!/bin/bash # takes an argument like v1, v2, or v3 # finds the pod IP of the recommendation version # curls the found IP with verbose output export REC_IP=`oc get pod -n user1-tutorial -l "app=recommendation,version=v2" -o jsonpath='{.items[0].status.podIP}'` oc exec -n user1-tutorial $(oc get pod -n user1-tutorial -l app=curl -o name | cut -f2 -d/) -- curl -sv $REC_IP:8080
package com.heima.model.behavior.pojos; import lombok.Data; import lombok.Getter; import org.apache.ibatis.type.Alias; import java.util.Date; @Data public class ApBehaviorEntry { private Integer id; private Short type; private Integer entryId; private Date createdTime; public String burst; @Alias("ApBehaviorEntryEnumType") public enum Type{ USER((short)1),EQUIPMENT((short)0); @Getter short code; Type(short code){ this.code = code; } } public boolean isUser(){ if(this.getType()!=null&&this.getType()== Type.USER.getCode()){ return true; } return false; } }
export const FormItems = [ { formType: 'input', disabled: false, isRequired: false, key: 'channelname', label: 'input', colSpan: 8, placeholder: 'input', hasFeedback: true, }, { formType: 'inputNumber', disabled: false, isRequired: false, key: 'inputNumber', label: 'inputNumber', placeholder: 'inputNumber', colSpan: 8, hasFeedback: true, }, { formType: 'inputMoney', disabled: false, isRequired: false, key: 'inputMoney', label: 'inputMoney', placeholder: 'inputMoney', colSpan: 8, hasFeedback: true, }, { formType: 'inputPhone', disabled: false, isRequired: false, key: 'inputPhone', label: 'inputPhone', placeholder: 'inputPhone', colSpan: 8, hasFeedback: true, }, { formType: 'select', disabled: false, isRequired: false, key: 'select', label: 'select', placeholder: 'select', selectOptions: [ { key: 'select1', value: 'select1', }, { key: 'select2', value: 'select2', }, ], popupContainer: 'scorllArea', hasFeedback: true, }, { formType: 'select', disabled: false, isRequired: false, multiple: true, key: 'selectMultiple', label: 'selectMultiple', placeholder: 'selectMultiple', selectOptions: [ { key: 'select1', value: 'select1', }, { key: 'select2', value: 'select2', }, ], popupContainer: 'scorllArea', hasFeedback: true, }, { formType: 'selectDynamic', disabled: false, isRequired: false, multiple: true, key: 'selectMultipleDynamic', label: 'selectMultipleDynamic', placeholder: 'selectMultipleDynamic', dictionaryKey: 'selectMultipleDynamic', fetchUrl: '/api/selectLists2', // initialValue: '其他', popupContainer: 'scorllArea', hasFeedback: true, }, { formType: 'selectDynamic', disabled: false, isRequired: false, key: 'selectDynamic', label: 'selectDynamic', placeholder: 'selectDynamic', dictionaryKey: 'selectDynamic1', fetchUrl: '/api/selectLists2', // initialValue: '其他', popupContainer: 'scorllArea', hasFeedback: true, }, { formType: 'selectGroup', key: 'selectGroup', label: 'selectGroup', placeholder: 'selectGroup', selectOptions: [ { label: 'selectGroup1', key: 'selectGroup1', childrenOptions: [ { key: 'selectGroup1_1', value: 'selectGroup1_1', }, { key: 'selectGroup1_2', value: 'selectGroup1_2', }, ], }, { label: 'selectGroup2', key: 'selectGroup2', childrenOptions: [ { key: 'selectGroup2_1', value: 'selectGroup2_1', }, { key: 'selectGroup2_2 ', value: 'selectGroup2_2', }, ], }, ], popupContainer: 'scorllArea', hasFeedback: true, }, { formType: 'selectDynamicGroup', multiple: true, disabled: false, isRequired: false, key: 'selectGroupDynamic', label: 'selectGroupDynamic', placeholder: 'selectDynamic', dictionaryKey: 'selectGroupDynamic', fetchUrl: '/api/selectGroupLists', // initialValue: '其他', popupContainer: 'scorllArea', hasFeedback: true, }, { formType: 'datePicker', showTime: false, disabled: false, isRequired: false, key: 'datePicker', label: 'datePicker', placeholder: 'datePicker', popupContainer: 'scorllArea', }, { formType: 'datePicker', showTime: true, disabled: false, isRequired: false, key: 'datePickerShowTime', label: 'datePickerShowTime', placeholder: 'datePicker', popupContainer: 'scorllArea', }, { formType: 'rangePicker', disabled: false, isRequired: false, key: 'rangePicker', label: 'rangePicker', popupContainer: 'scorllArea', }, { formType: 'rangePicker', showTime: true, disabled: false, isRequired: false, key: 'rangePickerShowTime', label: 'rangePickerShowTime', popupContainer: 'scorllArea', }, { formType: 'monthPicker', disabled: false, isRequired: false, key: 'monthPicker', label: 'monthPicker', popupContainer: 'scorllArea', }, { formType: 'timePicker', disabled: false, isRequired: false, key: 'timePicker', label: 'timePicker', popupContainer: 'scorllArea', }, { formType: 'checkboxGroup', disabled: false, isRequired: false, itemColSpan: 4, options: [ { label: 'Apple', value: 'Apple' }, { label: 'Pear', value: 'Pear' }, { label: 'Orange', value: 'Orange' }, { label: 'Apple1', value: 'Apple1' }, { label: 'Pear1', value: 'Pear1' }, { label: 'Orange1', value: 'Orange1' }, { label: 'Orange2', value: 'Orange3' }, ], key: 'checkbox', label: 'checkbox', colSpan: 24, // popupContainer: 'scorllArea' }, { formType: 'radioGroup', disabled: false, isRequired: false, itemColSpan: 4, options: [ { label: 'Apple', value: 'Apple' }, { label: 'Pear', value: 'Pear' }, { label: 'Orange', value: 'Orange' }, { label: 'Apple1', value: 'Apple1' }, { label: 'Pear1', value: 'Pear1' }, { label: 'Orange1', value: 'Orange1' }, { label: 'Orange2', value: 'Orange3' }, ], key: 'radioGroup', label: 'radioGroup', colSpan: 24, // popupContainer: 'scorllArea' }, { formType: 'upload', disabled: false, isRequired: false, key: 'upload1', label: 'upload-listType-text', placeholder: 'upload1', action: 'http://127.0.0.1:7001/form', multiple: true, acceptType: '*', // .jpg,.png,.pdf,.mp4,.gif,.word listType: 'text', // 1:text 2:picture 3:picture-card maxFileSize: 10, // 单位是M maxFileCounts: 3, colSpan: 24, }, { formType: 'upload', disabled: false, isRequired: false, key: 'upload3', label: 'upload-listType-picture', placeholder: 'upload-listType-picture', action: 'http://127.0.0.1:7001/form', multiple: true, acceptType: '*', // .jpg,.png,.pdf,.mp4,.gif,.word listType: 'picture', // 1:text 2:picture 3:picture-card maxFileSize: 10, // 单位是M maxFileCounts: 3, colSpan: 24, initialValue:[{ uid: -1, name: 'xxx.png', status: 'done', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', thumbUrl:'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' }] }, { formType: 'upload', disabled: false, isRequired: false, key: 'upload2', label: 'upload-listType-picture-card', placeholder: 'upload-listType-picture-card', action: 'http://127.0.0.1:7001/form', multiple: true, acceptType: '*', // .jpg,.png,.pdf,.mp4,.gif,.word listType: 'picture-card', // 1:text 2:picture 3:picture-card maxFileSize: 10, // 单位是M maxFileCounts: 5, colSpan: 24, }, { formType: 'textArea', // disabled: false, // isRequired: false, key: 'textArea', label: 'textArea', colSpan: 24, // autosize: { minRows: 3, maxRows: 7 } // placeholder: 'inputPhone' }, ];
<filename>imageeditor/src/main/java/com/createchance/imageeditor/shaders/AngularTransShader.java package com.createchance.imageeditor.shaders; import android.opengl.GLES20; /** * Angular transition shader. * * @author createchance * @date 2018/12/30 */ public class AngularTransShader extends TransitionMainFragmentShader { private static final String TAG = "AngularTransShader"; private final String TRANS_SHADER = "angular.glsl"; private final String U_START_ANGLE = "startingAngle"; private int mUStartAngle; public AngularTransShader() { initShader(new String[]{TRANSITION_FOLDER + BASE_SHADER, TRANSITION_FOLDER + TRANS_SHADER}, GLES20.GL_FRAGMENT_SHADER); } @Override public void initLocation(int programId) { super.initLocation(programId); mUStartAngle = GLES20.glGetUniformLocation(programId, U_START_ANGLE); loadLocation(programId); } public void setUStartAngular(float startAngular) { GLES20.glUniform1f(mUStartAngle, startAngular); } }
//package ru.job4j.tracker; // //import org.junit.Test; // //import java.io.ByteArrayOutputStream; //import java.io.PrintStream; //import java.util.StringJoiner; // //import static org.hamcrest.core.Is.is; //import static org.junit.Assert.assertThat; // // //public class StartUITest { // // @Test // public void whenUserAddItemThenTrackerHasNewItemWithSameName() { // Tracker tracker = new Tracker(); // // создаём Tracker // Input input = new StubInput(new String[]{"0", "test name", "desc", "6"}); // //создаём StubInput с последовательностью действий // new StartUI(input, tracker).init(); // // создаём StartUI и вызываем метод init() // assertThat(tracker.findAll()[0].getName(), is("test name")); // // проверяем, что нулевой элемент массива в трекере содержит имя, введённое при эмуляции. // } // // @Test // public void whenUpdateThenTrackerHasUpdatedValue() { // // создаём Tracker // Tracker tracker = new Tracker(); // //Напрямую добавляем заявку // Item item = new Item("test name", "desc", 1234L); // tracker.add(item); // //создаём StubInput с последовательностью действий(производим замену заявки) // String[] sequence = new String[]{"2", item.getId(), "заменили заявку", "test replace", "6"}; // StubInput input = new StubInput(sequence); // // создаём StartUI и вызываем метод init() // new StartUI(input, tracker).init(); // // проверяем, что нулевой элемент массива в трекере содержит имя, введённое при эмуляции. // assertThat(tracker.findById(item.getId()).getName(), is("test replace")); // } // // @Test // public void deleteItemTest() { // Tracker tracker = new Tracker(); // Item item = tracker.add(new Item("wantDeleteItem", "desc", 1235L)); // Input input = new StubInput(new String[]{"3", item.getId(), "6"}); // new StartUI(input, tracker).init(); // assertThat(tracker.delete(item.getId()), is(false)); // } // // @Test // public void searchByIDItemTest() { // Tracker tracker = new Tracker(); // Item item = tracker.add(new Item("wantFind", "desc", 12356L)); // Input input = new StubInput(new String[]{"4", item.getId(), "6"}); // new StartUI(input, tracker).init(); // assertThat(tracker.findById(item.getId()).getName(), is(item.getName())); // } // // @Test // public void whenPrtMenu() { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // PrintStream def = System.out; // System.setOut(new PrintStream(out)); // StubInput input = new StubInput( // new String[] {"0"} // ); // StubAction action = new StubAction(); // new StartUI(new ConsoleInput(), new Tracker()).init(); // String expect = new StringJoiner(System.lineSeparator(), "", System.lineSeparator()) // .add("Menu.") // .add("0. Stub action") // .toString(); // assertThat(new String(out.toByteArray()), is(expect)); // System.setOut(def); // } // @Test // public void whenExit() { // StubInput input = new StubInput( // new String[] {"0"} // ); // StubAction action = new StubAction(); // new StartUI().init(input, new Tracker(), new UserAction[] { action }); // assertThat(action.isCall(), is(true)); // } // //} // //
#!/bin/sh set -e set -u set -o pipefail if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy # frameworks to, so exit 0 (signalling the script phase was successful). exit 0 fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/InAppMachine/InAppMachine.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/InAppMachine/InAppMachine.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
def solve_problem(): count = 0 sunday_cycle = 6 # First Sunday in 1901 for year in range(1901, 2001): if sunday_cycle == 0: sunday_cycle = 7 if is_leap_year(year): count += get_sundays(sunday_cycle, True) sunday_cycle -= 2 else: count += get_sundays(sunday_cycle, False) sunday_cycle -= 1 # Adjust for non-leap year return count
from functools import wraps from framework import UseInterceptors, UsePipes, ValidationPipe def validate_input(validation_schema): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): # Apply UseInterceptors and UsePipes to utilize ValidationPipe for input validation @UseInterceptors(ValidationPipe) @UsePipes(ValidationPipe) def validate_input_data(data): return data # Validate the input data using the provided validation_schema validated_data = validate_input_data(validation_schema) # Call the original API endpoint handler function with the validated input data return func(validated_data, *args, **kwargs) return wrapper return decorator
# Biggest – big3.sh echo -n "Give value for A B and C: " read a b c if [ $a -gt $b -a $a -gt $c ] then echo "A is the Biggest number" elif [ $b -gt $c ] then echo "B is the Biggest number" else echo "C is the Biggest number" fi
package app.javachat.Garage; import app.javachat.Logger.Log; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public interface Sala { /** * Este método crear una nueva connexion para poder realizar operaciones con el servidor. * * @return socket creado */ static Socket crearConnexionConServer(String serverIp, int PORT) { Socket server = null; try { Log.show("Creando connexion con el server " + serverIp + ":" + PORT); server = new Socket(serverIp, PORT); Log.show("Servidor creado correctamente"); } catch (IOException e) { Log.error("Ha habido un fallo al crear la conexion. " + e.getMessage()); } return server; } /** * Este metodo crear una nueva conexion para poder leer msg del server. * * @return serverSocket */ static ServerSocket crearConnexionPropia(int PORT) { ServerSocket server = null; try { Log.show("Abriendo server en puerto " + PORT); server = new ServerSocket(PORT); } catch (IOException e) { Log.error(e.getMessage()); } return server; } /** * Este metodo cierra el socket Server atual. */ static void cerrarConnexionSocket(Socket server) { try { //Si el server no es nulo, cierra la connexion. if (server != null) server.close(); Log.show("Conexion cerrada."); } catch (IOException e) { Log.error(e.getMessage()); } } static void cerrarConnexionSocket(ServerSocket server) { try { //Si el server no es nulo, cierra la connexion. if (server != null) server.close(); Log.show("Server cerrado."); } catch (IOException e) { Log.error(e.getMessage()); } } }
const main = async () => { const domainContractFactory = await hre.ethers.getContractFactory('WaifuGen'); const domainContract = await domainContractFactory.deploy( 'WaifuGen', 'WAIFUGEN', 'ipfs://bafybeigv5iojhntwdswb4zx4oyunncqjpcxwm6jlyf4xqakft5nnvyekgm/' ); await domainContract.deployed(); console.log("Contract deployed to:", domainContract.address); } const runMain = async () => { try { await main(); process.exit(0); } catch (error) { console.log(error); process.exit(1); } }; runMain();
<filename>changingInlineStyles/inlineStyles.js<gh_stars>0 var currentPos = 0; var intervalHandle; function beginAnimate() { document.getElementById("join").style.position = "absolute"; document.getElementById("join").style.left = "0px"; document.getElementById("join").style.top = "100px"; // cause the animateBox function to be called intervalHandle = setInterval(animateBox, 50); } function animateBox() { // set new position currentPos += 5; document.getElementById("join").style.left = currentPos + "px"; // if (currentPos > 900) { // clear interval clearInterval(intervalHandle); // reset custom inline styles document.getElementById("join").style.position = ""; document.getElementById("join").style.left = ""; document.getElementById("join").style.top = ""; } } window.onload = function() { setTimeout(beginAnimate, 5000); };
#!/bin/bash export JENACONNECTIFIER_INSTALL_DIR=/Users/szd2013/git/vivo-import-data/vivo-import-data export HARVEST_NAME=delete-profile export DATE=`date +%Y-%m-%d'T'%T` export JENACONNECTIFIER_DIR=$JENACONNECTIFIER_INSTALL_DIR/src/main/resources/delete-profile # Add harvester binaries to path for execution # The tools within this script refer to binaries supplied within the harvester # Since they can be located in another directory their path should be # included within the classpath and the path environment variables. export PATH=$PATH:$JENACONNECTIFIER_INSTALL_DIR/bin export CLASSPATH=$CLASSPATH:$JENACONNECTIFIER_INSTALL_DIR/target/vivo-import-data-0.0.1-SNAPSHOT-jar-with-dependencies.jar:$JENACONNECTIFIER_INSTALL_DIR/lib/*.jar export CLASSPATH=$CLASSPATH:$JENACONNECTIFIER_INSTALL_DIR/lib/classes12.jar # Exit on first error # The -e flag prevents the script from continuing even though a tool fails. # Continuing after a tool failure is undesirable since the harvested # data could be rendered corrupted and incompatible. set -e ## Do not run if a handshake file exists if [ ! -f "handshake" ]; then touch handshake echo "Full Logging in $HARVEST_NAME.$DATE.log" if [ ! -d logs ]; then mkdir logs fi cd logs touch $HARVEST_NAME.$DATE.log ln -sf $HARVEST_NAME.$DATE.log $HARVEST_NAME.latest.log cd .. delete-profile echo 'Fetch completed successfully' rm handshake fi ## === Send email alerts if exceptions are found === export JENACONNECTIFIER_DIR=$JENACONNECTIFIER_INSTALL_DIR/src/main/resources/delete-profile EXCEPTION=$(grep Exception $JENACONNECTIFIER_DIR/logs/delete-profile.latest.log) if [ "$EXCEPTION" != "" ]; then HOST="{your host}" echo "$EXCEPTION" | mail -s $HOST": Exceptions found in "$HARVEST_NAME.$DATE.log {your email address} fi
import time def timer_every_hour(): start_time = time.time() end_time = start_time + 86400 # 86400 = # of seconds in 24 hours while time.time() < end_time: func() time.sleep(3600) # 3600 = # of seconds in 1 hour
package mezz.jei.config; import net.minecraftforge.fml.common.eventhandler.Event; public class BookmarkOverlayToggleEvent extends Event { private final boolean bookmarkOverlayEnabled; public BookmarkOverlayToggleEvent(boolean bookmarkOverlayEnabled) { this.bookmarkOverlayEnabled = bookmarkOverlayEnabled; } public boolean isBookmarkOverlayEnabled() { return bookmarkOverlayEnabled; } }
var _quantizer_test_8cpp = [ [ "MinMaxRange", "_quantizer_test_8cpp.xhtml#a997e96288bdb106c922202e3f33d5d7b", null ], [ "MinMaxRangeMap", "_quantizer_test_8cpp.xhtml#a061aafb62b3769f55369845c3990ec7a", null ], [ "MinMaxRanges", "_quantizer_test_8cpp.xhtml#ac757baefa4b72b54c38f713f86418f8a", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a8baf97065d802063eb9bcdd1a066dc86", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a9cec088786b209989fe9e04e1be9636d", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a7db6a78bb6eedbea7f0525f1fe59de28", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a2df3b432de50a9b9e8b486aa53e11cc5", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a3dd219b394b8186d1849ee595193268d", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a52e948b4bffc16a3933d812dbc384833", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#abf109580225cb949565c8223bceadd5d", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#acbf871a6ec0726bfe2746e761a278108", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a32068047cc7b37f1bed1830508891526", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a6c08ed3db08fcfca0592c62cd6080b76", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#ab182b6a1d2348a86472001c92586717a", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#adf59f87645d301e9b56dd70aed350e54", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#ae91bc23bf56bb5f9c2e0ddb1fc7be75e", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#aa6281ed3090b74167170c8f692688de5", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#ad432424d97021ae6c81e38130b1ec5d6", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a6e97e093453fc053a5c82386927a0d6c", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a881ab05533f917737509402730668e4a", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a69dd8c7608ff0935a247f3aa07f98212", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#aa117e0112fdc02a7a011cfb39dc596ab", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a9827adb2cf787460578999e0484568fa", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a1db5d836b83fc71602a7993616de5b42", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a891abdb9079715cbcf85792e2b450652", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#abd033569519fec65077ea983f6c75a9d", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a46d045b35ad6b8c2ffe0c04684f97779", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a7e94e9ab356805c498f5fc2fba87e4e6", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a4734542212b5811d0511ea6b16f35168", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#add22da50dd35a100548dde4c57ae89d1", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a9a6bc66017eb7c132fd6e13ff0dcb540", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#aa78ce2bbe65cae8f3d60839467dbfc83", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#aaa86b6903e41d2d2828e00b32f872375", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a369051e180246c66b20c93de5fecee8c", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#ae3af95ea62252012cf93a98167afef64", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#ab83f837cdd5bfcff537dae72a96d6fc8", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#add47ebcd4a59304a25c71996aea2b38b", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a9258afcd4c6d8443c9130d8c9bf26442", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a23a4f3c387a2a3a035e97764e34277c6", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a102f37a09de1b0d4d78740a3c12902bf", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a5f9c6094ae666c8e14907307d0481fac", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#aec7cf8e3927ee7d24f8b19d206ce3e84", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a733ef16d4eaaf8cce338320fa042f526", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a5e66fe270ca921faeecd26735192d08b", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#aec82007c45313f59d24b304e35b3db6c", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a77cba79eef903eb3d758b4edbcc626ef", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a46f313720b601ca97a9c2a5158814bff", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a728153b62fa66e6ed1243e09144bfe8c", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a898305dc4cdb78a5fbed481250f6cd35", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a94eb3bdf0e1c8c748c2e29dce048ace4", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#ab242670b85e047e79bb297cdb192cc93", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a061891029598224370aae4cd18b78406", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a4d4386cbb19dbc551e423992ecdd0d61", null ], [ "BOOST_AUTO_TEST_CASE", "_quantizer_test_8cpp.xhtml#a8c09fbb75d2c2dea48926a540fc5cce9", null ], [ "CompleteLeakyReluNetwork", "_quantizer_test_8cpp.xhtml#a6fff4b4b1b5d4d37c9cf53d0e31c05dd", null ], [ "CreateNetworkWithActivationLayer", "_quantizer_test_8cpp.xhtml#a5fbc1479db5f4ff70a750cf02d58971b", null ], [ "CreateNetworkWithFullyConnectedLayer", "_quantizer_test_8cpp.xhtml#aad4b8cb9a4d882a48bc21510f0d1a938", null ], [ "CreateNetworkWithInputOutputLayers", "_quantizer_test_8cpp.xhtml#aa9c6c1a7b5380a99a536f4740f87dd59", null ], [ "CreateNetworkWithSoftmaxLayer", "_quantizer_test_8cpp.xhtml#a9c91b774c3089c55df77cc3a42da72de", null ], [ "CreateStartOfLeakyReluNetwork", "_quantizer_test_8cpp.xhtml#a120c131df35d78b3a56cb0f07decaf35", null ], [ "GetInputTensorInfo", "_quantizer_test_8cpp.xhtml#ae52296dff1f4879854f320d59f92574e", null ], [ "PreserveTypeTestImpl", "_quantizer_test_8cpp.xhtml#abe34cf42d7c8515ecd15d11f4aeb399c", null ], [ "SetupQuantize", "_quantizer_test_8cpp.xhtml#a52cbff9d344ba4a1fe01d4da2c1f7ba2", null ], [ "TestQuantizeConvolution2d", "_quantizer_test_8cpp.xhtml#a14cfd39cfc30682fa821ade3dd298426", null ], [ "TestQuantizeDepthwiseConvolution2d", "_quantizer_test_8cpp.xhtml#a5abbe8a9ee003c1379a921dbe2745b81", null ], [ "TestQuantizeTransposeConvolution2d", "_quantizer_test_8cpp.xhtml#afa7a0a639e2772ff2ced67d77be810c0", null ], [ "ValidateFullyConnectedLayer", "_quantizer_test_8cpp.xhtml#a245661fc96c9c4a9b898e1d98c8c6962", null ], [ "VisitLayersTopologically", "_quantizer_test_8cpp.xhtml#a6482907b4c57873e197324f5cb66fd4d", null ], [ "g_AsymmS8QuantizationBase", "_quantizer_test_8cpp.xhtml#a09bdfaa922d72ce0d9ec014dfa8f8c95", null ], [ "g_AsymmU8QuantizationBase", "_quantizer_test_8cpp.xhtml#a19994153bdbd7710f0af3973403bc4cc", null ], [ "g_SymmS16QuantizationBase", "_quantizer_test_8cpp.xhtml#a1465480794787d2278d3f0d2e6d887b4", null ], [ "g_SymmS8QuantizationBase", "_quantizer_test_8cpp.xhtml#acd7f8820d124166a38c95bc8ad38811b", null ], [ "g_TestTolerance", "_quantizer_test_8cpp.xhtml#a1a9a6dea47de10df8e3c76dd45df56fb", null ] ];
package com.SentimentAnalysis.controller; import com.SentimentAnalysis.services.SentimentAnalysis; import com.SentimentAnalysis.data.PasswordRepository; import com.SentimentAnalysis.data.Review; import com.SentimentAnalysis.data.ReviewRepository; import com.SentimentAnalysis.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import javax.transaction.Transactional; import javax.validation.Valid; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @CrossOrigin(maxAge = 3600) @RestController @RequestMapping("/sentimentAnalysis") public class ReviewController { @Autowired ReviewRepository reviewRepository; @Autowired PasswordRepository passwordRepository; /** * Saves the sent review in the collection * * @param review A review of type @{@link ReviewModel} to be saved in the collection * @return HttpStatus.OK if the review was saved */ @PostMapping("/reviews/{password}") public ResponseEntity<?> saveReview(@Valid @RequestBody ReviewModel review, @PathVariable String password) { if (passwordRepository.existsByPassword(password)) { if (review.getReviewText().length() > 10000) { return new ResponseEntity<>(new ResponseMessage("Text is too long!"), HttpStatus.BAD_REQUEST); } Language language = getLanguage(review.getReviewText()); if (language.getConfidence() < 0.95) { return new ResponseEntity<>(new ResponseMessage("Language might be " + language.getLang() + ", but only " + Math.round(language.getConfidence() * 100) + " % confident!"), HttpStatus.BAD_REQUEST); } reviewRepository.save(new Review(review.getRating(), editReviewText(review.getReviewText()), language.getLang(), password)); trainSentimentModel(); return new ResponseEntity<>(new ResponseMessage("Review saved!"), HttpStatus.OK); } else { return new ResponseEntity<>(new ResponseMessage("Permission denied!"), HttpStatus.FORBIDDEN); } } /** * Deletes the sent review from the collection * * Should be of type @DeleteMapping but simplifies frontend code this way * * @param review A review of type @{@link ReviewModel} to be saved in the collection * @return HttpStatus.OK if the review was deleted */ @Transactional @PostMapping("/delete/reviews/{password}") public ResponseEntity<?> deleteReview(@Valid @RequestBody ReviewModel review, @PathVariable String password) { if (passwordRepository.existsByPassword(password)) { long count = reviewRepository.deleteByReviewTextAndRatingAndPassword(editReviewText(review.getReviewText()), review.getRating(), password); if (count > 0) { trainSentimentModel(); return new ResponseEntity<>(new ResponseMessage("Deleted " + count + " reviews!"), HttpStatus.OK); } return new ResponseEntity<>(new ResponseMessage("Review not found!"), HttpStatus.NOT_FOUND); } else { return new ResponseEntity<>(new ResponseMessage("Permission denied!"), HttpStatus.FORBIDDEN); } } // TODO: Use @RequestBody instead of @RequestParam. Throws error if URL is too long @PostMapping("/reviews/calcRating") public ResponseEntity<?> calcRating(@Valid @RequestBody TextModel text) { Language language = getLanguage(text.getText()); if (language.getLang().equals("de")) { if (language.getConfidence() < 0.95) { return new ResponseEntity<>(new ResponseMessage("Not sure that this is really german. Only" + " with a confidence of " + Math.round(language.getConfidence() * 100) + " %."), HttpStatus.BAD_REQUEST); } int rating = SentimentAnalysis.getInstance().classifyNewReview(editReviewText(text.getText())); return new ResponseEntity<>(new TextRating(rating, language.getConfidence()), HttpStatus.OK); } return new ResponseEntity<>(new ResponseMessage("Language currently not supported. Language found: " + language.getLang() + " with a confidence of " + Math.round(language.getConfidence() * 100) + " %."), HttpStatus.BAD_REQUEST); } private Language getLanguage(String text) { final String uri = "http://localhost:8082/languageDetection/detect"; RestTemplate restTemplate = new RestTemplate(); // request body parameters Map<String, String> map = new HashMap<>(); map.put("text", text); ResponseEntity<Language[]> response = restTemplate.postForEntity(uri, map, Language[].class); Language[] languages = response.getBody(); return languages[0]; } private String editReviewText(String text) { return text .replaceAll("\\„", " „ ") .replaceAll("\\“", " “" ) .replaceAll("\\.", " . ") .replaceAll("\\!", " ! ") .replaceAll("\\,", " , ") .replaceAll("\\:", " : ") .replaceAll("\\;", " ; "); } @EventListener(ApplicationReadyEvent.class) public void initialize() { trainSentimentModel(); } private void trainSentimentModel() { List<Review> reviews = reviewRepository.findByLang("de"); List<String> trainingData = new LinkedList<>(); for (Review review : reviews) { trainingData.add(review.getRating() + "\t" + review.getReviewText() + "\n"); } SentimentAnalysis.getInstance().trainModel("de", trainingData); } }
using System; using System.Linq; using System.Reflection; [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class AutoMapToAttribute : Attribute { private Type _targetType; public AutoMapToAttribute(Type targetType) { _targetType = targetType; } public void MapProperties(object source, object destination) { var sourceProperties = source.GetType().GetProperties(); var destinationProperties = _targetType.GetProperties(); foreach (var sourceProperty in sourceProperties) { var destinationProperty = destinationProperties.FirstOrDefault(p => p.Name == sourceProperty.Name && p.PropertyType == sourceProperty.PropertyType); if (destinationProperty != null) { var value = sourceProperty.GetValue(source); destinationProperty.SetValue(destination, value); } } } } // Example usage of AutoMapTo attribute [AutoMapTo(typeof(ProjectTask))] public class TaskViewModel { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } } public class ProjectTask { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } } // Usage var taskViewModel = new TaskViewModel { Id = 1, Title = "Sample Task", Description = "This is a sample task" }; var projectTask = new ProjectTask(); var autoMapAttribute = (AutoMapToAttribute)Attribute.GetCustomAttribute(typeof(TaskViewModel), typeof(AutoMapToAttribute)); autoMapAttribute.MapProperties(taskViewModel, projectTask); // Now projectTask properties are automatically mapped from taskViewModel
class FinancialInstrument: def __init__(self, name, commercial_paper=0): self.name = name self.commercial_paper = commercial_paper def calculate_total_value(self): total_value = self.commercial_paper return total_value # Example usage instrument1 = FinancialInstrument('Instrument 1', 5000.0) print(instrument1.calculate_total_value()) # Output: 5000.0 instrument2 = FinancialInstrument('Instrument 2') print(instrument2.calculate_total_value()) # Output: 0
/* * */ package net.community.chest.swing.component.list; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.swing.ListSelectionModel; import net.community.chest.util.collection.CollectionsUtils; /** * <P>Copyright 2008 as per GPLv2</P> * * <P>Used to convert between <code>int</code> values and {@link Enum}-s</P> * * @author <NAME>. * @since Oct 7, 2008 8:45:46 AM */ public enum ListSelectionMode { SINGLE(ListSelectionModel.SINGLE_SELECTION), INTERVAL(ListSelectionModel.SINGLE_INTERVAL_SELECTION), MULTIPLE(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); private final int _mode; public final int getMode () { return _mode; } ListSelectionMode (final int m) { _mode = m; } public static final List<ListSelectionMode> VALUES=Collections.unmodifiableList(Arrays.asList(values())); public static final ListSelectionMode fromString (final String s) { return CollectionsUtils.fromString(VALUES, s, false); } public static final ListSelectionMode fromMode (final int m) { for (final ListSelectionMode v : VALUES) { if ((v != null) && (v.getMode() == m)) return v; } return null; } }
<reponame>ACM-VIT/ACM-internals-Android<filename>app/src/main/java/com/acmvit/acm_app/ui/custom/OverlapItemDecorator.java package com.acmvit.acm_app.ui.custom; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentSender; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.UserHandle; import android.view.Display; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class OverlapItemDecorator extends RecyclerView.ItemDecoration { private final int overlap; private final int orientation; public OverlapItemDecorator(int orientation, int overlap) { this.overlap = overlap; this.orientation = orientation; } @Override public void getItemOffsets( @NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state ) { int pos = parent.getChildAdapterPosition(view); if (pos == RecyclerView.NO_POSITION || pos == 0) { return; } if (orientation == LinearLayoutManager.HORIZONTAL) { outRect.left = -overlap; } else if (orientation == LinearLayoutManager.VERTICAL) { outRect.top = -overlap; } else { throw new IllegalArgumentException( "Orientation should either be LinearLayoutManager.VERTICAL or LinearLayoutManager.Horizontal" ); } } @Override public void onDraw( @NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state ) { super.onDraw(c, parent, state); } }
<gh_stars>0 (function() { var FileSystemProxy, FileTransfer; FileSystemProxy = (function() { function FileSystemProxy() { this.__openFS(); } FileSystemProxy.prototype.resolveLocalFileSystemURL = function(path) { return new Promise((function(_this) { return function(resolve, reject) { return _this.__openFS().then(function() { return _this.fs.exists(path, function(exists) { if (exists) { return resolve(); } else { return reject(); } }); }); }; })(this)); }; FileSystemProxy.prototype.__ready = function(fs) { this.isReady = true; return this.fs = fs; }; FileSystemProxy.prototype.__openFS = function() { if (this.isReady) { return Promise.resolve(); } return new Promise((function(_this) { return function(resolve, reject) { return new Filer.FileSystem({ name: "uhura_filesystem" }, function(err, fs) { if (err) { return reject(err); } else { return _this.__ready(fs) && resolve(); } }); }; })(this)); }; return FileSystemProxy; })(); FileTransfer = (function() { function FileTransfer() {} FileTransfer.prototype.download = function(url, filename, resolve, reject) { var xhr; xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = "blob"; xhr.onreadystatechange = function() {}; if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { debugger; } else { reject(xhr); } } return xhr.send(); }; return FileTransfer; })(); window.FileTransfer = FileTransfer; window.FS = new FileSystemProxy; window.resolveLocalFileSystemURL = function(path, resolve, reject) { return FS.resolveLocalFileSystemURL(path).then(resolve, reject); }; }).call(this);
import {API} from "api"; import {passJoinRequestMiddleware} from "store/middleware/joinRequest"; import {ActionFactory} from "store/action"; import {MiddlewareAPI} from "redux"; jest.mock("api", () => ({ API: { acceptJoinRequests: jest.fn(), rejectJoinRequests: jest.fn(), }, })); beforeEach(() => { (API.acceptJoinRequests as jest.Mock).mockClear(); (API.rejectJoinRequests as jest.Mock).mockClear(); }); describe("joinRequest middleware", () => { test("acceptJoinRequest", () => { passJoinRequestMiddleware({} as MiddlewareAPI, jest.fn(), ActionFactory.acceptJoinRequests("boardId", ["userId"])); expect(API.acceptJoinRequests).toHaveBeenCalledWith("boardId", ["userId"]); }); test("rejectJoinRequest", () => { passJoinRequestMiddleware({} as MiddlewareAPI, jest.fn(), ActionFactory.rejectJoinRequests("boardId", ["userId"])); expect(API.rejectJoinRequests).toHaveBeenCalledWith("boardId", ["userId"]); }); });
# platform = multi_platform_wrlinux,multi_platform_rhel,multi_platform_fedora,multi_platform_ol,multi_platform_rhv,multi_platform_sle {{{ bash_instantiate_variables("var_password_pam_unix_remember") }}} AUTH_FILES[0]="/etc/pam.d/system-auth" AUTH_FILES[1]="/etc/pam.d/password-auth" for pamFile in "${AUTH_FILES[@]}" do if grep -q "pam_unix.so.*remember=" $pamFile; then sed -i --follow-symlinks "s/\(^password.*sufficient.*pam_unix.so.*\)\(\(remember *= *\)[^ $]*\)/\1remember=$var_password_pam_unix_remember/" $pamFile else sed -i --follow-symlinks "/^password[[:space:]]\+sufficient[[:space:]]\+pam_unix.so/ s/$/ remember=$var_password_pam_unix_remember/" $pamFile fi if grep -q "pam_pwhistory.so.*remember=" $pamFile; then sed -i --follow-symlinks "s/\(^password.*\)\(\(remember *= *\)[^ $]*\)/\1remember=$var_password_pam_unix_remember/" $pamFile else sed -i --follow-symlinks "/^password[[:space:]]\+\(requisite\|required\)[[:space:]]\+pam_pwhistory.so/ s/$/ remember=$var_password_pam_unix_remember/" $pamFile fi done
<gh_stars>10-100 package com.roadrover.sdk.utils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.annotation.NonNull; /** * 与第三方应用通信的工具类 </br> * 一般第三方APP通讯都是通过广播,将广播流程封装 */ public abstract class BaseThreeAppUtil { protected Context mContext; private boolean mIsRegister = false; private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { BaseThreeAppUtil.this.onReceive(context, intent); } }; public BaseThreeAppUtil(@NonNull Context context) { if (context != null) { mContext = context.getApplicationContext(); } } /** * 初始化监听 * @param actions */ public void init(String... actions) { if (mContext != null && !mIsRegister) { if (!ListUtils.isEmpty(actions)) { mIsRegister = true; IntentFilter filter = new IntentFilter(); for (String action : actions) { filter.addAction(action); } mContext.registerReceiver(mBroadcastReceiver, filter); } } } /** * 注销监听 */ public void release() { if (mIsRegister && mContext != null) { mIsRegister = false; mContext.unregisterReceiver(mBroadcastReceiver); } } /** * 广播监听 * @param context * @param intent */ protected abstract void onReceive(Context context, Intent intent); }
#!/bin/bash # Image name pattern: course/lab name/router name IMG='adr10/rede04/as100-r1' docker build -t $IMG .
@app.route('/time_zone') def time_zone(): location = request.args.get('location') time_zone = pytz.timezone(location) local_time = datetime.now(time_zone) utc_offset = local_time.utcoffset().total_seconds()/3600 return render_template('time_zone.html', location=location, utc_offset=utc_offset) // In the template <html> <h1>Time Zone: {{ location }}</h1> <h2>UTC Offset: {{ utc_offset }}</h2> <html>
<filename>WebUI/src/app/components/booking/booking.component.ts<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { BookingService } from 'src/app/services/booking.service'; import { SessionService } from 'src/app/services/session.service'; import { Router } from '@angular/router'; import { Show } from 'src/app/models/show'; @Component({ selector: 'app-booking', templateUrl: './booking.component.html', styleUrls: ['./booking.component.scss'] }) export class BookingComponent implements OnInit { selectedShow: Show = null; selectedSeats: number[] = []; constructor( private bookingService: BookingService, public session: SessionService, private router: Router ) { } ngOnInit() { if (this.session.getShow()) { this.selectedShow = this.session.getShow(); } } seat(int: number): boolean { return this.selectedShow.room.seats.includes(int); } toggleSeat(seat) { if (this.selectedSeats.includes(seat)) { this.selectedSeats.splice(this.selectedSeats.indexOf(seat), 1); } else { this.selectedSeats.push(seat); } console.log("picked a seat:"); console.log(seat); } clearSeats() { console.log("reset picked seats"); this.selectedSeats = []; } confirmBooking() { console.log("confirm picked seats"); this.bookingService.sendBooking(this.session.getShow(), this.selectedSeats) .subscribe(result => { console.log(result) this.router.navigate(['/home']); }); } }
def calculate_loss_percentage(revenue, expenses): loss_percentage = ((expenses - revenue) / revenue) * 100 return round(loss_percentage, 2)
<filename>caps.js<gh_stars>0 "use strict"; const {fakeOrderHandler} = require('./clients/driver'); setInterval(() => { fakeOrderHandler(); }, 5000);
/* * Copyright 2017-present Open Networking 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.onlab.packet.dhcp; import com.google.common.collect.Lists; import org.onlab.packet.DHCP6; import org.onlab.packet.DeserializationException; import org.onlab.packet.Deserializer; import java.nio.ByteBuffer; import java.util.List; import java.util.Objects; /** * DHCPv6 Identity Association for Non-temporary Addresses Option. * Based on RFC-3315 */ public final class Dhcp6IaNaOption extends Dhcp6Option { public static final int DEFAULT_LEN = 12; private int iaId; private int t1; private int t2; private List<Dhcp6Option> options; @Override public short getCode() { return DHCP6.OptionCode.IA_NA.value(); } @Override public short getLength() { return (short) (DEFAULT_LEN + options.stream() .mapToInt(opt -> (int) opt.getLength() + Dhcp6Option.DEFAULT_LEN) .sum()); } /** * Gets Identity Association ID. * * @return the Identity Association ID */ public int getIaId() { return iaId; } /** * Sets Identity Association ID. * * @param iaId the Identity Association ID. */ public void setIaId(int iaId) { this.iaId = iaId; } /** * Gets time 1. * The time at which the client contacts the * server from which the addresses in the IA_NA * were obtained to extend the lifetimes of the * addresses assigned to the IA_NA; T1 is a * time duration relative to the current time * expressed in units of seconds. * * @return the value of time 1 */ public int getT1() { return t1; } /** * Sets time 1. * * @param t1 the value of time 1 */ public void setT1(int t1) { this.t1 = t1; } /** * Gets time 2. * The time at which the client contacts any * available server to extend the lifetimes of * the addresses assigned to the IA_NA; T2 is a * time duration relative to the current time * expressed in units of seconds. * * @return the value of time 2 */ public int getT2() { return t2; } /** * Sets time 2. * * @param t2 the value of time 2 */ public void setT2(int t2) { this.t2 = t2; } /** * Gets sub-options. * * @return sub-options of this option */ public List<Dhcp6Option> getOptions() { return options; } /** * Sets sub-options. * * @param options the sub-options of this option */ public void setOptions(List<Dhcp6Option> options) { this.options = options; } /** * Default constructor. */ public Dhcp6IaNaOption() { } /** * Constructs a DHCPv6 IA NA option with DHCPv6 option. * * @param dhcp6Option the DHCPv6 option */ public Dhcp6IaNaOption(Dhcp6Option dhcp6Option) { super(dhcp6Option); } /** * Gets deserializer. * * @return the deserializer */ public static Deserializer<Dhcp6Option> deserializer() { return (data, offset, length) -> { Dhcp6Option dhcp6Option = Dhcp6Option.deserializer().deserialize(data, offset, length); if (dhcp6Option.getLength() < DEFAULT_LEN) { throw new DeserializationException("Invalid IA NA option data"); } Dhcp6IaNaOption iaNaOption = new Dhcp6IaNaOption(dhcp6Option); byte[] optionData = iaNaOption.getData(); ByteBuffer bb = ByteBuffer.wrap(optionData); iaNaOption.iaId = bb.getInt(); iaNaOption.t1 = bb.getInt(); iaNaOption.t2 = bb.getInt(); iaNaOption.options = Lists.newArrayList(); while (bb.remaining() >= Dhcp6Option.DEFAULT_LEN) { Dhcp6Option option; ByteBuffer optByteBuffer = ByteBuffer.wrap(optionData, bb.position(), optionData.length - bb.position()); short code = optByteBuffer.getShort(); short len = optByteBuffer.getShort(); int optLen = UNSIGNED_SHORT_MASK & len; byte[] subOptData = new byte[Dhcp6Option.DEFAULT_LEN + optLen]; bb.get(subOptData); // TODO: put more sub-options? if (code == DHCP6.OptionCode.IAADDR.value()) { option = Dhcp6IaAddressOption.deserializer() .deserialize(subOptData, 0, subOptData.length); } else { option = Dhcp6Option.deserializer() .deserialize(subOptData, 0, subOptData.length); } iaNaOption.options.add(option); } return iaNaOption; }; } @Override public byte[] serialize() { int payloadLen = DEFAULT_LEN + options.stream() .mapToInt(opt -> (int) opt.getLength() + Dhcp6Option.DEFAULT_LEN) .sum(); int len = Dhcp6Option.DEFAULT_LEN + payloadLen; ByteBuffer bb = ByteBuffer.allocate(len); bb.putShort(DHCP6.OptionCode.IA_NA.value()); bb.putShort((short) payloadLen); bb.putInt(iaId); bb.putInt(t1); bb.putInt(t2); options.stream().map(Dhcp6Option::serialize).forEach(bb::put); return bb.array(); } @Override public int hashCode() { return 31 * super.hashCode() + Objects.hash(iaId, t1, t2, options); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } if (!super.equals(obj)) { return false; } final Dhcp6IaNaOption other = (Dhcp6IaNaOption) obj; return Objects.equals(this.iaId, other.iaId) && Objects.equals(this.t1, other.t1) && Objects.equals(this.t2, other.t2) && Objects.equals(this.options, other.options); } @Override public String toString() { return getToStringHelper() .add("iaId", iaId) .add("t1", t1) .add("t2", t2) .add("options", options) .toString(); } }
<reponame>seanmay/bombscrubber<gh_stars>0 import React, { useState } from "react"; import Title from "../../design-components/title"; import Text from "../../design-components/text"; import type { BoardWidth, BoardHeight } from "../../game/core.types"; import { createBoard } from "../../game/services/game-board.service"; import TestSuite from "./test-suite"; import RerollButton from "./reroll-button"; const randomIntBetween = (min: number, max: number) => Math.floor(Math.random() * (max - min) + min); const Page = () => { const minSize = 5; const maxSize = 15 + 1; // Exclusive upper-bound on random function const [width, setWidth] = useState<BoardWidth>(randomIntBetween(minSize, maxSize) as BoardWidth); const [height, setHeight] = useState<BoardHeight>(randomIntBetween(minSize, maxSize) as BoardHeight); const [board, setBoard] = useState(createBoard(width, height)); const resetBoard = () => { const width = randomIntBetween(minSize, maxSize) as BoardWidth; const height = randomIntBetween(minSize, maxSize) as BoardHeight; const board = createBoard(width, height); setWidth(width); setHeight(height); setBoard(board); }; const widthTest = board.width === width; const heightTest = board.height === height; const rowTest = board.cells.length === height; const columnTest = board.cells[0]?.length === width; return ( <section> <header> <Title level={2}>Populate A 2D Grid</Title> <Text style={{ color: "var(--theme-subdued)" }} className="pv2 lh3"> The first step in making Bombscrubber work is to create a grid of a specified width and height. <br /> In the <code>/game/services</code> folder, find the <code>GameBoard</code> service and modify <code>createBoard</code> to take a width, a height, and produce a 2D array of that size. <br /> In order to appease the compiler, you will need to fill the grid with cells of one kind or another; whether they are all safe, all bombs, or a random distribution, at this point, is irrelevant. </Text> </header> <section className="pv3"> <Title level={3}>Tests:</Title> <Text className="pv3 lh3"> Making a <code>GameBoard</code> that is {width}&times;{height}. <br /> Testing that width = {width}, height = {height}, and that the dimensions of the 2D cells grid match. </Text> </section> <section className="pv3"> <Title level={3}>Test Results: <RerollButton onReset={resetBoard} /></Title> <TestSuite tests={[ { expression: `gameBoard.width == ${width};`, output: `${widthTest}`, passed: widthTest }, { expression: `gameBoard.height == ${height};`, output: `${heightTest}`, passed: heightTest }, { expression: `gameBoard.cells.length == gameBoard.height;`, output: `${rowTest}`, passed: rowTest }, { expression: `gameBoard.cells[0].length == gameBoard.width;`, output: `${columnTest}`, passed: columnTest }, ]} /> </section> </section> ); }; export default Page;
<filename>finalProject/src/FinalProject.java import java.util.Collections; import java.util.Scanner; import java.util.Vector; import org.apache.commons.lang3.*; /** * Task for the project * Napisz program, który pobierze od użytkownika napis – domyślnie pewną * liczbę. (PROTIP: czytaj string znak po znaku i wykorzystaj fakt, że za * pomocą kodowania ASCII jest możliwe za pomocą zwykłego rzutowania typu i * odejmowania obliczyć wartość liczbową znaku) * * Program pozwoli na wprowadzenie nieskończonej liczby liczb, a po * wprowadzeniu znaku N zakończy wprowadzanie danych. Weź pod uwagę, że * użytkownik nie będzie łaskawy i zamiast liczb poda także znaki. Zadbaj o * odpowiednią obsługę błędów i zaimplementuj mechanizm wyjątków. * * Tak przekonwertowane liczby wrzuć do jednej dowolnej kolekcji (może być * jedna z gotowych struktur danych z biblioteki javy), jednak takiej, * która umożliwi na uszeregowanie danych według przepisu: * * OPIS LICZBY | WARTOŚĆ, * * gdzie opis liczby będzie jedną z 3 możliwych wartości: * liczba ujemna, liczba dodatnia, liczba pierwsza. * * Weryfikację co do charakteru liczby wykonaj w wybrany przez siebie * sposób, przy czym jeśli liczba jest dodatnia i pierwsza to zapisz w * opisie liczby, że jest to liczba pierwsza. * np. * liczba ujemna | -10 * liczba dodatnia | 7 * liczba pierwsza | 80209 * liczba pierwsza | 4682927 * liczba dodatnia | 768596498 * * Test string: * | _ A @ B ^ C \ + 1 : 2 | 3 d e f - 4 ) 5 ( 6 a { b } c - 1 ! 2 @ 3 # D $ E % F ^ + & 4 * 5 : 6 ; N * replaceAll("\\s+","") * .replaceAll("[\\p{Blank}]", "").replaceAll("@", "").replaceAll("[\\p{Punct}[^+-]]", "") * */ public class FinalProject { public static void main(String[] args){ System.out.println("Please input your string:"); Scanner myScan = new Scanner(System.in); String myTmpInputString = ""; String tmpReader = ""; while(!tmpReader.endsWith("N")) { tmpReader = myScan.nextLine(); myTmpInputString = myTmpInputString.concat(tmpReader); } System.out.println(myTmpInputString); myTmpInputString = myTmpInputString.replaceAll("\\p{Space}", "").replaceAll("[\\p{Punct}&&[^-]]+","").replaceAll("N", ""); System.out.println(myTmpInputString); String[] result = myTmpInputString.split("[-]+[^A-z0-9]+|(?<=[A-z])(?=[-0-9])|(?<=[-0-9])(?=[A-z])"); Vector<Integer> myResult = new Vector<>(); Integer myResultContainer = 0; for (String tmp : result) { if (tmp.startsWith("-")){ tmp = tmp.replaceAll("-", ""); if (StringUtils.isNumeric(tmp)){ myResultContainer = -Integer.parseInt(tmp); myResult.add(myResultContainer); } // myResultContainer = -Integer.parseInt(tmp); // myResult.add(myResultContainer); //System.out.println(myResultContainer); } else { if (StringUtils.isNumeric(tmp)){ myResultContainer = Integer.parseInt(tmp); myResult.add(myResultContainer); //System.out.println(myResultContainer); } else { for (int i = 0; i < tmp.length(); ++i) { myResultContainer = (int)tmp.charAt(i); myResult.add(myResultContainer); //System.out.println((int)tmp.charAt(i)); } } } } System.out.println("=========================\n" + "Before sort():\n" + "========================="); printResult(myResult); System.out.println("=========================\n" + "After sort():\n" + "========================="); Collections.sort(myResult); printResult(myResult); } private static void printResult(Vector<Integer> myResult) { for (Integer i : myResult) { if (i < 0) { System.out.println("liczba ujemna |"+i); } else { if (isPrime(i)) { System.out.println("liczba pierwsza |"+i); } else { System.out.println("liczba dodatnia |"+i); } } //System.out.println(i); } } public static boolean isPrime(Integer tmpVar) { boolean flag = false; for(int i = 2; i <= tmpVar/2; ++i) { if(tmpVar % i == 0) { flag = true; break; } } return !flag; } }
package de.lmu.cis.ocrd.calamari; import de.lmu.cis.ocrd.ml.OCRWord; import de.lmu.cis.ocrd.util.Normalizer; class Word implements OCRWord { private final String normalized; private final String raw; private final String line; private final double[] charConfs; private final double conf; Word(String raw, String line, double conf, double[] charConfs) { this.raw = raw; this.normalized = Normalizer.normalize(raw); this.line = line; this.conf = conf; this.charConfs = charConfs; } @Override public String getWordNormalized() { return normalized; } @Override public String getLineNormalized() { return line; } @Override public String getWordRaw() { return raw; } @Override public double getCharacterConfidenceAt(int i) { if (this.charConfs == null || this.charConfs.length <= i) { return 0; } return charConfs[i]; } @Override public double getConfidence() { return conf; } }
<gh_stars>0 package services class Preference(val _mainColor: String, val _subColor: String) { val mainColor = _mainColor val subColor = _subColor }
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var Observable_1 = require("rxjs/Observable"); /** * service for navigator.geolocation methods */ var NavigatorGeolocation = (function () { function NavigatorGeolocation() { } NavigatorGeolocation.prototype.getCurrentPosition = function (geoLocationOptions) { geoLocationOptions = geoLocationOptions || { timeout: 5000 }; return new Observable_1.Observable(function (responseObserver) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { responseObserver.next(position); responseObserver.complete(); }, function (evt) { return responseObserver.error(evt); }, geoLocationOptions); } else { responseObserver.error('Browser Geolocation service failed.'); } }); }; ; return NavigatorGeolocation; }()); NavigatorGeolocation = __decorate([ core_1.Injectable() ], NavigatorGeolocation); exports.NavigatorGeolocation = NavigatorGeolocation; //# sourceMappingURL=navigator-geolocation.js.map
'use strict' global.__base = __dirname + '/../' const path = require('path') const util = require('util') const config = {} config.libPath = path.join(__base, 'src', 'libs', 'angular-signature-pad') config.debugMode = true config.validPreset = 'angular' config.ci = {} config.ci.validState = 'passed' module.exports = config
def calculate_duration(self) -> float: num_frames = self.get_num_frames() sampling_frequency = self.get_sampling_frequency() duration = num_frames / sampling_frequency return duration
<reponame>wp1016/wlan const express = require('express') const path = require('path') const app = express() app.use(express.static('dist')) app.use(function (req, res) { res.sendFile(path.dirname(require.main.filename) + '/dist/index.html') }) const port = 8091 app.listen(port, () => { // eslint-disable-next-line no-console console.log(`Local DevServer Started on port ${port}...`) })
import { GamepadButtonCode, InputBinding } from '../../core'; import { InputControl } from '../InputControl'; export class SecondaryGamepadInputBinding extends InputBinding { constructor() { super(); this.setDefault(InputControl.Up, GamepadButtonCode.Up); this.setDefault(InputControl.Down, GamepadButtonCode.Down); this.setDefault(InputControl.Left, GamepadButtonCode.Left); this.setDefault(InputControl.Right, GamepadButtonCode.Right); this.setDefault(InputControl.Select, GamepadButtonCode.Start); this.setDefault(InputControl.PrimaryAction, GamepadButtonCode.X); this.setDefault(InputControl.SecondaryAction, GamepadButtonCode.Y); this.setDefault(InputControl.Rewind, GamepadButtonCode.A); this.setDefault(InputControl.FastForward, GamepadButtonCode.B); } }
/** * Copyright (c) 2001-2017 <NAME> and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://robocode.sourceforge.net/license/epl-v10.html */ package net.sf.robocode.ui.dialog; import net.sf.robocode.io.Logger; import net.sf.robocode.repository.IRepositoryManager; import net.sf.robocode.repository.TeamProperties; import net.sf.robocode.ui.IWindowManager; import static net.sf.robocode.ui.util.ShortcutUtil.MENU_SHORTCUT_KEY_MASK; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; /** * @author <NAME> (original) * @author <NAME> (contributor) * @author <NAME> (contributor) */ @SuppressWarnings("serial") public class TeamCreator extends JDialog implements WizardListener { private JPanel teamCreatorContentPane; private WizardCardPanel wizardPanel; private WizardController wizardController; private RobotSelectionPanel robotSelectionPanel; private TeamCreatorOptionsPanel teamCreatorOptionsPanel; private final int minRobots = 2; private final int maxRobots = 10; private final EventHandler eventHandler = new EventHandler(); class EventHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Refresh")) { getRobotSelectionPanel().refreshRobotList(true); } } } private final IRepositoryManager repositoryManager; public TeamCreator(IWindowManager windowManager, IRepositoryManager repositoryManager) { super(windowManager.getRobocodeFrame()); this.repositoryManager = repositoryManager; initialize(); } protected TeamCreatorOptionsPanel getTeamCreatorOptionsPanel() { if (teamCreatorOptionsPanel == null) { teamCreatorOptionsPanel = new TeamCreatorOptionsPanel(this); } return teamCreatorOptionsPanel; } private JPanel getTeamCreatorContentPane() { if (teamCreatorContentPane == null) { teamCreatorContentPane = new JPanel(); teamCreatorContentPane.setLayout(new BorderLayout()); teamCreatorContentPane.add(getWizardController(), BorderLayout.SOUTH); teamCreatorContentPane.add(getWizardPanel(), BorderLayout.CENTER); getWizardPanel().getWizardController().setFinishButtonTextAndMnemonic("Create Team!", 'C', 0); teamCreatorContentPane.registerKeyboardAction(eventHandler, "Refresh", KeyStroke.getKeyStroke(KeyEvent.VK_R, MENU_SHORTCUT_KEY_MASK), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); teamCreatorContentPane.registerKeyboardAction(eventHandler, "Refresh", KeyStroke.getKeyStroke(KeyEvent.VK_R, MENU_SHORTCUT_KEY_MASK), JComponent.WHEN_FOCUSED); } return teamCreatorContentPane; } protected RobotSelectionPanel getRobotSelectionPanel() { if (robotSelectionPanel == null) { robotSelectionPanel = net.sf.robocode.core.Container.createComponent(RobotSelectionPanel.class); robotSelectionPanel.setup(minRobots, maxRobots, false, "Select the robots for this team.", false, true, true, false, false, false, null); } return robotSelectionPanel; } private WizardCardPanel getWizardPanel() { if (wizardPanel == null) { wizardPanel = new WizardCardPanel(this); wizardPanel.add(getRobotSelectionPanel(), "Select robots"); wizardPanel.add(getTeamCreatorOptionsPanel(), "Select options"); } return wizardPanel; } public void initialize() { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setTitle("Create a team"); setContentPane(getTeamCreatorContentPane()); } private WizardController getWizardController() { if (wizardController == null) { wizardController = getWizardPanel().getWizardController(); } return wizardController; } public void cancelButtonActionPerformed() { dispose(); } public void finishButtonActionPerformed() { try { int rc = createTeam(); if (rc == 0) { JOptionPane.showMessageDialog(this, "Team created successfully.", "Success", JOptionPane.INFORMATION_MESSAGE, null); this.dispose(); } else { JOptionPane.showMessageDialog(this, "Team creation cancelled", "Cancelled", JOptionPane.INFORMATION_MESSAGE, null); } } catch (IOException e) { JOptionPane.showMessageDialog(this, e.toString(), "Team Creation Failed", JOptionPane.ERROR_MESSAGE, null); } } public int createTeam() throws IOException { File file = new File(repositoryManager.getRobotsDirectory(), teamCreatorOptionsPanel.getTeamPackage().replace('.', File.separatorChar) + teamCreatorOptionsPanel.getTeamNameField().getText() + ".team"); if (file.exists()) { int ok = JOptionPane.showConfirmDialog(this, file + " already exists. Are you sure you want to replace it?", "Warning", JOptionPane.YES_NO_CANCEL_OPTION); if (ok == JOptionPane.NO_OPTION || ok == JOptionPane.CANCEL_OPTION) { return -1; } } if (!file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { Logger.logError("Can't create " + file.getParentFile().toString()); } } URL webPageUrl = null; String webPageFieldString = teamCreatorOptionsPanel.getWebpageField().getText(); if (webPageFieldString != null && webPageFieldString.length() > 0) { try { webPageUrl = new URL(webPageFieldString); } catch (MalformedURLException e) { try { webPageUrl = new URL("http://" + webPageFieldString); teamCreatorOptionsPanel.getWebpageField().setText(webPageUrl.toString()); } catch (MalformedURLException ignored) {} } } String members = robotSelectionPanel.getSelectedRobotsAsString(); String version = teamCreatorOptionsPanel.getVersionField().getText(); String author = teamCreatorOptionsPanel.getAuthorField().getText(); String desc = teamCreatorOptionsPanel.getDescriptionArea().getText(); TeamProperties props = new TeamProperties(); props.setMembers(members); props.setVersion(version); props.setAuthor(author); props.setDescription(desc); props.setWebPage(webPageUrl); repositoryManager.createTeam(file, props); return 0; } }
# Get twilio-ruby from twilio.com/docs/ruby/install require 'twilio-ruby' # Get your Account SID and Auth Token from twilio.com/console # To set up environmental variables, see http://twil.io/secure account_sid = ENV['TWILIO_ACCOUNT_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] # Initialize Twilio Client @client = Twilio::REST::Client.new(account_sid, auth_token) @number = @client .api.incoming_phone_numbers('PN2a0747eba6abf96b7e3c3ff0b4530f6e') .fetch @number.update( voice_url: 'http://demo.twilio.com/docs/voice.xml', sms_url: 'http://demo.twilio.com/docs/sms.xml' ) puts @number.voice_url
#!/bin/bash # docker rm -f mysql-server docker rm -f zabbix_server
#!/bin/bash if [[ ! $INSTALL_SCRIPT ]]; then echo "(!) Error: You must use the installer script." exit fi echo "Installing Deploy (Shell)" cd $PROJECT_TEMP_PATH wget https://github.com/visionmedia/deploy/archive/master.zip unzip master.zip cd deploy-master sudo make install cd $PROJECT_TEMP_PATH rm -rf deploy-master rm master.zip echo "(!) Complete! Use $ deploy" echo " For Project setup see: https://github.com/visionmedia/deploy" echo " For a step by step see: https://github.com/visionmedia/deploy/wiki" if [ $SKIP_SLEEP == false ]; then sleep 4 fi
<reponame>bonusly/bamboo-id module BambooId class StateCode def initialize(subdomain) self.subdomain = subdomain end def to_s Digest::MD5.hexdigest([Configuration.client_id, subdomain].join('')) end private attr_accessor :subdomain end end
#!/bin/sh set -e set -u set -o pipefail if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy # frameworks to, so exit 0 (signalling the script phase was successful). exit 0 fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Flurry-iOS-SDK/Flurry_iOS_SDK.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/Flurry-iOS-SDK/Flurry_iOS_SDK.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
<reponame>kiran1235/phalitha require "phalithacapcha/version" require 'rmagick' class Phalithacapcha def generate(Text,targetlocation) granite = Magick::ImageList.new('granite:') canvas = Magick::ImageList.new canvas.new_image(100, 50, Magick::TextureFill.new(granite)) text = Magick::Draw.new text.font_family = 'helvetica' text.pointsize = 16 text.gravity = Magick::CenterGravity text.annotate(canvas, 0,0,2,2, Text) { self.fill = 'gray83' } text.annotate(canvas, 0,0,-1.5,-1.5, Text) { self.fill = 'gray40' } text.annotate(canvas, 0,0,0,0, Text) { self.fill = 'darkred' } canvas.write(targetlocation) end end
angular.module('feedbackModule', []) .factory('feedbackService', ['feedbackChannel', '$log', function (feedbackChannel, $log) { var service = { showAnswer: false, showKeyBoard: false, revealAnswer: function () { this.showAnswer = true; //$log.log('feedback service show Answer true'); feedbackChannel.publishVisibilityChange(true); }, toggleKeyboardVisibilty: function () { this.showKeyBoard = !this.showKeyBoard; }, hideAnswer: function () { this.showAnswer = false; }, processResult: function (result) { //$log.log("RESULT : ", result); if (result.answer === "wrong") { feedbackChannel.publishWrongAnswerGiven(); } if (result.answer === "correct") { feedbackChannel.publishCorrectAnswerGiven(); } }, warn : function(){ //alert('warning'); } }; return service; }]) .service('feedbackChannel', ['$rootScope', '$log', function ($rootScope, $log) { var CHANGE_VISIBILITY = 'changeVisibilityMessage'; var changeVisibility; var onChangeVisibility; var ANSWER_GIVEN = 'answerGiven'; // used to publish events var publishVisibilityChange = function (passedIn) { //var wrongAnswer = function () { $rootScope.$broadcast(CHANGE_VISIBILITY, {showAnswer: passedIn}); }; // used to subscribe to an event // subscriber scope passed in to listen to events, and trigger a handler on the subscriber var subscribe = function ($scope, handler) { // need to pass scope so it can listen $scope.$on(CHANGE_VISIBILITY, function (event, message) { // note that the handler is passed the problem domain parameters handler(message.correctAnswer); }); }; var subscribeAnswerGiven = function ($scope, handler) { $scope.$on(ANSWER_GIVEN, function (event, message) { handler(message); }); }; var publishWrongAnswerGiven = function (passedIn) { //$log.log('wrong answer given'); $rootScope.$broadcast(ANSWER_GIVEN, 'WRONG'); }; var publishCorrectAnswerGiven = function (passedIn) { //$log.log('correct answer given'); $rootScope.$broadcast(ANSWER_GIVEN, 'CORRECT'); }; return { publishVisibilityChange: publishVisibilityChange, // sent subscribe: subscribe, // subscribe with handler publishWrongAnswerGiven: publishWrongAnswerGiven, publishCorrectAnswerGiven: publishCorrectAnswerGiven, subscribeAnswerGiven: subscribeAnswerGiven, }; }]);
import { QueueManagerOptions } from '../queue.manager.options'; import { QueueAbstract } from '../queue.abstract'; export abstract class JobAbstract { protected options: QueueManagerOptions; constructor(options: QueueManagerOptions) { this.options = options; } public abstract async listen(queues: QueueAbstract, callback?: Function); public async listenAll(queues: QueueAbstract[], callback?: Function) { const queuesPromises: Promise<QueueAbstract>[] = []; for (const queue of queues) { queuesPromises.push(this.listen(queue, callback)); } await Promise.all(queuesPromises); } }
<reponame>maheshrajamani/stargate package io.stargate.grpc.service.streaming; import io.stargate.db.Persistence; import io.stargate.grpc.service.BatchHandler; import io.stargate.grpc.service.ExceptionHandler; import io.stargate.grpc.service.StreamingSuccessHandler; import io.stargate.proto.QueryOuterClass; /** * Handles the response for Batch queries, constructs the {@link * io.stargate.proto.QueryOuterClass.StreamingResponse} for the {@link * io.stargate.proto.QueryOuterClass.Response}. Finally, invokes the {@link StreamingSuccessHandler} * for it. */ public class StreamingBatchHandler extends BatchHandler { private final StreamingSuccessHandler streamingSuccessHandler; StreamingBatchHandler( QueryOuterClass.Batch batch, Persistence.Connection connection, Persistence persistence, StreamingSuccessHandler streamingSuccessHandler, ExceptionHandler exceptionHandler) { super(batch, connection, persistence, exceptionHandler); this.streamingSuccessHandler = streamingSuccessHandler; } @Override protected void setSuccess(QueryOuterClass.Response response) { streamingSuccessHandler.handleResponse( QueryOuterClass.StreamingResponse.newBuilder().setResponse(response).build()); } }
#!/usr/bin/env bash $JRE9_HOME/bin/java -jar app7.jar
#!/bin/bash # BSD 3-Clause License # # Copyright (c) 2018, Sébastien Huss # 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 copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################## #@DESC@ chartmuseum #@GROUP@ apps #cm.sources.verify() { task.verify.permissive; } cm.source() { out.cmd go get -u github.com/helm/chartmuseum return 0 } cm.deps() { cd "$DIR_SOURCE/src/github.com/helm/chartmuseum" export GO111MODULE=on out.cmd go mod download out.cmd go mod vendor } cm.build.verify() { task.verify.permissive; } cm.build() { set.env cd $DIR_SOURCE/src/github.com/helm/chartmuseum mkdir -p "$DIR_BUILD/bin" local V=$(awk -F= '/^VERSION=/{print $2}' Makefile) local R=$(git rev-parse --short HEAD) export CGO_ENABLED=0 GO111MODULE=on out.cmd "go build -mod=vendor -v --ldflags='-w -X main.Version=$V -X main.Revision=$R' -o '$DIR_BUILD/bin/chartmuseum' cmd/chartmuseum/main.go" } cm.install() { install.init cp -Rapf "$DIR_BUILD/bin" "$DIR_DEST/bin" } cm.config() { cat >"$DIR_DEST/start.d/cm" <<ENDF exec /bin/chartmuseum --port=80 --storage-local-rootdir=/storage --storage="local" ENDF } cm.deploy() { CNAME=${CNAME:-"chartmuseum"} CPREFIX=${CPREFIX:-"chartmuseum-"} link.add www 80 store.claim.many ${CPREFIX}data "/storage" "${CM_CLAIM_SIZE:-"10Gi"}" container.add "${CPREFIX}$CNAME" "${REPODOCKER}/$CNAME:latest" '"cm"' #"$(json.res "100m" "100Mi")" deploy.public #TODO: ajouter: # livenessProbe: # httpGet: # path: /health # port: http # failureThreshold: 3 # initialDelaySeconds: 5 # periodSeconds: 10 # successThreshold: 1 # timeoutSeconds: 1 # # readinessProbe: # httpGet: # path: /health # port: http # failureThreshold: 3 # initialDelaySeconds: 5 # periodSeconds: 10 # successThreshold: 1 # timeoutSeconds: 1 } cm.addhelm() { IP=$(net.run "$MASTER" kubectl get svc chartmuseum|awk '$1=="chartmuseum"{print $3}') out.lvl CMD helm repo add maison "http://$IP/" net.run "$MASTER" helm repo add maison "http://$IP/" } step.add.source cm.source "Get the chartmuseum sources" step.add.source cm.deps "Get the chartmuseum dependencies" step.add.build cm.build "Build the chartmuseum sources" step.add.install cm.install "Install chartmuseum" step.add.install cm.config "Configure chartmuseum" step.add.deploy cm.deploy "Deploy chartmuseum to kubernetes" step.add.deploy cm.addhelm "Add chartmuseum to helm"
from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Product(Base): __tablename__ = 'product' id = Column(Integer, primary_key=True) name = Column(String) class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key=True) name = Column(String) class Customer(Base): __tablename__ = 'customer' id = Column(Integer, primary_key=True) name = Column(String) class Purchase(Base): __tablename__ = 'purchase' id = Column(Integer, primary_key=True) product_id = Column(Integer, ForeignKey('product.id')) employee_id = Column(Integer, ForeignKey('employee.id')) customer_id = Column(Integer, ForeignKey('customer.id'))
<reponame>guidiaalo/sdk-js<filename>src/modules/Account/devices.types.ts import { GenericID, GenericToken, Query, TagsObj, PermissionOption, ExpireTimeOption } from "../../common/common.types"; interface DeviceQuery extends Query< DeviceInfo, "name" | "visible" | "active" | "last_input" | "last_output" | "created_at" | "updated_at" > { resolveBucketName?: boolean; } interface DeviceCreateInfo { /** * A name for the device. */ name: string; /** * Description of the device. */ description?: string | null; /** * Set if the device will be active. */ active?: boolean; /** * Set if the device will be visible. */ visible?: boolean; /** * An array of configuration params */ configuration_params?: ConfigurationParams[]; /** * An array of tags */ tags?: TagsObj[]; /** * Device Serie Number */ serie_number?: string; /** * Connector ID */ connector?: GenericID; /** * Network ID */ network?: GenericID; /** * If device will use connector parser */ connector_parse?: boolean; /** * Javascript code for use as payload parser */ parse_function?: string; } interface DeviceInfo extends Omit<DeviceCreateInfo, "configuration_params"> { id: GenericID; profile: GenericID; bucket: { id: GenericID; name: string; }; last_output: Date | null; last_input: Date | null; updated_at: Date; created_at: Date; inspected_at: Date | null; } interface ConfigurationParams { sent: boolean; key: string; value: string; id?: string; } type DeviceCreateResponse = { device_id: GenericID; bucket_id: GenericID; token: GenericToken }; type DeviceListItem = Omit<DeviceInfo, "bucket"> & { bucket: GenericID }; interface DeviceTokenDataList { token: GenericToken; device_id: GenericID; network_id: GenericID; name: string; permission: PermissionOption; serie_number: string | void; last_authorization: string | void; expire_time: ExpireTimeOption; created_at: string; } interface ListDeviceTokenQuery extends Query<DeviceTokenDataList, "name" | "permission" | "serie_number" | "last_authorization" | "created_at"> {} export { DeviceQuery, DeviceCreateInfo, ConfigurationParams, DeviceInfo, DeviceCreateResponse, DeviceListItem, DeviceTokenDataList, ListDeviceTokenQuery, };
#!/usr/bin/env bash source /etc/profile now_dir=`pwd` cd `dirname $0` shell_dir=`pwd` cd .. cd echo-proxy-lib/ mvn -Pint -Dmaven.test.skip=true clean install cd .. cd echo-common/ mvn -Pint -Dmaven.test.skip=true clean install cd ${shell_dir} mvn -Pint -Pprod -Dmaven.test.skip=true clean package appassembler:assemble publish_version=`cat ./pom.xml | grep '<echo-nat-server-pom-version>' | awk -F "version>" '{print $2}' | awk -F "</echo-nat-server" '{print $1}'| sed 's/^\s*//;s/\s*$//' ` cd target/dist-echo-nat-${publish_version}/ chmod +x ./bin/EchoNatServer.sh echo ${publish_version} > conf/echo_nat_version.txt zip -r dist-echo-nat-${publish_version}.zip ./* mv dist-echo-nat-${publish_version}.zip ../ cp conf/echo_nat_version.txt ../
def reversePrintArray(array): for i in range(len(array)-1, -1, -1): print(array[i])
#!/bin/sh cd "$(dirname $0)" for d in ../test_regression/test_*/ do echo "Beginning $(basename $d)" printf "\tTesting cxx driver..." if ! ../../util/cxx_interface/cxxsimple "$d/model.xml" "model" 0.1 100.0 100 300; then printf " error!\n" exit -1 fi printf " done\n" printf "\tTesting c driver..." if ! ../../util/c_interface/csimple "$d/model.xml" "model" 0.1 100.0 100 300; then printf " error!\n" exit -1 fi printf " done\n" printf "\tTesting fortran driver..." if ! ../../util/f_interface/fsimple "$d/model.xml" "model" 0.1 100.0 100 300; then printf " error!\n" exit -1 fi printf " done\n" echo "" done
#!/bin/bash for file in $@; do events=`grep 'Events shown' $file` totals=`grep 'PROGRAM TOTALS' $file` FS=';' read -ra totals_arr <<< "$totals" Dr=` echo ${totals_arr[3]} | sed 's/,//g'` D1mr=`echo ${totals_arr[4]} | sed 's/,//g'` DLmr=`echo ${totals_arr[5]} | sed 's/,//g'` Dw=` echo ${totals_arr[6]} | sed 's/,//g'` D1mw=`echo ${totals_arr[7]} | sed 's/,//g'` DLmw=`echo ${totals_arr[8]} | sed 's/,//g'` D1mwp=`expr $(expr 100 '*' $D1mw) '/' $Dw` D1mrp=`expr $(expr 100 '*' $D1mr) '/' $Dr` DLmwp=`expr $(expr 100 '*' $DLmw) '/' $Dw` DLmrp=`expr $(expr 100 '*' $DLmr) '/' $Dr` echo '' printf '%s: Data, L1 write miss rate: % 3d%% of % 5d\n' $file $D1mwp $Dw printf '%s: read miss rate: % 3d%% of % 5d\n' $file $D1mrp $Dr printf '%s: LL write miss rate: % 3d%% of % 5d\n' $file $DLmwp $Dw printf '%s: read miss rate: % 3d%% of % 5d\n' $file $DLmrp $Dr echo '' done
<filename>src/main.js document.addEventListener('DOMContentLoaded', () => { // 整理資料 const buildData = data => { return new Promise((resolve, reject) => { // 最後所有的資料會存在這 let arrayData = []; try { // 取 data 的第一個 Object 的 key 當表頭 let arrayTitle = Object.keys(data[0]); arrayData.push(arrayTitle); // 取出每一個 Object 裡的 value,push 進新的 Array 裡 Array.prototype.forEach.call(data, d => { let items = []; Array.prototype.forEach.call(arrayTitle, title => { let item = d[title] || '無'; items.push(item); }); arrayData.push(items) }); } catch(err) { reject(err) } resolve(arrayData); }) } // 轉成 CSV 並下載 const downloadCSV = data => { let csvContent = ''; Array.prototype.forEach.call(data, d => { let dataString = d.join(',') + '\n'; csvContent += dataString; }) // 下載的檔案名稱 let fileName = '下載資料_' + (new Date()).getTime() + '.csv'; // 建立一個 a,並點擊它 let link = document.createElement('a'); link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURI(csvContent)); link.setAttribute('download', fileName); link.click(); } // 點擊按鈕時下載 const btn = document.getElementById('download'); btn.addEventListener('click', () => { try { let data = JSON.parse(document.getElementById('textarea').value); buildData(data) .then(data => downloadCSV(data)) .catch(err => window.alert(err)); } catch(err) { window.alert(err) } }) })