text
stringlengths
1
1.05M
<reponame>isabella232/aurora from restbasetest import * from common.rest.security_helper import KeypairHelper class TestKeypairsRequests(RESTBaseTest): @classmethod def setup_class(cls): super(TestKeypairsRequests, cls).setup_class() cls.khelper = KeypairHelper(cls.utils) def teardown(self): # remove remaining keypairs self.utils.cleanup_objects(self.khelper.delete_keypair, 'keypairs', id_key='name') def test_list_of_pairs(self): pairs = self.utils.get_list('keypairs') ok_(type(pairs) == list, "Unable to get list of keypairs.") def test_create_remove_keypair(self): # create and verify result created = self.khelper.create_keypair() pname = created['name'] new_pairs = [p for p in self.utils.get_list('keypairs') if p['name'] == pname] ok_(len(new_pairs) == 1, 'Unable to create keypair.') # delete and verify result ok_(self.khelper.delete_keypair(pname), 'Unable to delete keypair. Keypair named "%s" still exists.' % pname) def test_import_keypair(self): # generate unique name pairs = self.utils.get_list('keypairs') pname = self.utils.generate_string(3, *[p['name'] for p in pairs]) key = ("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDY6/QGRGrMQOCAlMAROANw7HwO+CtxdfGnBWIobm8+TwtmERdOV0/93WKkHW3" "uBI73zs1pbO3hOKftAKI7VHmjJHnShuTfnV0wgWwkIGlRXwOS7EnBomXhgWXtdtbFWZYqn9rKBlfT8HPP1McEHScyWRKpIF+Nsvr" "Rt/vT2n0fcC3QM/zR6oU4rSb0kgX6R4x4zsLtHKW6L16L0zOFFqjw2YsdSF8mVEEFIDnZmohnVbn7WSkyhM1ujPQscCvP9pqdhEI" "cBtisMmv7uPkMefBT5Wlfv35LPnuuIXvXmQxtRdZzfyZlnUqsytOZErH6+uhbSseypukSpLimq1Q0I2q9 " "<EMAIL>") self.khelper.import_keypair({'name': pname, 'publicKey': key}) new_pairs = [p for p in self.utils.get_list('keypairs') if p['name'] == pname] ok_(len(new_pairs) == 1, "'Import keypair' failed.") if __name__ == '__main__': t = TestKeypairsRequests() t.setup_class() #t.test_list_of_pairs() t.test_create_remove_keypair() #t.test_import_keypair() t.teardown()
def get_rectangle_bounds(points): min_x, min_y = points[0] max_x, max_y = points[0] for x, y in points[1:]: min_x = min(min_x, x) min_y = min(min_y, y) max_x = max(max_x, x) max_y = max(max_y, y) return (min_x, min_y), (max_x, max_y) def get_rectangle_area(points): (min_x, min_y), (max_x, max_y) = get_rectangle_bounds(points) return (max_x - min_x) * (max_y - min_y)
const sgMail = require("@sendgrid/mail"); // const { createTransport, getTestMessageUrl } = require("nodemailer"); // const sendGridTransport = require("nodemailer-sendgrid-transport"); const { SENDGRID_API_KEY } = require("../_constants.js"); const { logger } = require("./logger.js"); async function sendMail(to, from, subject, html) { // const transport = createTransport( // sendGridTransport({ // auth: { api_key: SENDGRID_API_KEY }, // }) // ); // const info = await transport.sendMail({ // from: "<EMAIL>", // to, // subject, // html, // }); sgMail.setApiKey(SENDGRID_API_KEY); const msg = { to, from, subject, html, }; sgMail.send(msg).catch((error) => { logger.error(error.message, error); }); } module.exports = sendMail;
func reverseAndPrint(_ arr: [Character]) { for char in arr.reversed() { print(char, separator: "", terminator:" ") } }
#!/bin/bash # Copyright 2016 The Kubernetes Authors All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # exit on any error set -e ROLE=$1 source $(dirname "${BASH_SOURCE}")/environment.sh source $(dirname "${BASH_SOURCE}")/util.sh install_minimal_dependencies install_docker clone_kube_deploy /home/vagrant/kube-deploy/docker-multinode/${ROLE}.sh
function fibonacci(length) { let sequence = [0, 1]; for (let i = 2; i < length; i++) { sequence.push(sequence[i - 2] + sequence[i - 1]); } return sequence; } console.log(fibonacci(10)); // -> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
<reponame>AkaruiDevelopment/aoi.js<filename>src/functions/Funcs/misc/reboot.js module.exports = d => { const {code} = d.util.aoiFunc(d); try { process.on("exit", () => { require("child_process").spawn(process.argv.shift(), process.argv, { cwd: process.cwd(), detached: true, stdio: "inherit", }); }); process.exit(); } catch (e) { return d.aoiError.fnError(d, 'custom', {}, `Failed To Restart With Reason: ${e}`); } }
package main import "fmt" func isSymmetric(matrix [][]int) bool { // Get size of matrix size := len(matrix) // Check if matrix is square matrix if size == 0 || size != len(matrix[0]) { return false } // Compare the elements in the upper triangular matrix with elements in the lower triangular matrix for i := 0; i < size-1; i++ { for j := i + 1; j < size; j++ { if matrix[i][j] != matrix[j][i] { return false } } } return true } func main() { matrix := [][]int{{2, 3, 4}, {3, 4, 5}, {4, 5, 6}} fmt.Println(isSymmetric(matrix)) matrix = [][]int{{2, 3, 4}, {3, 5, 5}, {4, 5, 6}} fmt.Println(isSymmetric(matrix)) } Output: true false
<filename>gatsby-config.js module.exports = { // Since `gatsby-plugin-typescript` is automatically included in Gatsby you // don't need to define it here (just if you need to change the options) plugins: [ `gatsby-plugin-material-ui`, `gatsby-plugin-use-query-params`, `gatsby-plugin-emotion`, { resolve: `gatsby-plugin-google-gtag`, options: { trackingIds: ['G-4F9TH5XYE6'], }, }, ], };
<!-- Copyright 2020 Kansaneläkelaitos 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 fi.kela.kanta.to; import java.io.Serializable; public class VaikuttavaAineTO implements Serializable { private static final long serialVersionUID = 16785685655533L; private String laakeaine; private String laakeaineenTarkenne; private double vahvuus; private String vahvuusYksikko; public String getLaakeaine() { return laakeaine; } public void setLaakeaine(String laakeaine) { this.laakeaine = laakeaine; } public String getLaakeaineenTarkenne() { return laakeaineenTarkenne; } public void setLaakeaineenTarkenne(String laakeaineenTarkenne) { this.laakeaineenTarkenne = laakeaineenTarkenne; } public double getVahvuus() { return vahvuus; } public void setVahvuus(double vahvuus) { this.vahvuus = vahvuus; } public String getVahvuusYksikko() { return vahvuusYksikko; } public void setVahvuusYksikko(String vahvuusYksikko) { this.vahvuusYksikko = vahvuusYksikko; } }
CREATE DATABASE movie_review; USE movie_review; CREATE TABLE users ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL ); CREATE TABLE movies ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, title VARCHAR(255) NOT NULL, release_date DATE NOT NULL ); CREATE TABLE reviews ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, user_id INT NOT NULL, movie_id INT NOT NULL, rating INT NOT NULL, review TEXT NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (movie_id) REFERENCES movies(id) ); CREATE TABLE tags ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL ); CREATE TABLE movie_tags ( movie_id INT NOT NULL, tag_id INT NOT NULL, FOREIGN KEY (movie_id) REFERENCES movies(id), FOREIGN KEY (tag_id) REFERENCES tags(id) );
#!/bin/bash echo "running notebook" if [ ! -z ${JUPI_DEBUG} ]; then set -x printenv fi DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" JUPI_VIM_USER=${JUPI_VIM_USER:=0} USER=$(stat -c '%U' /lab) if [ $USER != "dev" ]; then chown -R dev:dev /lab fi USER=$(stat -c '%U' /code) if [ $USER != "dev" ]; then chown -R dev:dev /code fi USER=$(stat -c '%U' /home/dev) if [ $USER != "dev" ]; then chown -R dev:dev /home/dev fi docker_gid='' if [ -e /var/run/balena.sock ]; then docker_gid=$(stat -c '%g' /var/run/balena.sock) elif [ -e /var/run/docker.sock ]; then docker_gid=$(stat -c '%g' /var/run/docker.sock) chmod g+rw /var/run/docker.sock fi if [ ! -z $docker_gid ]; then groupmod -g $docker_gid docker fi CONFIG_VERSION=3 if [ ! -e /program/.jupiter/jupiter_config_version ] || [ "$(cat /program/.jupiter/jupiter_config_version)" != $CONFIG_VERSION ]; then mkdir -p /program/.jupiter su - dev -c 'git config --global credential.helper "cache --timeout=14400"' su - dev -c ' sed -i "/####BEGIN JUPITER SETTINGS/,/####END JUPITER SETTINGS/d" /home/dev/.bashrc && \ cat << EOF >> /home/dev/.bashrc ####BEGIN JUPITER SETTINGS if [ -e "/var/run/balena.sock" ]; then export DOCKER_HOST=unix:///var/run/balena.sock export DBUS_SYSTEM_BUS_ADDRESS=unix:path=/host/run/dbus/system_bus_socket fi ####END JUPITER SETTINGS EOF ' su -w "JUPI_VIM_USER" - dev -c "bash ${DIR}/code-server-installs.sh" echo $CONFIG_VERSION > /program/.jupiter/jupiter_config_version sync fi SYSTEM_CREDENTIAL_VERSION=1 USER_CREDENTIAL_VERSION=${JUPI_CREDENTIAL_VERSION:=0} SYSTEM_CREDENTIAL_VERSION="${SYSTEM_CREDENTIAL_VERSION}-${USER_CREDENTIAL_VERSION}" if [ -f /program/.jupiter/jupiter_credential_version ]; then CURR_CREDENTIAL_VERSION=$(cat /program/.jupiter/jupiter_credential_version) fi CURR_CREDENTIAL_VERSION=${CURR_CREDENTIAL_VERSION:="x-x"} if [ "$CURR_CREDENTIAL_VERSION" != "$SYSTEM_CREDENTIAL_VERSION" ]; then mkdir -p /program/.jupiter su -w "JUPI_AWS_ACCESS_KEY_ID,JUPI_AWS_SECRET_ACCESS_KEY" - dev -c "bash ${DIR}/s3_config.sh" echo "${SYSTEM_CREDENTIAL_VERSION}" > /program/.jupiter/jupiter_credential_version sync fi if [ ! -z ${JUPI_OVERRIDE_USER_PASSWORD} ] && [ ${JUPI_OVERRIDE_USER_PASSWORD} != ${JUPI_DEFAULT_USER_PASSWORD} ]; then echo "dev:${JUPI_OVERRIDE_USER_PASSWORD}" | chpasswd fi CONF_DIR="/program/dropbear" SSH_KEY_DSS="${CONF_DIR}/dropbear_dss_host_key" SSH_KEY_RSA="${CONF_DIR}/dropbear_rsa_host_key" # Check if conf dir exists if [ ! -d ${CONF_DIR} ]; then mkdir -p ${CONF_DIR} chown root:root ${CONF_DIR} chmod 755 ${CONF_DIR} fi if [ ! -d /home/dev/.ssh ]; then mkdir -p /home/dev/.ssh chmod 700 /home/dev/.ssh touch /home/dev/.ssh/authorized_keys chmod 600 /home/dev/.ssh/authorized_keys touch /home/dev/.ssh/config chmod 600 /home/dev/.ssh/config chown -R dev:dev /home/dev/.ssh fi # Check if keys exists if [ ! -f ${SSH_KEY_DSS} ]; then dropbearkey -t dss -f ${SSH_KEY_DSS} chown root:root ${SSH_KEY_DSS} chmod 600 ${SSH_KEY_DSS} fi if [ ! -f ${SSH_KEY_RSA} ]; then dropbearkey -t rsa -f ${SSH_KEY_RSA} -s 2048 chown root:root ${SSH_KEY_RSA} chmod 600 ${SSH_KEY_RSA} fi # Check if jupyter notebook config exists. If not create it with delete to trash false if [ ! -f "/home/dev/.jupyter/jupyter_notebook_config.py" ]; then su -w "PATH" - dev -c "jupyter notebook --generate-config && sed -i -e 's/#c.FileContentsManager.delete_to_trash.*/c.FileContentsManager.delete_to_trash = False/' -e 's/#c.NotebookApp.allow_password_change = True*/c.NotebookApp.allow_password_change = True/' '/home/dev/.jupyter/jupyter_notebook_config.py'" fi # Make sure dev user can run docker commands if [ -e /var/run/docker.sock ]; then chgrp docker /var/run/docker.sock fi su -w "CARGO_HOME,RUSTUP_HOME,JUPI_AIRFLOW_SECRET_KEY,JUPI_AIRFLOW_WEB_BASE_URL,PATH,BALENA_DEVICE_UUID" - dev -c "/app/airflow.sh &" # Start the first process cd /code JUPI_CODESERVER_TOKEN=${JUPI_CODESERVER_TOKEN:-${BALENA_DEVICE_UUID:-jupiter}} su -w "JUPI_CODESERVER_TOKEN,JUPI_AWS_ACCESS_KEY_ID,JUPI_AWS_SECRET_ACCESS_KEY,PATH,CARGO_HOME,RUSTUP_HOME,BALENA_DEVICE_UUID" - dev -c "if [ -e /code/.jupi_dev_env ]; then source /code/.jupi_dev_env; fi; PASSWORD=${JUPI_CODESERVER_TOKEN} code-server ${JUPI_CODE_SERVER_ARGS} --bind-addr 0.0.0.0:8080 /code &" status=$? if [ $status -ne 0 ]; then echo "Failed to start code-server: $status" exit $status fi # Start the second process cd /lab JUPI_NOTEBOOK_TOKEN=${JUPI_NOTEBOOK_TOKEN:-${BALENA_DEVICE_UUID:-jupiter}} JUPI_CODESERVER_TOKEN=${JUPI_CODESERVER_TOKEN:-${BALENA_DEVICE_UUID:-jupiter}} su -w "JUPI_NOTEBOOK_TOKEN,JUPI_AWS_ACCESS_KEY_ID,JUPI_AWS_SECRET_ACCESS_KEY,PATH,JUPYTERLAB_DIR,BALENA_DEVICE_UUID,CARGO_HOME,RUSTUP_HOME" - dev -c "cd /lab; if [ -e .jupi_dev_env ]; then source .jupi_dev_env; fi; jupyter notebook --NotebookApp.token=${JUPI_NOTEBOOK_TOKEN} ${JUPI_NOTEBOOK_ARGS} --no-browser --ip=* --port=8082 &" #jupyter notebook --allow-root --no-browser --ip=* --port=8082 & status=$? if [ $status -ne 0 ]; then echo "Failed to start jupyter: $status" exit $status fi # Start the third process echo "starting dropbear" /usr/sbin/dropbear -g -r ${SSH_KEY_DSS} -r ${SSH_KEY_RSA} & status=$? if [ $status -ne 0 ]; then echo "Failed to start dropbear: $status" exit $status fi websocat --binary ws-l:0.0.0.0:8022 tcp:127.0.0.1:22 & for f in /dev/i2c-*; do if [ -e "$f" ]; then chown :i2c "$f" chmod g+rw "$f" fi done for f in /dev/spidev*; do if [ -e "$f" ]; then chown :spi "$f" chmod g+rw "$f" fi done for f in dev/ttyUSB* /dev/ttyACM* /dev/ttyAMA*; do if [ -e "$f" ]; then chown :dialout "$f" chmod g+rw "$f" fi done if [ -e /dev/gpiomem ]; then chown :gpio "/dev/gpiomem" chmod g+rw "/dev/gpiomem" fi for f in /dev/gpiochip* ; do if [ -e "$f" ]; then chown :gpio "$f" && chmod g+rw "$f" fi done sleep 5 su -w "JUPI_NOTEBOOK_TOKEN,BALENA_DEVICE_UUID" - dev -c "bash ${DIR}/credentials.sh > /tmp/credentials.txt" service grafana-server start # run user root required startup tasks if [ -e /program/jupiter_startup_tasks.sh ]; then bash /home/dev/jupiter_startup_tasks.sh & fi # run user required startup tasks if [ -e /home/dev/jupiter_startup_tasks.sh ]; then su -w "JUPI_NOTEBOOK_TOKEN,JUPI_AWS_ACCESS_KEY_ID,JUPI_AWS_SECRET_ACCESS_KEY,PATH,JUPYTERLAB_DIR,BALENA_DEVICE_UUID,CARGO_HOME,RUSTUP_HOME" - dev -c "bash /home/dev/jupiter_startup_tasks.sh &" fi while sleep 60; do ps aux |grep code-server | grep -q -v grep PROCESS_1_STATUS=$? ps aux |grep jupyter | grep -q -v grep PROCESS_2_STATUS=$? ps aux |grep dropbear | grep -q -v grep PROCESS_3_STATUS=$? if [ $PROCESS_1_STATUS -ne 0 -o $PROCESS_2_STATUS -ne 0 -o $PROCESS_3_STATUS -ne 0 ]; then echo "One of the processes has already exited." exit 1 fi done
<filename>spacin/__main__.py<gh_stars>1-10 """This is Spacin entrypoint""" import sys import argparse import textwrap import time from spacin.spacin import Spacin from spacin.algorithm import BasicAlgorithm def main(args=None): """Project entrypoint function""" argparser = argparse.ArgumentParser( description="""\r \r----------------------------- \r Spacin, puts space between! \r-----------------------------\n\n \rSpacin is a word-separator that distinguishes \reach word in a given string.\n \rexample: \r> spacin "hellofriend" \r... \ras a sentence: "hello friend" \ras separate words: ['hello', 'friend'] """, formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent( """developed by <NAME> \r\n """ ), prog='spacin', usage="""%(prog)s <string>""" ) argparser.add_argument( 'input_str', action='store', type=str, nargs="?", help=argparse.SUPPRESS, ) argparser.add_argument( '-t', '--text', action='store', metavar='<string>', type=str, help='accept input text in commandline', ) argparser.add_argument( '-w', '--words', action='store_true', help='output result as words (as a list)') argparser.add_argument( '-s', '--sentence', action='store_true', help='output result in a sentence (as string)') try: args = argparser.parse_args() if not any([args.input_str, args.text]): argparser.print_help() sys.exit(1) elif all([args.input_str, args.text]): argparser.print_help() sys.exit(1) else: # show process details: show_process = True show_process = not any([args.sentence, args.words]) # select input: input_str = args.input_str if args.input_str else args.text # choose algorithm(s): algo = BasicAlgorithm() # algorithm(s) and input details: if show_process: print(f"input text:\t{input_str}") print(f"algorithm:\t{algo}") print("processing...", end=' ', flush=True) # run algorithm(s): start_time = time.time() res = Spacin.run(algo, input_str) end_time = time.time() # yell finished: if show_process: print("done!") print(f"and it took {end_time-start_time:.3f} seconds\n") # show results: if not any([args.sentence, args.words]): print(f"as a sentence:\t\t\"{' '.join(res)}\"") print(f"as separate words:\t{res}") elif all([args.sentence, args.words]): print(f"\"{' '.join(res)}\"") print(f"{res}") elif args.sentence: print(f"\"{' '.join(res)}\"") elif args.words: print(f"{res}") except argparse.ArgumentTypeError as arge: print('\n\nan argument error occured:', arge) print('enter "spacin -h" for help') sys.exit(1) if __name__ == "__main__": main()
class SensorInterface: def __init__(self, sensor): self.sensor = sensor def read_register(self, address, functioncode): # Simulate communication with the sensor and return appropriate values if functioncode == 4 and address == 2: return "Firmware Version: 1.0" elif functioncode == 3 and address == 0: return "Sensor Address: 0x1234" else: return "Invalid function code or register address" def getFwVersion(self): return self.read_register(2, functioncode=4) def getAddress(self): return self.read_register(0, functioncode=3) # Example usage sensor = MockSensor() # Replace with actual sensor instance sensor_interface = SensorInterface(sensor) print(sensor_interface.getFwVersion()) # Output: Firmware Version: 1.0 print(sensor_interface.getAddress()) # Output: Sensor Address: 0x1234
func isPalindrome(_ str: String) -> Bool { let alphanumericString = str.components(separatedBy: CharacterSet.alphanumerics.inverted).joined().lowercased() return alphanumericString == String(alphanumericString.reversed()) } // Test cases print(isPalindrome("A man, a plan, a canal, Panama")) // Output: true print(isPalindrome("racecar")) // Output: true print(isPalindrome("hello world")) // Output: false
#!/bin/sh #------------------------------------------------------------------------------ # # build-cdn-assets.sh: rebuild the dist directory with the latest changes. # # Required environment variables # - AZ_BOOTSTRAP_FROZEN_DIR Internal directory with saved npm setup # - AZ_BOOTSTRAP_SOURCE_DIR Source directory for files and directories # #------------------------------------------------------------------------------ set -e copy-npm-config cd "$AZ_BOOTSTRAP_SOURCE_DIR" npm run dist
package de.unistuttgart.ims.coref.annotator.document; import java.util.List; import org.apache.uima.cas.FeatureStructure; import org.eclipse.collections.api.list.ImmutableList; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.factory.Lists; import de.unistuttgart.ims.coref.annotator.document.op.Operation; public interface Event extends Iterable<FeatureStructure> { public enum Type { /** * This event creates a new object under an existing one. Argument 1: the * parent, argument 2: the new object. If the first argument is null, we assume * to create a new top level thing. */ Add, /** * Remove encodes an event in which arg2-argn are removed from arg1. */ Remove, /** * An update event is an internal event on arg1-argn that does not change the * tree structure. If a color is changed, update events are fired for all * mentions of the entity (this is done in CoreferenceModel). */ Update, /** * This describes moving arg3 to argn from arg1 to arg2. Arg2 becomes the new * parent, arg1 is the old one. */ Move, Merge, Op, /** * Once a listener is registered with a model, the init-event is sent. */ Init }; Type getType(); Operation getOp(); int getArity(); public static FeatureStructureEvent get(Model src, Type type, FeatureStructure fs, Iterable<? extends FeatureStructure> fsi) { MutableList<FeatureStructure> l = Lists.mutable.withAll(fsi); l.add(0, fs); return new FeatureStructureEvent(src, type, l); } public static FeatureStructureEvent get(Model src, Type type, FeatureStructure arg1, FeatureStructure arg2, ImmutableList<? extends FeatureStructure> fsi) { MutableList<FeatureStructure> l = Lists.mutable.withAll(fsi); l.add(0, arg2); l.add(0, arg1); return new FeatureStructureEvent(src, type, l); } public static FeatureStructureEvent get(Model src, Type type, Iterable<? extends FeatureStructure> fs) { return new FeatureStructureEvent(src, type, fs); } public static FeatureStructureEvent get(Model src, Type type, List<FeatureStructure> fs) { return new FeatureStructureEvent(src, type, fs); } public static FeatureStructureEvent get(Model src, Type type, FeatureStructure... fs) { return new FeatureStructureEvent(src, type, fs); } }
'use strict'; //dependencies var expect = require('chai').expect; var faker = require('faker'); var path = require('path'); var Transport = require(path.join(__dirname, '..', '..')); describe('Transport', function () { it('should export functional constructor', function (done) { expect(Transport).to.be.a('function'); done(); }); it('should have a default base url equals to https://api.infobip.com', function (done) { var transport = new Transport(); expect(transport.baseUrl).to.be.equal('https://api.infobip.com'); done(); }); it('should have username and password undefined by default', function ( done) { var transport = new Transport(); expect(transport.username).to.be.undefined; expect(transport.password).to.be.undefined; done(); }); it( 'should receive `No username and password provided` error when fail to build authorization token', function (done) { var transport = new Transport(); transport.getAuthorizationToken(function (error, token) { expect(token).to.be.undefined; expect(error).to.exist; expect(error.message).to.equal( 'No username or password provided'); done(); }); }); it('should be able to parse a given json string safely', function (done) { var data = faker.helpers.userCard(); var dataAsString = JSON.stringify(data); var transport = new Transport(); var dataAsJson = transport._parse(dataAsString); expect(dataAsJson).to.eql(data); done(); }); it('should be able to parse a given json object safely', function (done) { var data = faker.helpers.userCard(); var transport = new Transport(); var dataAsJson = transport._parse(data); expect(dataAsJson).to.eql(data); done(); }); it('should be able to merge provided `request` options', function (done) { var requestOptions = { timeout: 20000 }; var transport = new Transport({ request: requestOptions }); expect(transport.request).to.eql(requestOptions); done(); }); describe('defaults', function () { before(function () { process.env.SMS_INFOBIP_USERNAME = 'A6N='; process.env.SMS_INFOBIP_PASSWORD = '<PASSWORD>='; }); it('should use env defaults to initialize', function (done) { var transport = new Transport(); transport.getAuthorizationToken(function (error, token) { expect(error).to.not.exist; expect(token).to.exist; done(error, token); }); }); after(function () { delete process.env.SMS_INFOBIP_USERNAME; delete process.env.SMS_INFOBIP_PASSWORD; }); }); });
<reponame>Sid1000/sample-page export * from "./pin-input"; export * from "./use-pin-input"; //# sourceMappingURL=index.d.ts.map
BASEDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" DOTFILES_DIR="${BASEDIR}/dotfiles" # Create symlinks for dotfiles # ln -fsv ${DOTFILES_DIR}/.zshrc ~ rm ~/.zshrc.pre-oh-my-zsh ln -fsv ${DOTFILES_DIR}/.vimrc ~ ln -fsv ${DOTFILES_DIR}/.config/nvim/init.vim ~/.config/nvim/init.vim ln -fsv ${DOTFILES_DIR}/.ctags ~ ln -fsv ${BASEDIR}/gitkurwa/config ~/.gitconfig_gitkurwa ln -fsv ${DOTFILES_DIR}/.gitconfig ~ ln -fsv ${DOTFILES_DIR}/.gitignore ~ ln -fsv ${DOTFILES_DIR}/.gitconfig_local ~ # Install lambda-pure mkdir ~/.zsh_functions ln -fsv ${DOTFILES_DIR}/lambda-pure/lambda-pure.zsh ~/.zsh_functions/prompt_lambda-pure_setup ln -fsv ${DOTFILES_DIR}/lambda-pure/async.zsh ~/.zsh_functions/async
package engine.events; import engine.fsm.State; /** * Used to publish new states from the fsm * * @author Simran */ public class StateEvent extends Event { private State state; public StateEvent(State currState) { super(EventType.STATE.getType()); this.state = currState; } public State getState() { return state; } }
#!/bin/bash #SBATCH -J Act_cube_1 #SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de #SBATCH --mail-type=FAIL #SBATCH -e /work/scratch/se55gyhe/log/output.err.%j #SBATCH -o /work/scratch/se55gyhe/log/output.out.%j #SBATCH -n 1 # Number of cores #SBATCH --mem-per-cpu=6000 #SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins #module load intel python/3.5 python3 /home/se55gyhe/Act_func/sequence_tagging/arg_min/PE-my.py cube 128 Nadam 2 0.23687732426215133 0.001348231159606572 varscaling 0.3
// // NPCHelpers.js // scripts/interaction // // Created by <NAME> on 3/20/17. // Copyright 2017 High Fidelity Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var audioInjector = false; var blocked = false; var playingResponseAnim = false; var storyURL = ""; var _qid = "start"; print("TESTTEST"); function strContains(str, sub) { return str.search(sub) != -1; } function callbackOnCondition(conditionFunc, ms, callback, count) { var thisCount = 0; if (typeof count !== 'undefined') { thisCount = count; } if (conditionFunc()) { callback(); } else if (thisCount < 10) { Script.setTimeout(function() { callbackOnCondition(conditionFunc, ms, callback, thisCount + 1); }, ms); } else { print("callbackOnCondition timeout"); } } function playAnim(animURL, looping, onFinished) { print("got anim: " + animURL); print("looping: " + looping); // Start caching the animation if not already cached. AnimationCache.getAnimation(animURL); // Tell the avatar to animate so that we can tell if the animation is ready without crashing Avatar.startAnimation(animURL, 30, 1, false, false, 0, 1); // Continually check if the animation is ready callbackOnCondition(function(){ var details = Avatar.getAnimationDetails(); // if we are running the request animation and are past the first frame, the anim is loaded properly print("running: " + details.running); print("url and animURL: " + details.url.trim().replace(/ /g, "%20") + " | " + animURL.trim().replace(/ /g, "%20")); print("currentFrame: " + details.currentFrame); return details.running && details.url.trim().replace(/ /g, "%20") == animURL.trim().replace(/ /g, "%20") && details.currentFrame > 0; }, 250, function(){ var timeOfAnim = ((AnimationCache.getAnimation(animURL).frames.length / 30) * 1000) + 100; // frames to miliseconds plus a small buffer print("animation loaded. length: " + timeOfAnim); // Start the animation again but this time with frame information Avatar.startAnimation(animURL, 30, 1, looping, true, 0, AnimationCache.getAnimation(animURL).frames.length); if (typeof onFinished !== 'undefined') { print("onFinished defined. setting the timeout with timeOfAnim"); timers.push(Script.setTimeout(onFinished, timeOfAnim)); } }); } function playSound(soundURL, onFinished) { callbackOnCondition(function() { return SoundCache.getSound(soundURL).downloaded; }, 250, function() { if (audioInjector) { audioInjector.stop(); } audioInjector = Audio.playSound(SoundCache.getSound(soundURL), {position: Avatar.position, volume: 1.0}); if (typeof onFinished !== 'undefined') { audioInjector.finished.connect(onFinished); } }); } function npcRespond(soundURL, animURL, onFinished) { if (typeof soundURL !== 'undefined' && soundURL != '') { print("npcRespond got soundURL!"); playSound(soundURL, function(){ print("sound finished"); var animDetails = Avatar.getAnimationDetails(); print("animDetails.lastFrame: " + animDetails.lastFrame); print("animDetails.currentFrame: " + animDetails.currentFrame); if (animDetails.lastFrame < animDetails.currentFrame + 1 || !playingResponseAnim) { onFinished(); } audioInjector = false; }); } if (typeof animURL !== 'undefined' && animURL != '') { print("npcRespond got animURL!"); playingResponseAnim = true; playAnim(animURL, false, function() { print("anim finished"); playingResponseAnim = false; print("injector: " + audioInjector); if (!audioInjector || !audioInjector.isPlaying()) { print("resetting Timer"); print("about to call onFinished"); onFinished(); } }); } } function npcRespondBlocking(soundURL, animURL, onFinished) { print("blocking response requested"); if (!blocked) { print("not already blocked"); blocked = true; npcRespond(soundURL, animURL, function(){ if (onFinished){ onFinished(); }blocked = false; }); } } function npcContinueStory(soundURL, animURL, nextID, onFinished) { if (!nextID) { nextID = _qid; } npcRespondBlocking(soundURL, animURL, function(){ if (onFinished){ onFinished(); }setQid(nextID); }); } function setQid(newQid) { print("setting quid"); print("_qid: " + _qid); _qid = newQid; print("_qid: " + _qid); doActionFromServer("init"); } function runOnClient(code) { Messages.sendMessage("interactionComs", "clientexec:" + code); } function doActionFromServer(action, data, useServerCache) { if (action == "start") { ignoreCount = 0; _qid = "start"; } var xhr = new XMLHttpRequest(); xhr.open("POST", "http://gserv_devel.studiolimitless.com/story", true); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if (xhr.status == 200) { print("200!"); print("evaluating: " + xhr.responseText); Script.evaluate(xhr.responseText, ""); } else if (xhr.status == 444) { print("Limitless Serv 444: API error: " + xhr.responseText); } else { print("HTTP Code: " + xhr.status + ": " + xhr.responseText); } } }; xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var postData = "url=" + storyURL + "&action=" + action + "&qid=" + _qid; if (typeof data !== 'undefined' && data != '') { postData += "&data=" + data; } if (typeof useServerCache !== 'undefined' && !useServerCache) { postData += "&nocache=true"; } print("Sending: " + postData); xhr.send(postData); }
const projects = [ { hash: 'rdYVgK', title: 'Calculator with React', pen: 'https://codepen.io/manAbl/pen/rdYVgK/' }, { hash: 'YvdLqK', title: 'circular-motion', pen: 'https://codepen.io/manAbl/pen/YvdLqK/' }, { hash: 'wXbMGb', title: 'understanding mo.js', pen: 'https://codepen.io/manAbl/pen/wXbMGb/' }, { hash: 'BeKGEP', title: 'Pomodoro Clock - FreeCodeCamp Certificate', pen: 'https://codepen.io/manAbl/pen/BeKGEP/' }, { hash: 'aKQgZE', title: 'Understanding HTML5 Canvas', pen: 'https://codepen.io/manAbl/pen/aKQgZE/' } // { // hash: 'QxOMPJ', // title: 'Drum Machine - FreeCodeCamp Project', // pen: 'https://codepen.io/manAbl/pen/QxOMPJ/' // } ] export default projects
import { combineReducers, Reducer } from 'redux'; import { RootState } from 'app/reducers/state'; import { apiReducer } from 'app/ducks/api'; import { routerReducer, RouterState } from 'react-router-redux'; import { Reducer as appointmentReducer } from 'app/ducks/appointment'; export { RootState, RouterState }; export const rootReducer: Reducer<RootState> = combineReducers<RootState>({ requests: apiReducer, router: routerReducer, appointment: appointmentReducer });
package io.opensphere.laf.dark; import java.awt.Color; import java.awt.Font; import java.awt.image.Kernel; import java.util.Enumeration; import javax.swing.BorderFactory; import javax.swing.LookAndFeel; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.InsetsUIResource; import javax.swing.plaf.metal.MetalLookAndFeel; import javax.swing.plaf.metal.MetalTheme; /** * The OpenSphere Dark Look and Feel is derived from ( or inspired by ) the * NimROD Look and Feel by <NAME>. NimROD is licensed under LGPL. We * have re-written every class, and though most of the algorithms used to * compose the look and feel remain very similar, it has been re-written and * re-worked to provide a consistent look and feel for the OpenSphere tool, and * also to allow more customization of the UI implementation along with a * different theme. */ @SuppressWarnings("serial") public class OpenSphereDarkLookAndFeel extends MetalLookAndFeel { protected static MetalTheme theme; public OpenSphereDarkLookAndFeel() { super(); final OSDarkLAFTheme nt = new OSDarkLAFTheme(); setCurrentTheme(nt); float[] elements = new float[OSDarkLAFUtils.TITLE_SHADOW_THICKNESS * OSDarkLAFUtils.TITLE_SHADOW_THICKNESS]; for (int i = 0; i < elements.length; i++) { elements[i] = 0.1f; } int mid = OSDarkLAFUtils.TITLE_SHADOW_THICKNESS / 2 + 1; elements[mid * mid] = .2f; OSDarkLAFUtils.titleShaodowKernel = new Kernel(OSDarkLAFUtils.TITLE_SHADOW_THICKNESS, OSDarkLAFUtils.TITLE_SHADOW_THICKNESS, elements); elements = new float[OSDarkLAFUtils.MENU_SHADOW_THICKNESS * OSDarkLAFUtils.MENU_SHADOW_THICKNESS]; for (int i = 0; i < elements.length; i++) { elements[i] = 0.1f; } mid = OSDarkLAFUtils.MENU_SHADOW_THICKNESS / 2 + 1; elements[mid * mid] = .2f; OSDarkLAFUtils.menuShadowKernel = new Kernel(OSDarkLAFUtils.MENU_SHADOW_THICKNESS, OSDarkLAFUtils.MENU_SHADOW_THICKNESS, elements); } @Override public void initialize() { try { final LookAndFeel laf = (LookAndFeel)Class.forName(UIManager.getSystemLookAndFeelClassName()).getDeclaredConstructor() .newInstance(); final UIDefaults def = laf.getDefaults(); final Enumeration<Object> keys = def.keys(); String key; while (keys.hasMoreElements()) { key = keys.nextElement().toString(); if (key.contains("InputMap")) { UIManager.getDefaults().put(key, def.get(key)); } } } catch (final Exception ex) { // ex.printStackTrace(); } } @Override public String getID() { return "OSDarkLAF"; } @Override public String getName() { return "OSDarkLAF"; } @Override public String getDescription() { return "OpenSphere Dark Look and Feel"; } @Override public boolean isNativeLookAndFeel() { return false; } @Override public boolean isSupportedLookAndFeel() { return true; } @Override public boolean getSupportsWindowDecorations() { return false; } public static void setCurrentTheme(MetalTheme metTheme) { MetalLookAndFeel.setCurrentTheme(metTheme); theme = metTheme; OSDarkLAFUtils.rolloverColor = null; } @Override protected void initClassDefaults(UIDefaults defaults) { super.initClassDefaults(defaults); defaults.put("ButtonUI", "io.opensphere.laf.dark.OSDarkLAFButtonUI"); defaults.put("ToggleButtonUI", "io.opensphere.laf.dark.OSDarkLAFToggleButtonUI"); defaults.put("TextFieldUI", "io.opensphere.laf.dark.OSDarkLAFTextFieldUI"); defaults.put("TextAreaUI", "io.opensphere.laf.dark.OSDarkLAFTextAreaUI"); defaults.put("PasswordFieldUI", "io.opensphere.laf.dark.OSDarkLAFPasswordFieldUI"); defaults.put("CheckBoxUI", "io.opensphere.laf.dark.OSDarkLAFCheckBoxUI"); defaults.put("RadioButtonUI", "io.opensphere.laf.dark.OSDarkLAFRadioButtonUI"); defaults.put("FormattedTextFieldUI", "io.opensphere.laf.dark.OSDarkLAFFormattedTextFieldUI"); defaults.put("SliderUI", "io.opensphere.laf.dark.OSDarkLAFSliderUI"); defaults.put("SpinnerUI", "io.opensphere.laf.dark.OSDarkLAFSpinnerUI"); defaults.put("ListUI", "io.opensphere.laf.dark.OSDarkLAFListUI"); defaults.put("ComboBoxUI", "io.opensphere.laf.dark.OSDarkLAFComboBoxUI"); defaults.put("ScrollBarUI", "io.opensphere.laf.dark.OSDarkLAFScrollBarUI"); defaults.put("ToolBarUI", "io.opensphere.laf.dark.OSDarkLAFToolBarUI"); defaults.put("ProgressBarUI", "io.opensphere.laf.dark.OSDarkLAFProgressBarUI"); defaults.put("ScrollPaneUI", "io.opensphere.laf.dark.OSDarkLAFScrollPaneUI"); defaults.put("TabbedPaneUI", "io.opensphere.laf.dark.OSDarkLAFTabbedPaneUI"); defaults.put("TableHeaderUI", "io.opensphere.laf.dark.OSDarkLAFTableHeaderUI"); defaults.put("SplitPaneUI", "io.opensphere.laf.dark.OSDarkLAFSplitPaneUI"); defaults.put("InternalFrameUI", "io.opensphere.laf.dark.OSDarkLAFInternalFrameUI"); defaults.put("DesktopIconUI", "io.opensphere.laf.dark.OSDarkLAFDesktopIconUI"); defaults.put("ToolTipUI", "io.opensphere.laf.dark.OSDarkLAFToolTipUI"); defaults.put("MenuBarUI", "io.opensphere.laf.dark.OSDarkLAFMenuBarUI"); defaults.put("MenuUI", "io.opensphere.laf.dark.OSDarkLAFMenuUI"); defaults.put("SeparatorUI", "io.opensphere.laf.dark.OSDarkLAFSeparatorUI"); defaults.put("PopupMenuUI", "io.opensphere.laf.dark.OSDarkLAFPopupMenuUI"); defaults.put("PopupMenuSeparatorUI", "io.opensphere.laf.dark.OSDarkLAFPopupMenuSeparatorUI"); defaults.put("MenuItemUI", "io.opensphere.laf.dark.OSDarkLAFMenuItemUI"); defaults.put("CheckBoxMenuItemUI", "io.opensphere.laf.dark.OSDarkLAFCheckBoxMenuItemUI"); defaults.put("RadioButtonMenuItemUI", "io.opensphere.laf.dark.OSDarkLAFRadioButtonMenuItemUI"); } @Override protected void initSystemColorDefaults(UIDefaults def) { super.initSystemColorDefaults(def); def.put("textHighlight", getMenuSelectedBackground()); def.put("textInactiveText", getInactiveSystemTextColor().darker()); } @Override protected void initComponentDefaults(UIDefaults uiDefaults) { super.initComponentDefaults(uiDefaults); try { final ColorUIResource colorForeground = (ColorUIResource)uiDefaults.get("MenuItem.disabledForeground"); final ColorUIResource colorBackground = (ColorUIResource)uiDefaults.get("MenuItem.foreground"); final ColorUIResource col = OSDarkLAFUtils.getThirdColor(colorBackground, colorForeground); uiDefaults.put("MenuItem.disabledForeground", col); uiDefaults.put("Label.disabledForeground", col); uiDefaults.put("CheckBoxMenuItem.disabledForeground", col); uiDefaults.put("Menu.disabledForeground", col); uiDefaults.put("RadioButtonMenuItem.disabledForeground", col); uiDefaults.put("ComboBox.disabledForeground", col); uiDefaults.put("Button.disabledText", col); uiDefaults.put("ToggleButton.disabledText", col); uiDefaults.put("CheckBox.disabledText", col); uiDefaults.put("RadioButton.disabledText", col); final ColorUIResource col2 = OSDarkLAFUtils.getThirdColor(OpenSphereDarkLookAndFeel.getWhite(), (Color)uiDefaults.get("TextField.inactiveBackground")); uiDefaults.put("TextField.inactiveBackground", col2); } catch (final Exception ex) { ex.printStackTrace(); } uiDefaults.put("MenuBar.border", OSDarkLAFBorders.getMenuBarBorder()); final Font fontMenu = ((Font)uiDefaults.get("Menu.font")).deriveFont(Font.BOLD); uiDefaults.put("MenuItem.acceleratorFont", fontMenu); uiDefaults.put("RadioButtonMenuItem.acceleratorFont", fontMenu); uiDefaults.put("CheckBoxMenuItem.acceleratorFont", fontMenu); final ColorUIResource colAcce = OSDarkLAFUtils.getThirdColor((ColorUIResource)uiDefaults.get("MenuItem.foreground"), (ColorUIResource)uiDefaults.get("MenuItem.acceleratorForeground")); uiDefaults.put("MenuItem.acceleratorForeground", colAcce); uiDefaults.put("RadioButtonMenuItem.acceleratorForeground", colAcce); uiDefaults.put("CheckBoxMenuItem.acceleratorForeground", colAcce); // For popupmenu's shadows uiDefaults.put("BorderPopupMenu.MenuShadowBottomIcon", OSDarkLAFUtils.loadImageResource("/icons/MenuShadowBottom.png")); uiDefaults.put("BorderPopupMenu.MenuShadowRight", OSDarkLAFUtils.loadImageResource("/icons/MenuShadowRight.png")); uiDefaults.put("BorderPopupMenu.MenuShadowTopLeft", OSDarkLAFUtils.loadImageResource("/icons/MenuShadowTopLeft.png")); uiDefaults.put("BorderPopupMenu.MenuShadowUp", OSDarkLAFUtils.loadImageResource("/icons/MenuShadowUp.png")); uiDefaults.put("BorderPopupMenu.MenuShadowTopRight", OSDarkLAFUtils.loadImageResource("/icons/MenuShadowTopRight.png")); // JTree Support uiDefaults.put("Tree.collapsedIcon", OSDarkLAFIconFactory.getTreeCollapsedIcon()); uiDefaults.put("Tree.expandedIcon", OSDarkLAFIconFactory.getTreeExpandedIcon()); uiDefaults.put("Tree.closedIcon", OSDarkLAFUtils.loadImageResource("/icons/ClosedFolder.png")); uiDefaults.put("Tree.openIcon", OSDarkLAFUtils.loadImageResource("/icons/OpenFolder.png")); uiDefaults.put("Tree.leafIcon", OSDarkLAFUtils.loadImageResource("/icons/TreeFileIcon.png")); uiDefaults.put("Tree.PickIcon", OSDarkLAFUtils.loadImageResource("/icons/TreeBubble.png")); // Dialogs and Files uiDefaults.put("FileView.directoryIcon", OSDarkLAFUtils.loadImageResource("/icons/DialogClosedFolder.png")); uiDefaults.put("FileView.fileIcon", OSDarkLAFUtils.loadImageResource("/icons/DialogFileIcon.png")); uiDefaults.put("FileView.floppyDriveIcon", OSDarkLAFUtils.loadImageResource("/icons/DialogFloppyIcon.png")); uiDefaults.put("FileView.hardDriveIcon", OSDarkLAFUtils.loadImageResource("/icons/DialogHDIcon.png")); uiDefaults.put("FileChooser.newFolderIcon", OSDarkLAFUtils.loadImageResource("/icons/DialogNewDir.png")); uiDefaults.put("FileChooser.homeFolderIcon", OSDarkLAFUtils.loadImageResource("/icons/DialogHome.png")); uiDefaults.put("FileChooser.upFolderIcon", OSDarkLAFUtils.loadImageResource("/icons/DialogDirUp.png")); uiDefaults.put("FileChooser.detailsViewIcon", OSDarkLAFUtils.loadImageResource("/icons/DialogDetails.png")); uiDefaults.put("FileChooser.listViewIcon", OSDarkLAFUtils.loadImageResource("/icons/DialogList.png")); // Check Boxes and Radio Buttons uiDefaults.put("CheckBoxMenuItem.checkIcon", OSDarkLAFIconFactory.getCheckBoxMenuItemIcon()); uiDefaults.put("RadioButtonMenuItem.checkIcon", OSDarkLAFIconFactory.getRadioButtonMenuItemIcon()); // Files and Combo Buttons uiDefaults.put("ComboBox.arrowIcon", OSDarkLAFUtils.loadImageResource("/icons/ComboButtonDown.png")); uiDefaults.put("ComboBox.buttonDownIcon", OSDarkLAFIconFactory.getComboArrowIcon()); // Menu Icons uiDefaults.put("Menu.checkIcon", OSDarkLAFIconFactory.getBandaMenuItemIcon()); uiDefaults.put("MenuItem.checkIcon", OSDarkLAFIconFactory.getBandaMenuItemIcon()); uiDefaults.put("MenuCheckBox.iconBase", OSDarkLAFUtils.loadImageResource("/icons/MenuCheckBoxBase.png")); uiDefaults.put("MenuCheckBox.iconTick", OSDarkLAFUtils.loadImageResource("/icons/MenuCheckBoxTick.png")); uiDefaults.put("MenuRadioButton.iconBase", OSDarkLAFUtils.loadImageResource("/icons/MenuRadioBase.png")); uiDefaults.put("MenuRadioButton.iconTick", OSDarkLAFUtils.loadImageResource("/icons/MenuRadioTick.png")); uiDefaults.put("CheckBox.iconBase", OSDarkLAFUtils.loadImageResource("/icons/CheckBoxBase.png")); uiDefaults.put("CheckBox.iconTick", OSDarkLAFUtils.loadImageResource("/icons/CheckBoxTick.png")); uiDefaults.put("OSTristateCheckBox.icon", OSDarkLAFUtils.loadImageResource("/icons/TriStateCheckBox.png")); uiDefaults.put("RadioButton.iconBase", OSDarkLAFUtils.loadImageResource("/icons/RadioButtonBase.png")); uiDefaults.put("RadioButton.iconTick", OSDarkLAFUtils.loadImageResource("/icons/RadioButtonTick.png")); // Border Icons uiDefaults.put("BorderGeneralTop", OSDarkLAFUtils.loadImageResource("/icons/BorderGeneralTop.png")); uiDefaults.put("BorderGeneralUpperRight", OSDarkLAFUtils.loadImageResource("/icons/BorderGeneralUpperRight.png")); uiDefaults.put("BorderGeneralRight", OSDarkLAFUtils.loadImageResource("/icons/BorderGeneralRight.png")); uiDefaults.put("BorderGeneralBottomRight", OSDarkLAFUtils.loadImageResource("/icons/BorderGeneralBottomRight.png")); uiDefaults.put("BorderGeneralBottom", OSDarkLAFUtils.loadImageResource("/icons/BorderGeneralBottom.png")); uiDefaults.put("BorderGeneralBottomLeft", OSDarkLAFUtils.loadImageResource("/icons/BorderGeneralBottomLeft.png")); uiDefaults.put("BorderGeneralLeft", OSDarkLAFUtils.loadImageResource("/icons/BorderGeneralLeft.png")); uiDefaults.put("BorderGeneralUpperLeft", OSDarkLAFUtils.loadImageResource("/icons/BorderGeneralUpperLeft.png")); // Standard Borders uiDefaults.put("List.border", OSDarkLAFBorders.getGenBorder()); uiDefaults.put("ScrollPane.viewportBorder", OSDarkLAFBorders.getGenBorder()); uiDefaults.put("Menu.border", OSDarkLAFBorders.getGenMenuBorder()); uiDefaults.put("ToolBar.border", OSDarkLAFBorders.getToolBarBorder()); uiDefaults.put("TextField.border", OSDarkLAFBorders.getTextFieldBorder()); uiDefaults.put("TextArea.border", OSDarkLAFBorders.getTextFieldBorder()); uiDefaults.put("FormattedTextField.border", OSDarkLAFBorders.getTextFieldBorder()); uiDefaults.put("PasswordField.border", OSDarkLAFBorders.getTextFieldBorder()); uiDefaults.put("ToolTip.border", OSDarkLAFBorders.getToolTipBorder()); uiDefaults.put("Table.focusCellHighlightBorder", OSDarkLAFBorders.getCellFocusBorder()); uiDefaults.put("ScrollPane.border", OSDarkLAFBorders.getScrollPaneBorder()); // Tool Tips final ColorUIResource col2 = OSDarkLAFUtils.getThirdColor(OpenSphereDarkLookAndFeel.getFocusColor(), (Color)uiDefaults.get("TextField.inactiveBackground")); uiDefaults.put("ToolTip.background", col2); uiDefaults.put("ToolTip.foregroundInactive", OpenSphereDarkLookAndFeel.getBlack()); uiDefaults.put("ToolTip.font", uiDefaults.get("Menu.font")); // Spinners uiDefaults.put("Spinner.editorBorderPainted", Boolean.FALSE); uiDefaults.put("Spinner.border", OSDarkLAFBorders.getTextFieldBorder()); uiDefaults.put("Spinner.arrowButtonBorder", BorderFactory.createEmptyBorder()); uiDefaults.put("Spinner.nextIcon", OSDarkLAFIconFactory.getSpinnerNextIcon()); uiDefaults.put("Spinner.previousIcon", OSDarkLAFIconFactory.getSpinnerPreviousIcon()); // Icons and Dialogs uiDefaults.put("OptionPane.errorIcon", OSDarkLAFUtils.loadImageResource("/icons/Error.png")); uiDefaults.put("OptionPane.informationIcon", OSDarkLAFUtils.loadImageResource("/icons/Inform.png")); uiDefaults.put("OptionPane.warningIcon", OSDarkLAFUtils.loadImageResource("/icons/Warn.png")); uiDefaults.put("OptionPane.questionIcon", OSDarkLAFUtils.loadImageResource("/icons/Question.png")); // Slider Icons uiDefaults.put("Slider.horizontalThumbIcon", OSDarkLAFIconFactory.getSliderHorizontalIcon()); uiDefaults.put("Slider.verticalThumbIcon", OSDarkLAFIconFactory.getSliderVerticalIcon()); uiDefaults.put("Slider.horizontalThumbIconImage", OSDarkLAFUtils.loadImageResource("/icons/HorizontalThumbIconImage.png")); uiDefaults.put("Slider.verticalThumbIconImage", OSDarkLAFUtils.loadImageResource("/icons/VerticalThumbIconImage.png")); // Scrollbar Icons uiDefaults.put("ScrollBar.horizontalThumbIconImage", OSDarkLAFUtils.loadImageResource("/icons/HorizontalScrollIconImage.png")); uiDefaults.put("ScrollBar.verticalThumbIconImage", OSDarkLAFUtils.loadImageResource("/icons/VerticalScrollIconImage.png")); uiDefaults.put("ScrollBar.northButtonIconImage", OSDarkLAFUtils.loadImageResource("/icons/ScrollBarNorthButtonIconImage.png")); uiDefaults.put("ScrollBar.southButtonIconImage", OSDarkLAFUtils.loadImageResource("/icons/ScrollBarSouthButtonIconImage.png")); uiDefaults.put("ScrollBar.eastButtonIconImage", OSDarkLAFUtils.loadImageResource("/icons/ScrollBarEastButtonIconImage.png")); uiDefaults.put("ScrollBar.westButtonIconImage", OSDarkLAFUtils.loadImageResource("/icons/ScrollBarWestButtonIconImage.png")); uiDefaults.put("ScrollBar.northButtonIcon", OSDarkLAFIconFactory.getScrollBarNorthButtonIcon()); uiDefaults.put("ScrollBar.southButtonIcon", OSDarkLAFIconFactory.getScrollBarSouthButtonIcon()); uiDefaults.put("ScrollBar.eastButtonIcon", OSDarkLAFIconFactory.getScrollBarEastButtonIcon()); uiDefaults.put("ScrollBar.westButtonIcon", OSDarkLAFIconFactory.getScrollBarWestButtonIcon()); // Button Margins uiDefaults.put("Button.margin", new InsetsUIResource(5, 14, 5, 14)); uiDefaults.put("ToggleButton.margin", new InsetsUIResource(5, 14, 5, 14)); // Internal Frames and Icons uiDefaults.put("Desktop.background", uiDefaults.get("MenuItem.background")); uiDefaults.put("InternalFrame.border", OSDarkLAFBorders.getInternalFrameBorder()); uiDefaults.put("InternalFrame.OSDarkLAFCloseIcon", OSDarkLAFUtils.loadImageResource("/icons/FrameClose.png")); uiDefaults.put("InternalFrame.OSDarkLAFCloseIconRoll", OSDarkLAFUtils.loadImageResource("/icons/FrameCloseRoll.png")); uiDefaults.put("InternalFrame.OSDarkLAFCloseIconPush", OSDarkLAFUtils.loadImageResource("/icons/FrameClosePush.png")); uiDefaults.put("InternalFrame.OSDarkLAFMaxIcon", OSDarkLAFUtils.loadImageResource("/icons/FrameMaximiza.png")); uiDefaults.put("InternalFrame.OSDarkLAFMaxIconRoll", OSDarkLAFUtils.loadImageResource("/icons/FrameMaximizaRoll.png")); uiDefaults.put("InternalFrame.OSDarkLAFMaxIconPush", OSDarkLAFUtils.loadImageResource("/icons/FrameMaximizaPush.png")); uiDefaults.put("InternalFrame.OSDarkLAFMinIcon", OSDarkLAFUtils.loadImageResource("/icons/FrameMinimiza.png")); uiDefaults.put("InternalFrame.OSDarkLAFMinIconRoll", OSDarkLAFUtils.loadImageResource("/icons/FrameMinimizaRoll.png")); uiDefaults.put("InternalFrame.OSDarkLAFMinIconPush", OSDarkLAFUtils.loadImageResource("/icons/FrameMinimizaPush.png")); uiDefaults.put("InternalFrame.OSDarkLAFResizeIcon", OSDarkLAFUtils.loadImageResource("/icons/FrameResize.png")); uiDefaults.put("InternalFrame.OSDarkLAFResizeIconRoll", OSDarkLAFUtils.loadImageResource("/icons/FrameResizeRoll.png")); uiDefaults.put("InternalFrame.OSDarkLAFResizeIconPush", OSDarkLAFUtils.loadImageResource("/icons/FrameResizePush.png")); uiDefaults.put("InternalFrame.closeIcon", OSDarkLAFIconFactory.getFrameCloseIcon()); uiDefaults.put("InternalFrame.minimizeIcon", OSDarkLAFIconFactory.getFrameAltMaximizeIcon()); uiDefaults.put("InternalFrame.maximizeIcon", OSDarkLAFIconFactory.getFrameMaxIcon()); uiDefaults.put("InternalFrame.iconifyIcon", OSDarkLAFIconFactory.getFrameMinIcon()); uiDefaults.put("InternalFrame.icon", OSDarkLAFUtils.loadImageResource("/icons/Frame.png")); uiDefaults.put("OSDarkLAFInternalFrameIconLit.width", Integer.valueOf(20)); uiDefaults.put("OSDarkLAFInternalFrameIconLit.height", Integer.valueOf(20)); final Font fontIcon = ((Font)uiDefaults.get("InternalFrame.titleFont")).deriveFont(Font.BOLD); uiDefaults.put("DesktopIcon.font", fontIcon); uiDefaults.put("OSDarkLAFDesktopIcon.width", Integer.valueOf(80)); uiDefaults.put("OSDarkLAFDesktopIcon.height", Integer.valueOf(60)); uiDefaults.put("OSDarkLAFDesktopIconBig.width", Integer.valueOf(48)); uiDefaults.put("OSDarkLAFDesktopIconBig.height", Integer.valueOf(48)); uiDefaults.put("InternalFrame.activeTitleBackground", getMenuSelectedBackground()); uiDefaults.put("InternalFrame.activeTitleGradient", getMenuSelectedBackground().darker()); uiDefaults.put("InternalFrame.inactiveTitleBackground", getMenuBackground().brighter()); uiDefaults.put("InternalFrame.inactiveTitleGradient", getMenuBackground().darker()); } }
package com.lambo.robot; import com.lambo.robot.model.RobotMsg; import com.lambo.robot.model.enums.MsgTypeEnum; import com.lambo.robot.model.msgs.HearMsg; import com.lambo.robot.model.msgs.InterruptMsg; import com.lambo.robot.model.msgs.ListeningMsg; import com.lambo.robot.model.msgs.SpeakMsg; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; /** * 当前应用的上下文. * Created by lambo on 2017/7/24. */ public class RobotAppContext { private final Logger logger = LoggerFactory.getLogger(getClass()); /** * 进行id. */ private final int pid; /** * 当前环境所属app. */ private final IApp app; /** * 查询任务运行的级别.越小越早被调用. */ private int runningLevel = 300; /** * 系统上下文. */ private final RobotSystemContext systemContext; public RobotAppContext(RobotSystemContext systemContext, IApp app, int pid) { this.systemContext = systemContext; this.app = app; this.pid = pid; } public RobotSystemContext getSystemContext() { return systemContext; } /** * 添加系统消息. * * @param robotMsg 应用消息. */ public void addMsg(RobotMsg<?> robotMsg) { systemContext.addMsg(this, robotMsg); } public RobotConfig getRobotConfig() { return systemContext.getRobotConfig(); } public IApp getApp() { return app; } public int getPid() { return pid; } public void regListener(MsgTypeEnum[] msgTypeEnums) { systemContext.getAppManager().regListener(app, msgTypeEnums); } public int getRunningLevel() { return runningLevel; } public void setRunningLevel(int runningLevel) { this.runningLevel = runningLevel; } @Override public String toString() { return "RobotAppContext{" + "pid=" + pid + ", app=" + app + ", systemContext=" + systemContext + '}'; } public boolean say(SpeakMsg speakMsg) throws Exception { return systemContext.getAppManager().msgHandle(systemContext, speakMsg); } public HearMsg listening() throws InterruptedException, ExecutionException, TimeoutException { addMsg(new ListeningMsg()); try { return (HearMsg) systemContext.getMsgManager().getRobotMsg(MsgTypeEnum.hear, 60000); } finally { addMsg(new InterruptMsg(MsgTypeEnum.listening)); } } }
'use strict'; const config = require('../../config/config'); module.exports.landings = function (ctx) { return ctx.mongo.collection(config.dbLandingsCollectionName) }; module.exports.users = function (ctx) { return ctx.mongo.collection(config.dbUsersCollectionName) }; module.exports.usersHistory = function (ctx) { return ctx.mongo.collection(config.dbUsersHistoryCollectionName) }; module.exports.usersSessions = function (ctx) { return ctx.mongo.collection(config.dbUsersSessionsCollectionName) }; module.exports.usersUploads = function (ctx) { return ctx.mongo.collection(config.dbUsersUploadsCollectionName) }; module.exports.features = function (ctx) { return ctx.mongo.collection(config.dbUsersFeaturesCollectionName) }; module.exports.tariffs = function (ctx) { return ctx.mongo.collection(config.dbUsersTariffsCollectionName) }; module.exports.tariffsHistory = function (ctx) { return ctx.mongo.collection(config.dbUsersTariffsHistoryCollectionName) }; module.exports.accountingUsers = function (ctx) { return ctx.mongo.collection(config.dbAccountingUsersCollectionName) }; module.exports.accountingInternal = function (ctx) { return ctx.mongo.collection(config.dbAccountingInternalCollectionName) };
<gh_stars>1-10 package ml.banq.atm; import javax.swing.SwingUtilities; // The main code entry point public class Main { private Main() {} public static void main(String[] args) { // Run the run method of the App singleton in the right Swing thread SwingUtilities.invokeLater(App.getInstance()); } }
/** * Copyright 2021 Shulie Technology, Co.Ltd * Email: <EMAIL> * 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, * See the License for the specific language governing permissions and * limitations under the License. */ package com.pamirs.attach.plugin.shadowjob.interceptor; import com.pamirs.pradar.interceptor.AroundInterceptor; import com.pamirs.pradar.pressurement.agent.shared.service.GlobalConfig; import com.shulie.instrument.simulator.api.listener.ext.Advice; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @Auther: vernon * @Date: 2020/4/8 00:24 * @Description: */ public class SpringMvcInterceptor extends AroundInterceptor { @Override public void doBefore(Advice advice) { Object[] args = advice.getParameterArray(); Set<String> apis = new HashSet<String>(); Map<RequestMappingInfo, HandlerMethod> arg = (Map<RequestMappingInfo, HandlerMethod>) args[0]; Set<RequestMappingInfo> sets = arg.keySet(); for (RequestMappingInfo info : sets) { String url = info.getPatternsCondition().toString(); String api = (url).substring(1, url.length() - 1); String type = info.getMethodsCondition().toString(); apis.add(api + "#" + type); } GlobalConfig.getInstance().setApis(apis); } }
using System; using System.Collections.Generic; public class AccountService { private Dictionary<string, Account> accounts; public AccountService() { this.accounts = new Dictionary<string, Account>(); } public void CreateAccount(string accountNumber, string name, decimal balance) { this.accounts.Add(accountNumber, new Account { AccountNumber = accountNumber, Name = name, Balance = balance }); } public Account GetAccount(string accountNumber) { return this.accounts[accountNumber]; } public void UpdateAccount(string accountNumber, decimal balance) { Account account = this.accounts[accountNumber]; account.Balance = balance; } } public class Account { public string AccountNumber { get; set; } public string Name { get; set; } public decimal Balance { get; set; } }
#!/bin/bash # Internal variables PELION_PACKAGE_NAME="pe-utils" PELION_PACKAGE_DIR=$(cd "`dirname \"$0\"`" && pwd) declare -A PELION_PACKAGE_COMPONENTS=( ["https://github.com/armPelionEdge/pe-utils.git"]="6a436d6986c67f36936a40d31f43462c97b6f615") source "$PELION_PACKAGE_DIR"/../../build-env/inc/build-common.sh pelion_main "$@"
import subprocess import os def is_process_running(process_name): try: subprocess.check_output(["pidof", process_name]) return True except subprocess.CalledProcessError: return False def start_process(process_path): try: subprocess.Popen([process_path]) print(f"Started {process_path}") except Exception as e: print(f"Error starting {process_path}: {e}") def stop_and_start_process(process_name, process_path): try: subprocess.run(["pkill", process_name]) print(f"Stopped {process_name}") start_process(process_path) except Exception as e: print(f"Error stopping {process_name} or starting {process_path}: {e}") if __name__ == "__main__": vna_process_name = "vna" vna_process_path = "/opt/redpitaya/www/apps/vna/vna" if is_process_running(vna_process_name): stop_and_start_process(vna_process_name, vna_process_path) else: start_process(vna_process_path)
<gh_stars>0 from multiprocessing import Process import time from time import sleep '''开启子进程的两种方式''' # def test(name): # print("%s is running",name) # sleep(1) # print("%s is done") # # if __name__ == '__main__': # p = Process(target=test,args=("jack",)) # p.start() # class MyProcess(Process): # def __init__(self,name): # super(MyProcess, self).__init__() # self.name = name # # def run(self): # print("%s is running", self.name) # sleep(1) # # if __name__ == '__main__': # p = MyProcess("jack") # p.start() '''进程间相互隔离''' # x = 1999 # # def test(): # global x # x = 0 # print("x is %s",x) # # if __name__ == '__main__': # print(x) # p = Process(target=test) # p.start() # print(x) '''join函数''' # 调用start函数之后,就由操作系统来玩了,至于何时开启进程,何时执行 # x = 1000 # def test(): # global x # x = 10 # print("test's x is", x) # # sleep(1) # # if __name__ == '__main__': # p = Process(target=test) # p.start() # # p.join() # 让父进程在原地等 # print(x) '''案例2''' # def test(num): # print("test num is %s" %num) # sleep(1) # # if __name__ == '__main__': # p1 = Process(target=test,args=(1,)) # p3= Process(target=test,args=(3,)) # p4 = Process(target=test,args=(4,)) # p5 = Process(target=test,args=(5,)) # p1.start() # p3.start() # p4.start() # p5.start() # # p1.join() # # p3.join() # # p4.join() def task(n): print('%s is running' % n) time.sleep(1) if __name__ == '__main__': start_time = time.time() p1 = Process(target=task, args=(1,)) p2 = Process(target=task, args=(2,)) p3 = Process(target=task, args=(3,)) p1.start() p2.start() p3.start() p3.join() # 3s p1.join() p2.join() print('主', (time.time() - start_time)) start_time = time.time() p_l = [] for i in range(1, 4): p = Process(target=task, args=(i,)) p_l.append(p) p.start() for p in p_l: p.join() print('主', (time.time() - start_time))
<filename>javafx-src/com/sun/webkit/dom/CSSPrimitiveValueImpl.java<gh_stars>1-10 /* * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.webkit.dom; import org.w3c.dom.DOMException; import org.w3c.dom.css.CSSPrimitiveValue; import org.w3c.dom.css.Counter; import org.w3c.dom.css.RGBColor; import org.w3c.dom.css.Rect; public class CSSPrimitiveValueImpl extends CSSValueImpl implements CSSPrimitiveValue { CSSPrimitiveValueImpl(long peer) { super(peer); } static CSSPrimitiveValue getImpl(long peer) { return (CSSPrimitiveValue)create(peer); } // Constants public static final int CSS_UNKNOWN = 0; public static final int CSS_NUMBER = 1; public static final int CSS_PERCENTAGE = 2; public static final int CSS_EMS = 3; public static final int CSS_EXS = 4; public static final int CSS_PX = 5; public static final int CSS_CM = 6; public static final int CSS_MM = 7; public static final int CSS_IN = 8; public static final int CSS_PT = 9; public static final int CSS_PC = 10; public static final int CSS_DEG = 11; public static final int CSS_RAD = 12; public static final int CSS_GRAD = 13; public static final int CSS_MS = 14; public static final int CSS_S = 15; public static final int CSS_HZ = 16; public static final int CSS_KHZ = 17; public static final int CSS_DIMENSION = 18; public static final int CSS_STRING = 19; public static final int CSS_URI = 20; public static final int CSS_IDENT = 21; public static final int CSS_ATTR = 22; public static final int CSS_COUNTER = 23; public static final int CSS_RECT = 24; public static final int CSS_RGBCOLOR = 25; public static final int CSS_VW = 26; public static final int CSS_VH = 27; public static final int CSS_VMIN = 28; public static final int CSS_VMAX = 29; // Attributes public short getPrimitiveType() { return getPrimitiveTypeImpl(getPeer()); } native static short getPrimitiveTypeImpl(long peer); // Functions public void setFloatValue(short unitType , float floatValue) throws DOMException { setFloatValueImpl(getPeer() , unitType , floatValue); } native static void setFloatValueImpl(long peer , short unitType , float floatValue); public float getFloatValue(short unitType) throws DOMException { return getFloatValueImpl(getPeer() , unitType); } native static float getFloatValueImpl(long peer , short unitType); public void setStringValue(short stringType , String stringValue) throws DOMException { setStringValueImpl(getPeer() , stringType , stringValue); } native static void setStringValueImpl(long peer , short stringType , String stringValue); public String getStringValue() throws DOMException { return getStringValueImpl(getPeer()); } native static String getStringValueImpl(long peer); public Counter getCounterValue() throws DOMException { return CounterImpl.getImpl(getCounterValueImpl(getPeer())); } native static long getCounterValueImpl(long peer); public Rect getRectValue() throws DOMException { return RectImpl.getImpl(getRectValueImpl(getPeer())); } native static long getRectValueImpl(long peer); public RGBColor getRGBColorValue() throws DOMException { return RGBColorImpl.getImpl(getRGBColorValueImpl(getPeer())); } native static long getRGBColorValueImpl(long peer); }
import React, {Component} from 'react'; class ContactForm extends Component { constructor(props) { super(props); this.state = { name: '', email: '' }; } handleChange = (e) => { this.setState({ [e.target.name]: e.target.value }); } handleSubmit = (e) => { e.preventDefault(); const data = { name: this.state.name, email: this.state.email }; // Make API call // ... this.setState({ name: '', email: '' }); } render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Name" /> <input type="email" name="email" value={this.state.email} onChange={this.handleChange} placeholder="Email" /> <button type="submit">Submit</button> </form> ); } } export default ContactForm;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.androidStopwatch = void 0; var androidStopwatch = { "viewBox": "0 0 512 512", "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "g", "attribs": { "id": "Icon_7_" }, "children": [{ "name": "g", "attribs": { "id": "Icon_7_" }, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "path", "attribs": { "d": "M232,306.667h48V176h-48V306.667z" }, "children": [{ "name": "path", "attribs": { "d": "M232,306.667h48V176h-48V306.667z" }, "children": [] }] }] }] }] }] }, { "name": "g", "attribs": {}, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "path", "attribs": { "d": "M407.67,170.271l30.786-30.786l-33.942-33.941l-30.785,30.786C341.217,111.057,300.369,96,256,96\r\n\t\t\tC149.961,96,64,181.961,64,288s85.961,192,192,192s192-85.961,192-192C448,243.631,432.943,202.783,407.67,170.271z\r\n\t\t\t M362.066,394.066C333.734,422.398,296.066,438,256,438s-77.735-15.602-106.066-43.934C121.602,365.735,106,328.066,106,288\r\n\t\t\ts15.602-77.735,43.934-106.066C178.265,153.602,215.934,138,256,138s77.734,15.602,106.066,43.934\r\n\t\t\tC390.398,210.265,406,247.934,406,288S390.398,365.735,362.066,394.066z" }, "children": [{ "name": "path", "attribs": { "d": "M407.67,170.271l30.786-30.786l-33.942-33.941l-30.785,30.786C341.217,111.057,300.369,96,256,96\r\n\t\t\tC149.961,96,64,181.961,64,288s85.961,192,192,192s192-85.961,192-192C448,243.631,432.943,202.783,407.67,170.271z\r\n\t\t\t M362.066,394.066C333.734,422.398,296.066,438,256,438s-77.735-15.602-106.066-43.934C121.602,365.735,106,328.066,106,288\r\n\t\t\ts15.602-77.735,43.934-106.066C178.265,153.602,215.934,138,256,138s77.734,15.602,106.066,43.934\r\n\t\t\tC390.398,210.265,406,247.934,406,288S390.398,365.735,362.066,394.066z" }, "children": [] }] }, { "name": "rect", "attribs": { "x": "192", "y": "32", "width": "128", "height": "48" }, "children": [{ "name": "rect", "attribs": { "x": "192", "y": "32", "width": "128", "height": "48" }, "children": [] }] }] }] }] }] }; exports.androidStopwatch = androidStopwatch;
// IgnoreList.cpp: implementation of the CIgnoreList class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "IgnoreList.h" #include <iostream> #include <fstream> #include <set> #include <ctime> #include <iomanip> #include <algorithm> #include <no5tl\mystring.h> using namespace std; class CIgnoreList : public IIgnoreList { private: struct Data { // CString m_name; time_t m_time; // Data() { m_time = 0; } Data(LPCSTR name) { m_name = name; m_time = time(NULL); } bool operator < ( const Data &data) const { return m_name.CompareNoCase(data.m_name) < 0; } friend ostream & operator << ( ostream & out,const Data &data) { if(!data.m_name.IsEmpty()){ out << data.m_name.GetLength() << endl; out << (LPCSTR) data.m_name << endl; out << (int)data.m_time; } return out; } friend istream & operator >> ( istream &in,Data &data) { int len; // read string length in >> ws >> len; if(len > 0){ data.m_name.Empty(); data.m_time = 0; { NO5TL::CStringBuffer buf(data.m_name,len); // skip white spaces in >> ws; // read name in.read(buf,len); // read time as int in >> ws >> len; // assign time data.m_time = (time_t)len; } } return in; } }; typedef set<Data> ListType; typedef ListType::iterator iter; typedef ListType::const_iterator citer; ListType m_list; bool m_dirty; public: CIgnoreList() { m_dirty = false; } virtual ~CIgnoreList() { } virtual bool read(LPCTSTR file) { ifstream in(file); int count = 0; bool res = false; // if the file doesnt exist it will fail, coz we are using ifstream. but thats ok if(in.is_open()){ int len = 0; Data data; int i; time_t cur = time(NULL); long days; // read number of items in >> count; m_list.clear(); m_dirty = false; for(i=0;i<count;i++){ if( in >> data ){ days = long(data.m_time - cur)/( 24 * 60 * 60 ); if(days > 0) m_list.insert(data); } } res = true; } return res; } virtual bool write(LPCTSTR file) { ofstream out(file); bool res = false; if(out){ time_t cur = time(NULL); long days; // write number of items out << m_list.size() << endl; res = true; //sort(); for(citer it = m_list.begin();res && it != m_list.end(); it++){ // dont add if time expired days = long(it->m_time - cur)/( 24 * 60 * 60 ); if(days > 0){ if(!(out << (*it) << endl)){ res = false; } } } } if(res) m_dirty = false; return res; } // add at a sorted position virtual void add(LPCTSTR name) { Data d; iter it; d.m_name = name; d.m_time = time(NULL); m_list.insert(d); m_dirty = true; } virtual void add(LPCTSTR name,long t) { Data d; iter it; d.m_name = name; d.m_time = static_cast<time_t>(t); m_list.insert(d); m_dirty = true; } virtual void remove(LPCTSTR name) { Data d; d.m_name = name; d.m_time = 0; m_list.erase(d); m_dirty = true; } bool find(LPCTSTR name,Data *p) { Data d(name); citer it = m_list.find(d); if(p && it != m_list.end()) *p = *it; return it != m_list.end(); } virtual bool find(LPCTSTR name) { return find(name,NULL); } virtual bool find(LPCTSTR name,long &t) { Data d; bool res = find(name,&d); if(res) t = static_cast<long>(d.m_time); return res; } virtual void clear(void) { m_list.clear(); m_dirty = true; } virtual int size(void) const { return (int)m_list.size(); } virtual bool is_dirty(void) const { return m_dirty; } virtual bool getat(int i,CString &name,long &t) { citer it = m_list.begin(); bool res = false; int j = 0; while(it != m_list.end() && !res){ if(j == i){ name = it->m_name; t = static_cast<long>(it->m_time); res = true; } else{ j++; it++; } } return res; } }; void IIgnoreList::CreateMe(IIgnoreList **pp) { ATLASSERT(pp && ( *pp == NULL ) ); *pp = (IIgnoreList *) new CIgnoreList(); } void IIgnoreList::DestroyMe(IIgnoreList **pp) { ATLASSERT(pp && (*pp != NULL)); if(*pp){ delete (CIgnoreList *)(*pp); *pp = NULL; } }
#!/bin/bash -x # # Generated - do not edit! # # Macros TOP=`pwd` CND_CONF=default CND_DISTDIR=dist TMPDIR=build/${CND_CONF}/${IMAGE_TYPE}/tmp-packaging TMPDIRNAME=tmp-packaging OUTPUT_PATH=dist/${CND_CONF}/${IMAGE_TYPE}/Proyecto1.X.${IMAGE_TYPE}.${OUTPUT_SUFFIX} OUTPUT_BASENAME=Proyecto1.X.${IMAGE_TYPE}.${OUTPUT_SUFFIX} PACKAGE_TOP_DIR=proyecto1.x/ # Functions function checkReturnCode { rc=$? if [ $rc != 0 ] then exit $rc fi } function makeDirectory # $1 directory path # $2 permission (optional) { mkdir -p "$1" checkReturnCode if [ "$2" != "" ] then chmod $2 "$1" checkReturnCode fi } function copyFileToTmpDir # $1 from-file path # $2 to-file path # $3 permission { cp "$1" "$2" checkReturnCode if [ "$3" != "" ] then chmod $3 "$2" checkReturnCode fi } # Setup cd "${TOP}" mkdir -p ${CND_DISTDIR}/${CND_CONF}/package rm -rf ${TMPDIR} mkdir -p ${TMPDIR} # Copy files and create directories and links cd "${TOP}" makeDirectory ${TMPDIR}/proyecto1.x/bin copyFileToTmpDir "${OUTPUT_PATH}" "${TMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}" 0755 # Generate tar file cd "${TOP}" rm -f ${CND_DISTDIR}/${CND_CONF}/package/proyecto1.x.tar cd ${TMPDIR} tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/package/proyecto1.x.tar * checkReturnCode # Cleanup cd "${TOP}" rm -rf ${TMPDIR}
//var slider = document.getElementById("myRange"); //var output = document.getElementById("demo"); //output.innerHTML = slider.value; // Display the default slider value // //// Update the current slider value (each time you drag the slider handle) //slider.oninput = function() { // output.innerHTML = this.value; //} function postToGoogle() { var field1 = $("#fname").val(); var field2 = $("#lname").val(); var field3 = $("#inputEmail").val(); var field4 = $("#phone").val(); var field5 = $("#description").val().trim(); var field6 = $("#inputWho").val(); var field7 = $("#inputWhat").val(); var field8 = $("#inputWhere").val(); var field9 = $("#inputLength").val(); var content = " I am " + field6 + " Looking for " + field7 + " at " + field8 + " for " + field9 + " moredetails " + field5 /*if(field1 == ""){ alert('Please Fill Your Name'); document.getElementById("contact_name").focus(); } if(field2 == ""){ alert('Please Fill Your Email'); document.getElementById("contact_email").focus(); } if(field3 == "" || field3.length > 5 || field3.length < 10){ alert('Please Fill Your Mobile Number'); document.getElementById("contact_phone").focus(); }*/ var settings = { "async": true, "crossDomain": true, "url": "http://54.243.19.57:80/espocrm/api/v1/LeadCapture/6f8d8c6efa159df0a4c1cb54edcc215f", "method": "POST", "headers": { "Content-Type": "application/json", "Accept": "application/json" }, "data": "{\"firstName\": \""+field1+"\",\"lastName\": \""+field2+"\",\"emailAddress\": \""+field3+"\",\"phoneNumber\": \""+field4+"\",\"description\": \""+content+"\",\"phoneNumberIsOptedOut\":1}" } $.ajax(settings).done(function (response) { console.log(field5); if(response == true){ $('#requestForm').hide(); $('#Submit').hide(); $('#note').hide(); $('.alert').show(); } if(response != true){ //$('#requestForm').hide(); //$('#Submit').hide(); //$('#note').hide(); // $('.alert').show(); } }); return false; }
package io.opensphere.core.model; import io.opensphere.core.math.Vector3d; /** A simple vertex which contains a model position. */ public class SimpleModelTesseraVertex extends SimpleTesseraVertex<ModelPosition> { /** * Constructor. * * @param coord The model position at this vertex. */ public SimpleModelTesseraVertex(ModelPosition coord) { super(coord); } @Override public SimpleModelTesseraVertex adjustToModelCenter(Vector3d modelCenter) { ModelPosition adjustedVertex = new ModelPosition(getCoordinates().asVector3d().subtract(modelCenter)); return new SimpleModelTesseraVertex(adjustedVertex); } }
<reponame>blushft/strana // Code generated by entc, DO NOT EDIT. package device const ( // Label holds the string label denoting the device type in the database. Label = "device" // FieldID holds the string denoting the id field in the database. FieldID = "id" // FieldManufacturer holds the string denoting the manufacturer field in the database. FieldManufacturer = "manufacturer" // FieldModel holds the string denoting the model field in the database. FieldModel = "model" // FieldName holds the string denoting the name field in the database. FieldName = "name" // FieldType holds the string denoting the type field in the database. FieldType = "type" // FieldVersion holds the string denoting the version field in the database. FieldVersion = "version" // FieldMobile holds the string denoting the mobile field in the database. FieldMobile = "mobile" // FieldTablet holds the string denoting the tablet field in the database. FieldTablet = "tablet" // FieldDesktop holds the string denoting the desktop field in the database. FieldDesktop = "desktop" // FieldProperties holds the string denoting the properties field in the database. FieldProperties = "properties" // EdgeEvents holds the string denoting the events edge name in mutations. EdgeEvents = "events" // Table holds the table name of the device in the database. Table = "devices" // EventsTable is the table the holds the events relation/edge. EventsTable = "events" // EventsInverseTable is the table name for the Event entity. // It exists in this package in order to avoid circular dependency with the "event" package. EventsInverseTable = "events" // EventsColumn is the table column denoting the events relation/edge. EventsColumn = "event_device" ) // Columns holds all SQL columns for device fields. var Columns = []string{ FieldID, FieldManufacturer, FieldModel, FieldName, FieldType, FieldVersion, FieldMobile, FieldTablet, FieldDesktop, FieldProperties, }
import re def count_github_stars(code_snippet: str) -> int: pattern = r'<gh_stars>(\d+)-\d+' match = re.search(pattern, code_snippet) if match: stars = int(match.group(1)) return stars else: return 0 # Return 0 if no match is found
#!/bin/bash SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )" echo "Running API Tests at $SCRIPTPATH" $SCRIPTPATH/run_test.sh 'iqe tests plugin cost_management -k test_api'
#!/usr/bin/env bats # # Load the helper functions in test_helper.bash # Note the .bash suffix is omitted intentionally # load test_helper # # Test to run is denoted with at symbol test like below # the string after is the test name and will be displayed # when the test is run # # This test is as the test name states a check when everythin # is peachy. # @test "Test where input workspace path does not exist" { # verify $KEPLER_SH is in path if not skip this test skipIfKeplerNotInPath # Run kepler.sh run $KEPLER_SH -runwf -redirectgui $THE_TMP -CWS_jobname jname -CWS_user joe -CWS_jobid 123 -imagedataset "$THE_TMP/doesnotexist" -CWS_outputdir $THE_TMP $WF # Check exit code [ "$status" -eq 0 ] # will only see this if kepler fails echoArray "${lines[@]}" # Check output from kepler.sh [[ "${lines[0]}" == "The base dir is"* ]] # Will be output if anything below fails cat "$THE_TMP/$README_TXT" # Verify we did not get a WORKFLOW.FAILED.txt file [ -e "$THE_TMP/$WORKFLOW_FAILED_TXT" ] cat "$THE_TMP/$WORKFLOW_FAILED_TXT" run cat "$THE_TMP/$WORKFLOW_FAILED_TXT" [ "${lines[0]}" == "simple.error.message=Input directory does not exist" ] [ "${lines[1]}" == "detailed.error.message=$THE_TMP/doesnotexist/data directory does not exist or is not a directory" ] # Verify we got a README.txt [ -s "$THE_TMP/$README_TXT" ] # Check read me header run cat "$THE_TMP/$README_TXT" [ "$status" -eq 0 ] [ "${lines[0]}" == "Single Slice CHM image dataset" ] [ "${lines[1]}" == "Job Name: jname" ] [ "${lines[2]}" == "User: joe" ] [ "${lines[3]}" == "Notify Email: " ] [ "${lines[4]}" == "Workflow Job Id: 123" ] # Check we got a workflow.status file [ -s "$THE_TMP/$WORKFLOW_STATUS" ] }
<reponame>HaneetGH/QuizApp<filename>app/src/main/java/com/technorapper/storage/room/model/Questions.java package com.technorapper.storage.room.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Questions { public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } @SerializedName("question") @Expose private String question; }
<reponame>JarredStanford/JarredStanford.github.io<filename>node_modules/grommet-controls/components/DropInput/DropInput.js<gh_stars>0 var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import { ThemeContext } from 'styled-components'; import { FormDown } from 'grommet-icons/icons/FormDown'; import { DropButton, Keyboard, Button, } from 'grommet'; import { StyledDropInput, StyledDropInputContainer, StyledWidgetsContainer } from './StyledDropInput'; /** * An Input control with an optional drop button with the specified 'dropContent' or widgets<br/> *`import { DropInput } from 'grommet-controls';`<br/> *`<DropInput`<br/> *&nbsp;&nbsp;`dropContent={(`<br/> *&nbsp;&nbsp;&nbsp;&nbsp;`...`<br/> *&nbsp;&nbsp;`]}`<br/> *`/>`<br/> */ var DropInput = /** @class */ (function (_super) { __extends(DropInput, _super); function DropInput() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.state = { open: false }; _this.inputRef = React.createRef(); _this.onUpdateValue = function (value) { var onChange = _this.props.onChange; var input = findDOMNode(_this.inputRef.current); input.value = value; _this.setState({ open: false, value: value }); if (onChange) { onChange({ target: input }); } }; _this.onOpen = function (e) { var _a = _this.props, onOpen = _a.onOpen, disabled = _a.disabled; _this.setState({ open: true }); if (onOpen && !disabled) { onOpen(e); } }; _this.onClose = function (e) { var _a = _this.props, onClose = _a.onClose, disabled = _a.disabled; _this.setState({ open: false }); if (onClose && !disabled) { onClose(e); } }; _this.onKeyDown = function (e) { var onKeyDown = _this.props.onKeyDown; _this.setState({ open: true }); if (onKeyDown) { onKeyDown(e); } }; _this.onKeyUp = function (e) { var onKeyUp = _this.props.onKeyUp; _this.setState({ open: false }); if (onKeyUp) { onKeyUp(e); } }; return _this; } DropInput.getDerivedStateFromProps = function (newProps, oldState) { if (newProps.value !== oldState.value || newProps.defaultValue !== oldState.defaultValue) { return { value: newProps.value, defaultValue: newProps.defaultValue, open: false, }; } return null; }; DropInput.prototype.render = function () { var _this = this; var _a = this.props, a11yTitle = _a.a11yTitle, a11yDropTitle = _a.a11yDropTitle, dropAlign = _a.dropAlign, dropTarget = _a.dropTarget, update = _a.update, widgets = _a.widgets, // eslint-disable-next-line @typescript-eslint/no-unused-vars onOpen = _a.onOpen, onClose = _a.onClose, onKeyDown = _a.onKeyDown, onKeyUp = _a.onKeyUp, defaultValue = _a.defaultValue, dropContent = _a.dropContent, dropIcon = _a.dropIcon, disabled = _a.disabled, rest = __rest(_a, ["a11yTitle", "a11yDropTitle", "dropAlign", "dropTarget", "update", "widgets", "onOpen", "onClose", "onKeyDown", "onKeyUp", "defaultValue", "dropContent", "dropIcon", "disabled"]); var open = this.state.open; if (typeof update === 'function') { update(this.onUpdateValue); } var numWidgets = (dropContent ? 1 : 0) + (widgets ? widgets.length : 0); var decorations; if (numWidgets > 0) { var drop = void 0; if (dropContent) { drop = (React.createElement(DropButton, { a11yTitle: a11yDropTitle, disabled: disabled, dropAlign: dropAlign, dropTarget: dropTarget, open: open, tabIndex: -1, focusIndicator: false, onOpen: this.onOpen, onClose: this.onClose, dropContent: dropContent, icon: dropIcon })); } decorations = (React.createElement(StyledWidgetsContainer, { align: 'center', direction: 'row' }, widgets.map(function (widget, index) { return (React.createElement(Button, __assign({ disabled: disabled, tabIndex: -1, key: "widget_" + index }, widget))); }), drop)); } return (React.createElement(Keyboard, { onDown: this.onKeyDown, onUp: this.onKeyUp }, React.createElement(StyledDropInputContainer, null, React.createElement(ThemeContext.Consumer, null, function (theme) { return (React.createElement(StyledDropInput, __assign({ ref: _this.inputRef, theme: theme, disabled: disabled, numWidgets: numWidgets, "aria-label": a11yTitle, defaultValue: defaultValue ? defaultValue.toString() : undefined }, rest))); }), decorations))); }; DropInput.defaultProps = { dropAlign: { top: 'bottom', right: 'left' }, dropIcon: (React.createElement(FormDown, null)), type: 'text', widgets: [], }; return DropInput; }(Component)); export { DropInput };
// Advanced functionality // Allow call self method with participant name export default `A->A:: Hello A->B:: Hello B B->A: So what `
import { Module } from '@nestjs/common'; import { DatabaseModule } from './database/database.module'; import { UserModule } from './user/user.module' import { AuthModule } from './auth/auth.module'; import { CryptomktModule } from './cryptomkt/cryptomkt.module'; import { CoinModule } from './coin/coin.module'; import { ExchangeModule } from './exchange/exchange.module'; import { LocalindicatorModule } from './localindicator/localindicator.module'; import { ScheduleModule } from '@nestjs/schedule' import { TasksModule } from './tasks/tasks.module'; import { PoloniexModule } from './poloniex/poloniex.module'; import { StatisticsModule } from './statistics/statistics.module'; import { ConfigModule } from '@nestjs/config'; import { ConfigurationModule } from './configuration/configuration.module'; import { BudaModule } from './buda/buda.module'; @Module({ imports: [ConfigModule.forRoot({isGlobal : true}),ScheduleModule.forRoot(),DatabaseModule, UserModule, AuthModule, CryptomktModule, CoinModule, ExchangeModule, LocalindicatorModule, TasksModule, PoloniexModule, StatisticsModule, ConfigurationModule, BudaModule], controllers: [], providers: [], }) export class AppModule {}
db.collection.find({ $or: [ {title: {$regex: /Python/, $options: 'i'} }, {description: {$regex: /Python/, $options: 'i'}}, {title: {$regex: /Programming/, $options: 'i'}}, {description: {$regex: /Programming/, $options: 'i'}}, {title: {$regex: /Web/, $options: 'i'}}, {description: {$regex: /Web/, $options: 'i' }} ]})
#!/bin/sh ################################################################ # LICENSED MATERIALS - PROPERTY OF IBM # "RESTRICTED MATERIALS OF IBM" # (C) COPYRIGHT IBM CORPORATION 2020. ALL RIGHTS RESERVED # US GOVERNMENT USERS RESTRICTED RIGHTS - USE, DUPLICATION, # OR DISCLOSURE RESTRICTED BY GSA ADP SCHEDULE # CONTRACT WITH IBM CORPORATION ################################################################ HLQ=IBMUSER FILES_CMD="rse" # for z/OSMF use "files" JOBS_CMD="rse" # for z/OSMF use "zos-jobs" PROFILE="" # to use a non-default profile use "--rse-proile profileName" echo "Deleting data sets for SAM app.." zowe ${FILES_CMD} delete data-set ${HLQ}.SAMPLE.COBOL $PROFILE zowe ${FILES_CMD} delete data-set ${HLQ}.SAMPLE.COBCOPY $PROFILE zowe ${FILES_CMD} delete data-set ${HLQ}.SAMPLE.CUSTFILE $PROFILE zowe ${FILES_CMD} delete data-set ${HLQ}.SAMPLE.TRANFILE $PROFILE zowe ${FILES_CMD} delete data-set ${HLQ}.SAMPLE.CUSTRPT $PROFILE zowe ${FILES_CMD} delete data-set ${HLQ}.SAMPLE.CUSTOUT $PROFILE zowe ${FILES_CMD} delete data-set ${HLQ}.SAMPLE.LOAD $PROFILE zowe ${FILES_CMD} delete data-set ${HLQ}.SAMPLE.OBJ $PROFILE
/** * Copyright 2014 isandlaTech * * 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.cohorte.remote.shell; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; /** * The shell server: accepts clients and starts shell session threads * * @author <NAME> */ public class Server implements Runnable { /** The client acceptance thread */ private Thread pListeningThread; /** The server socket */ private ServerSocket pServer; /** The parent shell service */ private final RemoteShellService pShellService; /** The stop flag */ private boolean pStop; /** * Sets up the server members * * @param aShellService * The parent shell service */ public Server(final RemoteShellService aShellService) { pShellService = aShellService; } /** * Closes the server socket * * @throws IOException * Error closing the socket */ public void close() throws IOException { // Set up the stop flag pStop = true; if (pServer != null) { try { pServer.close(); } finally { pServer = null; } } // Wait for the listening thread try { pListeningThread.join(); } catch (final InterruptedException ex) { // Ignore } pListeningThread = null; } /** * Returns the address the server socket is bound to (generally "::" or * "0.0.0.0"). Returns null if the server is down. * * @return The server binding address or null. */ public String getAddress() { if (pServer == null) { return null; } final InetAddress boundAddress = pServer.getInetAddress(); if (boundAddress == null) { return null; } return boundAddress.toString(); } /** * Returns the port the server is listening to. Returns -1 if the server is * down. * * @return The listening port or -1 */ public int getPort() { if (pServer == null) { return -1; } return pServer.getLocalPort(); } /** * Open the server, listening the given address and port * * @param aAddress * A binding address (can be null) * @param aPort * A listening port (can be 0) * @throws IOException * Error opening the server servlet */ public void open(final String aAddress, final int aPort) throws IOException { if (pServer != null) { // Refuse to re-open a connection throw new IOException("Server is already running"); } // Compute the binding address final InetAddress bindAddr; if (aAddress == null) { // Accept all connections bindAddr = null; } else { // Bind to a specific address bindAddr = InetAddress.getByName(aAddress); } // Reset the stop flag pStop = false; // Create the server pServer = new ServerSocket(aPort, 1, bindAddr); // Wait for clients in another thread pListeningThread = new Thread(this, "cohorte.remote.shell.acceptor"); pListeningThread.start(); } /** * The server client acceptance loop * * @see java.lang.Runnable#run() */ @Override public void run() { try { while (!pStop) { try { final Socket client = pServer.accept(); // Start a new client thread final Thread clientThread = new Thread( new ShellClientHandler(pShellService, client)); clientThread.setName("cohorte.remote.shell=" + client.getRemoteSocketAddress()); clientThread.start(); } catch (final SocketException ex) { // Log the exception pShellService.error("acceptLoop", "Error accepting client:", ex); } catch (final SocketTimeoutException ex) { // Ignore } } } catch (final IOException ex) { // Log the exception pStop = true; pShellService.error("acceptLoop", "Error waiting for clients:", ex); try { // Kill the server close(); } catch (final IOException ex2) { // Ignore } } } /** * Sets the socket timeout. Does nothing if the server has not been opened * * @param aTimeout * The timeout to set * @throws SocketException * Error setting up the timeout */ public void setSocketTimeout(final int aTimeout) throws SocketException { if (pServer != null) { pServer.setSoTimeout(aTimeout); } } }
#################################################################### # 50x6 images 20x20-20-tanh_linear-0.05--1.0-5.0-40-0.5 (Finished) #################################################################### #sudo python3 generate_new_metabatch.py --seed=42 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=88 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=1234 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=666 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=777 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=999 --metabatch_size=10 #################################################################### # 500 images 20x20-20-tanh_linear-0.05--1.0-5.0-40-0.5 (Finished) #################################################################### #sudo python3 generate_new_metabatch.py --N=500 --seed=42 --metabatch_size=10 #################################################################### # 500 images 20x20-20-sigmoid_linear-100000.0--2500000-5.0-40-0.5 (Finished) #################################################################### #sudo python3 generate_new_metabatch.py --N=500 --seed=42 --clip_fn=sigmoid_linear --a=100000.0 --b=-2500000.0 --metabatch_size=10 ##################################################################### # 50x6 images 20x20-20-tanh_linear-0.05--1.0-5.0-120-0.5 (Finished) ##################################################################### #sudo python3 generate_new_metabatch.py --seed=666 --nb_iter=120 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=1234 --nb_iter=120 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=42 --nb_iter=120 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=88 --nb_iter=120 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=777 --nb_iter=120 --metabatch_size=10 #sudo python3 generate_new_metabatch.py --seed=999 --nb_iter=120 --metabatch_size=10 ##################################################################### # 500 images canonical BagNet-9, -17 (Finished) ##################################################################### #sudo python3 generate_generic_new_metabatch.py -N=500 -seed=42 -metabatch_size=20 -model=bagnet9 #sudo python3 generate_generic_new_metabatch.py -N=500 -seed=42 -metabatch_size=20 -model=bagnet17 #sudo python3 generate_generic_new_metabatch.py -N=500 -seed=88 -metabatch_size=10 -model=bagnet17 #sudo python3 generate_generic_new_metabatch.py -N=500 -seed=88 -metabatch_size=10 -model=bagnet9 ###################################################################### # 2019-7-27 500 images random initialization, nb_iter = 40, 80, 120 (Finished) ###################################################################### #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=5 -stepsize=1 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=20 -stepsize=0.25 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=40 -stepsize=0.125 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=80 -stepsize=0.0625 -metabatch_size=10 -model=bagnet33 ###################################################################### # 2019-7-28 500 images random initialization, several step sizes (Planing) ###################################################################### #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=40 -stepsize=0.225 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=40 -stepsize=0.325 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=40 -stepsize=0.425 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=40 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 ####################################################################### # 2019-7-28 BagNet-33 500 images sticker size 5x5, 10x10, 15x15, 20x20, ... , 50x50 (Finished) ###################################################################### #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=50 -attack_size=50 -stride=50 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=45 -attack_size=45 -stride=45 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=40 -attack_size=40 -stride=40 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=35 -attack_size=35 -stride=35 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=30 -attack_size=30 -stride=30 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=25 -attack_size=25 -stride=25 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=15 -attack_size=15 -stride=15 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=10 -attack_size=10 -stride=10 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 ####################################################################### # 2019-7-28 BagNet-17 500 images sticker size 5x5, 10x10, 15x15, 20x20, ... , 50x50 (Finished) ###################################################################### #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=50 -attack_size=50 -stride=50 -stepsize=0.5 -metabatch_size=10 -model=bagnet17 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=45 -attack_size=45 -stride=45 -stepsize=0.5 -metabatch_size=10 -model=bagnet17 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=40 -attack_size=40 -stride=40 -stepsize=0.5 -metabatch_size=10 -model=bagnet17 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=35 -attack_size=35 -stride=35 -stepsize=0.5 -metabatch_size=10 -model=bagnet17 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=30 -attack_size=30 -stride=30 -stepsize=0.5 -metabatch_size=10 -model=bagnet17 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=25 -attack_size=25 -stride=25 -stepsize=0.5 -metabatch_size=10 -model=bagnet17 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=15 -attack_size=15 -stride=15 -stepsize=0.5 -metabatch_size=10 -model=bagnet17 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -seed=42 -nb_iter=10 -attack_size=10 -attack_size=10 -stride=10 -stepsize=0.5 -metabatch_size=10 -model=bagnet17 ###################################################################### # 2019-8-9 Clipped BagNet33 ratio=20 ###################################################################### sudo python3 generate_new_metabatch.py -rand_init=True -N=5 -nb_iter=10 -attack_size=20 -attack_size=20 -stride=20 -stepsize=2. -metabatch_size=5 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -nb_iter=10 -attack_size=20 -attack_size=20 -stride=20 -stepsize=2. -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -nb_iter=20 -attack_size=20 -attack_size=20 -stride=20 -stepsize=1. -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -nb_iter=40 -attack_size=20 -attack_size=20 -stride=20 -stepsize=0.5 -metabatch_size=10 -model=bagnet33 #sudo python3 generate_new_metabatch.py -rand_init=True -N=500 -nb_iter=80 -attack_size=20 -attack_size=20 -stride=20 -stepsize=0.25 -metabatch_size=10 -model=bagnet33
<gh_stars>10-100 package de.bitbrain.braingdx.graphics.pipeline; import com.badlogic.gdx.graphics.g3d.ModelBatch; public abstract class RenderLayer3D implements RenderLayer<ModelBatch> { @Override public Class<ModelBatch> getBatchCass() { return ModelBatch.class; } }
(function(){ var defaults = { prefix: '', format: 'json' }; var Utils = { serialize: function(obj){ if (obj === null) {return '';} var s = []; for (prop in obj){ s.push(prop + "=" + encodeURIComponent(obj[prop].toString())); } if (s.length === 0) { return ''; } return "?" + s.join('&'); }, clean_path: function(path) { return path.replace(/\/+/g, "/").replace(/[\)\(]/g, "").replace(/\.$/m, '').replace(/\/$/m, ''); }, extract: function(name, options) { var o = undefined; if (options.hasOwnProperty(name)) { o = options[name]; delete options[name]; } else if (defaults.hasOwnProperty(name)) { o = defaults[name]; } return o; }, extract_format: function(options) { var format = options.hasOwnProperty("format") ? options.format : defaults.format; delete options.format; return format ? "." + format : ""; }, extract_anchor: function(options) { var anchor = options.hasOwnProperty("anchor") ? options.anchor : null; delete options.anchor; return anchor ? "#" + anchor : ""; }, extract_options: function(number_of_params, args) { if (args.length > number_of_params) { return typeof(args[args.length-1]) == "object" ? args.pop() : {}; } else { return {}; } }, path_identifier: function(object) { if (!object) { return ""; } if (typeof(object) == "object") { return (object.to_param || object.id || object).toString(); } else { return object.toString(); } }, build_path: function(number_of_params, parts, optional_params, args) { args = Array.prototype.slice.call(args); var result = Utils.get_prefix(); var opts = Utils.extract_options(number_of_params, args); if (args.length > number_of_params) { throw new Error("Too many parameters provided for path"); } var params_count = 0, optional_params_count = 0; for (var i=0; i < parts.length; i++) { var part = parts[i]; if (Utils.optional_part(part)) { var name = optional_params[optional_params_count]; optional_params_count++; // try and find the option in opts var optional = Utils.extract(name, opts); if (Utils.specified(optional)) { result += part; result += Utils.path_identifier(optional); } } else { result += part; if (params_count < number_of_params) { params_count++; var value = args.shift(); if (Utils.specified(value)) { result += Utils.path_identifier(value); } else { throw new Error("Insufficient parameters to build path"); } } } } var format = Utils.extract_format(opts); var anchor = Utils.extract_anchor(opts); return Utils.clean_path(result + format + anchor) + Utils.serialize(opts); }, specified: function(value) { return !(value === undefined || value === null); }, optional_part: function(part) { return part.match(/\(/); }, get_prefix: function(){ var prefix = defaults.prefix; if( prefix !== "" ){ prefix = prefix.match('\/$') ? prefix : ( prefix + '/'); } return prefix; } }; window.AppRoutes = { // trees => /trees(.:format) trees_path: function(options) { return Utils.build_path(0, ["/trees"], ["format"], arguments) }, // new_tree => /trees/new(.:format) new_tree_path: function(options) { return Utils.build_path(0, ["/trees/new"], ["format"], arguments) }, // edit_tree => /trees/:id/edit(.:format) edit_tree_path: function(_id, options) { return Utils.build_path(1, ["/trees/", "/edit"], ["format"], arguments) }, // tree => /trees/:id(.:format) tree_path: function(_id, options) { return Utils.build_path(1, ["/trees/"], ["format"], arguments) }, // posts => /posts(.:format) posts_path: function(options) { return Utils.build_path(0, ["/posts"], ["format"], arguments) }, // new_post => /posts/new(.:format) new_post_path: function(options) { return Utils.build_path(0, ["/posts/new"], ["format"], arguments) }, // edit_post => /posts/:id/edit(.:format) edit_post_path: function(_id, options) { return Utils.build_path(1, ["/posts/", "/edit"], ["format"], arguments) }, // post => /posts/:id(.:format) post_path: function(_id, options) { return Utils.build_path(1, ["/posts/"], ["format"], arguments) }, // notes => /notes(.:format) notes_path: function(options) { return Utils.build_path(0, ["/notes"], ["format"], arguments) }, // new_note => /notes/new(.:format) new_note_path: function(options) { return Utils.build_path(0, ["/notes/new"], ["format"], arguments) }, // edit_note => /notes/:id/edit(.:format) edit_note_path: function(_id, options) { return Utils.build_path(1, ["/notes/", "/edit"], ["format"], arguments) }, // note => /notes/:id(.:format) note_path: function(_id, options) { return Utils.build_path(1, ["/notes/"], ["format"], arguments) }, // tags => /tags(.:format) tags_path: function(options) { return Utils.build_path(0, ["/tags"], ["format"], arguments) }, // new_tag => /tags/new(.:format) new_tag_path: function(options) { return Utils.build_path(0, ["/tags/new"], ["format"], arguments) }, // edit_tag => /tags/:id/edit(.:format) edit_tag_path: function(_id, options) { return Utils.build_path(1, ["/tags/", "/edit"], ["format"], arguments) }, // tag => /tags/:id(.:format) tag_path: function(_id, options) { return Utils.build_path(1, ["/tags/"], ["format"], arguments) }, // new_user_session => /users/sign_in(.:format) new_user_session_path: function(options) { return Utils.build_path(0, ["/users/sign_in"], ["format"], arguments) }, // user_session => /users/sign_in(.:format) user_session_path: function(options) { return Utils.build_path(0, ["/users/sign_in"], ["format"], arguments) }, // destroy_user_session => /users/sign_out(.:format) destroy_user_session_path: function(options) { return Utils.build_path(0, ["/users/sign_out"], ["format"], arguments) }, // user_omniauth_callback => /users/auth/:action/callback(.:format) user_omniauth_callback_path: function(_action, options) { return Utils.build_path(1, ["/users/auth/", "/callback"], ["format"], arguments) }, // user_password => /users/password(.:format) user_password_path: function(options) { return Utils.build_path(0, ["/users/password"], ["format"], arguments) }, // new_user_password => /users/password/new(.:format) new_user_password_path: function(options) { return Utils.build_path(0, ["/users/password/new"], ["format"], arguments) }, // edit_user_password => /users/password/edit(.:format) edit_user_password_path: function(options) { return Utils.build_path(0, ["/users/password/edit"], ["format"], arguments) }, // cancel_user_registration => /users/cancel(.:format) cancel_user_registration_path: function(options) { return Utils.build_path(0, ["/users/cancel"], ["format"], arguments) }, // user_registration => /users(.:format) user_registration_path: function(options) { return Utils.build_path(0, ["/users"], ["format"], arguments) }, // new_user_registration => /users/sign_up(.:format) new_user_registration_path: function(options) { return Utils.build_path(0, ["/users/sign_up"], ["format"], arguments) }, // edit_user_registration => /users/edit(.:format) edit_user_registration_path: function(options) { return Utils.build_path(0, ["/users/edit"], ["format"], arguments) }, // welcome_index => /welcome/index(.:format) welcome_index_path: function(options) { return Utils.build_path(0, ["/welcome/index"], ["format"], arguments) }, // root => / root_path: function(options) { return Utils.build_path(0, ["/"], [], arguments) }, // rails_info_properties => /rails/info/properties(.:format) rails_info_properties_path: function(options) { return Utils.build_path(0, ["/rails/info/properties"], ["format"], arguments) }} ; window.AppRoutes.options = defaults; })();
#!/bin/bash set -e set -o pipefail umask 0002 DATA_DIR=/srv/kenlab/celine/master_thesis/data/vcf_files/joint_genotyping/A_vcf_350/vcf_compressed SCRATCH_DIR=~/script_dir/runtime_scripts/joint_parallel_20samples/scratch_GATKv4_jointgenotype_sa0032 echo "Job runs on `hostname`" echo "at $SCRATCH_DIR" mkdir $SCRATCH_DIR || exit 1 source /usr/local/ngseq/etc/lmod_profile module add Variants/GATK/4.1.2.0 Tools/Picard/2.18.0 gunzip -c $DATA_DIR/sa0032/1.g.vcf.gz > $SCRATCH_DIR/1.g.vcf gunzip -c $DATA_DIR/sa0032/2.g.vcf.gz > $SCRATCH_DIR/2.g.vcf gunzip -c $DATA_DIR/sa0032/3.g.vcf.gz > $SCRATCH_DIR/3.g.vcf gunzip -c $DATA_DIR/sa0032/4.g.vcf.gz > $SCRATCH_DIR/4.g.vcf gunzip -c $DATA_DIR/sa0032/5.g.vcf.gz > $SCRATCH_DIR/5.g.vcf gunzip -c $DATA_DIR/sa0032/6.g.vcf.gz > $SCRATCH_DIR/6.g.vcf gunzip -c $DATA_DIR/sa0032/7.g.vcf.gz > $SCRATCH_DIR/7.g.vcf gunzip -c $DATA_DIR/sa0032/8.g.vcf.gz > $SCRATCH_DIR/8.g.vcf gunzip -c $DATA_DIR/sa0032/9.g.vcf.gz > $SCRATCH_DIR/9.g.vcf gunzip -c $DATA_DIR/sa0032/10.g.vcf.gz > $SCRATCH_DIR/10.g.vcf gunzip -c $DATA_DIR/sa0032/11.g.vcf.gz > $SCRATCH_DIR/11.g.vcf gunzip -c $DATA_DIR/sa0032/12.g.vcf.gz > $SCRATCH_DIR/12.g.vcf gunzip -c $DATA_DIR/sa0032/13.g.vcf.gz > $SCRATCH_DIR/13.g.vcf gunzip -c $DATA_DIR/sa0032/14.g.vcf.gz > $SCRATCH_DIR/14.g.vcf gunzip -c $DATA_DIR/sa0032/15.g.vcf.gz > $SCRATCH_DIR/15.g.vcf gunzip -c $DATA_DIR/sa0032/16.g.vcf.gz > $SCRATCH_DIR/16.g.vcf gunzip -c $DATA_DIR/sa0032/17.g.vcf.gz > $SCRATCH_DIR/17.g.vcf gunzip -c $DATA_DIR/sa0032/18.g.vcf.gz > $SCRATCH_DIR/18.g.vcf gunzip -c $DATA_DIR/sa0032/19.g.vcf.gz > $SCRATCH_DIR/19.g.vcf gunzip -c $DATA_DIR/sa0032/20.g.vcf.gz > $SCRATCH_DIR/20.g.vcf cd $SCRATCH_DIR || exit 1 gatk --java-options "-Xmx10G" CombineGVCFs -R /srv/GT/reference/Finger_millet/KEN/DENOVO_v2.0_A_subgenome/Sequence/WholeGenomeFasta/genome.fa -V 1.g.vcf -V 2.g.vcf -V 3.g.vcf -V 4.g.vcf -V 5.g.vcf -V 6.g.vcf -V 7.g.vcf -V 8.g.vcf -V 9.g.vcf -V 10.g.vcf -V 11.g.vcf -V 12.g.vcf -V 13.g.vcf -V 14.g.vcf -V 15.g.vcf -V 16.g.vcf -V 17.g.vcf -V 18.g.vcf -V 19.g.vcf -V 20.g.vcf -O GATKv4_Genotyping.g.vcf rm -r {1..20}.g.vcf gatk --java-options "-Xmx10G" GenotypeGVCFs -R /srv/GT/reference/Finger_millet/KEN/DENOVO_v2.0_A_subgenome/Sequence/WholeGenomeFasta/genome.fa -V GATKv4_Genotyping.g.vcf -O GATKv4_Genotyping.raw.vcf gatk --java-options "-Xmx10G" SelectVariants -R /srv/GT/reference/Finger_millet/KEN/DENOVO_v2.0_A_subgenome/Sequence/WholeGenomeFasta/genome.fa -V GATKv4_Genotyping.raw.vcf -O GATKv4_Genotyping.raw.snp.vcf -select-type SNP gatk --java-options "-Xmx10G" VariantFiltration -R /srv/GT/reference/Finger_millet/KEN/DENOVO_v2.0_A_subgenome/Sequence/WholeGenomeFasta/genome.fa -V GATKv4_Genotyping.raw.snp.vcf --filter-expression "! vc.hasAttribute('QD') || QD < 2.0" --filter-name "QD" --filter-expression "vc.isSNP() && (MQ < 30.0 || (vc.hasAttribute('MQRankSum') && MQRankSum < -15.0))" --filter-name "MQ" --genotype-filter-expression "GQ < 20 || DP == 0" --genotype-filter-name "GQ" -O GATKv4_Genotyping.filtered.vcf mv GATKv4_Genotyping.raw.snp.vcf GATKv4_Genotyping.raw.vcf gzip GATKv4_Genotyping.raw.vcf gzip GATKv4_Genotyping.filtered.vcf
export class EmployeeAddRequest { name: string; surname: string; userRole: string; }
<reponame>takeru1201/freemarket_sample_67d- class ChangeDatatypebirthdayOfusers < ActiveRecord::Migration[5.2] def change change_column_null :users, :birthday, :data, false end end
import warnings def get_device_memory_info(cuda, kind, rmm_managed): if cuda: if rmm_managed: if kind == "total": return int(cuda.current_context().get_memory_info()[0]) else: return int(cuda.current_context().get_memory_info()[1]) else: if kind == "total": return int(cuda.current_context().get_memory_info()[0]) else: return int(cuda.current_context().get_memory_info()[1]) else: warnings.warn("CUDA is not supported.")
SELECT user_id, setting_key, setting_value FROM Settings WHERE user_id = <USER_ID> AND setting_key IN ('show_accomplishments', 'show_achievements') ORDER BY setting_key ASC;
/** * Created at 16/5/19. * @Author Ling. * @Email <EMAIL> */ import { MIRROR_STATE_FAILED, MIRROR_STATE_SUCCEED, MIRROR_STATE_REQUEST } from '../actions/mirrorState' export default (state = {}, action) => { switch (action.type) { case MIRROR_STATE_REQUEST: return { ...state, loaded: false} case MIRROR_STATE_SUCCEED: return { ...state, loaded: true, success: true, mirrorState: action.mirrorState, guides: action.guides } case MIRROR_STATE_FAILED: return { ...state, loaded: true, success: false, error: action.error } default: return state } }
#!/bin/bash # YOLOv5 🚀 by Ultralytics, GPL-3.0 license # Download latest models from https://github.com/ultralytics/yolov5/releases # Example usage: bash path/to/download_weights.sh # parent # └── yolov5 # ├── yolov5s.pt ← downloads here # ├── yolov5m.pt # └── ... python - <<EOF from utils.downloads import attempt_download models = ['n', 's', 'm', 'l', 'x'] models.extend([x + '6' for x in models]) # add P6 models for x in models: attempt_download(f'yolov5{x}.pt') EOF
<reponame>sebastiand88/gatsby-test<gh_stars>0 import React from "react" import Layout from "../components/Layout" import * as styles from "../styles/about.module.css" import "bootstrap/dist/css/bootstrap.min.css" import { Carousel, Tabs, Tab, Image, Col, Row, Container, Accordion, Form, Button, } from "react-bootstrap" import { MdOutlineRecycling, MdPets } from "react-icons/md" import { BsFillTreeFill } from "react-icons/bs" import { FaBicycle } from "react-icons/fa" import { GiArchiveResearch, GiGuards } from "react-icons/gi" export default function About() { return ( <Layout> <div className={styles.aboutContainer}> <Carousel fade> <Carousel.Item style={{ height: "100vh" }}> <Image className={styles.carouselImg} src="https://images.unsplash.com/photo-1604009506606-fd4989d50e6d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2070&q=80" fluid alt="Second slide" /> <Carousel.Caption> <p className={styles.carouselDesc}>Reforestation.</p> </Carousel.Caption> </Carousel.Item> <Carousel.Item style={{ height: "100vh" }}> <Image className={styles.carouselImg} src="https://images.unsplash.com/photo-1624053335327-a57874e6d1fe?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2071&q=80" fluid alt="First slide" /> <Carousel.Caption> <p className={styles.carouselDesc}>Cleaning the oceans.</p> </Carousel.Caption> </Carousel.Item> <Carousel.Item style={{ height: "100vh" }}> <Image className={styles.carouselImg} src="https://images.unsplash.com/photo-1466611653911-95081537e5b7?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2070&q=80" fluid alt="Third slide" /> <Carousel.Caption> <p className={styles.carouselDesc}>Focusing on the future.</p> </Carousel.Caption> </Carousel.Item> </Carousel> <p className={styles.bottomLine}>What We Do</p> <Tabs defaultActiveKey="renewables" id="" className="mb-3"> <Tab eventKey="renewables" title="Renewable Energy" style={{ padding: "5rem 0" }} > <Row style={{ justifyContent: "center", margin: "0.1rem" }}> <Col sm={6} lg={6} xl={3} style={{ marginTop: "3rem" }}> <Image src="https://images.unsplash.com/photo-1619697101606-7c092a8e6281?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1974&q=80" fluid style={{ maxHeight: "600px", borderRadius: "15px" }} /> </Col> <Col sm={6} lg={6} xl={3} style={{ marginTop: "3rem" }}> <p className={styles.aboutTab}> <h1 className={styles.aboutTabTitle}>Wind Power</h1> Proin laoreet nisi ut risus suscipit, sed blandit lacus feugiat. Nam et nibh vitae nisi rhoncus imperdiet et tincidunt magna. Donec convallis mauris ullamcorper, cursus leo ac, ultrices lectus. Curabitur egestas massa gravida, euismod est non, condimentum tortor. Etiam eget maximus odio, lacinia rhoncus magna. Donec eu nibh ac est posuere semper porttitor ut diam. Donec blandit ipsum ut vulputate elementum. Nulla facilisi. Quisque vel pellentesque libero. Nullam quis enim fringilla, malesuada lorem vitae, suscipit tortor. </p> </Col> <Col sm={6} lg={6} xl={3} style={{ marginTop: "3rem" }}> <p className={styles.aboutTab}> <h1 className={styles.aboutTabTitle}>Hydropower</h1> Proin laoreet nisi ut risus suscipit, sed blandit lacus feugiat. Nam et nibh vitae nisi rhoncus imperdiet et tincidunt magna. Donec convallis mauris ullamcorper, cursus leo ac, ultrices lectus. Curabitur egestas massa gravida, euismod est non, condimentum tortor. Etiam eget maximus odio, lacinia rhoncus magna. Donec eu nibh ac est posuere semper porttitor ut diam. Donec blandit ipsum ut vulputate elementum. Nulla facilisi. Quisque vel pellentesque libero. Nullam quis enim fringilla, malesuada lorem vitae, suscipit tortor. </p> </Col> <Col sm={6} lg={6} xl={3} style={{ marginTop: "3rem" }}> <Image src="https://images.unsplash.com/photo-1518738617820-fb8e4d86fd54?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1970&q=80" fluid style={{ maxHeight: "600px", borderRadius: "15px" }} /> </Col> <Col sm={6} lg={6} xl={3} style={{ marginTop: "3rem" }}> <p className={styles.aboutTab}> <h1 className={styles.aboutTabTitle}>Tidal energy</h1> Proin laoreet nisi ut risus suscipit, sed blandit lacus feugiat. Nam et nibh vitae nisi rhoncus imperdiet et tincidunt magna. Donec convallis mauris ullamcorper, cursus leo ac, ultrices lectus. Curabitur egestas massa gravida, euismod est non, condimentum tortor. Etiam eget maximus odio, lacinia rhoncus magna. Donec eu nibh ac est posuere semper porttitor ut diam. Donec blandit ipsum ut vulputate elementum. Nulla facilisi. Quisque vel pellentesque libero. Nullam quis enim fringilla, malesuada lorem vitae, suscipit tortor. </p> </Col> <Col sm={6} lg={6} xl={3} style={{ marginTop: "3rem" }}> <Image src="https://images.unsplash.com/photo-1532426532228-533e74dc21c2?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1974&q=80" fluid style={{ maxHeight: "600px", borderRadius: "15px" }} /> </Col> <Col sm={6} lg={6} xl={3} style={{ marginTop: "3rem" }}> <Image src="https://images.unsplash.com/photo-1592833159057-6faf163494a9?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1974&q=80" fluid style={{ maxHeight: "600px", borderRadius: "15px" }} /> </Col> <Col sm={6} lg={6} xl={3} style={{ marginTop: "3rem" }}> <p className={styles.aboutTab}> <h1 className={styles.aboutTabTitle}>Solar Power</h1> Proin laoreet nisi ut risus suscipit, sed blandit lacus feugiat. Nam et nibh vitae nisi rhoncus imperdiet et tincidunt magna. Donec convallis mauris ullamcorper, cursus leo ac, ultrices lectus. Curabitur egestas massa gravida, euismod est non, condimentum tortor. Etiam eget maximus odio, lacinia rhoncus magna. Donec eu nibh ac est posuere semper porttitor ut diam. Donec blandit ipsum ut vulputate elementum. Nulla facilisi. Quisque vel pellentesque libero. Nullam quis enim fringilla, malesuada lorem vitae, suscipit tortor. </p> </Col> </Row> </Tab> <Tab eventKey="restore" title="Restoring our Planet"> <Row className={styles.restoreRow}> <Col sm={6} lg={6} xl={4} className={styles.restoreCol}> <div className={styles.restoreIcon}> <MdOutlineRecycling /> </div> <img className={styles.restoreImg} src="https://images.unsplash.com/photo-1621023140422-2c791279becf?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1974&q=80" alt="" /> <h3 className={styles.restoreTitle}>Recycling</h3> <p className={styles.restoreDesc}> Maecenas laoreet semper justo sed tristique. Phasellus lorem sem, tincidunt tempor ipsum ut, tempus pulvinar tortor. Vivamus mattis risus eget lobortis ullamcorper. Aliquam erat volutpat. Aenean nunc risus, posuere in consectetur et, laoreet a turpis. </p> </Col> <Col sm={6} lg={6} xl={4} className={styles.restoreCol}> <div className={styles.restoreIcon}> <BsFillTreeFill /> </div> <img className={styles.restoreImg} src="https://images.unsplash.com/photo-1598335624134-5bceb5de202d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1974&q=80" alt="" /> <h3 className={styles.restoreTitle}>Planting Trees</h3> <p className={styles.restoreDesc}> Maecenas laoreet semper justo sed tristique. Phasellus lorem sem, tincidunt tempor ipsum ut, tempus pulvinar tortor. Vivamus mattis risus eget lobortis ullamcorper. Aliquam erat volutpat. Aenean nunc risus, posuere in consectetur et, laoreet a turpis. </p> </Col> <Col sm={6} lg={6} xl={4} className={styles.restoreCol}> <div className={styles.restoreIcon}> <FaBicycle /> </div> <img className={styles.restoreImg} src="https://images.unsplash.com/photo-1541690983762-7da88c3f2a80?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1976&q=80" alt="" /> <h3 className={styles.restoreTitle}>Bicycle scheme</h3> <p className={styles.restoreDesc}> Maecenas laoreet semper justo sed tristique. Phasellus lorem sem, tincidunt tempor ipsum ut, tempus pulvinar tortor. Vivamus mattis risus eget lobortis ullamcorper. Aliquam erat volutpat. Aenean nunc risus, posuere in consectetur et, laoreet a turpis. </p> </Col> <Col sm={6} lg={6} xl={4} className={styles.restoreCol}> <div className={styles.restoreIcon}> <GiArchiveResearch /> </div> <img className={styles.restoreImg} src="https://images.unsplash.com/photo-1582719471384-894fbb16e074?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1974&q=80" alt="" /> <h3 className={styles.restoreTitle}>Investing in Research</h3> <p className={styles.restoreDesc}> Maecenas laoreet semper justo sed tristique. Phasellus lorem sem, tincidunt tempor ipsum ut, tempus pulvinar tortor. Vivamus mattis risus eget lobortis ullamcorper. Aliquam erat volutpat. Aenean nunc risus, posuere in consectetur et, laoreet a turpis. </p> </Col> <Col sm={6} lg={6} xl={4} className={styles.restoreCol}> <div className={styles.restoreIcon}> <MdPets /> </div> <img className={styles.restoreImg} src="https://images.unsplash.com/photo-1615705257733-6ac12f77d8ed?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1974&q=80" alt="" /> <h3 className={styles.restoreTitle}>Restoring Species</h3> <p className={styles.restoreDesc}> Maecenas laoreet semper justo sed tristique. Phasellus lorem sem, tincidunt tempor ipsum ut, tempus pulvinar tortor. Vivamus mattis risus eget lobortis ullamcorper. Aliquam erat volutpat. Aenean nunc risus, posuere in consectetur et, laoreet a turpis. </p> </Col> <Col sm={6} lg={6} xl={4} className={styles.restoreCol}> <div className={styles.restoreIcon}> <GiGuards /> </div> <img className={styles.restoreImg} src="https://images.unsplash.com/photo-1545122988-927ccd8c48fa?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1974&q=80" alt="" /> <h3 className={styles.restoreTitle}>Protecting Ecosystems</h3> <p className={styles.restoreDesc}> Maecenas laoreet semper justo sed tristique. Phasellus lorem sem, tincidunt tempor ipsum ut, tempus pulvinar tortor. Vivamus mattis risus eget lobortis ullamcorper. Aliquam erat volutpat. Aenean nunc risus, posuere in consectetur et, laoreet a turpis. </p> </Col> </Row> </Tab> <Tab eventKey="future" title="Building the Future"> <iframe width="95%" height="576" src="https://www.youtube.com/embed/e6rglsLy1Ys" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen ></iframe> <h5>Source: National Geographic YouTube Channel</h5> <p className={styles.bottomLine}>Our Future Responsability</p> <Container> <Accordion defaultActiveKey="0"> <Accordion.Item eventKey="0"> <Accordion.Header> <h5 className={styles.futureTitle}>Electric Transport</h5> </Accordion.Header> <Accordion.Body style={{ color: "#0892d0" }}> <Row> <Col xs={12} md={12} lg={4}> <Image src="https://images.unsplash.com/photo-1525962898597-a4ae6402826e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2069&q=80" rounded style={{ maxWidth: "300px", objectFit: "cover", }} /> </Col> <Col xs={12} md={12} lg={4}> <h5 className={styles.futureTitle}> Electric Transport </h5> <p className={styles.futureDesc}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </Col> <Col xs={12} md={12} lg={4}> <Image src="https://images.unsplash.com/photo-1607197109166-3ab4ee4b468f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80" rounded style={{ maxWidth: "300px", objectFit: "cover", }} /> </Col> </Row> </Accordion.Body> </Accordion.Item> <Accordion.Item eventKey="1"> <Accordion.Header> <h5 className={styles.futureTitle}> Environmentally Friendly Homes </h5> </Accordion.Header> <Accordion.Body style={{ color: "#228b22" }}> <Row> <Col xs={12} lg={6}> <Image src="https://images.unsplash.com/flagged/photo-1566838616631-f2618f74a6a2?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1974&q=80" rounded style={{ maxWidth: "300px", objectFit: "cover", }} /> </Col> <Col xs={12} lg={6}> <br /> <br /> <h5 className={styles.futureTitle}>Future Homes</h5> <br /> <br /> <p className={styles.futureDesc}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </Col> </Row> </Accordion.Body> </Accordion.Item> <Accordion.Item eventKey="2"> <Accordion.Header> <h5 className={styles.futureTitle}> Sustainable Agriculture </h5> </Accordion.Header> <Accordion.Body style={{ color: "#ff6600" }}> <Row> <Col xs={12} lg={6}> <br /> <h5 className={styles.futureTitle}>Crop Rotation</h5> <br /> <hr /> <p className={styles.futureDesc}> Crop rotation is the practice of growing a series of different types of crops in the same area across a sequence of growing seasons. It reduces reliance on one set of nutrients, pest and weed pressure, and the probability of developing resistant pest and weeds. Growing the same crop in the same place for many years in a row, known as monocropping, gradually depletes the soil of certain nutrients and selects for a highly competitive pest and weed community. Without balancing nutrient use and diversifying pest and weed communities, the productivity of monocultures is highly dependent on external inputs. Conversely, a well-designed crop rotation can reduce the need for synthetic fertilizers and herbicides by better using ecosystem services from a diverse set of crops. Additionally, crop rotations can improve soil structure and organic matter, which reduces erosion and increases farm system resilience. </p> <hr /> </Col> <Col xs={12} lg={6}> <br /> <h5 className={styles.futureTitle}>Mixed Farming</h5> <br /> <hr /> <p className={styles.futureDesc}> Mixed farming is a type of farming which involves both the growing of crops and the raising of livestock. Such agriculture occurs across Asia and in countries such as India, Malaysia, Indonesia, Afghanistan, South Africa, China, Central Europe, Canada, and Russia. Though at first it mainly served domestic consumption, countries such as the United States and Japan now use it for commercial purposes. The cultivation of crops alongside the rearing of animals for meat or eggs or milk defines mixed farming. For example, a mixed farm may grow cereal crops such as wheat or rye and also keep cattle, sheep, pigs or poultry. Often the dung from the cattle serves to fertilize the cereal crops. Before horses were commonly used for haulage, many young male cattle on such farms were often not butchered as surplus for meat but castrated and used as bullocks to haul the cart and the plough. </p> <br /> <br /> <hr /> </Col> </Row> </Accordion.Body> </Accordion.Item> </Accordion> </Container> </Tab> </Tabs> <div className={styles.aboutQuote}> <div className={styles.aboutQuoteContent}> <h3 className={styles.aboutQuoteDesc}> "It's surely our responsibility to do everything within our power to create a planet that provides a home not just for us, but for all life on Earth." <br /> <br /> <h5>― <NAME></h5> </h3> </div> </div> <p className={styles.bottomLine}>Send Us Your Feedback</p> <div> <Form className={styles.feedbackForm} style={{ padding: "20px" }}> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Your Email Address</Form.Label> <Form.Control type="email" required placeholder="<EMAIL>" /> </Form.Group> <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1" > <Form.Label>Your Feedback</Form.Label> <Form.Control as="textarea" required rows={3} /> </Form.Group> <Button type="submit" variant="outline-success" size="lg"> Submit </Button> </Form> </div> </div> </Layout> ) }
#!/usr/bin/env bash # # Copyright 2020 Google LLC # # 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 # # https://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. # # anthos-lab/prep.sh # This script helps configure your gcloud environment to deploy your Anthos lab. # It will create a service account with the proper role bindings and also create # a key for the containerized application to use # header color HC='\033[0;32m' # output color OC='\033[0;34m' # error color EC='\033[1;31m' # turn off forced color NC='\033[0m' # ensure config file exists CONFIG_FILE=default.config if [ -f "$CONFIG_FILE" ] then ACTION=$1 source $CONFIG_FILE else echo -e "${EC}--- Error: Unable to load configuration file. ${NC}" echo -e "${EC} Please make sure $PWD/$CONFIG_FILE exists. Exiting.\n${NC}" exit 1 fi echo -e "\n\n${HC}------------------- PREFLIGHT CHECKS --------------------${NC}\n" # Step 0 - make sure the SDK is installed echo -e "${OC} * Testing to insure the Google Cloud SDK is installed and available${NC}" SDK=$(which gcloud) if [ -f "$SDK" ] then echo -e "${OC} * SDK located at $SDK." echo -e "${OC} * Google Cloud SDK is installed and available.${NC}" else echo -e "${EC} * Unable to locate Google Cloud SDK.${NC}" echo -e "${EC} * Please refer to the documentation at https://cloud.google.com/sdk/install to remedy the issue and try again.${NC}" echo -e "${EC} * Exiting.${NC}" exit 2 fi # Step 0 part 2 - make sure docker is installed and running (optional) DOCKER=$(which docker) if [ -f "$DOCKER" ] then echo -e "${OC} * Docker runtime found at $DOCKER" DOCKER_CHECK=$(docker version | grep 'Cannot connect' | wc -l) if [ "$DOCKER_CHECK" -eq 0 ] then echo -e "${OC} * Docker seems to be running. Ready to proceed${NC}" else echo -e "${EC} * Docker doesn't appear to be running. Please verify and re-run" echo -e "${EC} * Exiting${NC}" exit 3 fi else echo -e "${EC} * Docker doesn't seem to be installed." echo -e "${EC} * Please refer to documentation for your Operating System and remedy" echo -e "${EC} * Exiting${NC}" exit 4 fi echo -e "${OC} * Checking current project${NC}" CURR_PROJECT=$(gcloud config get-value project) # we have initialized the SDK and we're in the desired project if [ "$CURR_PROJECT" = "$PROJECT" ];then echo -e "${OC} * Already using project $CURR_PROJECT ${NC}" echo -e "${OC} * Checking current Region${NC}" CURR_REGION=$(gcloud config get-value compute/region) if [ "$CURR_REGION" = "$REGION" ];then echo -e "${OC} * Already using region $CURR_REGION${NC}" else echo -e "${OC} * Setting region to $REGION${NC}" gcloud config set compute/region $REGION fi # we're assuming the value is unset here, so we'll run gcloud init # this will catch any missing values else echo -e "${OC} * No project set, running SDK initialization${NC}" gcloud init fi echo -e "${OC} * Ensuring needed APIs are enabled ${NC}" gcloud services enable \ container.googleapis.com \ compute.googleapis.com \ monitoring.googleapis.com \ logging.googleapis.com \ cloudtrace.googleapis.com \ meshca.googleapis.com \ meshtelemetry.googleapis.com \ meshconfig.googleapis.com \ iamcredentials.googleapis.com \ anthos.googleapis.com \ gkeconnect.googleapis.com \ gkehub.googleapis.com \ cloudresourcemanager.googleapis.com \ sourcerepo.googleapis.com \ anthos.googleapis.com > /dev/null # service account key verification SA_EXISTS=$(gcloud iam service-accounts list | egrep "^anthos-lab-sa\ .*" | wc -l) if [ "$SA_EXISTS" -gt 0 ];then #a service account with the desired name already exists. # we won't try to re-create it echo -e "${OC} * Service Account already exists. Continuing. ${NC}" else echo -e "${OC} * Creating Service Account anthos-lab-sa${NC}" gcloud iam service-accounts create anthos-lab-sa --project $PROJECT --display-name anthos-lab-sa --description "Service Account for Anthos Lab Container Deployment" > /dev/null echo -e "${OC} * Applying role bindings for Service Account anthos-lab-sa${NC}" gcloud projects add-iam-policy-binding $PROJECT --member serviceAccount:anthos-lab-sa@$PROJECT.iam.gserviceaccount.com --role=roles/owner > /dev/null fi # service account key verification if [ -f anthos-lab-sa.json ];then echo -e "${OC} * Account Key Present - anthos-lab-sa.json Continuing.${NC}" else echo -e "${OC} * Creating account keys for Service Account anthos-lab-sa${NC}" gcloud iam service-accounts keys create anthos-lab-sa.json \ --iam-account=anthos-lab-sa@$PROJECT.iam.gserviceaccount.com \ --project=$PROJECT > /dev/null fi echo -e "${OC} * Service Account Configuration Complete. Moving on to $ACTION${NC}" # deploy tasks if [ $ACTION == 'deploy' ];then echo -e "${OC} * Preparing for ACM configuration${NC}" # acm repos in the filesystem if [ -d $HOME/$REPO_DIR ];then echo -e "${OC} * ACM repository directory exists. Cleaning it out to start fresh.${NC}" rm -rf $HOME/$REPO_DIR > /dev/null mkdir $HOME/$REPO_DIR > /dev/null else echo -e "${OC} * Creating ACM repository directory.${NC}" mkdir $HOME/$REPO_DIR > /dev/null fi # nomos configuration if [ -f $HOME/nomos ];then echo -e "${OC} * nomos present at $HOME/nomos. Continuing. ${NC}" else echo -e "${OC} * Installing nomos ACM tool at $HOME/nomos. ${NC}" echo -e "${OC} * You can use nomos after deploying to manage ACM.${NC}" if [[ $OSTYPE == "darwin"* ]];then gsutil cp gs://config-management-release/released/latest/darwin_amd64/nomos $HOME/nomos fi if [[ $OSTYPE == "linux"* ]];then gsutil cp gs://config-management-release/released/latest/linux_amd64/nomos $HOME/nomos fi chmod +x $HOME/nomos fi echo -e "${OC} * Preflight checks complete. Continuing to deployment. ${NC}" docker run -it -e ACTION=$ACTION --env-file=$(pwd)/default.config \ -v $(pwd)/anthos-lab-sa.json:/opt/anthos-lab-sa.json \ -v $HOME/$REPO_DIR:/opt/$REPO_DIR \ -v $HOME/deploy:/opt/deploy \ jeduncan/anthos-lab:311.0.0-alpine echo -e "\n\n${HC}------------------- CLUSTER INFORMATION --------------------${NC}\n" gcloud container clusters list --filter="name:$CLUSTERS" --format="[box]" echo -e "${OC} * Generating kubeconfig entry for cluster.${NC}" gcloud container clusters get-credentials $CLUSTERS echo -e "${OC} * Getting current ACM status. This may take a few minutes to show proper status.${NC}" sleep 15 $HOME/nomos status fi # cleanup tasks if [ $ACTION == 'cleanup' ];then rm -rf $HOME/deploy rm -rf $HOME/$REPO_NAME docker run -it -e ACTION=$ACTION --env-file=$(pwd)/default.config \ -v $(pwd)/anthos-lab-sa.json:/opt/anthos-lab-sa.json \ jeduncan/anthos-lab:311.0.0-alpine fi
<reponame>liangyy/mixqtl-gtex import argparse parser = argparse.ArgumentParser(prog='run_r_mixfine.py', description=''' Prepare the bundle of input matrices for r-mixfine run ''') parser.add_argument('--hap-file', help=''' the genotype files in parquet format. It assumes that two haplotypes are separate and the filename should be like filename.hap{}.parquet. Inside, '{}' will be replaced by 1 and 2 for the two haplotypes. ''') parser.add_argument('--gene-list', default=None, help=''' specify a list of gene to map: filname:gene_col ''') parser.add_argument('--libsize', help=''' library size (specify sample and size columns): filename:sample_col:size_col. (formatted by prepare_matrices.py) ''') parser.add_argument('--covariate-matrix', help=''' covariate matrix (formatted by prepare_matrices.py) ''') parser.add_argument('--asc-matrix', help=''' alelle-specific count matrix (specify gene column): filename:gene_col (formatted by prepare_matrices.py). Similarly, use '{}' to point to the two haplotypes. ''') parser.add_argument('--trc-matrix', help=''' total count matrix (formatted by prepare_matrices.py). Or normalized expression matrix (if mode = nefine) ''') parser.add_argument('--param-yaml', default=None, help=''' yaml file to specify parameters for mixfine/trcfine run. Will be put as **kwargs in mixfine call. ''') parser.add_argument('--out-dir', help=''' directory of output (if not exists, it will be created) ''') parser.add_argument('--out-prefix', help=''' directory of output prefix ''') parser.add_argument('--tensorqtl', help=''' at this point, point to the tensorqtl code folder. ''') parser.add_argument('--chr', type=str, help=''' specify chromosome ''') parser.add_argument('--nthread', type=int, default=1, help=''' number of threads ''') parser.add_argument('--impute-trc', action='store_true', help=''' add it if want to impute zero trc as one. ''') parser.add_argument('--mode', type=str, help=''' finemapping mode: mixfine, nefine, trcfine. please make sure that the input is consistent with the mode. ''') parser.add_argument('--mode_extra', nargs='+', help=''' when finemapping mode is aimfine, need to specify the path to corresponding eqtl summary statistics, the path to aim repository, and the prefix for temporary files. ''') args = parser.parse_args() import logging, time, sys # configing util logging.basicConfig( level = logging.INFO, stream = sys.stderr, format = '%(asctime)s %(message)s', datefmt = '%Y-%m-%d %I:%M:%S %p' ) import numpy as np import scipy.stats import yaml def load_yaml(f): if f is None: return {} with open(f, 'r') as stream: data_loaded = yaml.safe_load(stream) return data_loaded def filter_by_gene_list(gene_list, trc, asc1, asc2, pos_df): gene_list_no_dot = [ i.split('.')[0] for i in gene_list ] isin = np.isin(phenotype_pos_df.index.to_list(), gene_list_no_dot) trc = filter_by_all( trc, [isin] ) asc1 = filter_by_all( asc1, [isin] ) asc2 = filter_by_all( asc2, [isin] ) pos_df = filter_by_all( pos_df, [isin] ) return trc, asc1, asc2, pos_df def filter_by_all(df, llogical): fl = llogical[0] for i in range(1, len(llogical)): fl = np.logical_and(fl, llogical[i]) df = df.loc[fl, :] return df def read_covar(df): filename, file_extension = os.path.splitext(df) if file_extension == 'gz': return pd.read_csv(df, sep = '\t', index_col = 0, compression = 'gzip').T else: return pd.read_csv(df, sep = '\t', index_col = 0).T def update_gene_id_index(df): tmp = df.reset_index(drop=False) new = trim_gene_id(tmp.gene_id.tolist()) # tmp.drop(columns='gene_id', inplace=True) tmp['gene_id'] = new tmp.set_index('gene_id', inplace=True) return tmp def trim_gene_id(ss): return [ i.split('.')[0] for i in ss ] import pandas as pd import numpy as np import scipy.stats as stats import torch import os ## setup number of threads for torch torch.set_num_threads(args.nthread) ## floating around dependency sys.path.insert(0, args.tensorqtl) import mixfine import tensorqtl ## ## check mode if args.mode == 'mixfine' or args.mode == 'trcfine' or args.mode == 'nefine' or args.mode == 'aimfine': pass else: raise ValueError('Unsupported mode: {}'.format(args.mode)) # input files ## genotypes hap1_file = args.hap_file.format(1) hap2_file = args.hap_file.format(2) ## total count matrix trc_bed_file = args.trc_matrix if args.mode != 'nefine': ## library size lib_file_ = args.libsize.split(':') lib_file = lib_file_[0] sample_col = lib_file_[1] size_col = lib_file_[2] ## allele-specific count matrix asc_ = args.asc_matrix.split(':') asc1_file = asc_[0].format(1) asc2_file = asc_[0].format(2) asc_gene_col = asc_[1] if args.mode == 'aimfine': aim_path = args.mode_extra[1] aim_prefix = args.mode_extra[2] aim_temp_dir = args.mode_extra[3] eqtl_df = pd.read_parquet(args.mode_extra[0]) if 'phenotype_id' not in eqtl_df.columns: eqtl_df = eqtl_df.rename(columns={'gene_id': 'phenotype_id'}) eqtl_df = eqtl_df[['phenotype_id', 'variant_id', 'pval_nominal', 'slope']] eqtl_df['zscore'] = -1 * np.sign(eqtl_df.slope) * scipy.stats.norm.ppf(eqtl_df.pval_nominal / 2) eqtl_df = eqtl_df.drop(columns=['pval_nominal', 'slope']) eqtl_df['phenotype_id'] = trim_gene_id(list(eqtl_df['phenotype_id'])) eqtl_df = eqtl_df.drop_duplicates(subset=['phenotype_id', 'variant_id']) extra_args = { 'eqtl': eqtl_df, 'aim_path': aim_path, 'temp_dir': aim_temp_dir, 'temp_prefix': aim_prefix } else: extra_args = {} ## covariate matrix covar_file = args.covariate_matrix # output output_prefix = args.out_prefix outdir = args.out_dir if not (os.path.exists(outdir) and os.path.isdir(outdir)): os.mkdir(outdir) # load parameters for mixfine param_mixfine = load_yaml(args.param_yaml) # main run # load genotypes logging.info('Load genotypes') hap1_df = pd.read_parquet(hap1_file) hap2_df = pd.read_parquet(hap2_file) variant_df = pd.DataFrame( { 'chrom':hap1_df.index.map(lambda x: x.split('_')[0]), 'pos': hap1_df.index.map(lambda x: int(x.split('_')[1])) }, index=hap1_df.index ) # load total counts and library size logging.info('Load total counts and library size') phenotype_df, phenotype_pos_df = tensorqtl.read_phenotype_bed(trc_bed_file) # breakpoint() phenotype_df = update_gene_id_index(phenotype_df) phenotype_pos_df = update_gene_id_index(phenotype_pos_df) if args.impute_trc is True and args.mode != 'nefine': phenotype_df = phenotype_df + 1 if args.mode != 'nefine': libsize_df = pd.read_csv(lib_file, header = 0, sep = '\t', compression = 'gzip') libsize_df = libsize_df.set_index(sample_col) libsize_s = libsize_df.loc[phenotype_df.columns.tolist(), size_col] ## compute log(count / libsize / 2) log_counts_df = np.log(phenotype_df / libsize_s / 2) log_counts_df = log_counts_df.loc[phenotype_df.index] log_counts_df[log_counts_df == -np.Inf] = np.NaN else: # add place holder libsize_df = pd.DataFrame({'indiv': phenotype_df.columns.tolist(), 'libsize': 1}).set_index('indiv') if args.mode == 'mixfine' or args.mode == 'aimfine': # load allele-specific counts logging.info('Load allele-specific counts') ref_df = pd.read_csv(asc1_file, sep = '\t', compression = 'gzip', header = 0) alt_df = pd.read_csv(asc2_file, sep = '\t', compression = 'gzip', header = 0) ref_df = ref_df.set_index(asc_gene_col) alt_df = alt_df.set_index(asc_gene_col) ref_df = ref_df.loc[~ref_df.index.duplicated(keep = 'first')] alt_df = alt_df.loc[~alt_df.index.duplicated(keep = 'first')] ref_df = ref_df.loc[:, phenotype_df.columns.to_list()] alt_df = alt_df.loc[:, phenotype_df.columns.to_list()] ref_df = ref_df.loc[phenotype_df.index.to_list(), :] alt_df = alt_df.loc[phenotype_df.index.to_list(), :] else: # add place holder ref_df = phenotype_df.copy() alt_df = phenotype_df.copy() # filter by gene list if args.gene_list is not None: filename, genecol = args.gene_list.split(':') _, file_extension = os.path.splitext(filename) if file_extension == '.gz': genelist_df = pd.read_csv(filename, sep='\t', compression='gzip', header=0) elif file_extension == '.parquet': genelist_df = pd.read_parquet(filename) genelist_df = genelist_df[genecol].to_list() phenotype_df, ref_df, alt_df, phenotype_pos_df = filter_by_gene_list(genelist_df, phenotype_df, ref_df, alt_df, phenotype_pos_df) # load covariates logging.info('Load covariates') covariates_df = read_covar(covar_file) covariates_df = covariates_df.loc[phenotype_df.columns.to_list(), :] # run mixfine logging.info('Run mixFine: mode = {}'.format(args.mode)) ix = phenotype_pos_df[phenotype_pos_df['chr']==args.chr].index mixfine.run_mixfine(hap1_df, hap2_df, variant_df, libsize_df, phenotype_df.loc[ix], ref_df.loc[ix], alt_df.loc[ix], phenotype_pos_df.loc[ix], covariates_df, output_prefix, output_dir=outdir, verbose=True, mode=args.mode, extra_args=extra_args, **param_mixfine)
#!/usr/bin/env bash set -e cd / # ----------------- # install languages # ----------------- apk update apk add --no-cache \ git \ go \ python python-dev py-pip \ ruby ruby-json \ build-base # --------------- # install linters # --------------- gem install scss_lint -v 0.48.0 -N go get -u gopkg.in/alecthomas/gometalinter.v1 ln -s $GOPATH/bin/gometalinter.v1 $GOPATH/bin/gometalinter npm -q install pip --no-cache-dir install -r requirements.txt npm cache clean mkdir -p /usr/src/shellcheck cd /usr/src/shellcheck git clone https://github.com/koalaman/shellcheck . apk add --no-cache --repository https://s3-us-west-2.amazonaws.com/alpine-ghc/7.10 --allow-untrusted ghc cabal-install stack cabal update cabal install cabal clean rm -rf /usr/src/shellcheck # ------------- # clean sources # ------------- gem sources -c rm -Rf /gopath/src rm -Rf /gopath/pkg rm -Rf /usr/lib/go apk del python-dev git go build-base ghc cabal-install stack # ------------- # create target # ------------- mkdir -p /src
<gh_stars>0 import React from 'react'; import { createDrawerNavigator, DrawerContentScrollView, DrawerItemList, DrawerItem, } from '@react-navigation/drawer'; import BottomTabNavigator from './BottomTabNavigator'; const Drawer = createDrawerNavigator(); const CustomDrawerContent = (props) => { return ( <DrawerContentScrollView {...props}> <DrawerItemList {...props} /> <DrawerItem label="Home" onPress={() => props.navigation.navigate('Home')} /> <DrawerItem label="Contact" onPress={() => props.navigation.navigate('Contact')} /> <DrawerItem label="About" onPress={() => props.navigation.navigate('About')} /> </DrawerContentScrollView> ); }; const DrawerNavigator = () => { return ( <Drawer.Navigator drawerContent={(props) => <CustomDrawerContent {...props} />}> <Drawer.Screen name="Menu" component={BottomTabNavigator} /> </Drawer.Navigator> ); }; export default DrawerNavigator;
import { WorkItemTypeClass } from "TFS/WorkItemTracking/ProcessContracts"; /** * @description Represents a work item to which tasks may be assignable. */ export class WorkItemComponent { private workItemId: number; private title: string; private appliedCss: string; private iconString: string; private outputHtml: string; // Properties that can be used for non ui functions private _workItemType: string; public get workItemType():string{ return this._workItemType } public set workItemType(v:string){ this._workItemType = v; } /** * @description The area path of the work item. */ private _areaPath:string; public get areaPath():string{ return this._areaPath; } public set areaPath(v:string){ this._areaPath = v; } /** * @description The iteration path of the work item. */ private _iterationPath:string; public get iterationPath():string{ return this._iterationPath; } public set iterationPath(v:string){ this._iterationPath = v; } /** * @description Creates a new instance of the object. */ constructor(title: string, workItemType: string, workItemId: number){ this.title = title; this._workItemType = workItemType; this.workItemId = workItemId; switch(workItemType.toLowerCase()){ case "bug": this.iconString = "<i class=\"fa fa-bug\"/>" this.appliedCss = "wit-bug" break; case "issue": this.iconString = "<i class=\"fa fa-asterisk\"/>" this.appliedCss = "wit-issue" break; case "user story": this.iconString = "<i class=\"fa fa-book\"/>" this.appliedCss = "wit-userstory" break; default: this.iconString = "<i class=\"fa fa-ban\"/>" this.appliedCss = "wit-invalid" } this.outputHtml = "<div class=\"col-md-6\">"; this.outputHtml += ` <div class=\"wit ${this.appliedCss} workItem\" data-workItemId=\"${this.workItemId}\" >`; this.outputHtml += ` ${this.iconString} <span class=\"wit-title\">${this._workItemType} ${this.workItemId}: ${this.title}</span>`; this.outputHtml += " </div>"; this.outputHtml += "</div>"; } /** * @description Gets the HTML string representation of the object. */ public toHtmlString():string{ return this.outputHtml; } }
module QuickSort def quick_sort(array, beg_index, end_index) if beg_index < end_index pivot_index = qs_partition(array, beg_index, end_index) quick_sort(array, beg_index, pivot_index - 1) quick_sort(array, pivot_index + 1, end_index) end return array end # returns an index of where the pivot ends up def qs_partition(array, beg_index, end_index) # current_index starts the subarray with larger numbers than the pivot current_index = beg_index i = beg_index while i < end_index if array[i] <= array[end_index] qs_swap(array, i, current_index) current_index += 1 end i += 1 end # after this qs_swap all of the elements before the pivot will be smaller and # after the pivot larger qs_swap(array, end_index, current_index) return current_index end def qs_swap(array, first_element, second_element) temp = array[first_element] array[first_element] = array[second_element] array[second_element] = temp end end
#!/usr/bin/env bash # # Build and push Docker images to Docker Hub and quay.io. # cd "$(dirname "$0")" || exit 1 export IMAGE_PREFIX=deisci VERSION=v2.1.0 docker login -e="$DOCKER_EMAIL" -u="$DOCKER_USERNAME" -p="$DOCKER_PASSWORD" DEIS_REGISTRY='' make -C .. docker-build docker-push docker login -e="$QUAY_EMAIL" -u="$QUAY_USERNAME" -p="$QUAY_PASSWORD" quay.io DEIS_REGISTRY=quay.io/ make -C .. docker-build docker-push
<reponame>imbush/sketches let width = 500; let height = 500; let points = []; let radius = 200; let k = 1; function setup() { createCanvas(width, height); noFill(); angleMode(DEGREES); background(0); stroke(255); }; function mouseClicked() { background(0); push(); translate(width/2, height/2); for (angle = 0; angle < 360; angle += 0.1){ for(let rad = radius; rad <= radius; rad += 20) { stroke(rad); point(rad * cos(k * angle) * cos(angle), rad * cos(k * angle) * sin(angle)); } } pop(); k += 0.1; }
<filename>src/test/java/org/allenai/ml/sequences/crf/CRFIndexedExampleTest.java<gh_stars>10-100 package org.allenai.ml.sequences.crf; import org.allenai.ml.linalg.SparseVector; import org.allenai.ml.linalg.Vector; import lombok.val; import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.testng.Assert.*; @Test public class CRFIndexedExampleTest { public void testGoldLabels() { List<Vector> toyNodePreds = CRFTestUtils.toyNodePreds(); List<Vector> toyEdgePreds = CRFTestUtils.toyEdgePreds(); int[] goldLabels = new int[]{0, 1, 2}; val example = new CRFIndexedExample(toyNodePreds, toyEdgePreds, goldLabels); assertTrue(example.isLabeled()); assertEquals(example.getGoldLabels(), goldLabels); } public void testZeroValuedCompatiction() { List<Vector> toyNodePreds = CRFTestUtils.toyNodePreds(); List<Vector> toyEdgePreds = CRFTestUtils.toyEdgePreds(); toyNodePreds.get(0).set(0L, 0.0); testPreds(toyNodePreds, toyEdgePreds); } public void testPredicateCompaction() { List<Vector> toyNodePreds = CRFTestUtils.toyNodePreds(); List<Vector> toyEdgePreds = CRFTestUtils.toyEdgePreds(); testPreds(toyNodePreds, toyEdgePreds); } private void testPreds(List<Vector> toyNodePreds, List<Vector> toyEdgePreds) { val example = new CRFIndexedExample(toyNodePreds, toyEdgePreds); List<Vector> extractedNodePreds = IntStream.range(0, 3) .mapToObj(idx -> SparseVector.make(10).addInPlace(example.getNodePredicateValues(idx))) .collect(Collectors.toList()); List<Vector> extractedEdgePreds = IntStream.range(0, 2) .mapToObj(idx -> SparseVector.make(10).addInPlace(example.getEdgePredicateValues(idx))) .collect(Collectors.toList()); assertFalse(example.isLabeled()); assertEquals(example.getSequenceLength(), 3); // Verify we can recover the vectors using the iterators for each positon in the node/edges for (int idx = 0; idx < extractedNodePreds.size(); idx++) { assertTrue(extractedNodePreds.get(idx).closeTo(toyNodePreds.get(idx))); } for (int idx = 0; idx < extractedEdgePreds.size(); idx++) { assertTrue(extractedEdgePreds.get(idx).closeTo(toyEdgePreds.get(idx))); } } }
#!/usr/bin/env bash # Preload base bash configuration and functions source bgord-scripts/base.sh CURRENT_BRANCH=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD) if test $CURRENT_BRANCH != "master" then error "You have to have the master branch checked out" exit 1 fi success "You are on the master branch" if test $(git rev-parse master) != $(git rev-parse origin/master) then error "There are some differences between master and origin/master" info "Please, sync them" exit 1 fi success "All changes are pushed to the remote master branch" info "Run yarn version --{major,minor,patch}" press_enter_to_continue git push --follow-tags success "Pushed the version commit and new tag to origin/master" if test ! $(npm whoami) then error "You're not logged in to npm" info "Run [npm login], you can find the credentials on Keeper" exit 1 fi success "You're logged in to npm" npm publish --dry-run success "Ran npm publish --dry-run" info "Run npm publish" press_enter_to_continue npm publish success "The package has been published!"
<reponame>Tri-stone/xupercore<gh_stars>0 package meta import ( "bytes" "errors" "fmt" "html/template" "sync" "github.com/golang/protobuf/proto" "github.com/xuperchain/xupercore/bcs/ledger/xledger/def" "github.com/xuperchain/xupercore/bcs/ledger/xledger/ledger" "github.com/xuperchain/xupercore/bcs/ledger/xledger/state/context" pb "github.com/xuperchain/xupercore/bcs/ledger/xledger/xldgpb" "github.com/xuperchain/xupercore/lib/logs" "github.com/xuperchain/xupercore/lib/storage/kvdb" "github.com/xuperchain/xupercore/protos" ) type Meta struct { log logs.Logger Ledger *ledger.Ledger Meta *pb.UtxoMeta // utxo meta MetaTmp *pb.UtxoMeta // tmp utxo meta MutexMeta *sync.Mutex // access control for meta MetaTable kvdb.Database // 元数据表,会持久化保存latestBlockid } var ( ErrProposalParamsIsNegativeNumber = errors.New("negative number for proposal parameter is not allowed") ErrProposalParamsIsNotPositiveNumber = errors.New("negative number of zero for proposal parameter is not allowed") ErrGetReservedContracts = errors.New("Get reserved contracts error") // TxSizePercent max percent of txs' size in one block TxSizePercent = 0.8 ) // reservedArgs used to get contractnames from InvokeRPCRequest type reservedArgs struct { ContractNames string } func genArgs(req []*protos.InvokeRequest) *reservedArgs { ra := &reservedArgs{} for i, v := range req { ra.ContractNames += v.GetContractName() if i < len(req)-1 { ra.ContractNames += "," } } return ra } func NewMeta(sctx *context.StateCtx, stateDB kvdb.Database) (*Meta, error) { obj := &Meta{ log: sctx.XLog, Ledger: sctx.Ledger, Meta: &pb.UtxoMeta{}, MetaTmp: &pb.UtxoMeta{}, MutexMeta: &sync.Mutex{}, MetaTable: kvdb.NewTable(stateDB, pb.MetaTablePrefix), } var loadErr error // load consensus parameters obj.Meta.MaxBlockSize, loadErr = obj.LoadMaxBlockSize() if loadErr != nil { sctx.XLog.Warn("failed to load maxBlockSize from disk", "loadErr", loadErr) return nil, loadErr } obj.Meta.ForbiddenContract, loadErr = obj.LoadForbiddenContract() if loadErr != nil { sctx.XLog.Warn("failed to load forbiddenContract from disk", "loadErr", loadErr) return nil, loadErr } obj.Meta.ReservedContracts, loadErr = obj.LoadReservedContracts() if loadErr != nil { sctx.XLog.Warn("failed to load reservedContracts from disk", "loadErr", loadErr) return nil, loadErr } obj.Meta.NewAccountResourceAmount, loadErr = obj.LoadNewAccountResourceAmount() if loadErr != nil { sctx.XLog.Warn("failed to load newAccountResourceAmount from disk", "loadErr", loadErr) return nil, loadErr } // load irreversible block height & slide window parameters obj.Meta.IrreversibleBlockHeight, loadErr = obj.LoadIrreversibleBlockHeight() if loadErr != nil { sctx.XLog.Warn("failed to load irreversible block height from disk", "loadErr", loadErr) return nil, loadErr } obj.Meta.IrreversibleSlideWindow, loadErr = obj.LoadIrreversibleSlideWindow() if loadErr != nil { sctx.XLog.Warn("failed to load irreversibleSlide window from disk", "loadErr", loadErr) return nil, loadErr } // load gas price obj.Meta.GasPrice, loadErr = obj.LoadGasPrice() if loadErr != nil { sctx.XLog.Warn("failed to load gas price from disk", "loadErr", loadErr) return nil, loadErr } // load group chain obj.Meta.GroupChainContract, loadErr = obj.LoadGroupChainContract() if loadErr != nil { sctx.XLog.Warn("failed to load groupchain from disk", "loadErr", loadErr) return nil, loadErr } newMeta := proto.Clone(obj.Meta).(*pb.UtxoMeta) obj.MetaTmp = newMeta return obj, nil } // GetNewAccountResourceAmount get account for creating an account func (t *Meta) GetNewAccountResourceAmount() int64 { t.MutexMeta.Lock() defer t.MutexMeta.Unlock() return t.Meta.GetNewAccountResourceAmount() } // LoadNewAccountResourceAmount load newAccountResourceAmount into memory func (t *Meta) LoadNewAccountResourceAmount() (int64, error) { newAccountResourceAmountBuf, findErr := t.MetaTable.Get([]byte(ledger.NewAccountResourceAmountKey)) if findErr == nil { utxoMeta := &pb.UtxoMeta{} err := proto.Unmarshal(newAccountResourceAmountBuf, utxoMeta) return utxoMeta.GetNewAccountResourceAmount(), err } else if def.NormalizedKVError(findErr) == def.ErrKVNotFound { genesisNewAccountResourceAmount := t.Ledger.GetNewAccountResourceAmount() if genesisNewAccountResourceAmount < 0 { return genesisNewAccountResourceAmount, ErrProposalParamsIsNegativeNumber } return genesisNewAccountResourceAmount, nil } return int64(0), findErr } // UpdateNewAccountResourceAmount ... func (t *Meta) UpdateNewAccountResourceAmount(newAccountResourceAmount int64, batch kvdb.Batch) error { if newAccountResourceAmount < 0 { return ErrProposalParamsIsNegativeNumber } tmpMeta := &pb.UtxoMeta{} newMeta := proto.Clone(tmpMeta).(*pb.UtxoMeta) newMeta.NewAccountResourceAmount = newAccountResourceAmount newAccountResourceAmountBuf, pbErr := proto.Marshal(newMeta) if pbErr != nil { t.log.Warn("failed to marshal pb meta") return pbErr } err := batch.Put([]byte(pb.MetaTablePrefix+ledger.NewAccountResourceAmountKey), newAccountResourceAmountBuf) if err == nil { t.log.Info("Update newAccountResourceAmount succeed") } t.MutexMeta.Lock() defer t.MutexMeta.Unlock() t.MetaTmp.NewAccountResourceAmount = newAccountResourceAmount return err } // GetMaxBlockSize get max block size effective in Utxo func (t *Meta) GetMaxBlockSize() int64 { t.MutexMeta.Lock() defer t.MutexMeta.Unlock() return t.Meta.GetMaxBlockSize() } // LoadMaxBlockSize load maxBlockSize into memory func (t *Meta) LoadMaxBlockSize() (int64, error) { maxBlockSizeBuf, findErr := t.MetaTable.Get([]byte(ledger.MaxBlockSizeKey)) if findErr == nil { utxoMeta := &pb.UtxoMeta{} err := proto.Unmarshal(maxBlockSizeBuf, utxoMeta) return utxoMeta.GetMaxBlockSize(), err } else if def.NormalizedKVError(findErr) == def.ErrKVNotFound { genesisMaxBlockSize := t.Ledger.GetMaxBlockSize() if genesisMaxBlockSize <= 0 { return genesisMaxBlockSize, ErrProposalParamsIsNotPositiveNumber } return genesisMaxBlockSize, nil } return int64(0), findErr } func (t *Meta) MaxTxSizePerBlock() (int, error) { maxBlkSize := t.GetMaxBlockSize() return int(float64(maxBlkSize) * TxSizePercent), nil } func (t *Meta) UpdateMaxBlockSize(maxBlockSize int64, batch kvdb.Batch) error { if maxBlockSize <= 0 { return ErrProposalParamsIsNotPositiveNumber } tmpMeta := &pb.UtxoMeta{} newMeta := proto.Clone(tmpMeta).(*pb.UtxoMeta) newMeta.MaxBlockSize = maxBlockSize maxBlockSizeBuf, pbErr := proto.Marshal(newMeta) if pbErr != nil { t.log.Warn("failed to marshal pb meta") return pbErr } err := batch.Put([]byte(pb.MetaTablePrefix+ledger.MaxBlockSizeKey), maxBlockSizeBuf) if err == nil { t.log.Info("Update maxBlockSize succeed") } t.MutexMeta.Lock() defer t.MutexMeta.Unlock() t.MetaTmp.MaxBlockSize = maxBlockSize return err } func (t *Meta) GetReservedContracts() []*protos.InvokeRequest { t.MutexMeta.Lock() defer t.MutexMeta.Unlock() return t.Meta.ReservedContracts } func (t *Meta) LoadReservedContracts() ([]*protos.InvokeRequest, error) { reservedContractsBuf, findErr := t.MetaTable.Get([]byte(ledger.ReservedContractsKey)) if findErr == nil { utxoMeta := &pb.UtxoMeta{} err := proto.Unmarshal(reservedContractsBuf, utxoMeta) return utxoMeta.GetReservedContracts(), err } else if def.NormalizedKVError(findErr) == def.ErrKVNotFound { return t.Ledger.GetReservedContracts() } return nil, findErr } //when to register to kernel method func (t *Meta) UpdateReservedContracts(params []*protos.InvokeRequest, batch kvdb.Batch) error { if params == nil { return fmt.Errorf("invalid reservered contract requests") } tmpNewMeta := &pb.UtxoMeta{} newMeta := proto.Clone(tmpNewMeta).(*pb.UtxoMeta) newMeta.ReservedContracts = params paramsBuf, pbErr := proto.Marshal(newMeta) if pbErr != nil { t.log.Warn("failed to marshal pb meta") return pbErr } err := batch.Put([]byte(pb.MetaTablePrefix+ledger.ReservedContractsKey), paramsBuf) if err == nil { t.log.Info("Update reservered contract succeed") } t.MutexMeta.Lock() defer t.MutexMeta.Unlock() t.MetaTmp.ReservedContracts = params return err } func (t *Meta) GetForbiddenContract() *protos.InvokeRequest { t.MutexMeta.Lock() defer t.MutexMeta.Unlock() return t.Meta.GetForbiddenContract() } func (t *Meta) GetGroupChainContract() *protos.InvokeRequest { t.MutexMeta.Lock() defer t.MutexMeta.Unlock() return t.Meta.GetGroupChainContract() } func (t *Meta) LoadGroupChainContract() (*protos.InvokeRequest, error) { groupChainContractBuf, findErr := t.MetaTable.Get([]byte(ledger.GroupChainContractKey)) if findErr == nil { utxoMeta := &pb.UtxoMeta{} err := proto.Unmarshal(groupChainContractBuf, utxoMeta) return utxoMeta.GetGroupChainContract(), err } else if def.NormalizedKVError(findErr) == def.ErrKVNotFound { requests, err := t.Ledger.GetGroupChainContract() if len(requests) > 0 { return requests[0], err } return nil, errors.New("unexpected error") } return nil, findErr } func (t *Meta) LoadForbiddenContract() (*protos.InvokeRequest, error) { forbiddenContractBuf, findErr := t.MetaTable.Get([]byte(ledger.ForbiddenContractKey)) if findErr == nil { utxoMeta := &pb.UtxoMeta{} err := proto.Unmarshal(forbiddenContractBuf, utxoMeta) return utxoMeta.GetForbiddenContract(), err } else if def.NormalizedKVError(findErr) == def.ErrKVNotFound { requests, err := t.Ledger.GetForbiddenContract() if len(requests) > 0 { return requests[0], err } return nil, errors.New("unexpected error") } return nil, findErr } func (t *Meta) UpdateForbiddenContract(param *protos.InvokeRequest, batch kvdb.Batch) error { if param == nil { return fmt.Errorf("invalid forbidden contract request") } tmpNewMeta := &pb.UtxoMeta{} newMeta := proto.Clone(tmpNewMeta).(*pb.UtxoMeta) newMeta.ForbiddenContract = param paramBuf, pbErr := proto.Marshal(newMeta) if pbErr != nil { t.log.Warn("failed to marshal pb meta") return pbErr } err := batch.Put([]byte(pb.MetaTablePrefix+ledger.ForbiddenContractKey), paramBuf) if err == nil { t.log.Info("Update forbidden contract succeed") } t.MutexMeta.Lock() defer t.MutexMeta.Unlock() t.MetaTmp.ForbiddenContract = param return err } func (t *Meta) LoadIrreversibleBlockHeight() (int64, error) { irreversibleBlockHeightBuf, findErr := t.MetaTable.Get([]byte(ledger.IrreversibleBlockHeightKey)) if findErr == nil { utxoMeta := &pb.UtxoMeta{} err := proto.Unmarshal(irreversibleBlockHeightBuf, utxoMeta) return utxoMeta.GetIrreversibleBlockHeight(), err } else if def.NormalizedKVError(findErr) == def.ErrKVNotFound { return int64(0), nil } return int64(0), findErr } func (t *Meta) LoadIrreversibleSlideWindow() (int64, error) { irreversibleSlideWindowBuf, findErr := t.MetaTable.Get([]byte(ledger.IrreversibleSlideWindowKey)) if findErr == nil { utxoMeta := &pb.UtxoMeta{} err := proto.Unmarshal(irreversibleSlideWindowBuf, utxoMeta) return utxoMeta.GetIrreversibleSlideWindow(), err } else if def.NormalizedKVError(findErr) == def.ErrKVNotFound { genesisSlideWindow := t.Ledger.GetIrreversibleSlideWindow() // negative number is not meaningful if genesisSlideWindow < 0 { return genesisSlideWindow, ErrProposalParamsIsNegativeNumber } return genesisSlideWindow, nil } return int64(0), findErr } func (t *Meta) GetIrreversibleBlockHeight() int64 { t.MutexMeta.Lock() defer t.MutexMeta.Unlock() return t.Meta.IrreversibleBlockHeight } func (t *Meta) GetIrreversibleSlideWindow() int64 { t.MutexMeta.Lock() defer t.MutexMeta.Unlock() return t.Meta.IrreversibleSlideWindow } func (t *Meta) UpdateIrreversibleBlockHeight(nextIrreversibleBlockHeight int64, batch kvdb.Batch) error { tmpMeta := &pb.UtxoMeta{} newMeta := proto.Clone(tmpMeta).(*pb.UtxoMeta) newMeta.IrreversibleBlockHeight = nextIrreversibleBlockHeight irreversibleBlockHeightBuf, pbErr := proto.Marshal(newMeta) if pbErr != nil { t.log.Warn("failed to marshal pb meta") return pbErr } err := batch.Put([]byte(pb.MetaTablePrefix+ledger.IrreversibleBlockHeightKey), irreversibleBlockHeightBuf) if err != nil { return err } t.log.Info("Update irreversibleBlockHeight succeed") t.MutexMeta.Lock() defer t.MutexMeta.Unlock() t.MetaTmp.IrreversibleBlockHeight = nextIrreversibleBlockHeight return nil } func (t *Meta) UpdateNextIrreversibleBlockHeight(blockHeight int64, curIrreversibleBlockHeight int64, curIrreversibleSlideWindow int64, batch kvdb.Batch) error { // negative number for irreversible slide window is not allowed. if curIrreversibleSlideWindow < 0 { return ErrProposalParamsIsNegativeNumber } // slideWindow为开启,不需要更新IrreversibleBlockHeight if curIrreversibleSlideWindow == 0 { return nil } // curIrreversibleBlockHeight小于0, 不符合预期,报警 if curIrreversibleBlockHeight < 0 { t.log.Warn("update irreversible block height error, should be here") return errors.New("curIrreversibleBlockHeight is less than 0") } nextIrreversibleBlockHeight := blockHeight - curIrreversibleSlideWindow // 下一个不可逆高度小于当前不可逆高度,直接返回 // slideWindow变大或者发生区块回滚 if nextIrreversibleBlockHeight <= curIrreversibleBlockHeight { return nil } // 正常升级 // slideWindow不变或变小 if nextIrreversibleBlockHeight > curIrreversibleBlockHeight { err := t.UpdateIrreversibleBlockHeight(nextIrreversibleBlockHeight, batch) return err } return errors.New("unexpected error") } func (t *Meta) UpdateNextIrreversibleBlockHeightForPrune(blockHeight int64, curIrreversibleBlockHeight int64, curIrreversibleSlideWindow int64, batch kvdb.Batch) error { // negative number for irreversible slide window is not allowed. if curIrreversibleSlideWindow < 0 { return ErrProposalParamsIsNegativeNumber } // slideWindow为开启,不需要更新IrreversibleBlockHeight if curIrreversibleSlideWindow == 0 { return nil } // curIrreversibleBlockHeight小于0, 不符合预期,报警 if curIrreversibleBlockHeight < 0 { t.log.Warn("update irreversible block height error, should be here") return errors.New("curIrreversibleBlockHeight is less than 0") } nextIrreversibleBlockHeight := blockHeight - curIrreversibleSlideWindow if nextIrreversibleBlockHeight <= 0 { nextIrreversibleBlockHeight = 0 } err := t.UpdateIrreversibleBlockHeight(nextIrreversibleBlockHeight, batch) return err } func (t *Meta) UpdateIrreversibleSlideWindow(nextIrreversibleSlideWindow int64, batch kvdb.Batch) error { if nextIrreversibleSlideWindow < 0 { return ErrProposalParamsIsNegativeNumber } tmpMeta := &pb.UtxoMeta{} newMeta := proto.Clone(tmpMeta).(*pb.UtxoMeta) newMeta.IrreversibleSlideWindow = nextIrreversibleSlideWindow irreversibleSlideWindowBuf, pbErr := proto.Marshal(newMeta) if pbErr != nil { t.log.Warn("failed to marshal pb meta") return pbErr } err := batch.Put([]byte(pb.MetaTablePrefix+ledger.IrreversibleSlideWindowKey), irreversibleSlideWindowBuf) if err != nil { return err } t.log.Info("Update irreversibleSlideWindow succeed") t.MutexMeta.Lock() defer t.MutexMeta.Unlock() t.MetaTmp.IrreversibleSlideWindow = nextIrreversibleSlideWindow return nil } // GetGasPrice get gas rate to utxo func (t *Meta) GetGasPrice() *protos.GasPrice { t.MutexMeta.Lock() defer t.MutexMeta.Unlock() return t.Meta.GetGasPrice() } // LoadGasPrice load gas rate func (t *Meta) LoadGasPrice() (*protos.GasPrice, error) { gasPriceBuf, findErr := t.MetaTable.Get([]byte(ledger.GasPriceKey)) if findErr == nil { utxoMeta := &pb.UtxoMeta{} err := proto.Unmarshal(gasPriceBuf, utxoMeta) return utxoMeta.GetGasPrice(), err } else if def.NormalizedKVError(findErr) == def.ErrKVNotFound { nofee := t.Ledger.GetNoFee() if nofee { gasPrice := &protos.GasPrice{ CpuRate: 0, MemRate: 0, DiskRate: 0, XfeeRate: 0, } return gasPrice, nil } else { gasPrice := t.Ledger.GetGasPrice() cpuRate := gasPrice.CpuRate memRate := gasPrice.MemRate diskRate := gasPrice.DiskRate xfeeRate := gasPrice.XfeeRate if cpuRate < 0 || memRate < 0 || diskRate < 0 || xfeeRate < 0 { return nil, ErrProposalParamsIsNegativeNumber } // To be compatible with the old version v3.3 // If GasPrice configuration is missing or value euqals 0, support a default value if cpuRate == 0 && memRate == 0 && diskRate == 0 && xfeeRate == 0 { gasPrice = &protos.GasPrice{ CpuRate: 1000, MemRate: 1000000, DiskRate: 1, XfeeRate: 1, } } return gasPrice, nil } } return nil, findErr } // UpdateGasPrice update gasPrice parameters func (t *Meta) UpdateGasPrice(nextGasPrice *protos.GasPrice, batch kvdb.Batch) error { // check if the parameters are valid cpuRate := nextGasPrice.GetCpuRate() memRate := nextGasPrice.GetMemRate() diskRate := nextGasPrice.GetDiskRate() xfeeRate := nextGasPrice.GetXfeeRate() if cpuRate < 0 || memRate < 0 || diskRate < 0 || xfeeRate < 0 { return ErrProposalParamsIsNegativeNumber } tmpMeta := &pb.UtxoMeta{} newMeta := proto.Clone(tmpMeta).(*pb.UtxoMeta) newMeta.GasPrice = nextGasPrice gasPriceBuf, pbErr := proto.Marshal(newMeta) if pbErr != nil { t.log.Warn("failed to marshal pb meta") return pbErr } err := batch.Put([]byte(pb.MetaTablePrefix+ledger.GasPriceKey), gasPriceBuf) if err != nil { return err } t.log.Info("Update gas price succeed") t.MutexMeta.Lock() defer t.MutexMeta.Unlock() t.MetaTmp.GasPrice = nextGasPrice return nil } func (t *Meta) GetReservedContractRequests(req []*protos.InvokeRequest, isPreExec bool) ([]*protos.InvokeRequest, error) { MetaReservedContracts := t.GetReservedContracts() if MetaReservedContracts == nil { return nil, nil } reservedContractstpl := MetaReservedContracts t.log.Info("MetaReservedContracts", "reservedContracts", reservedContractstpl) // if all reservedContracts have not been updated, return nil, nil ra := &reservedArgs{} if isPreExec || len(reservedContractstpl) == 0 { ra = genArgs(req) } else { // req should contrain reservedContracts, so the len of req should no less than reservedContracts if len(req) < len(reservedContractstpl) { t.log.Warn("req should contain reservedContracts") return nil, ErrGetReservedContracts } else if len(req) > len(reservedContractstpl) { ra = genArgs(req[len(reservedContractstpl):]) } } reservedContracts := []*protos.InvokeRequest{} for _, rc := range reservedContractstpl { rctmp := *rc rctmp.Args = make(map[string][]byte) for k, v := range rc.GetArgs() { buf := new(bytes.Buffer) tpl := template.Must(template.New("value").Parse(string(v))) tpl.Execute(buf, ra) rctmp.Args[k] = buf.Bytes() } reservedContracts = append(reservedContracts, &rctmp) } return reservedContracts, nil }
<reponame>seawindnick/javaFamily package com.java.study.algorithm.zuo.emiddle.class01; public class Code02_MinLengthForSort{ }
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.control.model; import com.google.common.truth.Truth; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for {@link ResourceName}. As resource names are mostly a wrapper around path * templates, not much needs to be done here. */ @RunWith(JUnit4.class) public class ResourceNameTest { @Test public void resourceNameMethods() { PathTemplate template = PathTemplate.create("buckets/*/objects/**"); ResourceName name = ResourceName.create(template, "buckets/b/objects/1/2"); Truth.assertThat(name.toString()).isEqualTo("buckets/b/objects/1/2"); Truth.assertThat(name.get("$1")).isEqualTo("1/2"); Truth.assertThat(name.get("$0")).isEqualTo("b"); Truth.assertThat(name.parentName().toString()).isEqualTo("buckets/b/objects"); } }
#!/usr/bin/env bash # Install command-line tools using Homebrew. # Ask for the administrator password upfront. sudo -v # Keep-alive: update existing `sudo` time stamp until the script has finished. while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null & # Make sure we’re using the latest Homebrew. brew update # Upgrade any already-installed formulae. brew upgrade --all # Install GNU core utilities (those that come with OS X are outdated). # Don’t forget to add `$(brew --prefix coreutils)/libexec/gnubin` to `$PATH`. brew install coreutils sudo ln -s /usr/local/bin/gsha256sum /usr/local/bin/sha256sum # Install some other useful utilities like `sponge`. brew install moreutils # Install GNU `find`, `locate`, `updatedb`, and `xargs`, `g`-prefixed. brew install findutils # Install GNU `sed`, overwriting the built-in `sed`. brew install gnu-sed --with-default-names # Install Bash 4. # Note: don’t forget to add `/usr/local/bin/bash` to `/etc/shells` before # running `chsh`. brew install bash brew tap homebrew/versions brew install bash-completion2 # Install `wget` with IRI support. brew install wget --with-iri # Install RingoJS and Narwhal. # Note that the order in which these are installed is important; # see http://git.io/brew-narwhal-ringo. #brew install ringojs #brew install narwhal # Install more recent versions of some OS X tools. brew install vim --override-system-vi brew install homebrew/dupes/grep brew install homebrew/dupes/openssh brew install homebrew/dupes/screen #brew install homebrew/php/php55 --with-gmp # Install font tools. brew tap bramstein/webfonttools brew install sfnt2woff brew install sfnt2woff-zopfli brew install woff2 # Install some CTF tools; see https://github.com/ctfs/write-ups. brew install aircrack-ng brew install bfg brew install binutils brew install binwalk brew install cifer brew install dex2jar brew install dns2tcp brew install fcrackzip brew install foremost brew install hashpump brew install hydra brew install john brew install knock brew install netpbm brew install nmap brew install pngcheck brew install socat brew install sqlmap brew install tcpflow brew install tcpreplay brew install tcptrace brew install ucspi-tcp # `tcpserver` etc. brew install xpdf brew install xz # Install other useful binaries. brew install ack brew install dark-mode #brew install exiv2 brew install git brew install git-lfs brew install imagemagick --with-webp brew install lua brew install lynx brew install p7zip brew install pigz brew install pv brew install rename brew install rhino brew install speedtest_cli brew install ssh-copy-id brew install testssl brew install tree brew install webkit2png brew install zopfli # Remove outdated versions from the cellar. brew cleanup # Patrick's stuff brew install tmux brew install pstree brew install htop # graphics compression brew install gif2png brew install pngcrush brew install gifsicle brew install libjpeg #comes with jpegtran # setup Vundle. it depends on git. via https://github.com/VundleVim/Vundle.vim git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim # invoke vim command from shell. via http://stackoverflow.com/questions/12834370/run-vim-command-from-commandline vim +PluginInstall +qall
#!/usr/bin/env bash install_blackfire_ext() { # special treatment for Blackfire; we enable it if we detect a server id and a server token for it # otherwise users would have to have it in their require section, which is annoying in development environments BLACKFIRE_SERVER_ID=${BLACKFIRE_SERVER_ID:-} BLACKFIRE_SERVER_TOKEN=${BLACKFIRE_SERVER_TOKEN:-} if [[ "$engine" == "php" && ( ${#exts[@]} -eq 0 || ! ${exts[*]} =~ "blackfire" ) && -n "$BLACKFIRE_SERVER_TOKEN" && -n "$BLACKFIRE_SERVER_ID" ]]; then if $engine $(which composer) require --quiet --update-no-dev -d "$build_dir/.heroku/php" -- "heroku-sys/ext-blackfire:*"; then install_ext "blackfire" "add-on detected" exts+=("blackfire") else warning_inline "Blackfire detected, but no suitable extension available" fi fi } install_blackfire_agent() { # blackfire defaults cat > $build_dir/.profile.d/blackfire.sh <<"EOF" if [[ -n "$BLACKFIRE_SERVER_TOKEN" && -n "$BLACKFIRE_SERVER_ID" ]]; then if [[ -f "/app/.heroku/php/bin/blackfire-agent" ]]; then touch /app/.heroku/php/var/blackfire/run/agent.sock /app/.heroku/php/bin/blackfire-agent -config=/app/.heroku/php/etc/blackfire/agent.ini -socket="unix:///app/.heroku/php/var/blackfire/run/agent.sock" & else echo >&2 "WARNING: Add-on 'blackfire' detected, but PHP extension not yet installed. Push an update to the application to finish installation of the add-on; an empty change ('git commit --allow-empty') is sufficient." fi fi EOF }
<filename>src/static/external/jeanne/dbl/clean.js let left = document.getElementsByClassName("left-container")[0]; let info = left.children[0]; let tags = left.nextElementSibling; let tagsTitle = document.getElementsByClassName("bot-tags-title")[0]; let old = document.getElementsByClassName("columns")[1]; let stats = document.getElementById("bot-stats"); tagsTitle.innerText = "Tags:"; stats.style.display = "block"; stats.innerHTML = `${info.innerHTML}<br/>${tags.innerHTML}`; old.innerHTML = ""; old.style.display = "none";
#!/bin/sh TESTDIR="$(dirname "${0}")" PLANDIR="$(dirname "${TESTDIR}")" SKIPBUILD=${SKIPBUILD:-0} hab pkg install --binlink core/bats hab pkg install core/busybox-static hab pkg binlink core/busybox-static ps hab pkg binlink core/busybox-static wc source "${PLANDIR}/plan.sh" if [ "${SKIPBUILD}" -eq 0 ]; then # Unload the service if its already loaded. hab svc unload "${HAB_ORIGIN}/${pkg_name}" set -e pushd "${PLANDIR}" > /dev/null build source results/last_build.env hab pkg install --binlink --force "results/${pkg_artifact}" hab svc load "${pkg_ident}" popd > /dev/null set +e # Give some time for the service to start up sleep 5 fi bats "${TESTDIR}/test.bats"
import {Component, OnInit} from '@angular/core'; import {Color} from '../../models/color'; import {ColorService} from '../../services/color.service'; @Component({ selector: 'app-color', templateUrl: './color.component.html', styleUrls: ['./color.component.css'] }) export class ColorComponent implements OnInit { colors: Color[] = []; currentColor:Color; constructor(private colorService: ColorService) { } ngOnInit(): void { this.getColors(); } getColors() { this.colorService.getColors().subscribe((response) => { this.colors = response.data; }); } setCurrentColor(color:Color){ this.currentColor=color; } }
/** * Boundaries * * @package bnd */ angular.module('bnd', [ 'bnd.general.service', 'bnd.specific.service' ]);
#!/bin/bash if [ "$#" -ne 1 ]; then echo "Illegal number of parameters; Please provide vm number as the parameter;" exit 1 fi vm=$1 echo `date` 'Starting VM '$vm'...' VBoxManage startvm ubuntu16-vm"$vm" --type headless
import { createStore, applyMiddleware, compose } from 'redux'; import rootReducer from '../reducers'; import createSagaMiddleware from 'redux-saga'; import apiSaga from '../sagas'; const initialiseSagaMiddleware = createSagaMiddleware(); const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore( rootReducer, storeEnhancers( applyMiddleware(initialiseSagaMiddleware) ) ); initialiseSagaMiddleware.run(apiSaga); export default store; // import thunk from 'redux-thunk'; // const store = createStore( // rootReducer, // storeEnhancers( // applyMiddleware(thunk) // ) // );
#!/bin/bash ADDRESS="192.168.0.254" echo " - Start ADB server" adb tcpip 5555 echo " - Connect to address $ADDRESS" adb connect $ADDRESS echo " - Done!"
<gh_stars>0 package uk.joshiejack.husbandry.network; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.network.PacketBuffer; import net.minecraft.particles.BasicParticleType; import net.minecraft.particles.ParticleTypes; import net.minecraft.world.World; import net.minecraftforge.fml.network.NetworkDirection; import uk.joshiejack.penguinlib.network.PenguinPacket; import uk.joshiejack.penguinlib.util.PenguinLoader; @PenguinLoader.Packet(NetworkDirection.PLAY_TO_CLIENT) public class SpawnHeartsPacket extends PenguinPacket { private int entityID; private boolean positive; public SpawnHeartsPacket(){} public SpawnHeartsPacket(int entityID, boolean positive) { this.entityID = entityID; this.positive = positive; } @Override public void encode(PacketBuffer to) { to.writeInt(entityID); to.writeBoolean(positive); } @Override public void decode(PacketBuffer from) { entityID = from.readInt(); positive = from.readBoolean(); } @Override public void handle(PlayerEntity player) { World world = player.level; Entity entity = world.getEntity(entityID); if (entity != null) { BasicParticleType type = positive ? ParticleTypes.HEART : ParticleTypes.DAMAGE_INDICATOR; int times = positive ? 3 : 16; double offset = positive ? -0.125D : 0D; for (int j = 0; j < times; j++) { double x = (entity.xo - 0.5D) + world.random.nextFloat(); double y = (entity.yo - 0.5D) + world.random.nextFloat(); double z = (entity.zo - 0.5D) + world.random.nextFloat(); world.addParticle(type, x, 1D + y + offset, z, 0, 0, 0); } } } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; public class CodeParser { public static (List<string> namespaces, List<string> classes) ParseCode(string codeSnippet) { List<string> namespaces = new List<string>(); List<string> classes = new List<string>(); string[] lines = codeSnippet.Split('\n'); foreach (string line in lines) { if (line.Trim().StartsWith("using")) { string namespaceName = Regex.Match(line, "using (.+?);").Groups[1].Value; namespaces.Add(namespaceName); } else if (line.Trim().StartsWith("public class")) { string className = Regex.Match(line, "public class (.+?) :").Groups[1].Value; classes.Add(className); } } return (namespaces, classes); } public static void Main() { string codeSnippet = @" using Kujikatsu086.Extensions; using Kujikatsu086.Numerics; using Kujikatsu086.Questions; namespace Kujikatsu086.Questions { /// <summary> /// https://atcoder.jp/contests/nomura2020/tasks/nomura2020_a /// </summary> public class QuestionA : AtCoderQuestionBase "; var result = ParseCode(codeSnippet); Console.WriteLine("Namespaces:"); foreach (var ns in result.namespaces) { Console.WriteLine("- " + ns); } Console.WriteLine("Class:"); foreach (var cls in result.classes) { Console.WriteLine("- " + cls); } } }
<filename>Giochi/Scacchi/pulsantieraScacchi.js // necessarieo scrivere func prima che vengano legate ai pulsanti var PulsantieraScacchi = function() { // this.randomFunction = function() { // Sudoku.nuovoRandom(); // // Sudoku.testP(1); // } // this.sudokuVuoto = function() { // Sudoku.nuovoRandom("vuoto"); // } // // this.mettiUnoFunction = function() { // // Sudoku.testP(6); // // } // this.risolviFunction = function() { // Sudoku.risolvi(); // } // this.testoStronzoFunction = function() { // testoStronzo = !testoStronzo; // } // this.clearSolFunction = function() { // Sudoku.clearSoluzione(); // } // this.controllaSolFunction = function() { // Sudoku.controllaErrori(); // } // this.mostraPossFunction = function() { // Sudoku.mostraTuttiPossibiliFlag = ! Sudoku.mostraTuttiPossibiliFlag; // } // this.scriviUno = function() { // scrivitore.cambiaCorrente(1); // } // this.scriviDue = function() { // scrivitore.cambiaCorrente(2); // } // this.scriviTre = function() { // scrivitore.cambiaCorrente(3); // } // this.scriviQat = function() { // scrivitore.cambiaCorrente(4); // } // this.scriviCin = function() { // scrivitore.cambiaCorrente(5); // } // this.scriviSei = function() { // scrivitore.cambiaCorrente(6); // } // this.scriviSet = function() { // scrivitore.cambiaCorrente(7); // } this.nuovaPartita = function() { // setup(); s.nuovaPartita(); s.calcolaPosPezzi(); s.controlloMosse(); // setup(); ia = new ChessIA(1,1,0); } this.caricaMappa = function(n) { s.nuovaPartita(n); } this.controlloMosse = function() { s.controlloMosse(); // console.log("puls moss") } this.enIa = function() { enableIAg = ! enableIAg; } this.nomeCas = function() { sposta.flagMostra = ! sposta.flagMostra; } this.mostraPox = function() { s.flagMostraPox = ! s.flagMostraPox; } this.nextPoxN = function() { s.mostraPossibiliNero(); } this.nextPoxB = function() { s.mostraPossibiliBian(); } this.consoleThis = function() { s.consoleMe(); } // this.scriviOtt = function() { // scrivitore.cambiaCorrente(8); // } // this.scriviNov = function() { // scrivitore.cambiaCorrente(9); // } // this.scriviN = function(n) { // scrivitore.cambiaCorrente(n); // } // this.scriviCanc = function() { // scrivitore.cambiaCorrente(-1); // } // this.scriviCancPoss = function() { // // scrivitore.cambiaCorrente(-1); // nope, mi serve n // scrivitore.tipoInserim = 2; // } // this.insFisso = function() { // scrivitore.tipoInserim = 0; // } // this.insSoluz = function() { // scrivitore.tipoInserim = 1; // } // this.consoleSudoku = function() { // Sudoku.consoleSudoku(); // } // this.randomSolFunc = function() { // da spostare // let gino = new CreatoreSudoku(); // gino.randomizzaSoluzione(); // console.log("Spostare creazione CreatoreSudoku da PulsantieraSudoku!") // } // this.modificaDimSudFunc = function() { // if(selfo.dimS == 3) { // dimS = 4; // dimS2 = 4*4; // } // else { // dimS = 3; // dimS2 = 3*3; // } // selfo.togliVecchiPulsanti(); // wow fiko funziona // setup(); // } // // (*) a dire il vero vedo che l'elemento esiste ancora in p5 anche se non lo visualizza in canvas, // // ho paura che l'istanza rimanga da qualche parte e che quindi continuare a crearne di nuovi // // senza distruggere realmente i vecchi possa gravare sulla memoria occupata viste le dimensioni // // di un elemento, da rivedere // this.togliVecchiPulsanti = function() { // questo funziona (o forse no, leggi nota sopra (*) ) // for(let i = selfo.arrP.length -1; i >= 0; i--) { // selfo.arrP[i].elt.remove(); // } // // free real estate (IN REALTà non sono sicuro tolga lunghezza ad arrP, anzi) // // for(let i = 0; i < selfo.arrP.length) { // // selfo.arrP[0].elt.remove(); // // } // } // this.dimS = dimS; // this.dimS2 = this.dimS * this.dimS; // this.arrP = []; // var selfo = this; // var spaziaturaDx = 17.5; // var spaziaturaOrizz = 450 / this.dimS2; // 50 per 3 (9), preferirei due righe per 4 (16) // var spaziaturaVert = 470; // // var spaziaturaOrizz = 50; // for(let i = 1; i < this.dimS2 + 1; i++) { // this.arrP.push( createButton(i).position(spaziaturaDx + spaziaturaOrizz * (i-1),spaziaturaVert) ); // // https://thenewstack.io/mastering-javascript-callbacks-bind-apply-call/ // // vorrei aver capito al 100% perché funziona ma magari la volta prossima // this.arrP[i-1].mousePressed(function() { // selfo.scriviN(i); // }); // } // // for(let i = 0; i < this.dimS2; i++) { // prove fallimentari di bindare args a callback di mousePressed // // this.arrP[i].mousePressed(this.scriviN); // // this.arrP[i].mousePressed(this.scriviN.bind(i)); // // this.arrP[i].mousePressed(this.scriviN.apply(i)); // // } // this.canc = createButton("Cancella Inserito").position(spaziaturaDx,spaziaturaVert + 40); // this.canc.mousePressed(this.scriviCanc); // this.canc = createButton("Cancella Possibile").position(spaziaturaDx,spaziaturaVert + 80); // this.canc.mousePressed(this.scriviCancPoss); // this.ins0 = createButton("Fisso").position(spaziaturaDx + 215,spaziaturaVert + 40); // this.ins0.mousePressed(this.insFisso); // this.ins1 = createButton("Soluz").position(spaziaturaDx + 295,spaziaturaVert + 40); // this.ins1.mousePressed(this.insSoluz); var selfo = this; this.posizioneXPuls = width + 10; // this.posizioneXPuls = width - 150; // per schermo Mac con debugger aperto e Sublime aperto di fianco this.posizioneYPuls = 30; this.spaziaturaY = 40; this.nuovaPartitaButton = createButton("Nuova Partita").position(this.posizioneXPuls,this.posizioneYPuls); this.nuovaPartitaButton.mousePressed(this.nuovaPartita); this.caricaMappaButton = createButton("Carica Mappa 2").position(this.posizioneXPuls,this.posizioneYPuls + this.spaziaturaY); this.caricaMappaButton.mousePressed(function() { selfo.caricaMappa(2); }); this.caricaMappaButton = createButton("Carica Mappa 4").position(this.posizioneXPuls,this.posizioneYPuls + this.spaziaturaY * 2); this.caricaMappaButton.mousePressed(function() { selfo.caricaMappa(4); }); this.enIaButton = createButton("IA enabler").position(this.posizioneXPuls,this.posizioneYPuls + this.spaziaturaY * 3); this.enIaButton.mousePressed(this.enIa); this.nomeCasButt = createButton("Nome Casel").position(this.posizioneXPuls,this.posizioneYPuls + this.spaziaturaY * 4); this.nomeCasButt.mousePressed(this.nomeCas); this.controlloMosseButton = createButton("Controllo Mosse").position(this.posizioneXPuls,this.posizioneYPuls + this.spaziaturaY * 5); this.controlloMosseButton.mousePressed(this.controlloMosse); this.mostraPoxButton = createButton("Mostra possibili").position(this.posizioneXPuls,this.posizioneYPuls + this.spaziaturaY * 6); this.mostraPoxButton.mousePressed(this.mostraPox); this.nextPoxButtonN = createButton("Next poss Nero").position(this.posizioneXPuls,this.posizioneYPuls + this.spaziaturaY * 7); this.nextPoxButtonN.mousePressed(this.nextPoxN); this.nextPoxButtonB = createButton("Next poss Bian").position(this.posizioneXPuls,this.posizioneYPuls + this.spaziaturaY * 8); this.nextPoxButtonB.mousePressed(this.nextPoxB); this.consoleScacchieraButton = createButton("Console this").position(this.posizioneXPuls,this.posizioneYPuls + this.spaziaturaY * 9); this.consoleScacchieraButton.mousePressed(this.consoleThis); // this.randomButton = createButton("Random").position(470,30); // this.randomButton.mousePressed(this.randomFunction); // // this.mettiUnoButton = createButton("Predef").position(470,80); // // this.mettiUnoButton.mousePressed(this.mettiUnoFunction); // this.mettiUnoButton = createButton("Svuota").position(470,80); // this.mettiUnoButton.mousePressed(this.sudokuVuoto); // this.testoStronzoButton = createButton("Dim Txt").position(470,130); // this.testoStronzoButton.mousePressed(this.testoStronzoFunction); // this.risolviButton = createButton("Risolvi").position(470,180); // this.risolviButton.mousePressed(this.risolviFunction); // this.mostraPossButton = createButton("MostraPoss").position(470,230); // this.mostraPossButton.mousePressed(this.mostraPossFunction); // this.clearSolButton = createButton("ClearSol").position(470,280); // this.clearSolButton.mousePressed(this.clearSolFunction); // this.controllaSolButton = createButton("ControllaSol").position(470,330); // this.controllaSolButton.mousePressed(this.controllaSolFunction); // // controllaSolButton.mouseOver(controllaSolFunction); // this.scriviConsole = createButton("Console").position(470,380); // this.scriviConsole.mousePressed(this.consoleSudoku); // this.randomSol = createButton("Random Sol").position(470,430); // this.randomSol.mousePressed(this.randomSolFunc); // this.modificaDimSud = createButton("Switch dim").position(500,480); // this.modificaDimSud.mousePressed(this.modificaDimSudFunc); }
use std::collections::HashMap; struct CorrelationMessageDto { message_name: Option<String>, business_key: Option<String>, tenant_id: Option<String>, without_tenant_id: Option<String>, process_instance_id: Option<String>, correlation_keys: Option<Vec<String>>, local_correlation_keys: Option<Vec<String>>, process_variables: Option<HashMap<String, String>>, process_variables_local: Option<HashMap<String, String>>, } impl CorrelationMessageDto { pub fn new() -> CorrelationMessageDto { CorrelationMessageDto { message_name: None, business_key: None, tenant_id: None, without_tenant_id: None, process_instance_id: None, correlation_keys: None, local_correlation_keys: None, process_variables: None, process_variables_local: None, } } pub fn set_message_name(&mut self, name: String) { self.message_name = Some(name); } pub fn set_business_key(&mut self, key: String) { self.business_key = Some(key); } pub fn set_tenant_id(&mut self, id: Option<String>) { self.tenant_id = id; } pub fn set_process_instance_id(&mut self, id: Option<String>) { self.process_instance_id = id; } pub fn set_correlation_keys(&mut self, keys: Option<Vec<String>>) { self.correlation_keys = keys; } pub fn set_process_variables(&mut self, variables: Option<HashMap<String, String>>) { self.process_variables = variables; } pub fn calculate_message_size(&self) -> usize { let mut size = 0; if let Some(name) = &self.message_name { size += name.len(); } if let Some(key) = &self.business_key { size += key.len(); } if let Some(id) = &self.tenant_id { size += id.len(); } if let Some(id) = &self.process_instance_id { size += id.len(); } if let Some(keys) = &self.correlation_keys { for key in keys { size += key.len(); } } if let Some(variables) = &self.process_variables { for (key, value) in variables { size += key.len() + value.len(); } } size } } fn main() { let mut dto = CorrelationMessageDto::new(); dto.set_message_name("OrderReceived".to_string()); dto.set_business_key("12345".to_string()); dto.set_tenant_id(Some("tenant1".to_string())); dto.set_process_instance_id(Some("process123".to_string())); dto.set_correlation_keys(Some(vec!["key1".to_string(), "key2".to_string()])); let mut variables = HashMap::new(); variables.insert("var1".to_string(), "value1".to_string()); variables.insert("var2".to_string(), "value2".to_string()); dto.set_process_variables(Some(variables)); let message_size = dto.calculate_message_size(); println!("Correlation message size: {} bytes", message_size); }
import scala.util.Try def sendSMS(numbers: List[String], message: String, sms_gateway: String): Try[Unit] { // Initialize http request import scalaj.http.{Http, HttpOptions} val http = Http(sms_gateway).options(HttpOptions.allowUnsafeSSL) // Send SMS to each number for (number <- numbers) { val params = Map( "recipients" -> number, "message" -> message ) http.postData(params).asString } } val numbers = List("+23456", "+987654", "+334567") val message = "This is a message!" val sms_gateway = "https://my-sms-gateway.com/api" sendSMS(numbers, message, sms_gateway)
#! /system/bin/sh LD_LIBRARY_PATH=/data/data/bcmon/libs LD_PRELOAD=/data/data/bcmon/libs/libfake_driver.so "$@"
import mongoose from "mongoose"; const schema = mongoose.Schema({ name: { type: String, required: true, min: 3, }, email: { type: String, required: true, min: 3, }, message: { type: String, required: true, min: 6, }, date: { type: Date, default: Date.now, }, }); const Queries = mongoose.model("Queries", schema); export default Queries;
const $log = require('../utils/logger'); const chalk = require(`chalk`); const fse = require(`fs-extra`); const S = require(`string`); const path = require(`path`); const fs = require(`../utils/fs`); const Project = require('../core/project'); const project = new Project; const root = process.cwd(); function handler (argv) { if (argv.source !== 'jekyll') { return $log.warn(chalk.red(`Sorry, only jekyll is supported now`)); } let dest = project.config.dest || argv.dest; project.loadConfigFromYamlFile(); project.change({ dest: dest, longname: project.config.title, }); project.saveYAML(true, root); dest = `${root}/${dest}`; if ((argv.exporto).lastIndexOf(`..`, 0) === 0) { $log.log(`Copying files to destination folder ${root}/${argv.exporto}`); fse.copySync(root, dest); } fse.walk(`${root}`).on('data', (item) => { if (S(item.path).include(dest)) {return;} item.isDirectory = item.stats.isDirectory(); item.shortPath = S(item.path).chompLeft(root).s; item.name = path.basename(item.path); item.basePath = S(item.shortPath).chompRight(item.name).s; item.extension = path.extname(item.path); if ((item.shortPath.lastIndexOf(`/.git`, 0) === 0) && item.name !== `.gitignore`) { return; } if (item.shortPath.lastIndexOf(`/_site`, 0) === 0) { return; } if ([ `.html`, `.md` ].indexOf(item.extension) !== -1) { $log.log(`migrating file`, item.path); let content = fse.readFileSync(item.path, `utf-8`); // content = convert('{liquid}') content = content.replace(/{%\s*include/g, `{{>`); content = content.replace(/{%\s*if/g, `{{#if`); content = content.replace(/{%\s*else/g, `{{^`); content = content.replace(/{%\s*endif/g, `{{/if`); content = content.replace(/^permalink:/, `url:`); content = content.replace(/\|.+}}/g, `}}`); content = content.replace(/{%/g, `{{`); content = content.replace(/%}/g, `}}`); try { fs.writeFileSync(item.path, content); } catch (err) { throw err; } $log.log(`Migrated file `, item.path); } }); } const builder = { source: { default: `jekyll`, description: `Source platform.`, }, exporto: { default: false, description: `When specified, the folder where the new files will be exported`, }, dest: { default: 'docs', }, }; module.exports = { command: `migrate [source]`, aliases: [], describe: `Migrates an existing website from a different platform to gloria. I'ts pretty buggy now and only works with jekyll. The replacement is pretty poor right now, it uses regex to find some liquid tags and replaces them with handlebars. It ignores some helpers like loops. It requires some extra manual work. If that's not cool with you, please consider a PR.`, builder: builder, handler: handler, };
<reponame>richardmarston/cim4j<filename>CGMES_2.4.15_27JAN2020/cim4j/Conductor.java<gh_stars>1-10 package cim4j; import java.util.List; import java.util.Map; import java.util.HashMap; import cim4j.ConductingEquipment; import java.lang.ArrayIndexOutOfBoundsException; import java.lang.IllegalArgumentException; import cim4j.Length; /* Combination of conducting material with consistent electrical characteristics, building a single electrical system, used to carry current between points in the power system. */ public class Conductor extends ConductingEquipment { private BaseClass[] Conductor_class_attributes; private BaseClass[] Conductor_primitive_attributes; private java.lang.String rdfid; public void setRdfid(java.lang.String id) { rdfid = id; } private abstract interface PrimitiveBuilder { public abstract BaseClass construct(java.lang.String value); }; private enum Conductor_primitive_builder implements PrimitiveBuilder { length(){ public BaseClass construct (java.lang.String value) { return new Length(value); } }, LAST_ENUM() { public BaseClass construct (java.lang.String value) { return new cim4j.Integer("0"); } }; } private enum Conductor_class_attributes_enum { length, LAST_ENUM; } public Conductor() { Conductor_primitive_attributes = new BaseClass[Conductor_primitive_builder.values().length]; Conductor_class_attributes = new BaseClass[Conductor_class_attributes_enum.values().length]; } public void updateAttributeInArray(Conductor_class_attributes_enum attrEnum, BaseClass value) { try { Conductor_class_attributes[attrEnum.ordinal()] = value; } catch (ArrayIndexOutOfBoundsException aoobe) { System.out.println("No such attribute: " + attrEnum.name() + ": " + aoobe.getMessage()); } } public void updateAttributeInArray(Conductor_primitive_builder attrEnum, BaseClass value) { try { Conductor_primitive_attributes[attrEnum.ordinal()] = value; } catch (ArrayIndexOutOfBoundsException aoobe) { System.out.println("No such attribute: " + attrEnum.name() + ": " + aoobe.getMessage()); } } public void setAttribute(java.lang.String attrName, BaseClass value) { try { Conductor_class_attributes_enum attrEnum = Conductor_class_attributes_enum.valueOf(attrName); updateAttributeInArray(attrEnum, value); System.out.println("Updated Conductor, setting " + attrName); } catch (IllegalArgumentException iae) { super.setAttribute(attrName, value); } } /* If the attribute is a String, it is a primitive and we will make it into a BaseClass */ public void setAttribute(java.lang.String attrName, java.lang.String value) { try { Conductor_primitive_builder attrEnum = Conductor_primitive_builder.valueOf(attrName); updateAttributeInArray(attrEnum, attrEnum.construct(value)); System.out.println("Updated Conductor, setting " + attrName + " to: " + value); } catch (IllegalArgumentException iae) { super.setAttribute(attrName, value); } } public java.lang.String toString(boolean topClass) { java.lang.String result = ""; java.lang.String indent = ""; if (topClass) { for (Conductor_primitive_builder attrEnum: Conductor_primitive_builder.values()) { BaseClass bc = Conductor_primitive_attributes[attrEnum.ordinal()]; if (bc != null) { result += " Conductor." + attrEnum.name() + "(" + bc.debugString() + ")" + " " + bc.toString(false) + System.lineSeparator(); } } for (Conductor_class_attributes_enum attrEnum: Conductor_class_attributes_enum.values()) { BaseClass bc = Conductor_class_attributes[attrEnum.ordinal()]; if (bc != null) { result += " Conductor." + attrEnum.name() + "(" + bc.debugString() + ")" + " " + bc.toString(false) + System.lineSeparator(); } } result += super.toString(true); } else { result += "(Conductor) RDFID: " + rdfid; } return result; } public final java.lang.String debugName = "Conductor"; public java.lang.String debugString() { return debugName; } public void setValue(java.lang.String s) { System.out.println(debugString() + " is not sure what to do with " + s); } public BaseClass construct() { return new Conductor(); } };
# # Copyright 2018 herd-mdl contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # #!/bin/bash echo "$@" # Check the error and fail if the last command is NOT successful function check_error { return_code=${1} cmd="$2" if [ ${return_code} -ne 0 ] then echo "$(date "+%m/%d/%Y %H:%M:%S") *** ERROR *** ${cmd} has failed with error $return_code" exit 1 fi } # Execute the given command and support resume option function execute_cmd { cmd="${1}" echo $cmd eval $cmd check_error ${PIPESTATUS[0]} "$cmd" } #MAIN configFile="/home/mdladmin/deploy/mdl/conf/deploy.props" if [ ! -f ${configFile} ] ; then echo "Config file does not exist ${configFile}" exit 1 fi . ${configFile} # Install packages execute_cmd "yum update -y aws-cfn-bootstrap" execute_cmd "yum install -y lynx" execute_cmd "yum install -y httpd" execute_cmd "yum install -y mod_ssl" execute_cmd "yum install -y openssl" execute_cmd "yum install -y jq" # Install docker execute_cmd "sudo yum install -y docker" execute_cmd "sudo service docker start" exit 0
#include <string> #include <codecvt> #include <locale> std::string FromWideString(const std::u16string& str) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter; return converter.to_bytes(str); } std::u16string ToWideString(const std::string& str) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter; return converter.from_bytes(str); }
import React from 'react'; import {Button_1} from './Buttons.js'; export function Navbar(props){ return ( <> <nav id="Navbar" className="cols_container space_between align_center"> <a href={props.AppURLs.domain} className="brand cols_container align_center"> <img src={props.AppURLs.icons+'logo_2.png'} /> <span>Fonts Vault</span> </a> <div className="cols_container"> <Button_1 tagname = {'button'} icon = {{position: 3, color: 'blue'}} events = {{onClick: props.toggleNavbar}} attr = {{id: 'opnNavbar'}} /> <div id="navbarLinks" className={(props.navbarShown ? 'shown': '')}> <div style={{display: 'flex', justifyContent: 'flex-start'}}> <button id="clsNavbar" type="button" onClick={props.toggleNavbar}> &times; </button> </div> <ul className="cols_container"> { props.navbarLinks.map((link, idx) => ( <li key={idx}> <a href={link.URL}>{link.text}</a> </li> )) } </ul> </div> </div> </nav> </>// ); } /* headerWidget = JSX headerWidgetBtn = JSX btn subHeader = { leftCol: JSX, rightCol: JSX } */ export class Header extends React.Component{ constructor(props){ super(props); this.state = { navbarShown: false, }; this.toggleNavbar = this.toggleNavbar.bind(this); } toggleNavbar(){ this.setState((state) => ({ navbarShown: !state.navbarShown })); } render(){ return ( <> <div className = "Header rows_container"> <div className = "row cols_container align_center section_padding"> <div className="rows_container center align_center"> {this.props.headerWidgetBtn} </div> <Navbar AppURLs = {this.props.AppURLs} navbarShown = {this.state.navbarShown} navbarLinks = {[ {URL: this.props.AppURLs.domain, text: 'Home'}, {URL: this.props.AppURLs.domain+'fonts', text: 'Applications'}, {URL: '#', text: 'About'}, {URL: this.props.AppURLs.domain+'admin/home', text: 'Login'}, ]} toggleNavbar = {this.toggleNavbar} /> </div> { (this.props.subHeader !== null ? <div className="subHeader cols_container space_between align_center section_padding"> <div className="cols_container align_center"> {this.props.subHeader.leftCol} </div> <div className="cols_container align_center"> {this.props.subHeader.rightCol} </div> </div> : '' ) } {this.props.headerWidget} </div> </> // ); } } export function Table(props){ return ( <> <div className="table"> <table> <thead> <tr> {props.headData.map((data, idx) => ( <th key={idx}>{data}</th> ))} </tr> </thead> <tbody> {props.bodyData.map((row, rowidx) => ( <tr key={rowidx}> {row.map((col, colidx) => ( <td key={colidx}>{col}</td> ))} </tr> ))} </tbody> </table> </div> </>// ); } export function SectionHeader(props){ const HeadingTag = props.headingTag; return ( <div className="sectionHeader section_padding cols_container space_between align_center"> <div className="rows_container"> <HeadingTag className="heading">{props.headingText}</HeadingTag> {( props.subHeadingText ? <span className="subHeading">{props.subHeadingText}</span> : '' )} </div> <div className="cols_container"> {props.headerActions} </div> </div> ); } export function ListWidget_1(props){ const ListTag = props.listTag; return ( <> <ListTag className="list_widget_1 section_padding cols_container space_between" {...props.attr}> <div className="cols_container align_center"> <div className={'bar '+props.barColor}></div> <div className="text rows_container"> <span className="mainText">{props.text.mainText}</span> {(props.text.subText ? <span className="subText">{props.text.subText}</span> : '' )} </div> </div> <section className="cols_container align_center list_actions"> {props.listActions} </section> </ListTag> </> // ); } export function Footer(props){ return ( <> <footer className="docFooter cols_container space_between align_center"> <div> Developed an designed by <a href="mailto: <EMAIL>" style={{marginLeft: '0.4rem'}}> <EMAIL> </a> </div> <div> <a href="#" style={{marginLeft: '1.4rem'}}>About</a> <a href="#" style={{marginLeft: '1.4rem'}}>Team</a> <a href="#" style={{marginLeft: '1.4rem'}}>Contract</a> </div> </footer> </>// ); }
<gh_stars>0 package com.mh.controltool2.method.type; import java.lang.reflect.Type; /* * use request body to object * need: * param parameterized type * */ public class InvokeRequestBody extends InvokeObjectInfo { private Type parameterizedType; @Override public TypeEnum getHandlerType() { return TypeEnum.RequestBody; } public Type getParameterizedType() { return parameterizedType; } public void setParameterizedType(Type parameterizedType) { this.parameterizedType = parameterizedType; } }
#include <bits/stdc++.h> #define endl '\n' using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int T, N; string s; cin>>T; while(T--){ cin>>N; stack<set<int>> st; int setidcnt=0; map<set<int>, int> setid; while(N--){ cin>>s; set<int> temp, temp1, temp2, temp3; switch(s[0]){ case 'P': st.push(temp); break; case 'D': temp = st.top(); st.push(temp); break; case 'U': temp1 = st.top(); st.pop(); temp2 = st.top(); st.pop(); for(auto t:temp2){ temp1.insert(t); } st.push(temp1); break; case 'I': temp = st.top(); st.pop(); temp2 = st.top(); st.pop(); for(auto t:temp){ if(temp2.count(t)){ temp3.insert(t); } } st.push(temp3); break; case 'A': temp = st.top(); st.pop(); if(!setid.count(temp)){ setid[temp] = setidcnt++; } st.top().insert(setid[temp]); break; } cout<<st.top().size()<<endl; } cout<<"***"<<endl; } }
module.exports = { fromIndexToPool: (poolId) => `./pools/${poolId}.html`, fromPoolToIndex: '../index.html', fromTestToPool: (poolId) => `../../${poolId}.html`, fromTestToIndex: '../../../index.html', fromLogsToIndex: '../../../../index.html', fromTestToLogs: (filename) => `./logs/${filename}`, fromLogsToTest: (testId) => `../${testId}.html`, fromLogsToPool: (poolId) => `../../../${poolId}.html` };