text
stringlengths
1
1.05M
def has_duplicates(array): seen = set() for element in array: if element in seen: return True seen.add(element) return False
TERMUX_PKG_HOMEPAGE=https://php.net TERMUX_PKG_DESCRIPTION="Server-side, HTML-embedded scripting language" TERMUX_PKG_VERSION=7.2.3 TERMUX_PKG_REVISION=2 TERMUX_PKG_SHA256=b3a94f1b562f413c0b96f54bc309706d83b29ac65d9b172bc7ed9fb40a5e651f TERMUX_PKG_SRCURL=http://www.php.net/distributions/php-${TERMUX_PKG_VERSION}.tar.xz # Build native php for phar to build (see pear-Makefile.frag.patch): TERMUX_PKG_HOSTBUILD=true # Build the native php without xml support as we only need phar: TERMUX_PKG_EXTRA_HOSTBUILD_CONFIGURE_ARGS="--disable-libxml --disable-dom --disable-simplexml --disable-xml --disable-xmlreader --disable-xmlwriter --without-pear" TERMUX_PKG_DEPENDS="libandroid-glob, libxml2, liblzma, openssl, pcre, libbz2, libcrypt, libcurl, libgd, readline, freetype" # mysql modules were initially shared libs TERMUX_PKG_CONFLICTS="php-mysql" TERMUX_PKG_REPLACES="php-mysql" TERMUX_PKG_RM_AFTER_INSTALL="php/php/fpm" TERMUX_PKG_EXTRA_CONFIGURE_ARGS=" ac_cv_func_res_nsearch=no --enable-bcmath --enable-calendar --enable-exif --enable-gd-native-ttf=$TERMUX_PREFIX --enable-mbstring --enable-opcache --enable-pcntl --enable-sockets --enable-zip --mandir=$TERMUX_PREFIX/share/man --with-bz2=$TERMUX_PREFIX --with-curl=$TERMUX_PREFIX --with-freetype-dir=$TERMUX_PREFIX --with-gd=$TERMUX_PREFIX --with-iconv=$TERMUX_PREFIX --with-libxml-dir=$TERMUX_PREFIX --with-openssl=$TERMUX_PREFIX --with-pcre-regex=$TERMUX_PREFIX --with-png-dir=$TERMUX_PREFIX --with-readline=$TERMUX_PREFIX --with-zlib --with-pgsql=shared,$TERMUX_PREFIX --with-pdo-pgsql=shared,$TERMUX_PREFIX --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-mysql-sock=$TERMUX_PREFIX/tmp/mysqld.sock --with-apxs2=$TERMUX_PREFIX/bin/apxs --enable-fpm --sbindir=$TERMUX_PREFIX/bin " termux_step_pre_configure () { LDFLAGS+=" -landroid-glob -llog" export PATH=$PATH:$TERMUX_PKG_HOSTBUILD_DIR/sapi/cli/ export NATIVE_PHP_EXECUTABLE=$TERMUX_PKG_HOSTBUILD_DIR/sapi/cli/php # Run autoconf since we have patched config.m4 files. autoconf export EXTENSION_DIR=$TERMUX_PREFIX/lib/php } termux_step_post_configure () { # Avoid src/ext/gd/gd.c trying to include <X11/xpm.h>: sed -i 's/#define HAVE_GD_XPM 1//' $TERMUX_PKG_BUILDDIR/main/php_config.h # Avoid src/ext/standard/dns.c trying to use struct __res_state: sed -i 's/#define HAVE_RES_NSEARCH 1//' $TERMUX_PKG_BUILDDIR/main/php_config.h } termux_step_post_make_install () { mkdir -p $TERMUX_PREFIX/etc/php-fpm.d cp sapi/fpm/php-fpm.conf $TERMUX_PREFIX/etc/ cp sapi/fpm/www.conf $TERMUX_PREFIX/etc/php-fpm.d/ sed -i 's/SED=.*/SED=sed/' $TERMUX_PREFIX/bin/phpize }
<filename>src/yimei/util/random/NormalSampler.java package yimei.util.random; import org.apache.commons.math3.random.RandomDataGenerator; public class NormalSampler extends AbstractRealSampler { private double mean; private double sd; public NormalSampler() { super(); } public NormalSampler(double mean, double sd) { super(); this.mean = mean; this.sd = sd; } public void set(double mean, double sd) { this.mean = mean; this.sd = sd; } public void setMean(double mean) { this.mean = mean; } public void setSd(double sd) { this.sd = sd; } public double getMean() { return mean; } public double getSd() { return sd; } @Override public double next(RandomDataGenerator rdg) { return rdg.nextGaussian(mean, sd); } @Override public void setLower(double lower) { // do nothing. } @Override public void setUpper(double upper) { // do nothing. } @Override public AbstractRealSampler clone() { return new NormalSampler(mean, sd); } }
from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB text_docs = [ "A document about the dog", "A document about the cat", "A document about the mouse" ] # Step 1: Create the input features matrix count_vect = CountVectorizer() X = count_vect.fit_transform(text_docs) # Step 2: Create and train the model clf = MultinomialNB() clf.fit(X, classes) # Step 3: Make predictions predictions = clf.predict(X)
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 22 10:19:44 2021 @author: sb069 """ import os import errno from os.path import expanduser os.system("sudo apt-get update") os.system("sudo apt install nvidia-cuda-toolkit") os.system("sudo apt install python3.8") os.system("conda install flye") try: os.system("mkdir -p ~/Documents/LMToolkit") except OSError as e: if e.errno != errno.EEXIST: raise try: os.system("mkdir -p ~/Documents/LMToolkit/MinionOut") except OSError as e: if e.errno != errno.EEXIST: raise try: os.system("mkdir -p ~/Documents/LMToolkit/Assembly_Out") except OSError as e: if e.errno != errno.EEXIST: raise #Downloads=str(os.environ['_']) #Downloads=Download.replace('/LMToolkit_Setup.py','') #print("THIS IS A TEST " + Downloads) #os.chdir(Downloads) #print("mv LMToolKit.py ~/Documents/LMToolkit") try: os.system("mv LMToolkit.py ~/Documents/LMToolkit/LMToolkit.py") except OSError as e: if e.errno != errno.EEXIST: raise try: os.system("mv README.md ~/Documents/LMToolkit/README.md") except OSError as e: if e.errno != errno.EEXIST: raise try: os.system("mv LMToolKit_License ~/Documents/LMToolkit/LMToolKit_License") except OSError as e: if e.errno != errno.EEXIST: raise def main(): hdir=os.path.expanduser('~') os.chdir(hdir+'/Documents/LMToolkit') with open("config.txt", 'w') as config1: Basecall=input("What is the path of your guppy basecaller (ont-guppy/bin/guppy_basecaller)?: ") config1.write(Basecall) config1.close() with open("guppyconfig.txt", "w") as config2: Basecallconfig=input("What is the path of your guppy basecaller config file (ont-guppy/data/config) please read readme for details )?: ") config2.write(Basecallconfig) config2.close() print("LMToolKit is now setup! Happy Basecalling!") main()
<filename>kernel/driver/console.h #ifndef _KERNEL_DRIVER_CONSOLE_H_ #define _KERNEL_DRIVER_CONSOLE_H_ void cons_init(); void cons_putc(int c); int cons_getc(); #endif
<reponame>minuk8932/Algorithm_BaekJoon package breadth_first_search; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; /** * * @author exponential-e * 백준 23563번: 벽 타기 * * @see https://www.acmicpc.net/problem/23563 * */ public class Boj23563 { private static final int INF = 1_000_000_000; private static final char BLOCK = '#'; private static final char START = 'S'; private static final char END = 'E'; private static final int[][] DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; private static final int ROW = 0; private static final int COL = 1; private static Point start; private static Point end; private static char[][] map; private static boolean[][] adjBlock; private static class Point { int row; int col; public Point(int row, int col) { this.row = row; this.col = col; } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int H = Integer.parseInt(st.nextToken()); int W = Integer.parseInt(st.nextToken()); map = new char[H][W]; adjBlock = new boolean[H][W]; for(int i = 0; i < H; i++) { String line = br.readLine(); for(int j = 0; j < W; j++) { map[i][j] = line.charAt(j); if(map[i][j] == START) start = new Point(i, j); if(map[i][j] == END) end = new Point(i, j); } } init(H, W); System.out.println(bfs(H, W)); } /** * * 0-1 BFS * * line 95 ~ 102: wall riding possibility * line 107 ~ 108: 0-1 process * * @param h * @param w * @return */ private static int bfs(int h, int w) { int[][] visit = new int[h][w]; for(int i = 0; i < h; i++) { Arrays.fill(visit[i], INF); } Deque<Point> deq = new ArrayDeque<>(); deq.offer(start); visit[start.row][start.col] = 0; while(!deq.isEmpty()) { Point current = deq.poll(); for(final int[] DIRECTION: DIRECTIONS) { int nextRow = current.row + DIRECTION[ROW]; int nextCol = current.col + DIRECTION[COL]; if(map[nextRow][nextCol] == BLOCK) continue; int cost = visit[current.row][current.col]; boolean path = false; if (adjBlock[current.row][current.col] && adjBlock[nextRow][nextCol]) { path = true; } else { cost += 1; } if(visit[nextRow][nextCol] <= cost) continue; visit[nextRow][nextCol] = cost; if (path) deq.offerFirst(new Point(nextRow, nextCol)); else deq.offerLast(new Point(nextRow, nextCol)); } } return visit[end.row][end.col]; } private static void init(int h, int w) { for(int row = 0; row < h; row++) { for(int col = 0; col < w; col++) { if(map[row][col] == BLOCK) continue; adjBlock[row][col] = isNearPost(new Point(row, col)); } } } private static boolean isNearPost(Point current) { for(final int[] DIRECTION: DIRECTIONS) { int nextRow = current.row + DIRECTION[ROW]; int nextCol = current.col + DIRECTION[COL]; if(map[nextRow][nextCol] == BLOCK) return true; } return false; } }
#!/bin/bash REPEAT=5 gcc -O2 c/syscall.c -o syscall_c go test -bench=. -count=$REPEAT -timeout 20m -v for i in `seq 1 ${REPEAT}`; do ./syscall_c done rm syscall_c
<filename>INFO/Books Codes/Oracle Database 10g PLSQL/Code/Chapter16/LoadFromFile.sql /* * LoadFromFile.sql * Chapter 16, Oracle10g PL/SQL Programming * by <NAME>, <NAME>, <NAME> * * This script tests the DBMS_LOB.LOADFROMFILE procedure */ exec CLEAN_SCHEMA.TABLES exec CLEAN_SCHEMA.OBJECTS exec CLEAN_SCHEMA.PROCS PROMPT PROMPT ** Create table book_samples PROMPT CREATE TABLE book_samples ( book_sample_id NUMBER (10) PRIMARY KEY, isbn CHAR(10 CHAR), description CLOB, nls_description NCLOB, misc BLOB, chapter_title VARCHAR2(30 CHAR), bfile_description BFILE ) LOB (misc) STORE AS blob_seg ( TABLESPACE blob_ts CHUNK 8192 PCTVERSION 0 NOCACHE NOLOGGING DISABLE STORAGE IN ROW) LOB (description, nls_description) STORE AS ( TABLESPACE clob_ts CHUNK 8192 PCTVERSION 10 NOCACHE LOGGING ENABLE STORAGE IN ROW); PROMPT PROMPT ** Insert a record into book_samples table PROMPT INSERT INTO book_samples ( book_sample_id, isbn, description, nls_description, misc, bfile_description) VALUES ( 1, '72230665', EMPTY_CLOB(), EMPTY_CLOB(), EMPTY_BLOB(), BFILENAME('BOOK_SAMPLES_LOC', 'bfile_example.pdf')); COMMIT; set serveroutput on DECLARE v_dest_blob BLOB; v_dest_clob CLOB; v_source_locator1 BFILE := BFILENAME('BOOK_SAMPLES_LOC', 'bfile_example.pdf'); v_source_locator2 BFILE := BFILENAME('BOOK_SAMPLES_LOC', 'bfile_example.txt'); BEGIN -- Empty the description and misc columns UPDATE book_samples SET description = EMPTY_CLOB(), misc = EMPTY_BLOB() WHERE book_sample_id = 1; -- Retrieve the locators for the two destination columns SELECT description, misc INTO v_dest_clob, v_dest_blob FROM book_samples WHERE book_sample_id = 1 FOR UPDATE; -- Open the BFILEs and destination LOBs DBMS_LOB.OPEN(v_source_locator1, DBMS_LOB.LOB_READONLY); DBMS_LOB.OPEN(v_source_locator2, DBMS_LOB.LOB_READONLY); DBMS_LOB.OPEN(v_dest_blob, DBMS_LOB.LOB_READWRITE); DBMS_LOB.OPEN(v_dest_clob, DBMS_LOB.LOB_READWRITE); DBMS_OUTPUT.PUT_LINE('Length of the BLOB file is: '||DBMS_LOB.GETLENGTH(v_source_locator1)); DBMS_OUTPUT.PUT_LINE('Length of the CLOB file is: '||DBMS_LOB.GETLENGTH(v_source_locator2)); DBMS_OUTPUT.PUT_LINE('Size of BLOB pre-load: '||DBMS_LOB.GETLENGTH(v_dest_blob)); DBMS_OUTPUT.PUT_LINE('Size of CLOB pre-load: '||DBMS_LOB.GETLENGTH(v_dest_clob)); -- Load the destination columns from the source DBMS_LOB.LOADFROMFILE(v_dest_blob, v_source_locator1, DBMS_LOB.LOBMAXSIZE, 1, 1); DBMS_LOB.LOADFROMFILE(v_dest_clob, v_source_locator2, DBMS_LOB.LOBMAXSIZE, 1, 1); DBMS_OUTPUT.PUT_LINE('Size of BLOB post-load: '||DBMS_LOB.GETLENGTH(v_dest_blob)); DBMS_OUTPUT.PUT_LINE('Size of CLOB post-load: '||DBMS_LOB.GETLENGTH(v_dest_clob)); -- Close the LOBs that we opened DBMS_LOB.CLOSE(v_source_locator1); DBMS_LOB.CLOSE(v_source_locator2); DBMS_LOB.CLOSE(v_dest_blob); DBMS_LOB.CLOSE(v_dest_clob); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(SQLERRM); DBMS_LOB.CLOSE(v_source_locator1); DBMS_LOB.CLOSE(v_source_locator2); DBMS_LOB.CLOSE(v_dest_blob); DBMS_LOB.CLOSE(v_dest_clob); END; / PROMPT PROMPT ** SELECT of the description column PROMPT SET LONG 64000 SELECT description FROM book_samples WHERE book_sample_id = 1;
#!/usr/bin/env bash # # Copyright (C) @2020 Webank Group Holding Limited # <p> # 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 # <p> # http://www.apache.org/licenses/LICENSE-2.0 # <p> # 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. # #============================================================================== #description :upgrade kubernetes cluster to 1.12.5. #author : #linux :centos7 #user :root #config file :install.properties #comment :master, #============================================================================== set -e function log() { level=$1 message=$2 log="`date +'%Y-%m-%d %H:%M:%S'`,$LINENO [$level] - $message" echo $log } # root if [ $UID -ne 0 ]; then echo "Superuser privileges are required to run this script." echo "e.g. \"sudo $0\"" exit 1 fi # restore manifests files log INFO "please restore files manually, because automatic file replacement is dangerous. see backup.sh" # backup manifests files log INFO "restore /data/kubernetes config..." cp -r config/* /data/kubernetes/config/ log INFO "restore /etc/kubernetes/" cp -r etc/kubernetes/* /etc/kubernetes/ log INFO "restore /var/lib/kubelet/config.yaml..." cp -r var/lib/kubelet/config.yaml /var/lib/kubelet/ log INFO "restore cni plugins..." cp -r cni/* /etc/cni/net.d/* log INFO "restore kubelet/kubeadm/kubectl binary files and unzip..." tar zxvfP binary.tar.gz systemctl stop kubelet cp -r binary/* /usr/bin/ systemctl restart kubelet
class MigrationOperation: def execute(self): pass class AddStylesMigration(MigrationOperation): def execute(self): # Perform the migration task for adding styles pass class UpdateDataMigration(MigrationOperation): def execute(self): # Perform the migration task for updating data pass class ModifySchemaMigration(MigrationOperation): def execute(self): # Perform the migration task for modifying the database schema raise Exception("Failed to modify the database schema") def execute_migrations(operations): for index, operation in enumerate(operations): try: operation.execute() except Exception as e: return index return None operations = [AddStylesMigration(), UpdateDataMigration(), ModifySchemaMigration()] result = execute_migrations(operations) print(result) # Output: 2 (if the ModifySchemaMigration operation fails)
<filename>client/admin/users/members/edit/edit.js 'use strict'; const identicon = require('nodeca.users/lib/identicon'); const avatarWidth = '$$ JSON.stringify(N.config.users.avatars.resize.orig.width) $$'; N.wire.once('navigate.done:' + module.apiPath, function init_handlers() { // Submit button handler // N.wire.on(module.apiPath + ':submit', function update_user(form) { let data = Object.assign({ user_hid: form.$this.data('user-hid') }, form.fields); return N.io.rpc('admin.users.members.edit.update', data) .then(() => N.wire.emit('notify.info', t('saved'))) .then(() => N.wire.emit('navigate.reload')); }); // Show delete avatar confirmation dialog // N.wire.before(module.apiPath + ':delete_avatar', function confirm_delete_avatar() { return N.wire.emit('admin.core.blocks.confirm', t('delete_avatar_confirm')); }); // Click on delete avatar button // N.wire.on(module.apiPath + ':delete_avatar', function delete_avatar(data) { let user_hid = data.$this.data('user-hid'); return N.io.rpc('admin.users.members.edit.delete_avatar', { user_hid }).then(() => { let $root = data.$this.parent('.user-edit-avatar'); let $img = $root.find('.user-edit-avatar__image'); $img.attr('src', identicon(N.runtime.user_id, avatarWidth)); $root.removeClass('user-edit-avatar__m-exists'); }); }); // Show account deletion confirmation dialog // N.wire.before(module.apiPath + ':delete_account', function confirm_delete_account() { return N.wire.emit('admin.core.blocks.confirm', t('delete_account_confirm')); }); // Click on delete account button // N.wire.on(module.apiPath + ':delete_account', function delete_account(data) { let user_hid = data.$this.data('user-hid'); return N.io.rpc('admin.users.members.edit.delete_account', { user_hid, delete: true }) .then(() => N.wire.emit('navigate.reload')); }); // Show restore account confirmation dialog // N.wire.before(module.apiPath + ':restore_account', function confirm_restore_account() { return N.wire.emit('admin.core.blocks.confirm', t('restore_account_confirm')); }); // Click on restore account button // N.wire.on(module.apiPath + ':restore_account', function restore_account(data) { let user_hid = data.$this.data('user-hid'); return N.io.rpc('admin.users.members.edit.delete_account', { user_hid, delete: false }) .then(() => N.wire.emit('navigate.reload')); }); // Show delete dialogs confirmation dialog // N.wire.before(module.apiPath + ':delete_dialogs', function confirm_delete_dialogs() { return N.wire.emit('admin.core.blocks.confirm', t('delete_dialogs_confirm')); }); // Click on delete dialogs button // N.wire.on(module.apiPath + ':delete_dialogs', function delete_dialogs(data) { let user_hid = data.$this.data('user-hid'); return N.io.rpc('admin.users.members.edit.delete_dialogs', { user_hid }) .then(() => N.wire.emit('notify.info', t('dialogs_deleted'))); }); // Show reset password confirmation dialog // N.wire.before(module.apiPath + ':reset_password', function confirm_reset_password() { return N.wire.emit('admin.core.blocks.confirm', t('reset_password_confirm')); }); // Click on reset password button // N.wire.on(module.apiPath + ':reset_password', function reset_password(data) { let user_hid = data.$this.data('user-hid'); return N.io.rpc('admin.users.members.edit.reset_password', { user_hid }) .then(() => N.wire.emit('notify.info', t('password_reset'))); }); // Show unblock confirmation dialog // N.wire.before(module.apiPath + ':unblock', function confirm_unblock() { return N.wire.emit('admin.core.blocks.confirm', t('unblock_confirm')); }); // Click on unblock button // N.wire.on(module.apiPath + ':unblock', function unblock(data) { let user_hid = data.$this.data('user-hid'); return N.io.rpc('admin.users.members.edit.unblock', { user_hid }) .then(() => N.wire.emit('navigate.reload')); }); // Show delete votes confirmation dialog // N.wire.before(module.apiPath + ':delete_votes', function confirm_delete_votes() { return N.wire.emit('admin.core.blocks.confirm', t('delete_votes_confirm')); }); // Click on delete votes button // N.wire.on(module.apiPath + ':delete_votes', function delete_votes(data) { let user_hid = data.$this.data('user-hid'); return N.io.rpc('admin.users.members.edit.delete_votes', { user_hid }) .then(() => N.wire.emit('notify.info', t('votes_deleted'))); }); });
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: edge.proto package com.ciat.bim.server.edge.gen; import java.util.Collections; /** * Protobuf type {@code edge.RuleChainMetadataUpdateMsg} */ public final class RuleChainMetadataUpdateMsg extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:edge.RuleChainMetadataUpdateMsg) RuleChainMetadataUpdateMsgOrBuilder { private static final long serialVersionUID = 0L; // Use RuleChainMetadataUpdateMsg.newBuilder() to construct. private RuleChainMetadataUpdateMsg(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RuleChainMetadataUpdateMsg() { msgType_ = 0; nodes_ = Collections.emptyList(); connections_ = java.util.Collections.emptyList(); ruleChainConnections_ = java.util.Collections.emptyList(); } @Override @SuppressWarnings({"unused"}) protected Object newInstance( UnusedPrivateParameter unused) { return new RuleChainMetadataUpdateMsg(); } @Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private RuleChainMetadataUpdateMsg( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { int rawValue = input.readEnum(); msgType_ = rawValue; break; } case 16: { ruleChainIdMSB_ = input.readInt64(); break; } case 24: { ruleChainIdLSB_ = input.readInt64(); break; } case 32: { firstNodeIndex_ = input.readInt32(); break; } case 42: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { nodes_ = new java.util.ArrayList<RuleNodeProto>(); mutable_bitField0_ |= 0x00000001; } nodes_.add( input.readMessage(RuleNodeProto.parser(), extensionRegistry)); break; } case 50: { if (!((mutable_bitField0_ & 0x00000002) != 0)) { connections_ = new java.util.ArrayList<NodeConnectionInfoProto>(); mutable_bitField0_ |= 0x00000002; } connections_.add( input.readMessage(NodeConnectionInfoProto.parser(), extensionRegistry)); break; } case 58: { if (!((mutable_bitField0_ & 0x00000004) != 0)) { ruleChainConnections_ = new java.util.ArrayList<RuleChainConnectionInfoProto>(); mutable_bitField0_ |= 0x00000004; } ruleChainConnections_.add( input.readMessage(RuleChainConnectionInfoProto.parser(), extensionRegistry)); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { nodes_ = java.util.Collections.unmodifiableList(nodes_); } if (((mutable_bitField0_ & 0x00000002) != 0)) { connections_ = java.util.Collections.unmodifiableList(connections_); } if (((mutable_bitField0_ & 0x00000004) != 0)) { ruleChainConnections_ = java.util.Collections.unmodifiableList(ruleChainConnections_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return EdgeProtos.internal_static_edge_RuleChainMetadataUpdateMsg_descriptor; } @Override protected FieldAccessorTable internalGetFieldAccessorTable() { return EdgeProtos.internal_static_edge_RuleChainMetadataUpdateMsg_fieldAccessorTable .ensureFieldAccessorsInitialized( RuleChainMetadataUpdateMsg.class, Builder.class); } public static final int MSGTYPE_FIELD_NUMBER = 1; private int msgType_; /** * <code>.edge.UpdateMsgType msgType = 1;</code> * @return The enum numeric value on the wire for msgType. */ @Override public int getMsgTypeValue() { return msgType_; } /** * <code>.edge.UpdateMsgType msgType = 1;</code> * @return The msgType. */ @Override public UpdateMsgType getMsgType() { @SuppressWarnings("deprecation") UpdateMsgType result = UpdateMsgType.valueOf(msgType_); return result == null ? UpdateMsgType.UNRECOGNIZED : result; } public static final int RULECHAINIDMSB_FIELD_NUMBER = 2; private long ruleChainIdMSB_; /** * <code>int64 ruleChainIdMSB = 2;</code> * @return The ruleChainIdMSB. */ @Override public long getRuleChainIdMSB() { return ruleChainIdMSB_; } public static final int RULECHAINIDLSB_FIELD_NUMBER = 3; private long ruleChainIdLSB_; /** * <code>int64 ruleChainIdLSB = 3;</code> * @return The ruleChainIdLSB. */ @Override public long getRuleChainIdLSB() { return ruleChainIdLSB_; } public static final int FIRSTNODEINDEX_FIELD_NUMBER = 4; private int firstNodeIndex_; /** * <code>int32 firstNodeIndex = 4;</code> * @return The firstNodeIndex. */ @Override public int getFirstNodeIndex() { return firstNodeIndex_; } public static final int NODES_FIELD_NUMBER = 5; private java.util.List<RuleNodeProto> nodes_; /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ @Override public java.util.List<RuleNodeProto> getNodesList() { return nodes_; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ @Override public java.util.List<? extends RuleNodeProtoOrBuilder> getNodesOrBuilderList() { return nodes_; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ @Override public int getNodesCount() { return nodes_.size(); } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ @Override public RuleNodeProto getNodes(int index) { return nodes_.get(index); } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ @Override public RuleNodeProtoOrBuilder getNodesOrBuilder( int index) { return nodes_.get(index); } public static final int CONNECTIONS_FIELD_NUMBER = 6; private java.util.List<NodeConnectionInfoProto> connections_; /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ @Override public java.util.List<NodeConnectionInfoProto> getConnectionsList() { return connections_; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ @Override public java.util.List<? extends NodeConnectionInfoProtoOrBuilder> getConnectionsOrBuilderList() { return connections_; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ @Override public int getConnectionsCount() { return connections_.size(); } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ @Override public NodeConnectionInfoProto getConnections(int index) { return connections_.get(index); } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ @Override public NodeConnectionInfoProtoOrBuilder getConnectionsOrBuilder( int index) { return connections_.get(index); } public static final int RULECHAINCONNECTIONS_FIELD_NUMBER = 7; private java.util.List<RuleChainConnectionInfoProto> ruleChainConnections_; /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ @Override public java.util.List<RuleChainConnectionInfoProto> getRuleChainConnectionsList() { return ruleChainConnections_; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ @Override public java.util.List<? extends RuleChainConnectionInfoProtoOrBuilder> getRuleChainConnectionsOrBuilderList() { return ruleChainConnections_; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ @Override public int getRuleChainConnectionsCount() { return ruleChainConnections_.size(); } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ @Override public RuleChainConnectionInfoProto getRuleChainConnections(int index) { return ruleChainConnections_.get(index); } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ @Override public RuleChainConnectionInfoProtoOrBuilder getRuleChainConnectionsOrBuilder( int index) { return ruleChainConnections_.get(index); } private byte memoizedIsInitialized = -1; @Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (msgType_ != UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE.getNumber()) { output.writeEnum(1, msgType_); } if (ruleChainIdMSB_ != 0L) { output.writeInt64(2, ruleChainIdMSB_); } if (ruleChainIdLSB_ != 0L) { output.writeInt64(3, ruleChainIdLSB_); } if (firstNodeIndex_ != 0) { output.writeInt32(4, firstNodeIndex_); } for (int i = 0; i < nodes_.size(); i++) { output.writeMessage(5, nodes_.get(i)); } for (int i = 0; i < connections_.size(); i++) { output.writeMessage(6, connections_.get(i)); } for (int i = 0; i < ruleChainConnections_.size(); i++) { output.writeMessage(7, ruleChainConnections_.get(i)); } unknownFields.writeTo(output); } @Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (msgType_ != UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, msgType_); } if (ruleChainIdMSB_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(2, ruleChainIdMSB_); } if (ruleChainIdLSB_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(3, ruleChainIdLSB_); } if (firstNodeIndex_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(4, firstNodeIndex_); } for (int i = 0; i < nodes_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, nodes_.get(i)); } for (int i = 0; i < connections_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(6, connections_.get(i)); } for (int i = 0; i < ruleChainConnections_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(7, ruleChainConnections_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof RuleChainMetadataUpdateMsg)) { return super.equals(obj); } RuleChainMetadataUpdateMsg other = (RuleChainMetadataUpdateMsg) obj; if (msgType_ != other.msgType_) return false; if (getRuleChainIdMSB() != other.getRuleChainIdMSB()) return false; if (getRuleChainIdLSB() != other.getRuleChainIdLSB()) return false; if (getFirstNodeIndex() != other.getFirstNodeIndex()) return false; if (!getNodesList() .equals(other.getNodesList())) return false; if (!getConnectionsList() .equals(other.getConnectionsList())) return false; if (!getRuleChainConnectionsList() .equals(other.getRuleChainConnectionsList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + MSGTYPE_FIELD_NUMBER; hash = (53 * hash) + msgType_; hash = (37 * hash) + RULECHAINIDMSB_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getRuleChainIdMSB()); hash = (37 * hash) + RULECHAINIDLSB_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getRuleChainIdLSB()); hash = (37 * hash) + FIRSTNODEINDEX_FIELD_NUMBER; hash = (53 * hash) + getFirstNodeIndex(); if (getNodesCount() > 0) { hash = (37 * hash) + NODES_FIELD_NUMBER; hash = (53 * hash) + getNodesList().hashCode(); } if (getConnectionsCount() > 0) { hash = (37 * hash) + CONNECTIONS_FIELD_NUMBER; hash = (53 * hash) + getConnectionsList().hashCode(); } if (getRuleChainConnectionsCount() > 0) { hash = (37 * hash) + RULECHAINCONNECTIONS_FIELD_NUMBER; hash = (53 * hash) + getRuleChainConnectionsList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static RuleChainMetadataUpdateMsg parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static RuleChainMetadataUpdateMsg parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static RuleChainMetadataUpdateMsg parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static RuleChainMetadataUpdateMsg parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static RuleChainMetadataUpdateMsg parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static RuleChainMetadataUpdateMsg parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static RuleChainMetadataUpdateMsg parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static RuleChainMetadataUpdateMsg parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static RuleChainMetadataUpdateMsg parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static RuleChainMetadataUpdateMsg parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static RuleChainMetadataUpdateMsg parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static RuleChainMetadataUpdateMsg parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(RuleChainMetadataUpdateMsg prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @Override protected Builder newBuilderForType( BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code edge.RuleChainMetadataUpdateMsg} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:edge.RuleChainMetadataUpdateMsg) RuleChainMetadataUpdateMsgOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return EdgeProtos.internal_static_edge_RuleChainMetadataUpdateMsg_descriptor; } @Override protected FieldAccessorTable internalGetFieldAccessorTable() { return EdgeProtos.internal_static_edge_RuleChainMetadataUpdateMsg_fieldAccessorTable .ensureFieldAccessorsInitialized( RuleChainMetadataUpdateMsg.class, Builder.class); } // Construct using RuleChainMetadataUpdateMsg.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getNodesFieldBuilder(); getConnectionsFieldBuilder(); getRuleChainConnectionsFieldBuilder(); } } @Override public Builder clear() { super.clear(); msgType_ = 0; ruleChainIdMSB_ = 0L; ruleChainIdLSB_ = 0L; firstNodeIndex_ = 0; if (nodesBuilder_ == null) { nodes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { nodesBuilder_.clear(); } if (connectionsBuilder_ == null) { connections_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); } else { connectionsBuilder_.clear(); } if (ruleChainConnectionsBuilder_ == null) { ruleChainConnections_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); } else { ruleChainConnectionsBuilder_.clear(); } return this; } @Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return EdgeProtos.internal_static_edge_RuleChainMetadataUpdateMsg_descriptor; } @Override public RuleChainMetadataUpdateMsg getDefaultInstanceForType() { return RuleChainMetadataUpdateMsg.getDefaultInstance(); } @Override public RuleChainMetadataUpdateMsg build() { RuleChainMetadataUpdateMsg result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @Override public RuleChainMetadataUpdateMsg buildPartial() { RuleChainMetadataUpdateMsg result = new RuleChainMetadataUpdateMsg(this); int from_bitField0_ = bitField0_; result.msgType_ = msgType_; result.ruleChainIdMSB_ = ruleChainIdMSB_; result.ruleChainIdLSB_ = ruleChainIdLSB_; result.firstNodeIndex_ = firstNodeIndex_; if (nodesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { nodes_ = java.util.Collections.unmodifiableList(nodes_); bitField0_ = (bitField0_ & ~0x00000001); } result.nodes_ = nodes_; } else { result.nodes_ = nodesBuilder_.build(); } if (connectionsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { connections_ = java.util.Collections.unmodifiableList(connections_); bitField0_ = (bitField0_ & ~0x00000002); } result.connections_ = connections_; } else { result.connections_ = connectionsBuilder_.build(); } if (ruleChainConnectionsBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0)) { ruleChainConnections_ = java.util.Collections.unmodifiableList(ruleChainConnections_); bitField0_ = (bitField0_ & ~0x00000004); } result.ruleChainConnections_ = ruleChainConnections_; } else { result.ruleChainConnections_ = ruleChainConnectionsBuilder_.build(); } onBuilt(); return result; } @Override public Builder clone() { return super.clone(); } @Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return super.setField(field, value); } @Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return super.setRepeatedField(field, index, value); } @Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return super.addRepeatedField(field, value); } @Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof RuleChainMetadataUpdateMsg) { return mergeFrom((RuleChainMetadataUpdateMsg)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(RuleChainMetadataUpdateMsg other) { if (other == RuleChainMetadataUpdateMsg.getDefaultInstance()) return this; if (other.msgType_ != 0) { setMsgTypeValue(other.getMsgTypeValue()); } if (other.getRuleChainIdMSB() != 0L) { setRuleChainIdMSB(other.getRuleChainIdMSB()); } if (other.getRuleChainIdLSB() != 0L) { setRuleChainIdLSB(other.getRuleChainIdLSB()); } if (other.getFirstNodeIndex() != 0) { setFirstNodeIndex(other.getFirstNodeIndex()); } if (nodesBuilder_ == null) { if (!other.nodes_.isEmpty()) { if (nodes_.isEmpty()) { nodes_ = other.nodes_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureNodesIsMutable(); nodes_.addAll(other.nodes_); } onChanged(); } } else { if (!other.nodes_.isEmpty()) { if (nodesBuilder_.isEmpty()) { nodesBuilder_.dispose(); nodesBuilder_ = null; nodes_ = other.nodes_; bitField0_ = (bitField0_ & ~0x00000001); nodesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getNodesFieldBuilder() : null; } else { nodesBuilder_.addAllMessages(other.nodes_); } } } if (connectionsBuilder_ == null) { if (!other.connections_.isEmpty()) { if (connections_.isEmpty()) { connections_ = other.connections_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureConnectionsIsMutable(); connections_.addAll(other.connections_); } onChanged(); } } else { if (!other.connections_.isEmpty()) { if (connectionsBuilder_.isEmpty()) { connectionsBuilder_.dispose(); connectionsBuilder_ = null; connections_ = other.connections_; bitField0_ = (bitField0_ & ~0x00000002); connectionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getConnectionsFieldBuilder() : null; } else { connectionsBuilder_.addAllMessages(other.connections_); } } } if (ruleChainConnectionsBuilder_ == null) { if (!other.ruleChainConnections_.isEmpty()) { if (ruleChainConnections_.isEmpty()) { ruleChainConnections_ = other.ruleChainConnections_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureRuleChainConnectionsIsMutable(); ruleChainConnections_.addAll(other.ruleChainConnections_); } onChanged(); } } else { if (!other.ruleChainConnections_.isEmpty()) { if (ruleChainConnectionsBuilder_.isEmpty()) { ruleChainConnectionsBuilder_.dispose(); ruleChainConnectionsBuilder_ = null; ruleChainConnections_ = other.ruleChainConnections_; bitField0_ = (bitField0_ & ~0x00000004); ruleChainConnectionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getRuleChainConnectionsFieldBuilder() : null; } else { ruleChainConnectionsBuilder_.addAllMessages(other.ruleChainConnections_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @Override public final boolean isInitialized() { return true; } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { RuleChainMetadataUpdateMsg parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (RuleChainMetadataUpdateMsg) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private int msgType_ = 0; /** * <code>.edge.UpdateMsgType msgType = 1;</code> * @return The enum numeric value on the wire for msgType. */ @Override public int getMsgTypeValue() { return msgType_; } /** * <code>.edge.UpdateMsgType msgType = 1;</code> * @param value The enum numeric value on the wire for msgType to set. * @return This builder for chaining. */ public Builder setMsgTypeValue(int value) { msgType_ = value; onChanged(); return this; } /** * <code>.edge.UpdateMsgType msgType = 1;</code> * @return The msgType. */ @Override public UpdateMsgType getMsgType() { @SuppressWarnings("deprecation") UpdateMsgType result = UpdateMsgType.valueOf(msgType_); return result == null ? UpdateMsgType.UNRECOGNIZED : result; } /** * <code>.edge.UpdateMsgType msgType = 1;</code> * @param value The msgType to set. * @return This builder for chaining. */ public Builder setMsgType(UpdateMsgType value) { if (value == null) { throw new NullPointerException(); } msgType_ = value.getNumber(); onChanged(); return this; } /** * <code>.edge.UpdateMsgType msgType = 1;</code> * @return This builder for chaining. */ public Builder clearMsgType() { msgType_ = 0; onChanged(); return this; } private long ruleChainIdMSB_ ; /** * <code>int64 ruleChainIdMSB = 2;</code> * @return The ruleChainIdMSB. */ @Override public long getRuleChainIdMSB() { return ruleChainIdMSB_; } /** * <code>int64 ruleChainIdMSB = 2;</code> * @param value The ruleChainIdMSB to set. * @return This builder for chaining. */ public Builder setRuleChainIdMSB(long value) { ruleChainIdMSB_ = value; onChanged(); return this; } /** * <code>int64 ruleChainIdMSB = 2;</code> * @return This builder for chaining. */ public Builder clearRuleChainIdMSB() { ruleChainIdMSB_ = 0L; onChanged(); return this; } private long ruleChainIdLSB_ ; /** * <code>int64 ruleChainIdLSB = 3;</code> * @return The ruleChainIdLSB. */ @Override public long getRuleChainIdLSB() { return ruleChainIdLSB_; } /** * <code>int64 ruleChainIdLSB = 3;</code> * @param value The ruleChainIdLSB to set. * @return This builder for chaining. */ public Builder setRuleChainIdLSB(long value) { ruleChainIdLSB_ = value; onChanged(); return this; } /** * <code>int64 ruleChainIdLSB = 3;</code> * @return This builder for chaining. */ public Builder clearRuleChainIdLSB() { ruleChainIdLSB_ = 0L; onChanged(); return this; } private int firstNodeIndex_ ; /** * <code>int32 firstNodeIndex = 4;</code> * @return The firstNodeIndex. */ @Override public int getFirstNodeIndex() { return firstNodeIndex_; } /** * <code>int32 firstNodeIndex = 4;</code> * @param value The firstNodeIndex to set. * @return This builder for chaining. */ public Builder setFirstNodeIndex(int value) { firstNodeIndex_ = value; onChanged(); return this; } /** * <code>int32 firstNodeIndex = 4;</code> * @return This builder for chaining. */ public Builder clearFirstNodeIndex() { firstNodeIndex_ = 0; onChanged(); return this; } private java.util.List<RuleNodeProto> nodes_ = java.util.Collections.emptyList(); private void ensureNodesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { nodes_ = new java.util.ArrayList<RuleNodeProto>(nodes_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< RuleNodeProto, RuleNodeProto.Builder, RuleNodeProtoOrBuilder> nodesBuilder_; /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public java.util.List<RuleNodeProto> getNodesList() { if (nodesBuilder_ == null) { return java.util.Collections.unmodifiableList(nodes_); } else { return nodesBuilder_.getMessageList(); } } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public int getNodesCount() { if (nodesBuilder_ == null) { return nodes_.size(); } else { return nodesBuilder_.getCount(); } } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public RuleNodeProto getNodes(int index) { if (nodesBuilder_ == null) { return nodes_.get(index); } else { return nodesBuilder_.getMessage(index); } } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public Builder setNodes( int index, RuleNodeProto value) { if (nodesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNodesIsMutable(); nodes_.set(index, value); onChanged(); } else { nodesBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public Builder setNodes( int index, RuleNodeProto.Builder builderForValue) { if (nodesBuilder_ == null) { ensureNodesIsMutable(); nodes_.set(index, builderForValue.build()); onChanged(); } else { nodesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public Builder addNodes(RuleNodeProto value) { if (nodesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNodesIsMutable(); nodes_.add(value); onChanged(); } else { nodesBuilder_.addMessage(value); } return this; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public Builder addNodes( int index, RuleNodeProto value) { if (nodesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureNodesIsMutable(); nodes_.add(index, value); onChanged(); } else { nodesBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public Builder addNodes( RuleNodeProto.Builder builderForValue) { if (nodesBuilder_ == null) { ensureNodesIsMutable(); nodes_.add(builderForValue.build()); onChanged(); } else { nodesBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public Builder addNodes( int index, RuleNodeProto.Builder builderForValue) { if (nodesBuilder_ == null) { ensureNodesIsMutable(); nodes_.add(index, builderForValue.build()); onChanged(); } else { nodesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public Builder addAllNodes( Iterable<? extends RuleNodeProto> values) { if (nodesBuilder_ == null) { ensureNodesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, nodes_); onChanged(); } else { nodesBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public Builder clearNodes() { if (nodesBuilder_ == null) { nodes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { nodesBuilder_.clear(); } return this; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public Builder removeNodes(int index) { if (nodesBuilder_ == null) { ensureNodesIsMutable(); nodes_.remove(index); onChanged(); } else { nodesBuilder_.remove(index); } return this; } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public RuleNodeProto.Builder getNodesBuilder( int index) { return getNodesFieldBuilder().getBuilder(index); } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public RuleNodeProtoOrBuilder getNodesOrBuilder( int index) { if (nodesBuilder_ == null) { return nodes_.get(index); } else { return nodesBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public java.util.List<? extends RuleNodeProtoOrBuilder> getNodesOrBuilderList() { if (nodesBuilder_ != null) { return nodesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(nodes_); } } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public RuleNodeProto.Builder addNodesBuilder() { return getNodesFieldBuilder().addBuilder( RuleNodeProto.getDefaultInstance()); } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public RuleNodeProto.Builder addNodesBuilder( int index) { return getNodesFieldBuilder().addBuilder( index, RuleNodeProto.getDefaultInstance()); } /** * <code>repeated .edge.RuleNodeProto nodes = 5;</code> */ public java.util.List<RuleNodeProto.Builder> getNodesBuilderList() { return getNodesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< RuleNodeProto, RuleNodeProto.Builder, RuleNodeProtoOrBuilder> getNodesFieldBuilder() { if (nodesBuilder_ == null) { nodesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< RuleNodeProto, RuleNodeProto.Builder, RuleNodeProtoOrBuilder>( nodes_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); nodes_ = null; } return nodesBuilder_; } private java.util.List<NodeConnectionInfoProto> connections_ = java.util.Collections.emptyList(); private void ensureConnectionsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { connections_ = new java.util.ArrayList<NodeConnectionInfoProto>(connections_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< NodeConnectionInfoProto, NodeConnectionInfoProto.Builder, NodeConnectionInfoProtoOrBuilder> connectionsBuilder_; /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public java.util.List<NodeConnectionInfoProto> getConnectionsList() { if (connectionsBuilder_ == null) { return java.util.Collections.unmodifiableList(connections_); } else { return connectionsBuilder_.getMessageList(); } } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public int getConnectionsCount() { if (connectionsBuilder_ == null) { return connections_.size(); } else { return connectionsBuilder_.getCount(); } } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public NodeConnectionInfoProto getConnections(int index) { if (connectionsBuilder_ == null) { return connections_.get(index); } else { return connectionsBuilder_.getMessage(index); } } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public Builder setConnections( int index, NodeConnectionInfoProto value) { if (connectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureConnectionsIsMutable(); connections_.set(index, value); onChanged(); } else { connectionsBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public Builder setConnections( int index, NodeConnectionInfoProto.Builder builderForValue) { if (connectionsBuilder_ == null) { ensureConnectionsIsMutable(); connections_.set(index, builderForValue.build()); onChanged(); } else { connectionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public Builder addConnections(NodeConnectionInfoProto value) { if (connectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureConnectionsIsMutable(); connections_.add(value); onChanged(); } else { connectionsBuilder_.addMessage(value); } return this; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public Builder addConnections( int index, NodeConnectionInfoProto value) { if (connectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureConnectionsIsMutable(); connections_.add(index, value); onChanged(); } else { connectionsBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public Builder addConnections( NodeConnectionInfoProto.Builder builderForValue) { if (connectionsBuilder_ == null) { ensureConnectionsIsMutable(); connections_.add(builderForValue.build()); onChanged(); } else { connectionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public Builder addConnections( int index, NodeConnectionInfoProto.Builder builderForValue) { if (connectionsBuilder_ == null) { ensureConnectionsIsMutable(); connections_.add(index, builderForValue.build()); onChanged(); } else { connectionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public Builder addAllConnections( Iterable<? extends NodeConnectionInfoProto> values) { if (connectionsBuilder_ == null) { ensureConnectionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, connections_); onChanged(); } else { connectionsBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public Builder clearConnections() { if (connectionsBuilder_ == null) { connections_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { connectionsBuilder_.clear(); } return this; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public Builder removeConnections(int index) { if (connectionsBuilder_ == null) { ensureConnectionsIsMutable(); connections_.remove(index); onChanged(); } else { connectionsBuilder_.remove(index); } return this; } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public NodeConnectionInfoProto.Builder getConnectionsBuilder( int index) { return getConnectionsFieldBuilder().getBuilder(index); } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public NodeConnectionInfoProtoOrBuilder getConnectionsOrBuilder( int index) { if (connectionsBuilder_ == null) { return connections_.get(index); } else { return connectionsBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public java.util.List<? extends NodeConnectionInfoProtoOrBuilder> getConnectionsOrBuilderList() { if (connectionsBuilder_ != null) { return connectionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(connections_); } } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public NodeConnectionInfoProto.Builder addConnectionsBuilder() { return getConnectionsFieldBuilder().addBuilder( NodeConnectionInfoProto.getDefaultInstance()); } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public NodeConnectionInfoProto.Builder addConnectionsBuilder( int index) { return getConnectionsFieldBuilder().addBuilder( index, NodeConnectionInfoProto.getDefaultInstance()); } /** * <code>repeated .edge.NodeConnectionInfoProto connections = 6;</code> */ public java.util.List<NodeConnectionInfoProto.Builder> getConnectionsBuilderList() { return getConnectionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< NodeConnectionInfoProto, NodeConnectionInfoProto.Builder, NodeConnectionInfoProtoOrBuilder> getConnectionsFieldBuilder() { if (connectionsBuilder_ == null) { connectionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< NodeConnectionInfoProto, NodeConnectionInfoProto.Builder, NodeConnectionInfoProtoOrBuilder>( connections_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); connections_ = null; } return connectionsBuilder_; } private java.util.List<RuleChainConnectionInfoProto> ruleChainConnections_ = java.util.Collections.emptyList(); private void ensureRuleChainConnectionsIsMutable() { if (!((bitField0_ & 0x00000004) != 0)) { ruleChainConnections_ = new java.util.ArrayList<RuleChainConnectionInfoProto>(ruleChainConnections_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilderV3< RuleChainConnectionInfoProto, RuleChainConnectionInfoProto.Builder, RuleChainConnectionInfoProtoOrBuilder> ruleChainConnectionsBuilder_; /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public java.util.List<RuleChainConnectionInfoProto> getRuleChainConnectionsList() { if (ruleChainConnectionsBuilder_ == null) { return java.util.Collections.unmodifiableList(ruleChainConnections_); } else { return ruleChainConnectionsBuilder_.getMessageList(); } } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public int getRuleChainConnectionsCount() { if (ruleChainConnectionsBuilder_ == null) { return ruleChainConnections_.size(); } else { return ruleChainConnectionsBuilder_.getCount(); } } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public RuleChainConnectionInfoProto getRuleChainConnections(int index) { if (ruleChainConnectionsBuilder_ == null) { return ruleChainConnections_.get(index); } else { return ruleChainConnectionsBuilder_.getMessage(index); } } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public Builder setRuleChainConnections( int index, RuleChainConnectionInfoProto value) { if (ruleChainConnectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRuleChainConnectionsIsMutable(); ruleChainConnections_.set(index, value); onChanged(); } else { ruleChainConnectionsBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public Builder setRuleChainConnections( int index, RuleChainConnectionInfoProto.Builder builderForValue) { if (ruleChainConnectionsBuilder_ == null) { ensureRuleChainConnectionsIsMutable(); ruleChainConnections_.set(index, builderForValue.build()); onChanged(); } else { ruleChainConnectionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public Builder addRuleChainConnections(RuleChainConnectionInfoProto value) { if (ruleChainConnectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRuleChainConnectionsIsMutable(); ruleChainConnections_.add(value); onChanged(); } else { ruleChainConnectionsBuilder_.addMessage(value); } return this; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public Builder addRuleChainConnections( int index, RuleChainConnectionInfoProto value) { if (ruleChainConnectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRuleChainConnectionsIsMutable(); ruleChainConnections_.add(index, value); onChanged(); } else { ruleChainConnectionsBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public Builder addRuleChainConnections( RuleChainConnectionInfoProto.Builder builderForValue) { if (ruleChainConnectionsBuilder_ == null) { ensureRuleChainConnectionsIsMutable(); ruleChainConnections_.add(builderForValue.build()); onChanged(); } else { ruleChainConnectionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public Builder addRuleChainConnections( int index, RuleChainConnectionInfoProto.Builder builderForValue) { if (ruleChainConnectionsBuilder_ == null) { ensureRuleChainConnectionsIsMutable(); ruleChainConnections_.add(index, builderForValue.build()); onChanged(); } else { ruleChainConnectionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public Builder addAllRuleChainConnections( Iterable<? extends RuleChainConnectionInfoProto> values) { if (ruleChainConnectionsBuilder_ == null) { ensureRuleChainConnectionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, ruleChainConnections_); onChanged(); } else { ruleChainConnectionsBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public Builder clearRuleChainConnections() { if (ruleChainConnectionsBuilder_ == null) { ruleChainConnections_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { ruleChainConnectionsBuilder_.clear(); } return this; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public Builder removeRuleChainConnections(int index) { if (ruleChainConnectionsBuilder_ == null) { ensureRuleChainConnectionsIsMutable(); ruleChainConnections_.remove(index); onChanged(); } else { ruleChainConnectionsBuilder_.remove(index); } return this; } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public RuleChainConnectionInfoProto.Builder getRuleChainConnectionsBuilder( int index) { return getRuleChainConnectionsFieldBuilder().getBuilder(index); } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public RuleChainConnectionInfoProtoOrBuilder getRuleChainConnectionsOrBuilder( int index) { if (ruleChainConnectionsBuilder_ == null) { return ruleChainConnections_.get(index); } else { return ruleChainConnectionsBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public java.util.List<? extends RuleChainConnectionInfoProtoOrBuilder> getRuleChainConnectionsOrBuilderList() { if (ruleChainConnectionsBuilder_ != null) { return ruleChainConnectionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(ruleChainConnections_); } } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public RuleChainConnectionInfoProto.Builder addRuleChainConnectionsBuilder() { return getRuleChainConnectionsFieldBuilder().addBuilder( RuleChainConnectionInfoProto.getDefaultInstance()); } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public RuleChainConnectionInfoProto.Builder addRuleChainConnectionsBuilder( int index) { return getRuleChainConnectionsFieldBuilder().addBuilder( index, RuleChainConnectionInfoProto.getDefaultInstance()); } /** * <code>repeated .edge.RuleChainConnectionInfoProto ruleChainConnections = 7;</code> */ public java.util.List<RuleChainConnectionInfoProto.Builder> getRuleChainConnectionsBuilderList() { return getRuleChainConnectionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< RuleChainConnectionInfoProto, RuleChainConnectionInfoProto.Builder, RuleChainConnectionInfoProtoOrBuilder> getRuleChainConnectionsFieldBuilder() { if (ruleChainConnectionsBuilder_ == null) { ruleChainConnectionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< RuleChainConnectionInfoProto, RuleChainConnectionInfoProto.Builder, RuleChainConnectionInfoProtoOrBuilder>( ruleChainConnections_, ((bitField0_ & 0x00000004) != 0), getParentForChildren(), isClean()); ruleChainConnections_ = null; } return ruleChainConnectionsBuilder_; } @Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:edge.RuleChainMetadataUpdateMsg) } // @@protoc_insertion_point(class_scope:edge.RuleChainMetadataUpdateMsg) private static final RuleChainMetadataUpdateMsg DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new RuleChainMetadataUpdateMsg(); } public static RuleChainMetadataUpdateMsg getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RuleChainMetadataUpdateMsg> PARSER = new com.google.protobuf.AbstractParser<RuleChainMetadataUpdateMsg>() { @Override public RuleChainMetadataUpdateMsg parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RuleChainMetadataUpdateMsg(input, extensionRegistry); } }; public static com.google.protobuf.Parser<RuleChainMetadataUpdateMsg> parser() { return PARSER; } @Override public com.google.protobuf.Parser<RuleChainMetadataUpdateMsg> getParserForType() { return PARSER; } @Override public RuleChainMetadataUpdateMsg getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
#!/bin/bash FN="mogene21sttranscriptcluster.db_8.7.0.tar.gz" URLS=( "https://bioconductor.org/packages/3.13/data/annotation/src/contrib/mogene21sttranscriptcluster.db_8.7.0.tar.gz" "https://bioarchive.galaxyproject.org/mogene21sttranscriptcluster.db_8.7.0.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-mogene21sttranscriptcluster.db/bioconductor-mogene21sttranscriptcluster.db_8.7.0_src_all.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-mogene21sttranscriptcluster.db/bioconductor-mogene21sttranscriptcluster.db_8.7.0_src_all.tar.gz" ) MD5="0f131b607470652724d7b22ae2af1c7a" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
#! /bin/bash addInternals() { dotnet sln "$1" add "$SCHEMA_PKG" dotnet sln "$1" add "$CONTRACT_PKG" dotnet sln "$1" add "$DOMAIN_PKG" } addInfra() { dotnet sln "$1" add "$CLIENT_INFRA_PKG" } echo "branch=$CI_COMMIT_REF_NAME" dotnet nuget add source "$SDK_NUGETS_URL" -n "M5x SDK Nugets" -u "$LOGATRON_CID_USR" -p "$LOGATRON_CID_PWD" --store-password-in-clear-text dotnet nuget add source "$LOGATRON_NUGETS_URL" -n "Logatron Nugets" -u "$LOGATRON_CID_USR" -p "$LOGATRON_CID_PWD" --store-password-in-clear-text ## hosts solution dotnet new sln -n packages addInternals packages.sln addInfra packages.sln dotnet restore --disable-parallel if [ "$CI_COMMIT_REF_NAME" = "master" ]; then dotnet build -o ./PKG/ packages.sln for f in ./PKG/*.nupkg; do dotnet nuget push "$f" -k "$LOGATRON_NUGETS_API_KEY" -s "$LOGATRON_NUGETS_URL" done else dotnet build -o ./PKG/ --version-suffix "debug" packages.sln fi
#!/bin/bash # # # Downloads, builds and installs librdkafka into <install-dir> # if [[ $1 == "--require-ssl" ]]; then REQUIRE_SSL=1 shift fi VERSION=$1 INSTALLDIR=$2 BUILDDIR=$PWD/tmp-build set -ex set -o pipefail if [[ -z "$VERSION" ]]; then echo "Usage: $0 --require-ssl <librdkafka-version> [<install-dir>]" 1>&2 exit 1 fi if [[ $INSTALLDIR != /* ]]; then INSTALLDIR="$PWD/$INSTALLDIR" fi mkdir -p "$BUILDDIR/librdkafka" pushd "$BUILDDIR/librdkafka" test -f configure || curl -q -L "https://github.com/edenhill/librdkafka/archive/${VERSION}.tar.gz" | \ tar -xz --strip-components=1 -f - ./configure --clean make clean if [[ $OSTYPE == "linux"* ]]; then EXTRA_OPTS="--disable-gssapi" fi ./configure --enable-static --install-deps --source-deps-only $EXTRA_OPTS --prefix="$INSTALLDIR" if [[ $REQUIRE_SSL == 1 ]]; then grep '^#define WITH_SSL 1$' config.h || \ (echo "ERROR: OpenSSL support required" ; cat config.log config.h ; exit 1) fi make -j examples/rdkafka_example -X builtin.features if [[ $INSTALLDIR == /usr && $(whoami) != root ]]; then sudo make install else make install fi popd
package model type Passport struct { Model Token string UserId uint Ip string Ua string Client uint } func (t *Passport) IsLogin() bool { return t.UserId != 0 } type PassportCreateResult struct { Passport string `json:"passport"` Uid uint `json:"uid"` Access []PermissionAccess `json:"access"` }
<reponame>goistjt/CSSE490-Hadoop<gh_stars>0 package edu.rosehulman.goistjt; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; /** * Created by <NAME> on 12/5/2016. */ public class FriendListReducer extends Reducer<Text, Text, Text, Text> { @Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { Set<String> occurred = new HashSet<>(); SortedSet<String> dups = new TreeSet<>(); for (Text t : values) { String[] friends = t.toString().split(","); for (String friend : friends) { if (occurred.contains(friend)) { dups.add(friend); } else { occurred.add(friend); } } } List<String> inCommon = dups.stream().collect(Collectors.toList()); StringBuilder builder = new StringBuilder(); for (String s : inCommon) { builder.append(s); builder.append(","); } String toReturn = builder.toString(); if (toReturn.length() > 0) { toReturn = toReturn.substring(0, toReturn.length() - 1); } context.write(key, new Text(toReturn)); } }
def process_data(data_source, description='', copy_data=False): if copy_data: return data_source[:] # Create a copy of the data using slicing elif description: # Perform processing based on the provided description # For demonstration purposes, simply adding a prefix to the data processed_data = f"{description}: {data_source}" return processed_data else: return data_source # Return the original data without any processing
<filename>node_modules/react-icons-kit/fa/tv.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.tv = void 0; var tv = { "viewBox": "0 0 2048 1792", "children": [{ "name": "path", "attribs": { "d": "M1792 1248v-960q0-13-9.5-22.5t-22.5-9.5h-1600q-13 0-22.5 9.5t-9.5 22.5v960q0 13 9.5 22.5t22.5 9.5h1600q13 0 22.5-9.5t9.5-22.5zM1920 288v960q0 66-47 113t-113 47h-736v128h352q14 0 23 9t9 23v64q0 14-9 23t-23 9h-832q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h352v-128h-736q-66 0-113-47t-47-113v-960q0-66 47-113t113-47h1600q66 0 113 47t47 113z" } }] }; exports.tv = tv;
<reponame>grpc-web-all-about-communication/services<filename>leaderboard/src/test/java/xyz/breakit/game/leaderboard/service/LeaderboardServiceTest.java package xyz.breakit.game.leaderboard.service; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; public class LeaderboardServiceTest { private LeaderboardService leaderboardService = new LeaderboardService(0); @Test(timeout = 1000L) public void testLeaderboardUpdatesFlux() { Flux<Boolean> leaderboardUpdatesFlux = leaderboardService.getLeaderboardUpdatesFlux(); leaderboardService.recordScore("a", 300); leaderboardService.recordScore("b", 200); leaderboardService.recordScore("c", 400); StepVerifier.create(leaderboardUpdatesFlux) .expectNext(true) .expectNext(true) .expectNext(true) .thenCancel() .verify(); } }
function isNumberPresent(str) { let regex = /\d/; return regex.test(str); } let str = "Hello World"; if (isNumberPresent(str)) { console.log("The string contains a number.") } else { console.log("The string does not contain a number.") }
<filename>src/vuejsclient/ts/components/dashboard_builder/widgets/table_widget/pagination/TablePaginationComponent.ts import Component from 'vue-class-component'; import { Prop, Watch } from 'vue-property-decorator'; import ThrottleHelper from '../../../../../../../shared/tools/ThrottleHelper'; import VueComponentBase from '../../../../VueComponentBase'; import './TablePaginationComponent.scss'; import 'vue-slider-component/theme/default.css'; @Component({ template: require('./TablePaginationComponent.pug'), components: { } }) export default class TablePaginationComponent extends VueComponentBase { @Prop() private pagination_count: number; @Prop() private pagination_offset: number; @Prop() private pagination_pagesize: number; @Prop({ default: false }) private compressed: boolean; private throttled_update_slider = ThrottleHelper.getInstance().declare_throttle_without_args(this.update_slider.bind(this), 50, { leading: false, trailing: true }); private throttled_change_offset = ThrottleHelper.getInstance().declare_throttle_without_args(this.change_offset.bind(this), 400, { leading: false, trailing: true }); private page: number = 0; private max_page: number = 0; private new_page: number = 0; private new_page_str: string = "0"; get pagination_offset_end_page() { let res = this.pagination_offset + this.pagination_pagesize; if (res >= this.pagination_count) { return this.pagination_count; } return res; } @Watch('new_page_str') private onchange_new_page_str() { let new_page_num: number = null; try { new_page_num = parseInt(this.new_page_str); if ((!new_page_num) || isNaN(new_page_num)) { new_page_num = 1; } if (new_page_num > this.max_page) { new_page_num = this.max_page; this.new_page_str = new_page_num.toString(); } if (new_page_num < 1) { new_page_num = 1; this.new_page_str = new_page_num.toString(); } } catch (error) { this.new_page_str = this.new_page.toString(); return; } if (this.new_page != new_page_num) { console.log('onchange_new_page_str>new_page=' + new_page_num); this.new_page = new_page_num; } } @Watch('new_page') private onchange_new_page() { if (!this.new_page) { return; } if (this.new_page_str != this.new_page.toString()) { console.log('onchange_new_page>new_page_str=' + this.new_page); this.new_page_str = this.new_page.toString(); } } @Watch("pagination_count", { immediate: true }) @Watch("pagination_offset", { immediate: true }) @Watch("pagination_pagesize", { immediate: true }) private throttle_update_slider() { this.throttled_update_slider(); } private update_slider() { this.page = Math.floor(this.pagination_offset / this.pagination_pagesize) + 1; this.new_page = this.page; this.max_page = Math.floor((this.pagination_count ? (this.pagination_count - 1) : 0) / this.pagination_pagesize) + 1; if (this.new_page > this.max_page) { this.new_page = this.max_page; this.page = this.new_page; } this.throttled_change_offset(); } private goto_next() { this.new_page++; this.throttled_change_offset(); } private goto_previous() { if (this.new_page <= 1) { return; } this.new_page--; this.throttled_change_offset(); } private change_page_str() { this.onchange_new_page_str(); this.throttled_change_offset(); } private change_offset() { let offset = (this.new_page - 1) * this.pagination_pagesize; offset = (offset >= this.pagination_count) ? Math.floor((this.pagination_count > 0 ? (this.pagination_count - 1) : 0) / this.pagination_pagesize) * this.pagination_pagesize : offset; this.$emit("change_offset", offset); } }
#ifndef SPX_PARAMS_H #define SPX_PARAMS_H /* Hash output length in bytes. */ #define SPX_N 16 /* Height of the hypertree. */ #define SPX_FULL_HEIGHT 63 /* Number of subtree layer. */ #define SPX_D 7 /* FORS tree dimensions. */ #define SPX_FORS_HEIGHT 12 #define SPX_FORS_TREES 14 /* Winternitz parameter, */ #define SPX_WOTS_W 16 /* The hash function is defined by linking a different hash.c file, as opposed to setting a #define constant. */ /* For clarity */ #define SPX_ADDR_BYTES 32 /* WOTS parameters. */ #if SPX_WOTS_W == 256 #define SPX_WOTS_LOGW 8 #elif SPX_WOTS_W == 16 #define SPX_WOTS_LOGW 4 #else #error SPX_WOTS_W assumed 16 or 256 #endif #define SPX_WOTS_LEN1 (8 * SPX_N / SPX_WOTS_LOGW) /* SPX_WOTS_LEN2 is floor(log(len_1 * (w - 1)) / log(w)) + 1; we precompute */ #if SPX_WOTS_W == 256 #if SPX_N <= 1 #define SPX_WOTS_LEN2 1 #elif SPX_N <= 256 #define SPX_WOTS_LEN2 2 #else #error Did not precompute SPX_WOTS_LEN2 for n outside {2, .., 256} #endif #elif SPX_WOTS_W == 16 #if SPX_N <= 8 #define SPX_WOTS_LEN2 2 #elif SPX_N <= 136 #define SPX_WOTS_LEN2 3 #elif SPX_N <= 256 #define SPX_WOTS_LEN2 4 #else #error Did not precompute SPX_WOTS_LEN2 for n outside {2, .., 256} #endif #endif #define SPX_WOTS_LEN (SPX_WOTS_LEN1 + SPX_WOTS_LEN2) #define SPX_WOTS_BYTES (SPX_WOTS_LEN * SPX_N) #define SPX_WOTS_PK_BYTES SPX_WOTS_BYTES /* Subtree size. */ #define SPX_TREE_HEIGHT (SPX_FULL_HEIGHT / SPX_D) #if SPX_TREE_HEIGHT * SPX_D != SPX_FULL_HEIGHT #error SPX_D should always divide SPX_FULL_HEIGHT #endif /* FORS parameters. */ #define SPX_FORS_MSG_BYTES ((SPX_FORS_HEIGHT * SPX_FORS_TREES + 7) / 8) #define SPX_FORS_BYTES ((SPX_FORS_HEIGHT + 1) * SPX_FORS_TREES * SPX_N) #define SPX_FORS_PK_BYTES SPX_N /* Resulting SPX sizes. */ #define SPX_BYTES (SPX_N + SPX_FORS_BYTES + SPX_D * SPX_WOTS_BYTES +\ SPX_FULL_HEIGHT * SPX_N) #define SPX_PK_BYTES (2 * SPX_N) #define SPX_SK_BYTES (2 * SPX_N + SPX_PK_BYTES) /* Optionally, signing can be made non-deterministic using optrand. This can help counter side-channel attacks that would benefit from getting a large number of traces when the signer uses the same nodes. */ #define SPX_OPTRAND_BYTES 32 #include "../sha256_offsets.h" #endif
import os from datetime import datetime import tensorflow as tf from src.data_loader import get_training_datasets from src.cycle_gan import CycleGan import src.utils.argument_parser as argument_parser from src.utils.utils import get_logger, makedirs logger = get_logger("main") def is_video_data(train_A): return len(train_A.output_shapes) is 5 and (train_A.output_shapes[1] > 1) def train(model, train_A, train_B, logdir, learning_rate): next_a = train_A.make_one_shot_iterator().get_next() next_b = train_B.make_one_shot_iterator().get_next() variables_to_save = tf.global_variables() init_op = tf.variables_initializer(variables_to_save) init_all_op = tf.global_variables_initializer() var_list_fnet = tf.get_collection(tf.GraphKeys.MODEL_VARIABLES, scope='fnet') fnet_loader = tf.train.Saver(var_list_fnet) summary_writer = tf.summary.FileWriter(logdir) def initialize_session(sess): logger.info('Initializing all parameters.') sess.run(init_all_op) fnet_loader.restore(sess, './fnet/fnet-0') config = tf.ConfigProto() config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: sess.run(init_op) initialize_session(sess) summary_writer.add_graph(sess.graph) model.savers.load_all(sess) logger.info(f"Starting {'video' if model.train_videos else 'image'} training.") if model.train_videos: model.train_on_videos(sess, summary_writer, next_a, next_b, learning_rate) else: model.train_on_images(sess, summary_writer, next_a, next_b, learning_rate) def main(): training_config = argument_parser.get_training_config() logger.info('Building datasets...') if not training_config.force_image_training: train_A, train_B = get_training_datasets(training_config.task_name, training_config.data_size, training_config.batch_size, dataset_dir=training_config.dataset_directory, frame_sequence_length=training_config.frame_sequence_length, force_video=training_config.force_video_data) else: train_A, train_B = get_training_datasets(training_config.task_name, training_config.data_size, training_config.batch_size, dataset_dir=training_config.dataset_directory, frame_sequence_length=1, force_video=training_config.force_video_data) train_videos = is_video_data(train_A) for i in range(training_config.training_runs): if training_config.model_directory == '' or training_config.training_runs > 1: date = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") training_config.model_directory = f"{training_config.task_name}_{date}_{i}-{training_config.training_runs}" if not training_config.run_name is None: training_config.model_directory = training_config.run_name + "_" + training_config.model_directory log_dir = training_config.logging_directory makedirs(log_dir) training_config.initialization_model = os.path.join(log_dir, training_config.initialization_model) training_config.model_directory = os.path.join(log_dir, training_config.model_directory) logger.info(f"Checkpoints and Logs will be saved to {training_config.model_directory}") logger.info('Building cyclegan:') model = CycleGan(training_config=training_config, train_videos=train_videos, train_images=not train_videos) train(model, train_A, train_B, training_config.model_directory, training_config.learning_rate) tf.reset_default_graph() if __name__ == "__main__": main()
<filename>spec/url_helper_spec.rb require_relative 'spec_helper' require 'mocha' require_relative '../lib/doc_juan/url_helper' describe 'DocJuan#url' do before :each do DocJuan.config.host = 'doc-juan.example.com' DocJuan.config.secret = 'zecret' end it 'passes its arguments to a UrlGenerator instance and uses it to generate the url' do generator = stub generator.expects(:generate).returns 'generated-url' DocJuan::UrlGenerator.expects(:new). with('http://example.com', 'the_file', 'pdf', size: 'A4'). returns(generator) url = DocJuan.url 'http://example.com', 'the_file', size: 'A4' url.must_equal 'generated-url' end it 'passes format if set to UrlGenerator instance' do generator = stub generator.expects(:generate) DocJuan::UrlGenerator.expects(:new). with('http://example.com', 'the_file', 'jpg', {}). returns(generator) DocJuan.url 'http://example.com', 'the_file', format: 'jpg' end end
#!/bin/bash # Copyright (c) Microsoft Corporation # All rights reserved. # # MIT License # # 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. pushd $(dirname "$0") > /dev/null cp -arf "../../../version" "../version" popd > /dev/null
package fr.clementgre.pdf4teachers.panel.sidebar.texts; import fr.clementgre.pdf4teachers.datasaving.Config; import fr.clementgre.pdf4teachers.utils.fonts.FontUtils; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import java.io.DataInputStream; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; public class TextListItem{ private Font font; private String text; private Color color; private long uses; private long creationDate; public TextListItem(Font font, String text, Color color, long uses, long creationDate){ this.font = font; this.text = text; this.color = color; this.uses = uses; this.creationDate = creationDate; } public TextTreeItem toTextTreeItem(int type){ return new TextTreeItem(font, text, color, type, uses, creationDate); } public LinkedHashMap<Object, Object> getYAMLData(){ LinkedHashMap<Object, Object> data = new LinkedHashMap<>(); data.put("color", color.toString()); data.put("font", font.getFamily()); data.put("size", font.getSize()); data.put("bold", FontUtils.getFontWeight(font) == FontWeight.BOLD); data.put("italic", FontUtils.getFontPosture(font) == FontPosture.ITALIC); data.put("uses", uses); data.put("date", creationDate); data.put("text", text); return data; } public static TextListItem readDataAndGive(DataInputStream reader) throws IOException{ double fontSize = reader.readFloat(); boolean isBold = reader.readBoolean(); boolean isItalic = reader.readBoolean(); String fontName = reader.readUTF(); short colorRed = (short) (reader.readByte() + 128); short colorGreen = (short) (reader.readByte() + 128); short colorBlue = (short) (reader.readByte() + 128); long uses = reader.readLong(); long creationDate = reader.readLong(); String text = reader.readUTF(); Font font = FontUtils.getFont(fontName, isItalic, isBold, (int) fontSize); return new TextListItem(font, text, Color.rgb(colorRed, colorGreen, colorBlue), uses, creationDate); } public static TextListItem readYAMLDataAndGive(HashMap<String, Object> data){ double fontSize = Config.getDouble(data, "size"); boolean isBold = Config.getBoolean(data, "bold"); boolean isItalic = Config.getBoolean(data, "italic"); String fontName = Config.getString(data, "font"); Color color = Color.valueOf(Config.getString(data, "color")); long uses = Config.getLong(data, "uses"); long creationDate = Config.getLong(data, "date"); String text = Config.getString(data, "text"); Font font = FontUtils.getFont(fontName, isItalic, isBold, (int) fontSize); return new TextListItem(font, text, color, uses, creationDate); } public Font getFont(){ return font; } public void setFont(Font font){ this.font = font; } public String getText(){ return text; } public void setText(String text){ this.text = text; } public Color getColor(){ return color; } public void setColor(Color color){ this.color = color; } public long getUses(){ return uses; } public void setUses(long uses){ this.uses = uses; } public long getCreationDate(){ return creationDate; } public void setCreationDate(long creationDate){ this.creationDate = creationDate; } }
// Returns the square root of a number function calculate_square_root($num) { return sqrt($num); }
package com.example.loadcameramap; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.io.File; /** * bitmap 和 ImageView 相互转化: * Bitmap bmMeIcon = ((BitmapDrawable) ivMeIcon.getDrawable()).getBitmap(); * ivMeIcon.setImageBitmap(bitmap); */ public class MainActivity extends Activity implements View.OnClickListener { private ImageView ivTitleBack; private TextView tvTitle; private ImageView ivTitleSetting; private ImageView ivMeIcon; private RelativeLayout rlMeIcon; private TextView tvMeName; private RelativeLayout rlMe; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViews(); initTitle(); } public void findViews() { ivTitleBack = findViewById(R.id.iv_title_back); tvTitle = findViewById(R.id.tv_title); ivTitleSetting = findViewById(R.id.iv_title_setting); ivMeIcon = findViewById(R.id.iv_me_icon); rlMeIcon = findViewById(R.id.rl_me_icon); tvMeName = findViewById(R.id.tv_me_name); rlMe = findViewById(R.id.rl_me); ivTitleSetting.setOnClickListener(this); ivMeIcon.setOnClickListener(this); tvMeName.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = null; switch (v.getId()) { case R.id.iv_title_setting: case R.id.iv_me_icon: case R.id.tv_me_name: //启动用户信息界面的Activity intent = new Intent(MainActivity.this, UserInfoActivity.class); startActivity(intent); break; default: break; } } @Override public void onResume() { super.onResume(); //读取本地保存的图片;注意这里的生命周期 readImage(); } private boolean readImage() { File filesDir; //判断sd卡是否挂载 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //路径1:storage/sdcard/Android/data/包名/files filesDir = getExternalFilesDir(""); } else {//手机内部存储 //路径:data/data/包名/files filesDir = getFilesDir(); } File file = new File(filesDir, "icon.png"); if (file.exists()) { //存储--->内存 Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); ivMeIcon.setImageBitmap(bitmap); return true; } return false; } protected void initTitle() { ivTitleBack.setVisibility(View.INVISIBLE); tvTitle.setText("设置头像"); ivTitleSetting.setVisibility(View.VISIBLE); } public int dp2px(int dp) { //获取手机密度 float density = getResources().getDisplayMetrics().density; //实现四舍五入 return (int) (dp * density + 0.5); } }
import { shallowEqual } from "react-redux"; import safeObjectKeys from "../util/safeObjectKeys"; import { useSelector } from "../store"; import { Notes, PatternId } from "../store/types"; const areNotesEqual = (a: Notes | undefined, b: Notes | undefined): boolean => { const aNoteIds = a && safeObjectKeys(a); const bNoteIds = b && safeObjectKeys(b); const flattenNotes = (notes: Notes): string[] => safeObjectKeys(notes).reduce<string[]>( (acc, noteId) => [ ...acc, ...safeObjectKeys(notes[noteId]!.beats).map( (beatId) => `${noteId}-${beatId}-${ notes[noteId]!.beats[beatId]!.isActive }`, ), ], [], ); return ( shallowEqual(aNoteIds, bNoteIds) && shallowEqual( a && aNoteIds && flattenNotes(a), b && bNoteIds && flattenNotes(b), ) ); }; export default function usePatternNotes( patternId: PatternId | undefined, ): Notes | undefined { return useSelector((state) => { if (patternId === undefined) { return undefined; } const pattern = state.track.patterns[patternId]; return pattern?.notes; }, areNotesEqual); }
<filename>app/src/main/java/org/spongycastle/tls/crypto/impl/bc/BcTlsSigner.java package org.spongycastle.tls.crypto.impl.bc; import org.spongycastle.crypto.params.AsymmetricKeyParameter; import org.spongycastle.tls.SignatureAndHashAlgorithm; import org.spongycastle.tls.crypto.TlsSigner; import org.spongycastle.tls.crypto.TlsStreamSigner; public abstract class BcTlsSigner implements TlsSigner { protected final BcTlsCrypto crypto; protected final AsymmetricKeyParameter privateKey; protected BcTlsSigner(BcTlsCrypto crypto, AsymmetricKeyParameter privateKey) { if (crypto == null) { throw new NullPointerException("'crypto' cannot be null"); } if (privateKey == null) { throw new NullPointerException("'privateKey' cannot be null"); } if (!privateKey.isPrivate()) { throw new IllegalArgumentException("'privateKey' must be private"); } this.crypto = crypto; this.privateKey = privateKey; } public TlsStreamSigner getStreamSigner(SignatureAndHashAlgorithm algorithm) { return null; } }
package org.hisp.dhis.system.util; /* * Copyright (c) 2004-2012, University of Oslo * 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 HISP project 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 OWNER 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. */ import java.math.BigDecimal; import java.math.MathContext; import java.util.List; import java.util.Random; import java.util.regex.Pattern; import org.hisp.dhis.expression.Operator; import org.nfunk.jep.JEP; /** * @author <NAME> * @version $Id: MathUtil.java 4712 2008-03-12 10:32:45Z larshelg $ */ public class MathUtils { public static final double INVALID = -1.0; public static final Double ZERO = new Double( 0 ); private static final double TOLERANCE = 0.01; private static final Pattern NUMERIC_PATTERN = Pattern.compile( "^[ \\t]*[\\.]?[0-9]+[ \\t]*$|^[ \\t]*[0-9]+[\\.][0-9]+[ \\t]*$" ); /** * Validates whether an expression is true or false. * * @param leftSide The left side of the expression. * @param operator The expression operator. * @param rightSide The right side of the expression. * @return True if the expressio is true, fals otherwise. */ public static boolean expressionIsTrue( double leftSide, Operator operator, double rightSide ) { final String expression = leftSide + operator.getMathematicalOperator() + rightSide; final JEP parser = new JEP(); parser.parseExpression( expression ); return ( parser.getValue() == 1.0 ); } /** * Calculates a regular mathematical expression. * * @param expression The expression to calculate. * @return The result of the operation. */ public static double calculateExpression( String expression ) { final JEP parser = new JEP(); parser.parseExpression( expression ); double result = parser.getValue(); return ( result == Double.NEGATIVE_INFINITY || result == Double.POSITIVE_INFINITY ) ? INVALID : result; } /** * Investigates whether the expression is valid or has errors. * * @param expression The expression to validate. * @return True if the expression has errors, false otherwise. */ public static boolean expressionHasErrors( String expression ) { final JEP parser = new JEP(); parser.parseExpression( expression ); return parser.hasError(); } /** * Returns the error information for an invalid expression. * * @param expression The expression to validate. * @return The error information for an invalid expression, null if * the expression is valid. */ public static String getExpressionErrorInfo( String expression ) { final JEP parser = new JEP(); parser.parseExpression( expression ); return parser.getErrorInfo(); } /** * Rounds off downwards to the next distinct value. * * @param value The value to round off * @return The rounded value */ public static double getFloor( double value ) { return Math.floor( value ); } /** * Returns a number rounded off to the given number of decimals. * * @param value the value to round off. * @param decimals the number of decimals. * @return a number rounded off to the given number of decimals. */ public static double getRounded( double value, int decimals ) { final double factor = Math.pow( 10, decimals ); return Math.round( value * factor ) / factor; } /** * Returns a string representation of number rounded to given number * of significant figures * * @param value * @param significantFigures * @return */ public static String roundToString(double value, int significantFigures) { MathContext mc = new MathContext(significantFigures); BigDecimal num = new BigDecimal(value); return num.round( mc ).toPlainString(); } /** * Returns the given number if larger or equal to minimun, otherwise minimum. * * @param number the number. * @param min the minimum. * @return the given number if larger or equal to minimun, otherwise minimum. */ public static int getMin( int number, int min ) { return number < min ? min : number; } /** * Returns the given number if smaller or equal to maximum, otherwise maximum. * * @param number the number. * @param max the maximum. * @return the the given number if smaller or equal to maximum, otherwise maximum. */ public static int getMax( int number, int max ) { return number > max ? max : number; } /** * Returns true if the provided String argument can be converted to a Double, * false if not. * * @param value the value. * @return true if the provided String argument can be converted to a Double. */ public static boolean isNumeric( String value ) { return value != null && NUMERIC_PATTERN.matcher( value ).matches(); } /** * Tests whether the two decimal numbers are equal with a tolerance of 0.01. * If one or both of the numbers are null, false is returned. * * @param d1 the first value. * @param d2 the second value. * @return true if the two decimal numbers are equal with a tolerance of 0.01. */ public static boolean isEqual( Double d1, Double d2 ) { if ( d1 == null || d2 == null ) { return false; } return Math.abs( d1 - d2 ) < TOLERANCE; } /** * Tests whether the two decimal numbers are equal with a tolerance of 0.01. * * @param d1 the first value. * @param d2 the second value. * @return true if the two decimal numbers are equal with a tolerance of 0.01. */ public static boolean isEqual( double d1, double d2 ) { return Math.abs( d1 - d2 ) < TOLERANCE; } /** * Returns a random int between 0 and 999. */ public static int getRandom() { return new Random().nextInt( 999 ); } /** * Returns the minimum value from the given array. * * @param array the array of numbers. * @return the minimum value. */ public static Double getMin( double[] array ) { if ( array == null || array.length == 0 ) { return null; } double min = array[ 0 ]; for ( int i = 1; i < array.length; i++ ) { if ( array[ i ] < min ) { min = array[ i ]; } } return min; } /** * Returns the maximum value from the given array. * * @param array the array of numbers. * @return the maximum value. */ public static Double getMax( double[] array ) { if ( array == null || array.length == 0 ) { return null; } double max = array[ 0 ]; for ( int i = 1; i < array.length; i++ ) { if ( array[ i ] > max ) { max = array[ i ]; } } return max; } /** * Returns the average of the given values. * * @param values the values. * @return the average. */ public static Double getAverage( List<Double> values ) { Double sum = getSum( values ); return sum / values.size(); } /** * Returns the sum of the given values. * * @param values the values. * @return the sum. */ public static Double getSum( List<Double> values ) { Double sum = 0.0; for ( Double value : values ) { if ( value != null ) { sum += value; } } return sum; } }
#!/bin/bash docker stop twelve-factor-base docker rm twelve-factor-base docker ps -a
#!/usr/bin/env sh echo "Copying configuration file..." cp "${CONFIG_FILE}" ./package.json removeLatestTag() { LATEST_TAG_EXISTS=false if [ "$(git tag -l "$LATEST_TAG")" ]; then LATEST_TAG_EXISTS=true echo "Temporary removing 'latest' tag..." LATEST_TAG_REV=$(git rev-list -n 1 "${LATEST_TAG}") LATEST_TAG_MESSAGE=$(git tag -l --format='%(contents)' "${LATEST_TAG}") git tag -d "${LATEST_TAG}" fi } if [ "$SKIP_REMOVING_LATEST" != "true" ]; then removeLatestTag fi
#!/bin/bash # Check current branch is "master" current_branch=$(git rev-parse --abbrev-ref HEAD) if [[ $current_branch != master ]]; then echo "execution on non-master branch is not allowed" exit 1 fi echo -e "\033[0;32mDeploying updates to GitHub...\033[0m" # Build the project make html # Go to html folder cd build/html # Add changes to git git add . # Commit changes msg="Rebulding site date" if [ $# -eq 1 ]; then msg="$1" fi git commit -m "$msg" # Push source and build repos git push origin gh-pages # Come back up to the project root cd ../../
/** * Copyright © 2016-2021 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ciat.bim.server.state; import com.ciat.bim.data.DataConstants; import com.ciat.bim.data.id.CustomerId; import com.ciat.bim.data.id.DeviceId; import com.ciat.bim.data.id.TenantId; import com.ciat.bim.msg.*; import com.ciat.bim.server.cluster.TbClusterService; import com.ciat.bim.server.common.data.page.PageData; import com.ciat.bim.server.common.data.page.PageLink; import com.ciat.bim.server.common.msg.queue.TbCallback; import com.ciat.bim.server.queue.discovery.PartitionService; import com.ciat.bim.server.queue.discovery.TbApplicationEventListener; import com.ciat.bim.server.queue.discovery.event.PartitionChangeEvent; import com.ciat.bim.server.queue.util.TbCoreComponent; import com.ciat.bim.server.telemetry.TelemetrySubscriptionService; import com.ciat.bim.server.timeseries.TimeseriesService; import com.ciat.bim.server.transport.TransportProtos; import com.ciat.bim.server.utils.JacksonUtil; import com.ciat.bim.server.utils.ThingsBoardThreadFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Function; import com.google.common.util.concurrent.*; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.jeecg.modules.device.entity.*; import org.jeecg.modules.device.service.IAttributeKvService; import org.jeecg.modules.device.service.IDeviceService; import org.jeecg.modules.tenant.entity.Tenant; import org.jeecg.modules.tenant.service.ITenantService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.*; import java.util.concurrent.*; import static com.ciat.bim.data.DataConstants.CONNECT_EVENT; import static com.ciat.bim.data.DataConstants.SERVER_SCOPE; /** * Created by ashvayka on 01.05.18. */ @Service @TbCoreComponent @Slf4j public class DefaultDeviceStateService extends TbApplicationEventListener<PartitionChangeEvent> implements DeviceStateService { public static final String ACTIVITY_STATE = "active"; public static final String LAST_CONNECT_TIME = "lastConnectTime"; public static final String LAST_DISCONNECT_TIME = "lastDisconnectTime"; public static final String LAST_ACTIVITY_TIME = "lastActivityTime"; public static final String INACTIVITY_ALARM_TIME = "inactivityAlarmTime"; public static final String INACTIVITY_TIMEOUT = "inactivityTimeout"; public static final List<String> PERSISTENT_ATTRIBUTES = Arrays.asList(ACTIVITY_STATE, LAST_CONNECT_TIME, LAST_DISCONNECT_TIME, LAST_ACTIVITY_TIME, INACTIVITY_ALARM_TIME, INACTIVITY_TIMEOUT); @Autowired private ITenantService tenantService; @Autowired private IDeviceService deviceService; @Autowired private PartitionService partitionService; @Autowired private IAttributeKvService attributesService; @Autowired private TimeseriesService tsService; @Autowired private TbClusterService clusterService; @Autowired private TelemetrySubscriptionService tsSubService; @Value("${state.defaultInactivityTimeoutInSec}") @Getter private long defaultInactivityTimeoutInSec; @Value("${state.defaultStateCheckIntervalInSec}") @Getter private int defaultStateCheckIntervalInSec; @Value("${state.persistToTelemetry:false}") @Getter private boolean persistToTelemetry; @Value("${state.initFetchPackSize:1000}") @Getter private int initFetchPackSize; private ListeningScheduledExecutorService scheduledExecutor; private ExecutorService deviceStateExecutor; private final ConcurrentMap<TopicPartitionInfo, Set<DeviceId>> partitionedDevices = new ConcurrentHashMap<>(); final ConcurrentMap<DeviceId, DeviceStateData> deviceStates = new ConcurrentHashMap<>(); final Queue<Set<TopicPartitionInfo>> subscribeQueue = new ConcurrentLinkedQueue<>(); @PostConstruct public void init() { deviceStateExecutor = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), ThingsBoardThreadFactory.forName("device-state")); // Should be always single threaded due to absence of locks. scheduledExecutor = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor(ThingsBoardThreadFactory.forName("device-state-scheduled"))); scheduledExecutor.scheduleAtFixedRate(this::updateInactivityStateIfExpired, new Random().nextInt(defaultStateCheckIntervalInSec), defaultStateCheckIntervalInSec, TimeUnit.SECONDS); } @PreDestroy public void stop() { if (deviceStateExecutor != null) { deviceStateExecutor.shutdownNow(); } if (scheduledExecutor != null) { scheduledExecutor.shutdownNow(); } } @Override public void onDeviceConnect(String tenantId, DeviceId deviceId) { log.trace("on Device Connect [{}]", deviceId.getId()); DeviceStateData stateData = getOrFetchDeviceStateData(deviceId); long ts = System.currentTimeMillis(); stateData.getState().setLastConnectTime(ts); saveDateTime(deviceId, LAST_CONNECT_TIME, ts); pushRuleEngineMessage(stateData, CONNECT_EVENT); checkAndUpdateState(deviceId, stateData); cleanDeviceStateIfBelongsExternalPartition(tenantId, deviceId); } @Override public void onDeviceActivity(String tenantId, DeviceId deviceId, long lastReportedActivity) { log.trace("on Device Activity [{}], lastReportedActivity [{}]", deviceId.getId(), lastReportedActivity); final DeviceStateData stateData = getOrFetchDeviceStateData(deviceId); if (lastReportedActivity > 0 && lastReportedActivity > stateData.getState().getLastActivityTime()) { updateActivityState(deviceId, stateData, lastReportedActivity); } cleanDeviceStateIfBelongsExternalPartition(tenantId, deviceId); } void updateActivityState(DeviceId deviceId, DeviceStateData stateData, long lastReportedActivity) { log.trace("updateActivityState - fetched state {} for device {}, lastReportedActivity {}", stateData, deviceId, lastReportedActivity); if (stateData != null) { saveDateTime(deviceId, LAST_ACTIVITY_TIME, lastReportedActivity); DeviceState state = stateData.getState(); state.setLastActivityTime(lastReportedActivity); if (!state.isActive()) { state.setActive(true); save(deviceId, ACTIVITY_STATE, true); pushRuleEngineMessage(stateData, DataConstants.ACTIVITY_EVENT); } } else { log.debug("updateActivityState - fetched state IN NULL for device {}, lastReportedActivity {}", deviceId, lastReportedActivity); cleanUpDeviceStateMap(deviceId); } } @Override public void onDeviceDisconnect(String tenantId, DeviceId deviceId) { DeviceStateData stateData = getOrFetchDeviceStateData(deviceId); long ts = System.currentTimeMillis(); stateData.getState().setLastDisconnectTime(ts); saveDateTime(deviceId, LAST_DISCONNECT_TIME, ts); pushRuleEngineMessage(stateData, DataConstants.DISCONNECT_EVENT); cleanDeviceStateIfBelongsExternalPartition(tenantId, deviceId); } @Override public void onDeviceInactivityTimeoutUpdate(String tenantId, DeviceId deviceId, long inactivityTimeout) { if (inactivityTimeout <= 0L) { return; } log.trace("on Device Activity Timeout Update device id {} inactivityTimeout {}", deviceId, inactivityTimeout); DeviceStateData stateData = getOrFetchDeviceStateData(deviceId); stateData.getState().setInactivityTimeout(inactivityTimeout); checkAndUpdateState(deviceId, stateData); cleanDeviceStateIfBelongsExternalPartition(tenantId, deviceId); } @Override public void onQueueMsg(TransportProtos.DeviceStateServiceMsgProto proto, TbCallback callback) { try { TenantId tenantId = new TenantId(proto.getTenantIdMSB()+""); DeviceId deviceId = new DeviceId(proto.getDeviceIdMSB()+""); if (proto.getDeleted()) { onDeviceDeleted(tenantId.getId(), deviceId); callback.onSuccess(); } else { Device device = deviceService.getById(deviceId); if (device != null) { if (proto.getAdded()) { Futures.addCallback(fetchDeviceState(device), new FutureCallback<DeviceStateData>() { @Override public void onSuccess(@Nullable DeviceStateData state) { TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId.getId(), device.getId()); if (partitionedDevices.containsKey(tpi)) { addDeviceUsingState(tpi, state); save(deviceId, ACTIVITY_STATE, false); callback.onSuccess(); } else { log.debug("[{}][{}] Device belongs to external partition. Probably rebalancing is in progress. Topic: {}" , tenantId, deviceId, tpi.getFullTopicName()); callback.onFailure(new RuntimeException("Device belongs to external partition " + tpi.getFullTopicName() + "!")); } } @Override public void onFailure(Throwable t) { log.warn("Failed to register device to the state service", t); callback.onFailure(t); } }, deviceStateExecutor); } else if (proto.getUpdated()) { DeviceStateData stateData = getOrFetchDeviceStateData(DeviceId.fromString(device.getId())); TbMsgMetaData md = new TbMsgMetaData(); md.putValue("deviceName", device.getName()); md.putValue("deviceType", device.getType()); stateData.setMetaData(md); callback.onSuccess(); } } else { //Device was probably deleted while message was in queue; callback.onSuccess(); } } } catch (Exception e) { log.trace("Failed to process queue msg: [{}]", proto, e); callback.onFailure(e); } } /** * DiscoveryService will call this event from the single thread (one-by-one). * Events order is guaranteed by DiscoveryService. * The only concurrency is expected from the [main] thread on Application started. * Async implementation. Locks is not allowed by design. * Any locks or delays in this module will affect DiscoveryService and entire system */ @Override protected void onTbApplicationEvent(PartitionChangeEvent partitionChangeEvent) { if (ServiceType.TB_CORE.equals(partitionChangeEvent.getServiceType())) { log.debug("onTbApplicationEvent ServiceType is TB_CORE, processing queue {}", partitionChangeEvent); subscribeQueue.add(partitionChangeEvent.getPartitions()); scheduledExecutor.submit(this::pollInitStateFromDB); } } void pollInitStateFromDB() { final Set<TopicPartitionInfo> partitions = getLatestPartitionsFromQueue(); if (partitions == null) { log.info("Device state service. Nothing to do. partitions is null"); return; } initStateFromDB(partitions); } // TODO: move to utils Set<TopicPartitionInfo> getLatestPartitionsFromQueue() { log.debug("getLatestPartitionsFromQueue, queue size {}", subscribeQueue.size()); Set<TopicPartitionInfo> partitions = null; while (!subscribeQueue.isEmpty()) { partitions = subscribeQueue.poll(); log.debug("polled from the queue partitions {}", partitions); } log.debug("getLatestPartitionsFromQueue, partitions {}", partitions); return partitions; } private void initStateFromDB(Set<TopicPartitionInfo> partitions) { try { log.info("CURRENT PARTITIONS: {}", partitionedDevices.keySet()); log.info("NEW PARTITIONS: {}", partitions); Set<TopicPartitionInfo> addedPartitions = new HashSet<>(partitions); addedPartitions.removeAll(partitionedDevices.keySet()); log.info("ADDED PARTITIONS: {}", addedPartitions); Set<TopicPartitionInfo> removedPartitions = new HashSet<>(partitionedDevices.keySet()); removedPartitions.removeAll(partitions); log.info("REMOVED PARTITIONS: {}", removedPartitions); // We no longer manage current partition of devices; removedPartitions.forEach(partition -> { Set<DeviceId> devices = partitionedDevices.remove(partition); devices.forEach(this::cleanUpDeviceStateMap); }); addedPartitions.forEach(tpi -> partitionedDevices.computeIfAbsent(tpi, key -> ConcurrentHashMap.newKeySet())); initPartitions(addedPartitions); scheduledExecutor.submit(() -> { log.info("Managing following partitions:"); partitionedDevices.forEach((tpi, devices) -> { log.info("[{}]: {} devices", tpi.getFullTopicName(), devices.size()); }); }); } catch (Throwable t) { log.warn("Failed to init device states from DB", t); } } //TODO 3.0: replace this dummy search with new functionality to search by partitions using SQL capabilities. //Adding only entities that are in new partitions boolean initPartitions(Set<TopicPartitionInfo> addedPartitions) { if (addedPartitions.isEmpty()) { return false; } List<Tenant> tenants = tenantService.list(); for (Tenant tenant : tenants) { log.debug("Finding devices for tenant [{}]", tenant.getTitle()); final PageLink pageLink = new PageLink(initFetchPackSize); scheduledExecutor.submit(() -> processPageAndSubmitNextPage(addedPartitions, tenant, pageLink, scheduledExecutor)); } return true; } private void processPageAndSubmitNextPage(final Set<TopicPartitionInfo> addedPartitions, final Tenant tenant, final PageLink pageLink, final ExecutorService executor) { log.trace("[{}] Process page {} from {}", tenant, pageLink.getPage(), pageLink.getPageSize()); List<ListenableFuture<Void>> fetchFutures = new ArrayList<>(); PageData<Device> page = deviceService.findDevicesByTenantId(tenant.getId(), pageLink); for (Device device : page.getData()) { TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenant.getId(), device.getId()); if (addedPartitions.contains(tpi)) { log.debug("[{}][{}] Device belong to current partition. tpi [{}]. Fetching state from DB", device.getName(), device.getId(), tpi); ListenableFuture<Void> future = Futures.transform(fetchDeviceState(device), new Function<DeviceStateData, Void>() { @Nullable @Override public Void apply(@Nullable DeviceStateData state) { if (state != null) { addDeviceUsingState(tpi, state); checkAndUpdateState(new DeviceId(device.getId()), state); } else { log.warn("{}][{}] Fetched null state from DB", device.getName(), device.getId()); } return null; } }, deviceStateExecutor); fetchFutures.add(future); } else { log.debug("[{}][{}] Device doesn't belong to current partition. tpi [{}]", device.getName(), device.getId(), tpi); } } Futures.addCallback(Futures.successfulAsList(fetchFutures), new FutureCallback<List<Void>>() { @Override public void onSuccess(List<Void> result) { log.trace("[{}] Success init device state from DB for batch size {}", tenant.getId(), result.size()); } @Override public void onFailure(Throwable t) { log.warn("[" + tenant.getId() + "] Failed to init device state service from DB", t); log.warn("[{}] Failed to init device state service from DB", tenant.getId(), t); } }, deviceStateExecutor); final PageLink nextPageLink = page.hasNext() ? pageLink.nextPageLink() : null; if (nextPageLink != null) { log.trace("[{}] Submit next page {} from {}", tenant, nextPageLink.getPage(), nextPageLink.getPageSize()); executor.submit(() -> processPageAndSubmitNextPage(addedPartitions, tenant, nextPageLink, executor)); } } void checkAndUpdateState(@Nonnull DeviceId deviceId, @Nonnull DeviceStateData state) { if (state.getState().isActive()) { updateInactivityStateIfExpired(System.currentTimeMillis(), deviceId, state); } else { //trying to fix activity state if (isActive(System.currentTimeMillis(), state.getState())) { updateActivityState(deviceId, state, state.getState().getLastActivityTime()); } } } private void addDeviceUsingState(TopicPartitionInfo tpi, DeviceStateData state) { Set<DeviceId> deviceIds = partitionedDevices.get(tpi); if (deviceIds != null) { deviceIds.add(state.getDeviceId()); deviceStates.put(state.getDeviceId(), state); } else { log.debug("[{}] Device belongs to external partition {}", state.getDeviceId(), tpi.getFullTopicName()); throw new RuntimeException("Device belongs to external partition " + tpi.getFullTopicName() + "!"); } } void updateInactivityStateIfExpired() { final long ts = System.currentTimeMillis(); partitionedDevices.forEach((tpi, deviceIds) -> { log.debug("Calculating state updates. tpi {} for {} devices", tpi.getFullTopicName(), deviceIds.size()); for (DeviceId deviceId : deviceIds) { updateInactivityStateIfExpired(ts, deviceId); } }); } void updateInactivityStateIfExpired(long ts, DeviceId deviceId) { DeviceStateData stateData = getOrFetchDeviceStateData(deviceId); updateInactivityStateIfExpired(ts, deviceId, stateData); } void updateInactivityStateIfExpired(long ts, DeviceId deviceId, DeviceStateData stateData) { log.trace("Processing state {} for device {}", stateData, deviceId); if (stateData != null) { DeviceState state = stateData.getState(); if (!isActive(ts, state) && (state.getLastInactivityAlarmTime() == 0L || state.getLastInactivityAlarmTime() < state.getLastActivityTime()) && stateData.getDeviceCreationTime() + state.getInactivityTimeout() < ts) { state.setActive(false); state.setLastInactivityAlarmTime(ts); saveDateTime(deviceId, INACTIVITY_ALARM_TIME, ts); save(deviceId, ACTIVITY_STATE, false); pushRuleEngineMessage(stateData, DataConstants.INACTIVITY_EVENT); } } else { log.debug("[{}] Device that belongs to other server is detected and removed.", deviceId); cleanUpDeviceStateMap(deviceId); } } boolean isActive(long ts, DeviceState state) { return ts < state.getLastActivityTime() + state.getInactivityTimeout(); } @Nonnull DeviceStateData getOrFetchDeviceStateData(DeviceId deviceId) { DeviceStateData deviceStateData = deviceStates.get(deviceId); if (deviceStateData != null) { return deviceStateData; } return fetchDeviceStateData(deviceId); } DeviceStateData fetchDeviceStateData(final DeviceId deviceId) { final Device device = deviceService.getById(deviceId.getId()); if (device == null) { log.warn("[{}] Failed to fetch device by Id!", deviceId); throw new RuntimeException("Failed to fetch device by Id " + deviceId); } try { DeviceStateData deviceStateData = fetchDeviceState(device).get(); deviceStates.putIfAbsent(deviceId, deviceStateData); return deviceStateData; } catch (InterruptedException | ExecutionException e) { log.warn("[{}] Failed to fetch device state!", deviceId, e); throw new RuntimeException(e); } } private void cleanDeviceStateIfBelongsExternalPartition(String tenantId, final DeviceId deviceId) { TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId, deviceId.getId()); if (!partitionedDevices.containsKey(tpi)) { cleanUpDeviceStateMap(deviceId); log.debug("[{}][{}] device belongs to external partition. Probably rebalancing is in progress. Topic: {}" , tenantId, deviceId, tpi.getFullTopicName()); } } private void onDeviceDeleted(String tenantId, DeviceId deviceId) { cleanUpDeviceStateMap(deviceId); TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId, deviceId.getId()); Set<DeviceId> deviceIdSet = partitionedDevices.get(tpi); deviceIdSet.remove(deviceId); } private void cleanUpDeviceStateMap(DeviceId deviceId) { deviceStates.remove(deviceId); } private ListenableFuture<DeviceStateData> fetchDeviceState(Device device) { ListenableFuture<DeviceStateData> future; if (persistToTelemetry) { ListenableFuture<List<TsKv>> tsData = tsService.findLatest(TenantId.fromString(TenantId.SYS_TENANT_ID), DeviceId.fromString(device.getId()), PERSISTENT_ATTRIBUTES); future = Futures.transform(tsData, extractDeviceStateData(device), deviceStateExecutor); } else { ListenableFuture<List<AttributeKv>> attrData = attributesService.find(TenantId.SYS_TENANT_ID, DeviceId.fromString(device.getId()), SERVER_SCOPE, PERSISTENT_ATTRIBUTES); future = Futures.transform(attrData, extractDeviceStateData(device), deviceStateExecutor); } return transformInactivityTimeout(future); } private ListenableFuture<DeviceStateData> transformInactivityTimeout(ListenableFuture<DeviceStateData> future) { return Futures.transformAsync(future, deviceStateData -> { if (!persistToTelemetry || deviceStateData.getState().getInactivityTimeout() != TimeUnit.SECONDS.toMillis(defaultInactivityTimeoutInSec)) { return future; //fail fast } ListenableFuture<Optional<AttributeKv>> attributesFuture = attributesService.find(TenantId.fromString(TenantId.SYS_TENANT_ID), deviceStateData.getDeviceId(), SERVER_SCOPE, INACTIVITY_TIMEOUT); return Futures.transform(attributesFuture, attributes -> { if (attributes.get().getLongValue() > 0) { deviceStateData.getState().setInactivityTimeout(attributes.get().getLongValue()); } ; return deviceStateData; }, deviceStateExecutor); }, deviceStateExecutor); } private <T extends KvEntry> Function<List<T>, DeviceStateData> extractDeviceStateData(Device device) { return new Function<>() { @Nonnull @Override public DeviceStateData apply(@Nullable List<T> data) { try { long lastActivityTime = getEntryValue(data, LAST_ACTIVITY_TIME, 0L); long inactivityAlarmTime = getEntryValue(data, INACTIVITY_ALARM_TIME, 0L); long inactivityTimeout = getEntryValue(data, INACTIVITY_TIMEOUT, TimeUnit.SECONDS.toMillis(defaultInactivityTimeoutInSec)); //Actual active state by wall-clock will updated outside this method. This method is only for fetch persistent state final boolean active = getEntryValue(data, ACTIVITY_STATE, false); DeviceState deviceState = DeviceState.builder() .active(active) .lastConnectTime(getEntryValue(data, LAST_CONNECT_TIME, 0L)) .lastDisconnectTime(getEntryValue(data, LAST_DISCONNECT_TIME, 0L)) .lastActivityTime(lastActivityTime) .lastInactivityAlarmTime(inactivityAlarmTime) .inactivityTimeout(inactivityTimeout) .build(); TbMsgMetaData md = new TbMsgMetaData(); md.putValue("deviceName", device.getName()); md.putValue("deviceType", device.getType()); DeviceStateData deviceStateData = DeviceStateData.builder() .customerId(new CustomerId(device.getCustomerId())) .tenantId(new TenantId(device.getTenantId())) .deviceId(new DeviceId(device.getId())) .deviceCreationTime(device.getCreateTime().getTime()) .metaData(md) .state(deviceState).build(); log.debug("[{}] Fetched device state from the DB {}", device.getId(), deviceStateData); return deviceStateData; } catch (Exception e) { log.warn("[{}] Failed to fetch device state data", device.getId(), e); throw new RuntimeException(e); } } }; } private long getEntryValue(List<? extends KvEntry> kvEntries, String attributeName, long defaultValue) { if (kvEntries != null) { for (KvEntry entry : kvEntries) { if (entry != null && !StringUtils.isEmpty(entry.getKey()) && entry.getKey().equals(attributeName)) { return entry.getLongValue(); } } } return defaultValue; } private boolean getEntryValue(List<? extends KvEntry> kvEntries, String attributeName, boolean defaultValue) { if (kvEntries != null) { for (KvEntry entry : kvEntries) { if (entry != null && !StringUtils.isEmpty(entry.getKey()) && entry.getKey().equals(attributeName)) { return entry.getBooleanValue().equals("Y"); } } } return defaultValue; } private void pushRuleEngineMessage(DeviceStateData stateData, String msgType) { DeviceState state = stateData.getState(); try { String data; if (msgType.equals(CONNECT_EVENT)) { ObjectNode stateNode = JacksonUtil.convertValue(state, ObjectNode.class); stateNode.remove(ACTIVITY_STATE); data = JacksonUtil.toString(stateNode); } else { data = JacksonUtil.toString(state); } TbMsgMetaData md = stateData.getMetaData().copy(); if (!persistToTelemetry) { md.putValue(DataConstants.SCOPE, SERVER_SCOPE); } TbMsg tbMsg = TbMsg.newMsg(msgType, stateData.getDeviceId(), stateData.getCustomerId(), md, TbMsgDataType.JSON, data); clusterService.pushMsgToRuleEngine(stateData.getTenantId().getId(), stateData.getDeviceId(), tbMsg, null); } catch (Exception e) { log.warn("[{}] Failed to push inactivity alarm: {}", stateData.getDeviceId(), state, e); } } private void save(DeviceId deviceId, String key, long value) { if (persistToTelemetry) { tsSubService.saveAndNotifyInternal( TenantId.fromString(TenantId.SYS_TENANT_ID), deviceId, Collections.singletonList(new TsKv( new LongDataEntry(key, value),System.currentTimeMillis())), new TelemetrySaveCallback<>(deviceId, key, value)); } else { tsSubService.saveAttrAndNotify(TenantId.fromString(TenantId.SYS_TENANT_ID), deviceId, DataConstants.SERVER_SCOPE, key, value, new TelemetrySaveCallback<>(deviceId, key, value)); } } private void saveDateTime(DeviceId deviceId, String key, long value) { if (persistToTelemetry) { tsSubService.saveAndNotifyInternal( TenantId.fromString(TenantId.SYS_TENANT_ID), deviceId, Collections.singletonList(new TsKv( new DateTimeDataEntry(key, value),System.currentTimeMillis())), new TelemetrySaveCallback<>(deviceId, key, value)); } else { tsSubService.saveAttrTimeAndNotify(TenantId.fromString(TenantId.SYS_TENANT_ID), deviceId, DataConstants.SERVER_SCOPE, key, value, new TelemetrySaveCallback<>(deviceId, key, value)); } } private void save(DeviceId deviceId, String key, boolean value) { if (persistToTelemetry) { tsSubService.saveAndNotifyInternal( TenantId.fromString(TenantId.SYS_TENANT_ID), deviceId, Collections.singletonList(new TsKv( new BooleanDataEntry(key, value),System.currentTimeMillis())), new TelemetrySaveCallback<>(deviceId, key, value)); } else { tsSubService.saveAttrAndNotify(TenantId.fromString(TenantId.SYS_TENANT_ID), deviceId, DataConstants.SERVER_SCOPE, key, value, new TelemetrySaveCallback<>(deviceId, key, value)); } } private static class TelemetrySaveCallback<T> implements FutureCallback<T> { private final DeviceId deviceId; private final String key; private final Object value; TelemetrySaveCallback(DeviceId deviceId, String key, Object value) { this.deviceId = deviceId; this.key = key; this.value = value; } @Override public void onSuccess(@Nullable T result) { log.trace("[{}] Successfully updated attribute [{}] with value [{}]", deviceId, key, value); } @Override public void onFailure(Throwable t) { log.warn("[{}] Failed to update attribute [{}] with value [{}]", deviceId, key, value, t); } } }
package kariminf.langpi.basic.finnish; import kariminf.langpi.basic.BasicInfo; public class FiInfo implements BasicInfo { @Override public String getIndicator() { return "fi"; } @Override public String getLangEnglishName() { return "Finnish"; } @Override public String getLangName() { return "suomi"; } @Override public String getClassPrefix() { return "Fi"; } }
#!/bin/sh python app.py taska python app.py taskb python app.py taskc python app.py taskd python app.py taske
<filename>WikipediaDataApi.js var https = require('https'); var Promise = require('promise'); var cheerio = require('cheerio'); module.exports = { getPageAbstractLinks: function(page, lang) { return new Promise(function (resolve, reject) { //If no page specified, return error if(!page) reject("ERROR: No page specified."); lang = lang || "en"; //If the language was not specified, set en (English) var requestUrl = "https://" + lang + ".wikipedia.org/w/api.php?action=parse&section=0&prop=text&format=json&page=" + page; httpsGet(requestUrl).then(function(reqData) { //Parse json object that contains only the abstract portion of the page var reqObj = JSON.parse(reqData) //Check some error if(reqObj['error']) { //Throw reject error reject("ERROR:" + reqObj['error']['code'] + " | " + reqObj['error']['info']); } //Get the abstract html data htmlData = reqObj['parse']['text']['*'] //Load it on cheerio (jQuery like module) $ = cheerio.load(htmlData); var links = [] //Get all the links on the abstract (<p> tags) and put them into the links array $('p').children('a').each(function(i, elem){ links.push($(this).attr('href')) }); //Resolve request with links array resolve(links); }, function(err) { reject(err); }); }); }, getPageLinks: function(page, lang) { return new Promise(function (resolve, reject) { //If no page specified, return error if(!page) reject("ERROR: No page specified."); lang = lang || "en"; //If the language was not specified, set en (English) var requestUrl = "https://" + lang + ".wikipedia.org/w/api.php?action=query&pllimit=500&format=json&prop=links&titles=" + page; getPartialLinks(requestUrl, function(buffer, err) { //If error if(err) //reject with error obj reject(err); else //if no error, resolve with buffer resolve(buffer); }); }); } } function getPartialLinks(url, callback, originalUrl, buffer) { //Set optional options originalUrl = originalUrl || url; //Original url to be used for continue options buffer = buffer || []; //Buffer to store links //Execute get request httpsGet(url).then(function(recData) { //Parse json result recObj = JSON.parse(recData); //Iterate thru the pages for(var page in recObj['query']['pages']) { var pageObj = recObj['query']['pages'][page]; //Iterate thru the links on the page for(var link in pageObj['links']) { var linkObj = pageObj['links'][link]; buffer.push(linkObj['title']); } } //If we still got results to go if(recObj['continue']) { //Recurse this function again var continueUrl = originalUrl + "plcontinue=" + recObj['continue']["plcontinue"]; getPartialLinks(continueUrl, callback, originalUrl, buffer); } else { //If there is no continue (results to gather), resolve the callback callback(buffer); } }, function(err) { //If some error, resolve callback with null callback(null, err); }); } function httpsGet(url) { return new Promise(function (resolve, reject) { var recData = ''; https.get(url, function(res) { res.setEncoding('utf8'); res.on('data', (chunk) => { recData += chunk; }); res.on('end', () => { resolve(recData); }); res.on('error', (e) => { reject(e); }); }).on('error', (e) => { reject(e); }); }); }
<!DOCTYPE html> <html> <head> <title>Quiz</title> <script> // code to create a graphical frontend for the text-based quiz </script> </head> <body> <h1>Quiz</h1> <div id="questions"></div> </body> </html>
<filename>example/rpc.js<gh_stars>1-10 /* * * Publisher subscriber pattern * */ "use strict"; var cluster = require('cluster'), comb = require("comb"), hare = require('../index.js'), rpcClient = hare().rpc("rpc_queue"); var CALC_TO = 45; if (cluster.isMaster) { for (var i = 0; i < 4; i++) { cluster.fork(); } cluster.on('death', function (worker) { console.log('worker ' + worker.pid + ' died'); }); var nums = []; for (i = 1; i < CALC_TO; i++) { nums.push(i); } comb.async.array(nums).map(function (i) { console.log("calling for %d", i); return rpcClient.call({num: i}).chain(function (res) { return res.fib; }, function (err) { console.log(err.stack); }); }).chain(function (res) { console.log("DONE", res); }); } else { var fib = function (num) { return num === 0 ? 0 : num === 1 ? 1 : fib(num - 1) + fib(num - 2); }; rpcClient.handle(function (msg) { console.log("calculating %d", msg.num); return {fib: fib(msg.num)}; }); }
<reponame>wnbx/snail package com.acgist.snail.context.recycle; import java.io.File; import com.acgist.snail.utils.StringUtils; /** * <p>回收站</p> * * @author acgist */ public abstract class Recycle { /** * <p>删除文件路径</p> * <p>必须是完整路径(不能填写相对路径)</p> */ protected final String path; /** * <p>删除文件</p> */ protected final File file; /** * @param path 文件路径 */ protected Recycle(String path) { if(StringUtils.isEmpty(path)) { throw new IllegalArgumentException("删除文件路径错误:" + path); } this.path = path; this.file = new File(path); } /** * <p>删除文件</p> * * @return 是否删除成功 */ public abstract boolean delete(); }
<filename>src/objects/ChampsDataParser.java package objects; import java.util.ArrayList; import java.util.Scanner; import utilities.FileConverter; public class ChampsDataParser { private static FileConverter fc; public ChampsDataParser() { fc = new FileConverter(); } @SuppressWarnings("resource") public ArrayList<TeamData> process(String fileName) { ArrayList<TeamData> teams = new ArrayList<TeamData>(); ArrayList<String> lines = fc.convert(fileName); boolean init = true; for( String l : lines ) { if( init ) { init = false; continue; } Scanner sc = new Scanner(l); sc.useDelimiter(",|%,"); String name = sc.next(); String[] stats = new String[21]; Double[] conv = new Double[21]; for( int f=0; f<21; f++ ) { stats[f] = sc.next(); if( stats[f].equals("#DIV/0!") || stats[f].equals("") ) { conv[f] = 0D; } else { conv[f] = Double.parseDouble(stats[f]); } } TeamData td = new TeamData(name, conv); teams.add(td); // AutonGears 0 // AutonCross 1 // CrossPoints 2 // AutonHighGoalBalls 3 // AutonHighGoalPoints 4 // AutonLowGoalBalls 5 // AutonLowGoalPoints 6 // AvgTeleopGears 7 // MaxTeleopGears 8 // AvgFullCycleGears 9 // MaxFullCycleGears 10 // AvgTotalGears 11 // MaxTotalGears 12 // TeleHighGoalBalls 13 // TeleHighGoalPoints 14 // TeleLowGoalBalls 15 // TeleLowGoalPoints 16 // ClimbPercentage 17 // AvgClimbPoints 18 // ClimbTime 19 // CatchTime 20 } return teams; } }
import numpy as np def process_galaxy_data(redshifts, mchars, amplitudes, hubble): new_redshifts = np.append(0.1, redshifts) new_mchars = np.append(10.525 - 2 * np.log10(hubble), mchars) new_amplitudes = np.append(0.0083 * hubble ** 3, amplitudes) return new_redshifts, new_mchars, new_amplitudes
<reponame>iShubhamPrakash/scoar-front import React, { useEffect } from "react"; import Dialog from "@material-ui/core/Dialog"; import MuiDialogTitle from "@material-ui/core/DialogTitle"; import MuiDialogContent from "@material-ui/core/DialogContent"; import MuiDialogActions from "@material-ui/core/DialogActions"; import IconButton from "@material-ui/core/IconButton"; import CloseIcon from "@material-ui/icons/Close"; import Typography from "@material-ui/core/Typography"; import GetAppIcon from "@material-ui/icons/GetApp"; import { withStyles } from "@material-ui/core/styles"; import { Card, Button, Avatar, TextField } from "@material-ui/core"; import SubjectIcon from "@material-ui/icons/Subject"; import ScheduleIcon from "@material-ui/icons/Schedule"; import EditIcon from "@material-ui/icons/Edit"; import FormControl from "@material-ui/core/FormControl"; import FormLabel from "@material-ui/core/FormLabel"; import Select from "@material-ui/core/Select"; import InputLabel from "@material-ui/core/InputLabel"; import MenuItem from "@material-ui/core/MenuItem"; import FormHelperText from "@material-ui/core/FormHelperText"; const styles = (theme) => ({ root: { margin: 0, padding: theme.spacing(2), }, closeButton: { position: "absolute", right: theme.spacing(1), top: theme.spacing(1), color: theme.palette.grey[500], }, }); const DialogTitle = withStyles(styles)((props) => { const { children, classes, onClose, ...other } = props; return ( <MuiDialogTitle disableTypography className={classes.root} {...other}> <Typography variant="h6">{children}</Typography> {onClose ? ( <IconButton aria-label="close" className={classes.closeButton} onClick={onClose} > <CloseIcon /> </IconButton> ) : null} </MuiDialogTitle> ); }); const DialogContent = withStyles((theme) => ({ root: { padding: theme.spacing(2), }, }))(MuiDialogContent); const EditClassModal = (props) => { const [open, setOpen] = React.useState(false); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <div> <Button size="small" variant="contained" className="topBtn" startIcon={<EditIcon />} onClick={handleClickOpen} > Edit </Button> <Dialog onClose={handleClose} aria-labelledby="customized-dialog-title" open={open} className="addStudentModal" fullWidth={true} maxWidth={"sm"} > <DialogTitle id="customized-dialog-title" onClose={handleClose}> <img src="/logo-full-small.png" alt="" style={{ width: "100px" }} /> <h3 className="text-center m-0">Edit class room Details</h3> </DialogTitle> <DialogContent> <div className="createClassRommForm" style={{ marginTop:"-1em"}}> <div className="createClassRommForm__body"> <form autoComplete="off" className="form"> <TextField id="name" label="Name" variant="outlined" size="small" className="input" /> <br /> <FormControl variant="outlined"> <InputLabel>Tution Type</InputLabel> <Select labelId="demo-simple-select-outlined-label" id="demo-simple-select-outlined" value={"one"} onChange={(e) => {}} label="Type of teacher" size="small" className="input" > <MenuItem value={"one"}>one</MenuItem> <MenuItem value={"two"}>two</MenuItem> <MenuItem value={"three"}>three</MenuItem> </Select> </FormControl> <br /> <TextField id="addSchedule" label="Add Schedule" variant="outlined" size="small" className="input" /> <br /> <FormControl variant="outlined"> <InputLabel>Instruction mode</InputLabel> <Select labelId="demo-simple-select-outlined-label" id="demo-simple-select-outlined" value={"one"} onChange={(e) => {}} label="Type of teacher" size="small" className="input" > <MenuItem value={"one"}>one</MenuItem> <MenuItem value={"two"}>two</MenuItem> <MenuItem value={"three"}>three</MenuItem> </Select> </FormControl> <br /> <div className="feeRow"> <TextField id="fee" label="Enter Fee" variant="outlined" size="small" /> <FormControl variant="outlined" className="periodSelect"> <InputLabel>Billing period</InputLabel> <Select labelId="timeperiod" id="timeperiod" value={"one"} onChange={(e) => {}} label="Type of teacher" size="small" style={{ height: "40px" }} > <MenuItem value={"one"}>per month</MenuItem> <MenuItem value={"two"}>quaterly</MenuItem> <MenuItem value={"three"}>Yearly</MenuItem> </Select> </FormControl> </div> <br /> <TextField id="description" label="Description" variant="outlined" size="small" style={{ width: "300px" }} multiline rows={4} rowsMax={4} /> <br /> <Button variant="contained" className="createClassbtn" onClick={(e) => ""} > Save </Button> </form> </div> </div> </DialogContent> </Dialog> </div> ); }; export default EditClassModal;
<reponame>muthukumaravel7/armnn var _timeline_tests_8cpp = [ [ "BOOST_AUTO_TEST_CASE", "_timeline_tests_8cpp.xhtml#a48319064222492223dfa27d2ea4b6774", null ], [ "BOOST_AUTO_TEST_CASE", "_timeline_tests_8cpp.xhtml#aa50403517c534c8fb2ee7d6ff102a60f", null ], [ "BOOST_AUTO_TEST_CASE", "_timeline_tests_8cpp.xhtml#a0c3d8093d05ab9aaef39f204123a5d80", null ], [ "PushEntity", "_timeline_tests_8cpp.xhtml#a5d037fb2a573ca0e8b284ff0f4ba4b5b", null ], [ "PushEvent", "_timeline_tests_8cpp.xhtml#a152615febf988e6fc95d7e3284f0b139", null ], [ "PushEventClass", "_timeline_tests_8cpp.xhtml#a3b3046bf976af84f1afaf90604fdb5a5", null ], [ "PushLabel", "_timeline_tests_8cpp.xhtml#ad3941381c7ffa8b2804d4d5708abd488", null ], [ "PushRelationship", "_timeline_tests_8cpp.xhtml#a5f9ab9422ed7d18bdc693338d3e5e6b6", null ], [ "SendTimelinePacketToCommandHandler", "_timeline_tests_8cpp.xhtml#ac7f0a814e6156ecdbcfa323befed6645", null ] ];
#!/usr/bin/env bash ############################################################################### # Copyright (c) 2017. All rights reserved. # Mike Klusman IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A # COURTESY TO YOU. BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS # ONE POSSIBLE IMPLEMENTATION OF THIS FEATURE, APPLICATION OR # STANDARD, Mike Klusman IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION # IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE # FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION. # Mike Klusman EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO # THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO # ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE # FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS FOR A PARTICULAR PURPOSE. ############################################################################### ############################################################################### # # Author : Mike Klusman # Software Package : Shell Automated Testing -- Wish Wrapper # Application : Support Functionality # Language : Bourne Shell # ############################################################################### # -------------------------------------------------------------------- [ -z "${SLCF_SHELL_TOP}" ] && return "${FAIL}" ### ### Pull in the path functionality to be able to resolve paths ### . "${SLCF_SHELL_TOP}/utilities/common/.define_pather.sh" [ $? -ne "${PASS}" ] && return "${FAIL}" if [ -z "${HARNESS_BINDIR}" ] then #SLCF_TEST_SUITE_DIR=$( ${__REALPATH} ${__REALPATH_OPTS} "$( dirname '$0' )" ) . "${__HARNESS_TOPLEVEL}/bin/setup.sh" . "${__HARNESS_TOPLEVEL}/test/base_testing.sh" . "${__HARNESS_TOPLEVEL}/test/test_framework.sh" fi . "${SLCF_SHELL_FUNCTIONDIR}/assertions.sh" [ $? -ne "${PASS}" ] && return "${FAIL}" . "${__HARNESS_TOPLEVEL}/utilities/wrappers/wrapper_common.sh" if [ -n "$( __extract_value 'DETAIL' )" ] && [ "$( __extract_value 'DETAIL' )" -eq "${YES}" ] then __stdout '----------------------------------------------------------------' __stdout 'This is the bash wrapper script for Wish' __stdout '----------------------------------------------------------------' fi __result_file="$( run_wrapper $@ )" __RC=$? return "${__RC}"
package com.dabe.skyapp.view.ui.fragments; import android.content.Context; import android.view.inputmethod.InputMethodManager; import com.dabe.skyapp.interfaces.OnLoginCallbackListener; import com.dabe.skyapp.view.interfaces.IBaseView; /** * Created by <NAME> on 26.01.2017 1:08. * Project: SkyApp; Skype: pandamoni1 */ public class BaseLoginFragment extends BaseFragment implements IBaseView { private OnLoginCallbackListener activityCallback; @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnLoginCallbackListener) { activityCallback = (OnLoginCallbackListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnLoginCallbackListener"); } } @Override public void onErrorOccurred(String errorMessage) { if (activityCallback != null) { activityCallback.onErrorOccurred(errorMessage); } } @Override public void onShowLoading(String loadingMessage) { hideKeyboard(); if (activityCallback != null) { activityCallback.onShowLoading(loadingMessage); } } @Override public void onHideLoading() { if (activityCallback != null) { activityCallback.onHideLoading(); } } public void hideKeyboard() { if (getView() != null && getView().getWindowToken() != null) { final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getView().getWindowToken(), 0); } } public OnLoginCallbackListener getActivityCallback() { return activityCallback; } }
#!/bin/bash echo Using IF $1 for 10.1.3.3 echo Using IF $2 for 10.1.4.3 ip rule add from 10.1.3.3 table 1 ip rule add from 10.1.4.3 table 2 ip route add 10.1.3.0/24 dev $1 scope link table 1 ip route add default via 10.1.3.2 dev $1 table 1 ip route add 10.1.4.0/24 dev $2 scope link table 2 ip route add default via 10.1.4.2 dev $2 table 2
import template from './payone-payment-plugin-icon.html.twig'; import './payone-payment-plugin-icon.scss'; const { Component } = Shopware; Component.register('payone-payment-plugin-icon', { template });
# Copyright (c) Microsoft Corporation. All rights reserved. # # Licensed under the MIT License. See LICENSE in the project root # for license information. from __future__ import absolute_import, division, print_function, unicode_literals """Python 2/3 compatibility helpers. """ import functools import inspect import itertools import sys from debugpy.common import fmt try: import __builtin__ as builtins except ImportError: import builtins try: unicode = builtins.unicode bytes = builtins.str except AttributeError: unicode = builtins.str bytes = builtins.bytes try: xrange = builtins.xrange except AttributeError: xrange = builtins.range try: izip = itertools.izip except AttributeError: izip = builtins.zip try: reload = builtins.reload except AttributeError: from importlib import reload # noqa try: import queue except ImportError: import Queue as queue # noqa def force_unicode(s, encoding, errors="strict"): """Converts s to Unicode, using the provided encoding. If s is already Unicode, it is returned as is. """ return s.decode(encoding, errors) if isinstance(s, bytes) else unicode(s) def force_bytes(s, encoding, errors="strict"): """Converts s to bytes, using the provided encoding. If s is already bytes, it is returned as is. If errors="strict" and s is bytes, its encoding is verified by decoding it; UnicodeError is raised if it cannot be decoded. """ if isinstance(s, unicode): return s.encode(encoding, errors) else: s = bytes(s) if errors == "strict": # Return value ignored - invoked solely for verification. s.decode(encoding, errors) return s def force_str(s, encoding="ascii", errors="strict"): """Converts s to str (which is bytes on Python 2, and unicode on Python 3), using the provided encoding if necessary. If s is already str, it is returned as is. If errors="strict", str is bytes, and s is str, its encoding is verified by decoding it; UnicodeError is raised if it cannot be decoded. """ return (force_bytes if str is bytes else force_unicode)(s, encoding, errors) def force_ascii(s, errors="strict"): """Same as force_bytes(s, "ascii", errors) """ return force_bytes(s, "ascii", errors) def force_utf8(s, errors="strict"): """Same as force_bytes(s, "utf8", errors) """ return force_bytes(s, "utf8", errors) def filename(s, errors="strict"): """Same as force_unicode(s, sys.getfilesystemencoding(), errors) """ return force_unicode(s, sys.getfilesystemencoding(), errors) def filename_bytes(s, errors="strict"): """Same as force_bytes(s, sys.getfilesystemencoding(), errors) """ return force_bytes(s, sys.getfilesystemencoding(), errors) def filename_str(s, errors="strict"): """Same as force_str(s, sys.getfilesystemencoding(), errors) """ return force_str(s, sys.getfilesystemencoding(), errors) def nameof(obj, quote=False): """Returns the most descriptive name of a Python module, class, or function, as a Unicode string If quote=True, name is quoted with repr(). Best-effort, but guaranteed to not fail - always returns something. """ try: name = obj.__qualname__ except Exception: try: name = obj.__name__ except Exception: # Fall back to raw repr(), and skip quoting. try: name = repr(obj) except Exception: return "<unknown>" else: quote = False if quote: try: name = repr(name) except Exception: pass return force_unicode(name, "utf-8", "replace") def unicode_repr(obj): """Like repr(), but guarantees that the result is Unicode even on Python 2. """ return force_unicode(repr(obj), "ascii") def srcnameof(obj): """Returns the most descriptive name of a Python module, class, or function, including source information (filename and linenumber), if available. Best-effort, but guaranteed to not fail - always returns something. """ name = nameof(obj, quote=True) # Get the source information if possible. try: src_file = filename(inspect.getsourcefile(obj), "replace") except Exception: pass else: name += fmt(" (file {0!r}", src_file) try: _, src_lineno = inspect.getsourcelines(obj) except Exception: pass else: name += fmt(", line {0}", src_lineno) name += ")" return name def kwonly(f): """Makes all arguments with default values keyword-only. If the default value is kwonly.required, then the argument must be specified. """ try: inspect.getfullargspec except AttributeError: arg_names, args_name, kwargs_name, arg_defaults = inspect.getargspec(f) else: arg_names, args_name, kwargs_name, arg_defaults, _, _, _ = inspect.getfullargspec(f) assert args_name is None and kwargs_name is None argc = len(arg_names) pos_argc = argc - len(arg_defaults) required_names = { name for name, val in zip(arg_names[pos_argc:], arg_defaults) if val is kwonly.required } @functools.wraps(f) def kwonly_f(*args, **kwargs): if len(args) > pos_argc: raise TypeError("too many positional arguments") if not required_names.issubset(kwargs): missing_names = required_names.difference(kwargs) missing_names = ", ".join(repr(s) for s in missing_names) raise TypeError("missing required keyword-only arguments: " + missing_names) return f(*args, **kwargs) return kwonly_f kwonly.required = object()
import os import copy from pathlib import Path import numpy as np from random import shuffle, getrandbits, randrange class NeuralNetwork: """Create an instance of the neural network""" def __init__(self): self.parameters = NeuralNetwork.ReadNeuralNetwork() self.layers = np.array([np.zeros(layer_size) for layer_size in [9, 16, 16, 2]], dtype=object) self.zlayers = np.array([np.zeros(layer_size) for layer_size in [9, 16, 16, 2]], dtype=object) def Predict(self, a0): """Predict the result of a single sample and set the layer values""" z1 = np.matmul(self.parameters[0], a0) + self.parameters[3] a1 = self.Sigmoid(z1) # First hidden layer z2 = np.matmul(self.parameters[1], a1) + self.parameters[4] a2 = self.Sigmoid(z2) # Second hidden layer z3 = np.matmul(self.parameters[2], a2) + self.parameters[5] a3 = self.HypTan(z3) # Output layer self.zlayers = np.array([a0, z1, z2, z3], dtype=object) # Save the results in arrays self.layers = np.array([a0, a1, a2, a3], dtype=object) return np.copy(a3.flatten()) def DetermineGradient(self, y): """Determine the gradient vector dC to the corresponding label y""" # print(f"{np.linalg.norm((self.layers[3] - y)**2):0.01f}") common_factor3 = 2 * (self.layers[3] - y) * NeuralNetwork.dHypTan(self.zlayers[3]) common_factor2 = NeuralNetwork.dSigmoid(self.zlayers[2]) * np.dot(np.matmul(self.parameters[2], np.ones((len(self.layers[2]),1))).T, common_factor3) common_factor1 = NeuralNetwork.dSigmoid(self.zlayers[1]) * np.dot(np.matmul(self.parameters[1], np.ones((len(self.layers[1]),1))).T, common_factor2) dW1 = np.matmul(common_factor1, self.layers[0].T) dW2 = np.matmul(common_factor2, self.layers[1].T) dW3 = np.matmul(common_factor3, self.layers[2].T) db1 = common_factor1 db2 = common_factor2 db3 = common_factor3 return copy.deepcopy(np.array([dW1, dW2, dW3, db1, db2, db3], dtype=object)) @staticmethod def SaveNeuralNetwork(parameters): """Save the neural network in a file""" np.savez("neural-network-parameters.npz", parameters) @staticmethod def ReadNeuralNetwork(): """Read the neural network from a file""" parameters = np.load("neural-network-parameters.npz", allow_pickle=True)['arr_0'] return parameters @staticmethod def GenerateRandomNetwork(): layer_sizes = [9, 120, 120, 2] weight_shapes = [(a, b) for a, b in zip(layer_sizes[1:], layer_sizes[:-1])] weights = np.array([np.random.standard_normal(weight_shape)/(weight_shape[1]**.5) for weight_shape in weight_shapes], dtype=object) biases = np.array([np.random.standard_normal((layer_size, 1)) for layer_size in layer_sizes[1:]], dtype=object) parameters = np.array([weights[0], weights[1], weights[2], biases[0], biases[1], biases[2]], dtype=object) return parameters @staticmethod def Sigmoid(x): """Sigmoid activation function""" return 1/(1 + np.exp(-x)) @staticmethod def dSigmoid(x): """Derivative of Sigmoid activation function""" return NeuralNetwork.Sigmoid(x) * (1 - NeuralNetwork.Sigmoid(x)) @staticmethod def HypTan(x): """Hyperbolic tangent activation function""" return (np.exp(x) - np.exp(-x))/(np.exp(x) + np.exp(-x)) @staticmethod def dHypTan(x): """Derivative of hyperbolic tangent activation function""" return 4 / (np.exp(x) + np.exp(-x))**2 @staticmethod def Gaussian(x): """Gaussian activation function""" return np.exp(-(x**2)/2.0) @staticmethod def CombineGenes(network1, network2): parameters1 = copy.deepcopy(network1.parameters) parameters2 = copy.deepcopy(network2.parameters) parameters = copy.deepcopy(parameters1) for i in range(parameters1.size): for j in range(parameters1[i].shape[0]): for k in range(parameters1[i].shape[1]): if bool(getrandbits(1)): parameters[i][j][k] = parameters1[i][j][k] else: parameters[i][j][k] = parameters2[i][j][k] if randrange(100) < 4: parameters[i][j][k] += np.random.standard_normal()/2.0 # if parameters[i][j][k] != parameters1[i][j][k] and parameters[i][j][k] != parameters2[i][j][k]: # print("MUTATION") # elif parameters[i][j][k] == parameters1[i][j][k] and parameters[i][j][k] != parameters2[i][j][k]: # print("PARENT 1") # elif parameters[i][j][k] == parameters2[i][j][k] and parameters[i][j][k] != parameters1[i][j][k]: # print("PARENT 2") # else: # print("INVALID") return parameters def ResetNetwork(self): self.parameters = NeuralNetwork.GenerateRandomNetwork() NeuralNetwork.SaveNeuralNetwork(self.parameters) # network = NeuralNetwork() # network.ResetNetwork() # print(network.Predict(np.array([[5], [5], [5], [5], [5], [5], [5], [5], [5]])))
<reponame>lananh265/social-network "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.computer_download = void 0; var computer_download = { "viewBox": "0 0 64 64", "children": [{ "name": "g", "attribs": { "id": "COMPUTER__x2F__DOWNLOAD_1_", "enable-background": "new " }, "children": [{ "name": "g", "attribs": { "id": "COMPUTER__x2F__DOWNLOAD" }, "children": [{ "name": "g", "attribs": { "id": "COMPUTER__x2F__DOWNLOAD" }, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "path", "attribs": { "d": "M22,19c0,0.828,0.336,1.578,0.879,2.121l7,7C30.422,28.664,31.172,29,32,29s1.578-0.336,2.121-0.879l7-7\r\n\t\t\t\tC41.664,20.579,42,19.828,42,19c0-1.657-1.343-3-3-3c-0.828,0-1.578,0.336-2.121,0.879L35,18.758V5c0-1.657-1.343-3-3-3\r\n\t\t\t\ts-3,1.343-3,3v13.757l-1.879-1.879C26.578,16.336,25.828,16,25,16C23.343,16,22,17.343,22,19z M60,6H38v4h21v34H5V10h21V6H4\r\n\t\t\t\tC2.343,6,1,7.343,1,9v40c0,1.657,1.343,3,3,3h19v5l-4,4v1h26v-1l-4-4v-5h19c1.657,0,3-1.343,3-3V9C63,7.343,61.657,6,60,6z" }, "children": [{ "name": "path", "attribs": { "d": "M22,19c0,0.828,0.336,1.578,0.879,2.121l7,7C30.422,28.664,31.172,29,32,29s1.578-0.336,2.121-0.879l7-7\r\n\t\t\t\tC41.664,20.579,42,19.828,42,19c0-1.657-1.343-3-3-3c-0.828,0-1.578,0.336-2.121,0.879L35,18.758V5c0-1.657-1.343-3-3-3\r\n\t\t\t\ts-3,1.343-3,3v13.757l-1.879-1.879C26.578,16.336,25.828,16,25,16C23.343,16,22,17.343,22,19z M60,6H38v4h21v34H5V10h21V6H4\r\n\t\t\t\tC2.343,6,1,7.343,1,9v40c0,1.657,1.343,3,3,3h19v5l-4,4v1h26v-1l-4-4v-5h19c1.657,0,3-1.343,3-3V9C63,7.343,61.657,6,60,6z" }, "children": [] }] }] }] }] }] }] }] }; exports.computer_download = computer_download;
#include <iostream> #include <cstdlib> // Base Allocator class with pure virtual functions class Allocator { public: virtual void* allocate(size_t size) = 0; virtual void deallocate(void* ptr) = 0; }; // Custom allocator inheriting from the base Allocator class class MySystemAllocator : public Allocator { public: // Override the allocate function to use aligned version of malloc void* allocate(size_t size) override { return aligned_malloc(size, 16); // Using aligned_malloc for aligned memory allocation } // Override the deallocate function to free the allocated memory void deallocate(void* ptr) override { aligned_free(ptr); // Freeing the memory allocated using aligned_malloc } private: // Custom aligned memory allocation function void* aligned_malloc(size_t size, size_t alignment) { void* ptr = nullptr; if (posix_memalign(&ptr, alignment, size) != 0) { throw std::bad_alloc(); // Throw bad_alloc exception if memory allocation fails } return ptr; } // Custom aligned memory deallocation function void aligned_free(void* ptr) { free(ptr); // Free the memory allocated using aligned_malloc } }; int main() { MySystemAllocator customAllocator; void* memory = customAllocator.allocate(100); // Allocate 100 bytes of memory std::cout << "Memory allocated using custom allocator" << std::endl; customAllocator.deallocate(memory); // Deallocate the memory std::cout << "Memory deallocated using custom allocator" << std::endl; return 0; }
#!/usr/bin/env sh base=$1 version=$2 mkdir -p "$base/releases"; cd "$base/dist/"; files=./* for file in $files do echo "working on folder -> $file" package=$(ls "./$file" | sed "s/.js$/$version.zip/"); echo "pacakge is $package"; cp "$base/README.md" "$base/dist/$file/"; cp "$base/LICENSE" "$base/dist/$file/"; zip -r "$package" "$file/"; mv "$package" "$base/releases/" done; cd $base;
// Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) // EventContext event context // // swagger:model EventContext type EventContext struct { // ID of the event EventID string `json:"eventId,omitempty"` // Keptn Context ID of the event KeptnContext string `json:"keptnContext,omitempty"` // Time of the event Time string `json:"time,omitempty"` } // Validate validates this event context func (m *EventContext) Validate(formats strfmt.Registry) error { return nil } // MarshalBinary interface implementation func (m *EventContext) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *EventContext) UnmarshalBinary(b []byte) error { var res EventContext if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
package com.microsoft.azure.pixeltracker.server.api; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import javax.inject.Singleton; import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by dcibo on 6/5/2017. */ @ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc class PixelControllerTest { @BeforeAll static void beforeAll() { Map<String, String> map = new HashMap<>(); map.put("ServiceBusNamespaceName", "pixelTracker"); map.put("EventHubName", "pixelTracker"); map.put("sharedAccessSignatureKeyName", "RootManageSharedAccessKey"); map.put("SharedAccessSignatureKey", "<KEY> setEnv(map); } @Autowired @Singleton private MockMvc mvc; @Test void pixel() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/pixel").accept(MediaType.IMAGE_GIF)) .andExpect(status().isOk()); } @Test void pixel2() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/pixel?this=that").accept(MediaType.IMAGE_GIF)) .andExpect(status().isOk()); } @SuppressWarnings("unchecked") private static void setEnv(Map<String, String> newenv) { try { Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { try { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } } } catch (Exception e2) { e2.printStackTrace(); } } catch (Exception e1) { e1.printStackTrace(); } } }
import assert from "assert"; import chain from "../src/chain"; import connect from "../src/connect"; import pipe from "../src/pipe"; import { createTestWritable, createTestReadable, broker } from "./utils"; suite("chain"); test("check chaining", done => { let readable, writable, transform, testChain; // Create test streams readable = createTestReadable( [1,2,3] ); transform = pipe( k=>k ); writable = createTestWritable( assert ); // End case broker.on(writable.signals.close, done); // Connect the streams testChain = chain( new transform, new transform, new transform ); return connect( readable, testChain, writable ); });
<gh_stars>1-10 /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ module.exports = { preset: 'ts-jest', testEnvironment: 'node', collectCoverage: true, moduleFileExtensions: [ "ts", "tsx", "js" ], globals: { 'ts-jest': { tsconfig: { sourceMap: true, }, }, }, testRegex: "/src/.*\\.spec\\.(ts|tsx|js)$" };
package cryptix.alg.chacha; import cryptix.X; import cryptix.Support; /** * This is an implementation of Salsa20 taken directly from the DJB paper * http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.64.8844&rep=rep1&type=pdf * * </p><p> * Each round is: 16 add, 16 xor, 16 constant distance rotations (currently 1 transposition) * </p><p> * The limitations are thus: * key => 2^64 streams * stream => 2^64 blocks * block == 2^9 bits, 64 bytes, 16 words * </p><p> * Given all possible nonces, each key expands to 2^64 streams, each * stream, given all possible block counters produces 2^64 64 byte * blocks. * * </p><p> * Each block is independent of the last, so you can randomly start your * stream with any given block counter and nounce. * * </p><p> * In the C code it was the users responsibility to prevent the production * of more than 2^70 bytes/nonce (comment in Bernstien's code). (Each * nonce generates 2^64 blocks which is 2^62 * 2^9 = 2^73 bits = 2^70 bytes.) * * </p><p> * It is recommended to use full sizes / rounds: key of 32b/256bits and 20 rounds. * Indeed, that is the only mode supported in this Salsa implementation! * </p><p> * It is also recommended to use ChaCha rather than Salsa as it has a few tiny * improvements. * </p> * * <p>Todo</p> * <ul> * <li>XXX: Ian please check this implementation * <li>My code requires the user to update the nonce. * <li>Check: The user may begin crypting * with any block number, an exception will be thrown if the block number exceeds * the max long length. * <li>Merge this more with ChaCha. * <li>Add support for rounds8/12 and keysize 128/16. * </ul> * * @author adalovelace */ public class MySalsa20 extends ChaCha // is the recommended one, therefore is the super class { /* * TAU, SIGMA and other constants are taken from ChaCha */ public static void crypto_stream_xor(byte[] returnme, byte[] xorme, int xorlen, byte[] iv, long blockcounter , byte[] key){ int[] [] matrix = new int[4][4]; int[] keys = new int[8]; int[] block_counter = new int[2]; int[] noncez = new int[2]; /* * Notes: * For all the silly people like me who get matrices confused, * the matrix is laid out this way: * int [rows] [columns] */ for(int i = 0; i < 32; i += WORD){ // 8 times, 8 key words keys[i/WORD] = bytes2littleendian(key[i], key[i+1], key[i+2], key[i+3]); } for(int i = 0; i < 8; i += WORD){ // twice, 2 nonce words noncez[i/WORD] = bytes2littleendian(iv[i], iv[i+1], iv[i+2], iv[i+3]); } /* * Little endian -- low order int comes first. */ block_counter[0] = (int) (INT_M & blockcounter); block_counter[1] = (int) (INT_M & (blockcounter >>> 32)); initialize_matrix(matrix, keys, noncez, block_counter); crypt(matrix, returnme, xorme, xorlen ); } private static void crypt(int[][] matrix0, byte[] returnme, byte[] xorme, int xorlen){ int num = (xorlen+63)/OUTPUT_BLOCK_SIZE; for(int j = 0; j < num; j++ ){ int[][]matrix = salsa20(matrix0); int start = j << 6; // multiply by OUTPUT_BLOCK_SIZE byte[] b = new byte[OUTPUT_BLOCK_SIZE]; int x = 0; for(int i = start; i< (OUTPUT_BLOCK_SIZE/WORD)+start; i++){ byte[] temp = littleendian2bytes(matrix[(i/4)%4][i%4]); b[x++] = temp[0]; b[x++] = temp[1]; b[x++] = temp[2]; b[x++] = temp[3]; } for(int i = start; (i < OUTPUT_BLOCK_SIZE + start) && (i < xorlen); i += 1){ returnme[i] = (byte) (xorme[i] ^ b[i%OUTPUT_BLOCK_SIZE]); } increment_bc(matrix0); } } //does 20 rounds of salsa, returning the matrix to //xor... private static int[][] salsa20(int[] [] matrix){ int[][] matrix0 = round(matrix); for(int i = 0; i < 19; i++){ matrix0 = round(matrix0); } matrix0 = add4x4(matrix0, matrix); return matrix0; } //XXX: ask if these things need to be switched for little/big endian stuff??? private static void initialize_matrix(int[] [] matrix, int keys[], int[] nonce, int[] block_counter) { // matrix[0] [0] = TAU[0]; // matrix[0] [1] = keys[0]; // matrix[0] [2] = keys[1]; // matrix[0] [3] = keys[2]; // matrix[1] [0] = keys[3]; // matrix[1] [1] = TAU [1]; // matrix[1] [2] = nounce[0]; // matrix[1] [3] = nounce[1]; // matrix[2] [0] = block_counter[0]; // matrix[2] [1] = block_counter[1]; // matrix[2] [2] = TAU[2]; // matrix[2] [3] = keys[4]; // matrix[3] [0] = keys[5]; // matrix[3] [1] = keys[6]; // matrix[3] [2] = keys[7]; // matrix[3] [3] = TAU[3]; for(int i = 0; i < 4; i++){ matrix[i][i] = SIGMA_32[i]; } matrix[1] [2] = nonce[0]; matrix[1] [3] = nonce[1]; matrix[2] [0] = block_counter[0]; matrix[2] [1] = block_counter[1]; matrix[0] [1] = keys[0]; matrix[0] [2] = keys[1]; matrix[0] [3] = keys[2]; matrix[1] [0] = keys[3]; matrix[2] [3] = keys[4]; matrix[3] [0] = keys[5]; matrix[3] [1] = keys[6]; matrix[3] [2] = keys[7]; } //this method increments nothing if all block positions are used. //XXX: ask if I should do the first one first? or the second?? // XXX CHECK THE C CODE!!!! //should it return null? or go back to the beginning? //are we including negative numbers in this as well?? private static void increment_bc(int[][] matrix){ // XXX need to fix this to use UNsigned ints not SIGNed ints if(matrix[2][0] < Integer.MAX_VALUE) matrix[2][0] += 1; else if(matrix[2][1] < Integer.MAX_VALUE) { matrix[2][0] = 0; matrix[2][1] += 1; } return; } /** * Performs 1 round of Salsa. * It is currently rolled up into methods for each * step so as to assist with future ChaCha algorithm. * Once we get this all working, it would be * good to unroll all the little steps into one method. */ //method, but it is going to be easier to do //ChaCha if we leave it separated.... private static int[][] round(int[][] matrix){ int[][] matrix0 = step1(matrix); step2(matrix0); step3(matrix0); step4(matrix0); matrix0 = transpose(matrix0); return matrix0; } private static int[][] step1(int[] [] matrix){ int[][] matrix0 = new int[4][4]; for(int i = 0; i < 4; i++){ matrix0[0][i] = matrix[0][i]; matrix0[1][i] = matrix[1][i]; matrix0[2][i] = matrix[2][i]; matrix0[3][i] = matrix[3][i]; int modify = i + 1; int input = matrix[(modify + 3) % 4][i] + matrix[(modify + 2) % 4][i]; input = rotateleft(input, 7); matrix0[modify % 4][i] = matrix[modify % 4][i] ^ input; } return matrix0; } private static void step2(int[] [] matrix){ for(int i =0; i < 4; i++){ int modify = i + 2; int input = matrix[(modify + 2) % 4][i] + matrix[(modify + 3) % 4][i]; input = rotateleft(input, 9); matrix[modify % 4][i] ^= input; } } private static void step3(int[] [] matrix){ for(int i =0; i < 4; i++){ int modify = i + 3; int input = matrix[(modify + 2) % 4][i] + matrix[(modify + 3) % 4][i]; input = rotateleft(input, 13); matrix[modify % 4][i] ^= input; } } private static void step4(int[] [] matrix){ for(int i =0; i < 4; i++){ int modify = i; int input = matrix[(modify + 2) % 4][i] + matrix[(modify + 3) % 4][i]; input = rotateleft(input, 18); matrix[modify % 4][i] ^= input; } } private static int[][] transpose(int[] [] matrix){ int [] [] matrix1 = new int[4][4]; for(int i =0; i < 4; i++){ for(int j = 0; j < 4; j++){ matrix1[j][i] = matrix[i][j]; } } return matrix1; } /** * Test the algorithm with the test vectors found in * the original paper. * For a wider test, see the Salsa20Test which tries * some of the ECRYPT test vectors. * @return a diag string that says "all ok". */ public static String selfTest(){ String s = "Salsa20: "; s += " " +baseTest(); int[][] matrix = testround1(testmatrix0); matrix = round(matrix); if(! eq4x4(matrix, testmatrixround2)) throw new RuntimeException(s+"\nround2 matrices are not equal\n" + matrix2string(matrix)+"\ntestmatrixround2\n"+matrix2string(testmatrixround2)); s += " Round2."; for(int i = 0; i <18; i++){ matrix = round(matrix); } if(! eq4x4(matrix, testmatrixround20)) throw new RuntimeException(s+"\nround20 matrices are not equal\n" + matrix2string(matrix)+"\ntestmatrixround20\n"+matrix2string(testmatrixround20)); s += " Round20."; matrix = salsa20(testmatrix0); if(! eq4x4(matrix, finaltestmatrix20)) throw new RuntimeException(s+"\nfinalround20 matrices are not equal\n" + matrix2string(matrix)+"\ntestmatrixfinal20\n"+matrix2string(finaltestmatrix20)); s += " Final."; s += " " + oroborousSalsa20(); return s; } private static int[][] testround1(int[][] matrix){ int[][] matrix0 = new int[4][4]; matrix0 = step1(matrix); if(! eq4x4(matrix0, testmatrix1)) throw new RuntimeException("matrix != testmatrix1"); step2(matrix0); if(! eq4x4(matrix0, testmatrix2)) throw new RuntimeException("matrix != testmatrix2"); step3(matrix0); if(! eq4x4(matrix0, testmatrix3)) throw new RuntimeException("matrix != testmatrix3"); step4(matrix0); if(! eq4x4(matrix0, testmatrix4)) throw new RuntimeException("matrix != testmatrix4\n" ); matrix0 = transpose(matrix0); if(! eq4x4(matrix0, testmatrix5)) throw new RuntimeException("matrix != testmatrix5"); return matrix0; } /** * These are the test matrices taken from the original paper. */ private static final int[][] testmatrix0 = { { 0x61707865, 0x04030201, 0x08070605, 0x0c0b0a09 }, { 0x100f0e0d, 0x3320646e, 0x01040103, 0x06020905 }, { 0x00000007, 0x00000000, 0x79622d32, 0x14131211 }, { 0x18171615, 0x1c1b1a19, 0x201f1e1d, 0x6b206574 } }; private static final int[][] testmatrix1 = { { 0x61707865, 0x04030201, 0x08070605, 0x95b0c8b6 }, { 0xd3c83331, 0x3320646e, 0x01040103, 0x06020905 }, { 0x00000007, 0x91b3379b, 0x79622d32, 0x14131211 }, { 0x18171615, 0x1c1b1a19, 0x130804a0, 0x6b206574 } }; private static final int[][] testmatrix2 = { { 0x61707865, 0x04030201, 0xdc64a31d, 0x95b0c8b6 }, { 0xd3c83331, 0x3320646e, 0x01040103, 0xa45e5d04 }, { 0x71572c6d, 0x91b3379b, 0x79622d32, 0x14131211 }, { 0x18171615, 0xbb230990, 0x130804a0, 0x6b206574 } }; private static final int[][] testmatrix3 = { { 0x61707865, 0xcc266b9b, 0xdc64a31d, 0x95b0c8b6 }, { 0xd3c83331, 0x3320646e, 0x95f3bcee, 0xa45e5d04 }, { 0x71572c6d, 0x91b3379b, 0x79622d32, 0xf0a45550 }, { 0xf3e4deb6, 0xbb230990, 0x130804a0, 0x6b206574 } }; private static final int[][] testmatrix4 = { { 0x4dfdec95, 0xcc266b9b, 0xdc64a31d, 0x95b0c8b6 }, { 0xd3c83331, 0xe78e794b, 0x95f3bcee, 0xa45e5d04 }, { 0x71572c6d, 0x91b3379b, 0xf94fe453, 0xf0a45550 }, { 0xf3e4deb6, 0xbb230990, 0x130804a0, 0xa272317e } }; private static final int[][] testmatrix5 = { { 0x4dfdec95, 0xd3c83331, 0x71572c6d, 0xf3e4deb6 }, { 0xcc266b9b, 0xe78e794b, 0x91b3379b, 0xbb230990 }, { 0xdc64a31d, 0x95f3bcee, 0xf94fe453, 0x130804a0 }, { 0x95b0c8b6, 0xa45e5d04, 0xf0a45550, 0xa272317e } }; private static final int[][] testmatrixround2 = { { 0xba2409b1, 0x1b7cce6a, 0x29115dcf, 0x5037e027 }, { 0x37b75378, 0x348d94c8, 0x3ea582b3, 0xc3a9a148 }, { 0x825bfcb9, 0x226ae9eb, 0x63dd7748, 0x7129a215 }, { 0x4effd1ec, 0x5f25dc72, 0xa6c3d164, 0x152a26d8 } }; private static final int[][] testmatrixround20 = { { 0x58318d3e, 0x0292df4f, 0xa28d8215, 0xa1aca723 }, { 0x697a34c7, 0xf2f00ba8, 0x63e9b0a1, 0x27250e3a }, { 0xb1c7f1f3, 0x62066edc, 0x66d3ccf1, 0xb0365cf3 }, { 0x091ad09e, 0x64f0c40f, 0xd60d95ea, 0x00be78c9 } }; private static final int[][] finaltestmatrix20 = { { 0xb9a205a3, 0x0695e150, 0xaa94881a, 0xadb7b12c }, { 0x798942d4, 0x26107016, 0x64edb1a4, 0x2d27173f }, { 0xb1c7f1fa, 0x62066edc, 0xe035fa23, 0xc4496f04 }, { 0x2131e6b3, 0x810bde28, 0xf62cb407, 0x6bdede3d } }; public static String oroborousSalsa20(){ for(int i = 0; i <100; i++){ byte[] key = Support.exampleData(32); byte[] nounce = Support.exampleData(8); int bc = 0; byte[] pt = Support.exampleData( Support.exampleInt(0, 1000) ); byte[] ct = new byte[pt.length]; byte[] pt2 = new byte[pt.length]; MySalsa20.crypto_stream_xor(ct, pt, pt.length, nounce, bc, key); Salsa20.crypto_stream_xor(pt2, ct, ct.length, nounce, bc, key); //public static int crypto_stream_xor(byte[] c, byte[] m, int mlen, byte[] n, int noffset, byte[] key) if(!X.ctEquals(pt, pt2)) throw new RuntimeException("they're not equal!!!"); } return "oroborous!"; } public static void main(String[] args){ System.out.println(selfTest()); } } //private static int rotateleft(int rotate, int how_much){ // how_much = how_much % 32; // int rotateL = rotate << how_much; // rotate >>>= (32 - how_much); // return rotate | rotateL; //} // ///* //* Test code. //*/ //private static boolean eq4x4(int[][]matrix0, int[][]matrix1){ // if(matrix0.length != matrix1.length) // return false; // for(int i = 0; i < matrix0.length; i++){ // if(matrix0[i].length != matrix1[i].length) // return false; // // for(int j = 0; j < matrix0[i].length; j++){ // if(matrix0[i][j] != matrix1[i][j]) // return false; // } // } // return true; //} // //private static int[][] add4x4(int[][]matrix0, int[][]matrix1){ // if((matrix0.length != 4) || ( matrix1.length != 4)) // throw new RuntimeException("lengths are not equal to 4"); // // int[] [] matrix = new int[4][4]; // // for(int i = 0; i < 4; i++){ // if((matrix0[i].length != 4) ||( matrix1[i].length != 4)) // throw new RuntimeException("lengths are not equal to 4"); // // for(int j = 0; j < 4; j++){ // matrix[i][j] = matrix0[i][j] + matrix1[i][j]; // } // // } // return matrix; //} // //private static String matrix2string(int[][] matrix){ // String s = ""; // for(int i = 0; i < matrix.length; i++){ // for(int j = 0; j < matrix[i].length; j++){ // s += " " + Integer.toHexString(matrix[i][j]); // } // s += "\n"; // } // return s; //} // ///** //* The original algorithm was optimised for Intel's small-endian //* architecture. As Java is big-endian (natural or network order) //* we need to convert it all in that way. //*/ //private static int bytes2littleendian(byte b0, byte b1, byte b2, byte b3){ // int i = ((BYTE_M & b3) << 24) | ((BYTE_M & b2) << 16) | ((BYTE_M & b1) << 8) | (BYTE_M & b0); // return i; //} // //private static byte[] littleendian2bytes(int littleEndian){ // byte[] b = new byte[4]; // for(int i = 0; i < 4; i++){ // b[i] = (byte) (BYTE_M & littleEndian); // littleEndian >>>= 8; // } // return b; //}
puts "What is your name?" name = gets.chomp puts "Hello #{name}!"
/* eslint-disable react/jsx-props-no-spreading */ import React from 'react'; import { makeStyles, createStyles } from '@material-ui/core'; interface TabPanelProps { children: React.ReactNode | undefined; index: number; value: number; className?: string; } const useStyles = makeStyles(() => createStyles({ list: { overflow: 'auto', height: '80vh', }, }) ); export default function TabPanel(props: TabPanelProps) { const { children, value, index, className, ...other } = props; const defaultClasses = useStyles(); return ( <div role="tabpanel" hidden={value !== index} id={`scrollable-force-tabpanel-${index}`} aria-labelledby={`scrollable-force-tab-${index}`} className={className ?? defaultClasses.list} {...other} > {value === index && children} </div> ); } TabPanel.defaultProps = { className: undefined, };
#!/bin/bash #SBATCH -J Act_sin_1 #SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de #SBATCH --mail-type=FAIL #SBATCH -e /work/scratch/se55gyhe/log/output.err.%j #SBATCH -o /work/scratch/se55gyhe/log/output.out.%j #SBATCH -n 1 # Number of cores #SBATCH --mem-per-cpu=6000 #SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins #module load intel python/3.5 python3 /home/se55gyhe/Act_func/sequence_tagging/arg_min/PE-my.py sin 273 sgd 4 0.16312535132334438 0.009162261522908643 orth 0.3
<filename>src/js/inline.js var INLINE_NS = 'inline', _hiddenClass, _inlinePlaceholder, _lastInlineElement, _putInlineElementsBack = function() { if(_lastInlineElement) { _inlinePlaceholder.after( _lastInlineElement.addClass(_hiddenClass) ).detach(); _lastInlineElement = null; } }; $.magnificPopup.registerModule(INLINE_NS, { options: { hiddenClass: 'hide', // will be appended with `mfp-` prefix markup: '<div class="mfp-inline-wrapper">'+ '<div class="mfp-header-wrapper">' + '<div class="mfp-file-name"></div>'+ '<div class = "mfp-extra-center">' + '<a class="mfp-download" target="_blank" download=""><i class="icon2-download"></i>下载</a>'+ '<label class = "mfp-update" for = "mfp-update-file"><input id = "mfp-update-file" type = "file" hide /><i class = "icon2-reload"></i>更新</label>' + '<button class="mfp-edit-minder"><i class="icon2-edit-tab"></i>编辑</button>'+ '<button class="mfp-edit-office"><i class="icon2-edit-tab"></i>编辑</button>'+ '</div>' + '<div class="mfp-close"></div>'+ '</div>'+ '<div class="mfp-inline"></div>'+ '</div>', tNotFound: 'Content not found' }, proto: { initInline: function() { mfp.types.push(INLINE_NS); _mfpOn(CLOSE_EVENT+'.'+INLINE_NS, function() { _putInlineElementsBack(); }); }, getInline: function(item, template) { _putInlineElementsBack(); $('.mfp-file-name', template).html(item.fileName); $('.mfp-download', template).attr('href', item.downloadUrl); if(item.src) { var inlineSt = mfp.st.inline, el = $(item.src); if(el.length) { el.addClass('mfp-inline'); // If target element has parent - we replace it with placeholder and put it back after popup is closed // var parent = el[0].parentNode; // if(parent && parent.tagName) { // if(!_inlinePlaceholder) { // _hiddenClass = inlineSt.hiddenClass; // _inlinePlaceholder = _getEl(_hiddenClass); // _hiddenClass = 'mfp-'+_hiddenClass; // } // // replace target inline element with placeholder // _lastInlineElement = el.after(_inlinePlaceholder).detach().removeClass(_hiddenClass); // } // mfp.updateStatus('ready'); } else { mfp.updateStatus('error', inlineSt.tNotFound); el = $('<div>'); } // template.find('.mfp-inline').append(el); item.inlineElement = el; // return template; } mfp.updateStatus('ready'); mfp._parseMarkup(template, { inline_replaceWith: item.inlineElement }, item); return template; } } });
<gh_stars>0 package info.tritusk.adventure.platform.forge.impl.audience; import info.tritusk.adventure.platform.forge.impl.AdventureBookInfo; import info.tritusk.adventure.platform.forge.impl.ComponentWrapper; import info.tritusk.adventure.platform.forge.impl.KeyMapper; import info.tritusk.adventure.platform.forge.impl.SoundMapper; import java.util.function.Function; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.MessageType; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.inventory.Book; import net.kyori.adventure.sound.Sound; import net.kyori.adventure.sound.SoundStop; import net.kyori.adventure.text.Component; import net.kyori.adventure.title.Title; import net.kyori.adventure.util.Ticks; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.gui.screen.ReadBookScreen; import net.minecraft.network.play.server.SUpdateBossInfoPacket; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.BossInfo; import org.jetbrains.annotations.NotNull; public class ClientAudience implements Audience { private final Function<BossBar, ? extends BossInfo> bossBarMapper; public ClientAudience(Function<BossBar, ? extends BossInfo> bossBarMapper) { this.bossBarMapper = bossBarMapper; } @Override public void sendMessage(final @NotNull Identity source, final @NotNull Component message, final @NotNull MessageType type) { final ClientPlayerEntity p = Minecraft.getInstance().player; if (p != null) { p.sendMessage(new TranslationTextComponent("chat.type.text", source.examinableName(), message), source.uuid()); } } @Override public void sendActionBar(@NotNull Component message) { Minecraft.getInstance().gui.setOverlayMessage(new ComponentWrapper(message), false); } @Override public void sendPlayerListHeader(@NotNull Component header) { Minecraft.getInstance().gui.getTabList().setHeader(new ComponentWrapper(header)); } @Override public void sendPlayerListFooter(@NotNull Component footer) { Minecraft.getInstance().gui.getTabList().setFooter(new ComponentWrapper(footer)); } @Override public void sendPlayerListHeaderAndFooter(@NotNull Component header, @NotNull Component footer) { this.sendPlayerListHeader(header); this.sendPlayerListFooter(footer); } @Override public void showTitle(@NotNull Title title) { Title.Times titleTimes = title.times(); if (titleTimes == null) { // How are you suppose to handle this case anyway? this.clearTitle(); } else { Minecraft.getInstance().gui.setTitles(new ComponentWrapper(title.title()), new ComponentWrapper(title.subtitle()), (int) (titleTimes.fadeIn().toMillis() / Ticks.SINGLE_TICK_DURATION_MS), (int) (titleTimes.stay().toMillis() / Ticks.SINGLE_TICK_DURATION_MS), (int) (titleTimes.fadeOut().toMillis() / Ticks.SINGLE_TICK_DURATION_MS)); } } @Override public void clearTitle() { Minecraft.getInstance().gui.setTitles(null, null, 0, 0, 0); } @Override public void resetTitle() { Minecraft.getInstance().gui.resetTitleTimes(); } @Override public void showBossBar(@NotNull BossBar bar) { final BossInfo nativeBossBar = this.bossBarMapper.apply(bar); final SUpdateBossInfoPacket fakePacket = new SUpdateBossInfoPacket(SUpdateBossInfoPacket.Operation.ADD, nativeBossBar); Minecraft.getInstance().gui.getBossOverlay().update(fakePacket); // Trick Minecraft to add a new boss bar wtf } @Override public void hideBossBar(@NotNull BossBar bar) { final BossInfo nativeBossBar = this.bossBarMapper.apply(bar); final SUpdateBossInfoPacket fakePacket = new SUpdateBossInfoPacket(SUpdateBossInfoPacket.Operation.REMOVE, nativeBossBar); Minecraft.getInstance().gui.getBossOverlay().update(fakePacket); // Trick Minecraft to remove a new boss bar wtf } @Override public void playSound(@NotNull Sound sound) { final ClientPlayerEntity p = Minecraft.getInstance().player; if (p == null) { Minecraft.getInstance().getSoundManager().play(SoundMapper.toNative(sound)); } else { this.playSound(sound, p.getX(), p.getY(), p.getZ()); } } @Override public void playSound(@NotNull Sound sound, double x, double y, double z) { Minecraft.getInstance().getSoundManager().play(SoundMapper.toNative(sound, x, y, z, true)); } @Override public void stopSound(@NotNull SoundStop stop) { Minecraft.getInstance().getSoundManager().stop(KeyMapper.toNative(stop.sound()), SoundMapper.toNative(stop.source())); } @Override public void openBook(@NotNull Book book) { Minecraft.getInstance().setScreen(new ReadBookScreen(new AdventureBookInfo(book))); } }
from django import forms from .models import SubjectGrade class UpdateSubjectGrade(forms.ModelForm): class Meta: model = SubjectGrade fields = ['final_grade', 'is_finalized']
#!/usr/bin/env bash # Copyright 2016 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This script is a vestigial redirection. Please do not add "real" logic. set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname "${BASH_SOURCE}")/.. # For help output ARGHELP="" if [[ "$#" -gt 0 ]]; then ARGHELP="WHAT='$@'" fi echo "NOTE: $0 has been replaced by 'make test'" echo echo "The equivalent of this invocation is: " echo " make test ${ARGHELP}" echo echo make --no-print-directory -C "${KUBE_ROOT}" test WHAT="$*"
#!/usr/bin/env bash if [ "$(whoami)" != "root" ]; then echo "Root privileges required" exit 1 fi MNT=/tmp/mnt umount ${MNT}/usr/local umount ${MNT}/opt umount ${MNT}/srv umount ${MNT}/tmp umount ${MNT}/root umount ${MNT}/var umount ${MNT}/boot umount ${MNT}/home umount ${MNT}/efi umount ${MNT}
package org.rzo.netty.ahessian.application.file.remote.service; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanRegistration; import javax.management.MBeanRegistrationException; import javax.management.NotCompliantMBeanException; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.QueryExp; import javax.management.ReflectionException; public interface AsyncFileService { public FileObject getFile(String file); public List<FileObject> list(String filter); public InputStream getInputStream(String file); }
<filename>src/components/Tools/TrafficAnalysis.js import React, { useEffect, useState, useRef } from "react"; import BootstrapTable from "react-bootstrap-table-next"; import GetApiKey from "../../GetApiKey.js"; import SkeletonTable from "../SkeletonTable"; import ToolkitProvider, { Search, CSVExport, } from "react-bootstrap-table2-toolkit"; import paginationFactory from "react-bootstrap-table2-paginator"; import "react-bootstrap-table-next/dist/react-bootstrap-table2.min.css"; import "react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit.min.css"; import "react-bootstrap-table2-paginator/dist/react-bootstrap-table2-paginator.min.css"; import Select from "react-select"; export default function TrafficAnalysis(ac) { const [showtable, setshowtable] = useState(false); const [trigger, settrigger] = useState(0); const [switchTimeInterval, setswitchTimeInterval] = useState(7200); const [switchDeviceType, setswitchDeviceType] = useState("combined"); // eslint-disable-next-line const [netwanalysis, setnetwanalysis] = useState([]); const [dataInventory, setdataInventory] = useState([]); const [loading, setloading] = useState(false); const { SearchBar } = Search; const { ExportCSVButton } = CSVExport; let callApikey = GetApiKey(ac.dc.User, ac.dc.isSignedIn); let apiKey = callApikey.apikey.current; const APIbody = { "X-Cisco-Meraki-API-Key": `${apiKey}`, DEV_TYPE: switchDeviceType, NET_ID: `${ac.dc.networkID}`, TIME_SPAN: switchTimeInterval, }; const time_interval = [ { time: "2 hours", seconds: 7200 }, { time: "8 hours", seconds: 28800 }, { time: "1 day", seconds: 86400 }, { time: "7 days", seconds: 604800 }, { time: "1 month", seconds: 2592000 }, ]; const TIMEINTERVAL = time_interval.map((opt, index) => ({ label: opt.time, index: index, })); const selectTimeInterval = (opt) => { if (opt === null) { setswitchTimeInterval(7200); } else if (opt.index === 1) { setswitchTimeInterval(28800); } else if (opt.index === 2) { setswitchTimeInterval(86400); } else if (opt.index === 3) { setswitchTimeInterval(604800); } else if (opt.index === 4) { setswitchTimeInterval(2592000); } }; const device_type = [ { device: "Combined" }, { device: "Wireless" }, { device: "Switch" }, { device: "Appliance" }, ]; const DEVICETYPE = device_type.map((opt, index) => ({ label: opt.device, index: index, })); const selectDeviceType = (opt) => { if (opt === null) { setswitchDeviceType("combined"); } else if (opt.index === 1) { setswitchDeviceType("wireless"); } else if (opt.index === 2) { setswitchDeviceType("switch"); } else if (opt.index === 3) { setswitchDeviceType("appliance"); } }; const handleTopUsers = (e) => { e.preventDefault(); settrigger(trigger + 1); if (trigger > 3) { settrigger(0); ac.dc.setflashMessages(null); } }; const isFirstRun = useRef(true); useEffect(() => { const abortController = new AbortController(); const signal = abortController.signal; if (isFirstRun.current) { isFirstRun.current = false; return; } async function APIcall() { if (ac.dc.isOrgSelected && ac.dc.isNetSelected === true) { if (trigger < 4) { try { setloading(true); fetch("/flask/traffic_analysis/", { method: ["POST"], cache: "no-cache", headers: { content_type: "application/json", }, body: JSON.stringify(APIbody), }).then((response) => { return response.json; }); fetch("/flask/traffic_analysis/", { signal: signal }) .then((res) => { return res.json(); }) .then((data) => { if (data.error) { setshowtable(false); ac.dc.setflashMessages( <div className="form-input-error-msg alert alert-danger"> <span className="glyphicon glyphicon-exclamation-sign"></span> {data.error[0]} </div> ); setloading(false); } else { setnetwanalysis(data.analysis); let R1 = []; let deviceData = []; // eslint-disable-next-line data.analysis.map((item) => { let randomKey = Math.random().toString(36).substring(2, 15); var rowModel = { application: item.application, destination: item.destination, protocol: item.protocol, port: item.port, sent: item.sent, recv: item.recv, flows: item.flows, activeTime: item.activeTime, numClients: item.numClients, key: randomKey, }; R1.push(rowModel); deviceData.push(rowModel); setdataInventory({ ...columns, rows: R1 }); }); } }) .then(() => { if (dataInventory.length !== 0) { setshowtable(true); } setloading(false); }); } catch (err) { if (err) { console.log("This is the error:", err); setloading(false); } } } else { setloading(false); } } else { ac.dc.setswitchAlertModal(true); ac.dc.setAlertModalError("Please set Organization and Network."); ac.dc.setswitchToolsTemplate(false); } } APIcall(); return () => { abortController.abort(); setnetwanalysis([]); setshowtable(false); ac.dc.setflashMessages(null); setloading(false); }; // eslint-disable-next-line }, [trigger]); const columns = [ { dataField: "application", text: "Application", editable: false, key: "application", sort: true, headerStyle: (colum, colIndex) => { return { textAlign: "center" }; }, }, { dataField: "destination", text: "Destination", editable: false, key: "destination", sort: true, headerStyle: (colum, colIndex) => { return { textAlign: "center" }; }, }, { dataField: "protocol", text: "Protocol", editable: false, key: "protocol", sort: true, headerStyle: (colum, colIndex) => { return { textAlign: "center" }; }, }, { dataField: "port", text: "Port", editable: false, key: "port", sort: true, headerStyle: (colum, colIndex) => { return { textAlign: "center" }; }, }, { dataField: "sent", text: "Sent (Kb)", editable: false, key: "sent", sort: true, headerStyle: (colum, colIndex) => { return { textAlign: "center" }; }, }, { dataField: "recv", text: "Received (Kb)", editable: false, key: "recv", sort: true, headerStyle: (colum, colIndex) => { return { textAlign: "center" }; }, }, { dataField: "flows", text: "Flows", editable: false, key: "flows", sort: true, headerStyle: (colum, colIndex) => { return { textAlign: "center" }; }, }, { dataField: "activeTime", text: "Active Time (sec)", editable: false, key: "activeTime", sort: true, headerStyle: (colum, colIndex) => { return { textAlign: "center" }; }, }, { dataField: "numClients", text: "Clients", editable: false, key: "numClients", sort: true, headerStyle: (colum, colIndex) => { return { textAlign: "center" }; }, }, { dataField: "key", text: "key", editable: false, hidden: "true", }, ]; const Paginationoptions = { paginationSize: 4, pageStartIndex: 0, // alwaysShowAllBtns: true, // Always show next and previous button // withFirstAndLast: false, // Hide the going to First and Last page button // hideSizePerPage: true, // Hide the sizePerPage dropdown always // hidePageListOnlyOnePage: true, // Hide the pagination list when only one page firstPageText: "First", prePageText: "Back", nextPageText: "Next", lastPageText: "Last", nextPageTitle: "First page", prePageTitle: "Pre page", firstPageTitle: "Next page", lastPageTitle: "Last page", showTotal: true, disablePageTitle: true, sizePerPageList: [ { text: "10", value: 10, }, { text: "25", value: 25, }, { text: "50", value: 50, }, { text: "100", value: 100, }, { text: "250", value: 250, }, { text: "500", value: 500, }, { text: "1000", value: 1000, }, { text: "All", ...(showtable ? { value: dataInventory.rows.length } : { value: 100 }), }, ], }; return ( <div id="page-inner-main-templates"> <div className="row"> <div className="col-xs-12"> <div className="panel panel-default"> <div className="panel-body"> <div className="panel-group" id="accordion"> <div className="panel panel-default"> <div className="panel-heading"> <h4 className="panel-title-description"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" className="collapsed" > <span className="glyphicon glyphicon-info-sign"></span> </a> </h4> </div> <div id="collapseOne" className="panel-collapse collapse"> <div className="panel-body"> <dl> <dt> This script aggregates all of the detected applications for a given time frame or device type. </dt> <dt> Time frame options for hourly, weekly, daily and monthly are available. </dt> <dt> Device type options for combined, switch, wireless and appliance are available(default combined). </dt> </dl> </div> </div> </div> </div> </div> <div className="panel-body"> <form className="form-inline"> <div className="form-group"> <Select className="select_network_change-log" options={TIMEINTERVAL} placeholder="Select Interval" onChange={selectTimeInterval} classNamePrefix="time-interval" isClearable={true} /> </div> <div className="form-group"> <Select className="select_network_change-log" options={DEVICETYPE} placeholder="Device type" onChange={selectDeviceType} classNamePrefix="time-interval" isClearable={true} /> </div> </form> <button id="runButton" className="btn btn-primary" onClick={!loading ? handleTopUsers : null} disabled={loading} > {loading && ( <i className="fa fa-refresh fa-spin" style={{ marginRight: "5px" }} /> )} {loading && <span>Loading Data</span>} {!loading && <span>RUN</span>} </button> </div> </div> </div> </div> <div className="row"> <div className="col-xs-12"> <div className="panel panel-default"> {showtable ? ( <div> <div className="panel-body"> <div className="bootstrap-table-panel"> <ToolkitProvider search keyField="key" data={dataInventory.rows} columns={columns} > {(props) => ( <div> <SearchBar style={{ width: "299px" }} {...props.searchProps} /> <ExportCSVButton className="export-csv" {...props.csvProps} > Export CSV </ExportCSVButton> <BootstrapTable {...props.baseProps} striped hover pagination={paginationFactory(Paginationoptions)} /> </div> )} </ToolkitProvider> </div> </div> </div> ) : ( <div> <div>{loading ? <SkeletonTable /> : <div></div>}</div> </div> )} </div> </div> </div> </div> ); }
<reponame>kallsave/vue-router-cache<gh_stars>10-100 import { hasData, } from '@/common/helpers/dom.js' export default { mounted() { this.addEventListenerFocus() this.addEventListenerBlur() }, methods: { addEventListenerFocus() { this.$el.addEventListener('focus', this.cacheScrollTop, true) }, addEventListenerBlur() { this.$el.addEventListener('blur', this.recoverScrollTop, true) }, removeEventListenerFocus() { this.$el.removeEventListener('focus', this.cacheScrollTop, true) }, removeEventListenerBlur() { this.$el.removeEventListener('blur', this.recoverScrollTop, true) }, cacheScrollTop() { this.scrollTop = document.documentElement.scrollTop || document.body.scrollTop }, recoverScrollTop(event) { const target = event.target const tagNameList = ['INPUT', 'TEXTAREA'] const isNoRollback = hasData(target, 'no-rollback') if (tagNameList.indexOf(target.tagName) !== -1 && !isNoRollback) { window.scrollTo({ top: this.scrollTop, }) } }, }, beforeDestroy() { this.removeEventListenerFocus() this.removeEventListenerBlur() } }
#!/usr/bin/env bash # Run all of our tests in this repository robot -d results tests
package register import ( api "Open_IM/pkg/base_info" "Open_IM/pkg/common/config" "Open_IM/pkg/common/constant" "Open_IM/pkg/common/db" "Open_IM/pkg/common/db/mysql_model/im_mysql_model" http2 "Open_IM/pkg/common/http" "Open_IM/pkg/common/log" "Open_IM/pkg/utils" "encoding/json" "fmt" "github.com/gin-gonic/gin" "net/http" ) type ParamsSetPassword struct { Email string `json:"email"` Name string `json:"name"` PhoneNumber string `json:"phoneNumber"` Password string `json:"password"` VerificationCode string `json:"verificationCode"` Platform int32 `json:"platform" binding:"required,min=1,max=7"` Ex string `json:"ex"` OperationID string `json:"operationID" binding:"required"` } func SetPassword(c *gin.Context) { params := ParamsSetPassword{} if err := c.BindJSON(&params); err != nil { log.NewError(params.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error()) c.JSON(http.StatusBadRequest, gin.H{"errCode": constant.FormattingError, "errMsg": err.Error()}) return } var account string if params.Email != "" { account = params.Email } else { account = params.PhoneNumber } if params.Name == "" { params.Name = account } if params.VerificationCode != config.Config.Demo.SuperCode { accountKey := account + "_" + constant.VerificationCodeForRegisterSuffix v, err := db.DB.GetAccountCode(accountKey) if err != nil || v != params.VerificationCode { log.NewError(params.OperationID, "password Verification code error", account, params.VerificationCode) data := make(map[string]interface{}) data["PhoneNumber"] = account c.JSON(http.StatusOK, gin.H{"errCode": constant.CodeInvalidOrExpired, "errMsg": "Verification code error!", "data": data}) return } } url := fmt.Sprintf("http://%s:10000/auth/user_register", utils.ServerIP) openIMRegisterReq := api.UserRegisterReq{} openIMRegisterReq.OperationID = params.OperationID openIMRegisterReq.Platform = params.Platform openIMRegisterReq.UserID = account openIMRegisterReq.Nickname = params.Name openIMRegisterReq.Secret = config.Config.Secret openIMRegisterResp := api.UserRegisterResp{} bMsg, err := http2.Post(url, openIMRegisterReq, config.Config.MessageCallBack.CallBackTimeOut) if err != nil { log.NewError(params.OperationID, "request openIM register error", account, "err", err.Error()) c.JSON(http.StatusOK, gin.H{"errCode": constant.RegisterFailed, "errMsg": err.Error()}) return } err = json.Unmarshal(bMsg, &openIMRegisterResp) if err != nil || openIMRegisterResp.ErrCode != 0 { log.NewError(params.OperationID, "request openIM register error", account, "err", "resp: ", openIMRegisterResp.ErrCode) if err != nil { log.NewError(params.OperationID, utils.GetSelfFuncName(), err.Error()) } c.JSON(http.StatusOK, gin.H{"errCode": constant.RegisterFailed, "errMsg": "register failed: " + openIMRegisterResp.ErrMsg}) return } log.Info(params.OperationID, "begin store mysql", account, params.Password) err = im_mysql_model.SetPassword(account, params.Password, params.Ex) if err != nil { log.NewError(params.OperationID, "set phone number password error", account, "err", err.Error()) c.JSON(http.StatusOK, gin.H{"errCode": constant.RegisterFailed, "errMsg": err.Error()}) return } log.Info(params.OperationID, "end setPassword", account, params.Password) c.JSON(http.StatusOK, gin.H{"errCode": constant.NoError, "errMsg": "", "data": openIMRegisterResp.UserToken}) return }
class Span: def __init__(self, service, name, resource, span_type, error): self.service = service self.name = name self.resource = resource self.span_type = span_type self.error = error def validate_spans(spans): for span in spans: assert span.service == 'flask', "Service attribute should be 'flask'" req_span = spans[0] assert req_span.service == 'flask', "Service attribute should be 'flask'" assert req_span.name == 'flask.request', "Name attribute should be 'flask.request'" assert req_span.resource == 'GET /501', "Resource attribute should be 'GET /501'" assert req_span.span_type == 'web', "Span type attribute should be 'web'" assert req_span.error == 1, "Error attribute should be 1" # Test the function with example spans spans = [ Span('flask', 'flask.request', 'GET /501', 'web', 1), Span('flask', 'flask.request', 'POST /user', 'web', 0), Span('flask', 'flask.request', 'GET /404', 'web', 1) ] validate_spans(spans) # Should not raise any exceptions
package main import ( _ "embed" "text/template" ) type Basic struct{} //go:embed basic.tmd var TplBasic string func (Basic) Template() *template.Template { t, _ := template.New("templatePFI").Parse(TplBasic) return t }
COLOR_GIT_CLEAN='\[\033[1;30m\]' COLOR_GIT_MODIFIED='\[\033[0;33m\]' COLOR_GIT_STAGED='\[\033[0;36m\]' COLOR_RESET='\[\033[0m\]' function git_prompt() { if [ -e ".git" ]; then branch_name=$(git symbolic-ref -q HEAD) branch_name=${branch_name##refs/heads/} branch_name=${branch_name:-HEAD} echo -n "→ " if [[ $(git status 2> /dev/null | tail -n1) = *"nothing to commit"* ]]; then echo -n "$COLOR_GIT_CLEAN$branch_name$COLOR_RESET" elif [[ $(git status 2> /dev/null | head -n5) = *"Changes to be committed"* ]]; then echo -n "$COLOR_GIT_STAGED$branch_name$COLOR_RESET" else echo -n "$COLOR_GIT_MODIFIED$branch_name*$COLOR_RESET" fi echo -n " " fi }
#!/bin/bash cd ./bin/ ./CreateEntry $* cd ..
<reponame>dyscalculia94/AdventOfCode2021<filename>src/day14.cpp #include "day14.h" #include <vector> #include <fstream> #include <algorithm> #include <unordered_map> #include <iostream> using Input = std::pair<std::string, std::unordered_map<std::string, char>>; namespace { Input read_input(std::string filename) { Input res; std::ifstream in(filename); std::string polymer; in >> polymer; std::unordered_map<std::string, char> map; while (!in.eof()) { std::string pair, temp; in >> pair >> temp; map[pair] = temp[0]; } return {polymer, map}; } long long task1(Input input) { long long result = 0; std::unordered_map<std::string, long long> counts; auto map = input.second; std::string polymer = input.first; for (int i = 0; i < polymer.length() - 1; i++) { std::string pair = std::string() + polymer[i] + polymer[i + 1]; counts[pair]++; } for (int i = 0; i < 10; i++) { std::unordered_map<std::string, long long> next_counts; for (auto pair : counts) { char c = map[pair.first]; std::string next_pair1 = std::string() + pair.first[0] + c; std::string next_pair2 = std::string() + c + pair.first[1]; next_counts[next_pair1] += pair.second; next_counts[next_pair2] += pair.second; } counts = next_counts; } std::array<long long, 26> letters = {0}; for (auto pair : counts) { letters[pair.first[0] - 'A'] += pair.second; letters[pair.first[1] - 'A'] += pair.second; } letters[polymer.front() - 'A']++; letters[polymer.back() - 'A']++; long long min = letters[polymer.front() - 'A']; long long max = 0; for (auto& i : letters) { i /= 2; if (i && i < min) { min = i; } max = std::max(max, i); } result = max - min; return result; } long long task2(Input input) { long long result = 0; std::unordered_map<std::string, long long> counts; auto map = input.second; std::string polymer = input.first; for (int i = 0; i < polymer.length() - 1; i++) { std::string pair = std::string() + polymer[i] + polymer[i + 1]; counts[pair]++; } for (int i = 0; i < 40; i++) { std::unordered_map<std::string, long long> next_counts; for (auto pair : counts) { char c = map[pair.first]; std::string next_pair1 = std::string() + pair.first[0] + c; std::string next_pair2 = std::string() + c + pair.first[1]; next_counts[next_pair1] += pair.second; next_counts[next_pair2] += pair.second; } counts = next_counts; } std::array<long long, 26> letters = {0}; for (auto pair : counts) { letters[pair.first[0] - 'A'] += pair.second; letters[pair.first[1] - 'A'] += pair.second; } letters[polymer.front() - 'A']++; letters[polymer.back() - 'A']++; long long min = letters[polymer.front() - 'A']; long long max = 0; for (auto& i : letters) { i /= 2; if (i && i < min) { min = i; } max = std::max(max, i); } result = max - min; return result; } } std::pair<long long, long long> day14(std::string filedir) { Input input = read_input(filedir + "/day14.txt"); long long first = task1(input); long long second = task2(input); return {first, second}; }
import { Directive, HostBinding, Input } from '@angular/core'; @Directive({ // tslint:disable-next-line selector: '[toggler]' }) export class ToggleDirective { // @HostBinding('attr.role') get role() { return 'switch' }; @HostBinding('attr.role') role = 'switch'; @HostBinding('attr.aria-checked') @Input() on; constructor() {} }
<filename>hexo_GUI/GeneratedFiles/ui_hexo_GUI.h /******************************************************************************** ** Form generated from reading UI file 'hexo_GUI.ui' ** ** Created by: Qt User Interface Compiler version 5.9.6 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_HEXO_GUI_H #define UI_HEXO_GUI_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHeaderView> #include <QtWidgets/QListView> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenu> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QTabWidget> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_hexo_GUIClass { public: QWidget *centralWidget; QTabWidget *functional_area; QWidget *blog_area; QPushButton *up_button; QPushButton *tsst_button; QWidget *article_area; QPushButton *new_blog_button; QListView *listView; QWidget *configure_area; QPushButton *open_local_button; QPushButton *theme_y_button; QPushButton *hexo_y_button; QPushButton *ssh_button; QPushButton *button_to_blog; QPushButton *button_to_article; QPushButton *button_to_configuration; QMenuBar *menuBar; QMenu *menu; QMenu *menu_2; void setupUi(QMainWindow *hexo_GUIClass) { if (hexo_GUIClass->objectName().isEmpty()) hexo_GUIClass->setObjectName(QStringLiteral("hexo_GUIClass")); hexo_GUIClass->resize(482, 470); centralWidget = new QWidget(hexo_GUIClass); centralWidget->setObjectName(QStringLiteral("centralWidget")); functional_area = new QTabWidget(centralWidget); functional_area->setObjectName(QStringLiteral("functional_area")); functional_area->setGeometry(QRect(130, 10, 341, 421)); blog_area = new QWidget(); blog_area->setObjectName(QStringLiteral("blog_area")); up_button = new QPushButton(blog_area); up_button->setObjectName(QStringLiteral("up_button")); up_button->setGeometry(QRect(30, 60, 71, 28)); tsst_button = new QPushButton(blog_area); tsst_button->setObjectName(QStringLiteral("tsst_button")); tsst_button->setGeometry(QRect(30, 100, 71, 28)); functional_area->addTab(blog_area, QString()); article_area = new QWidget(); article_area->setObjectName(QStringLiteral("article_area")); new_blog_button = new QPushButton(article_area); new_blog_button->setObjectName(QStringLiteral("new_blog_button")); new_blog_button->setGeometry(QRect(70, 30, 101, 28)); listView = new QListView(article_area); listView->setObjectName(QStringLiteral("listView")); listView->setGeometry(QRect(50, 80, 256, 301)); functional_area->addTab(article_area, QString()); configure_area = new QWidget(); configure_area->setObjectName(QStringLiteral("configure_area")); open_local_button = new QPushButton(configure_area); open_local_button->setObjectName(QStringLiteral("open_local_button")); open_local_button->setGeometry(QRect(20, 80, 151, 28)); theme_y_button = new QPushButton(configure_area); theme_y_button->setObjectName(QStringLiteral("theme_y_button")); theme_y_button->setGeometry(QRect(40, 50, 111, 28)); hexo_y_button = new QPushButton(configure_area); hexo_y_button->setObjectName(QStringLiteral("hexo_y_button")); hexo_y_button->setGeometry(QRect(70, 210, 131, 28)); ssh_button = new QPushButton(configure_area); ssh_button->setObjectName(QStringLiteral("ssh_button")); ssh_button->setGeometry(QRect(50, 300, 93, 28)); functional_area->addTab(configure_area, QString()); button_to_blog = new QPushButton(centralWidget); button_to_blog->setObjectName(QStringLiteral("button_to_blog")); button_to_blog->setGeometry(QRect(20, 100, 93, 28)); button_to_article = new QPushButton(centralWidget); button_to_article->setObjectName(QStringLiteral("button_to_article")); button_to_article->setGeometry(QRect(20, 200, 93, 28)); button_to_configuration = new QPushButton(centralWidget); button_to_configuration->setObjectName(QStringLiteral("button_to_configuration")); button_to_configuration->setGeometry(QRect(20, 310, 93, 28)); hexo_GUIClass->setCentralWidget(centralWidget); menuBar = new QMenuBar(hexo_GUIClass); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 482, 26)); menu = new QMenu(menuBar); menu->setObjectName(QStringLiteral("menu")); menu_2 = new QMenu(menuBar); menu_2->setObjectName(QStringLiteral("menu_2")); hexo_GUIClass->setMenuBar(menuBar); menuBar->addAction(menu->menuAction()); menuBar->addAction(menu_2->menuAction()); retranslateUi(hexo_GUIClass); functional_area->setCurrentIndex(2); QMetaObject::connectSlotsByName(hexo_GUIClass); } // setupUi void retranslateUi(QMainWindow *hexo_GUIClass) { hexo_GUIClass->setWindowTitle(QApplication::translate("hexo_GUIClass", "hexo_GUI", Q_NULLPTR)); up_button->setText(QApplication::translate("hexo_GUIClass", "\344\270\212\344\274\240\345\215\232\345\256\242", Q_NULLPTR)); tsst_button->setText(QApplication::translate("hexo_GUIClass", "\346\265\213\350\257\225\345\215\232\345\256\242", Q_NULLPTR)); functional_area->setTabText(functional_area->indexOf(blog_area), QApplication::translate("hexo_GUIClass", "\345\215\232\345\256\242", Q_NULLPTR)); new_blog_button->setText(QApplication::translate("hexo_GUIClass", "\345\210\233\345\273\272\346\226\260\347\232\204\345\215\232\345\256\242", Q_NULLPTR)); functional_area->setTabText(functional_area->indexOf(article_area), QApplication::translate("hexo_GUIClass", "\345\215\232\346\226\207", Q_NULLPTR)); open_local_button->setText(QApplication::translate("hexo_GUIClass", "\346\234\254\345\234\260\346\211\223\345\274\200hexo\346\226\207\344\273\266\345\244\271", Q_NULLPTR)); theme_y_button->setText(QApplication::translate("hexo_GUIClass", "\346\237\245\347\234\213theme\346\226\207\344\273\266", Q_NULLPTR)); hexo_y_button->setText(QApplication::translate("hexo_GUIClass", "\346\237\245\347\234\213hexo\346\240\267\345\274\217\346\226\207\344\273\266", Q_NULLPTR)); ssh_button->setText(QApplication::translate("hexo_GUIClass", "\346\237\245\347\234\213SSH\345\257\206\351\222\245", Q_NULLPTR)); functional_area->setTabText(functional_area->indexOf(configure_area), QApplication::translate("hexo_GUIClass", "\351\205\215\347\275\256", Q_NULLPTR)); button_to_blog->setText(QApplication::translate("hexo_GUIClass", "\345\215\232\345\256\242", Q_NULLPTR)); button_to_article->setText(QApplication::translate("hexo_GUIClass", "\345\215\232\346\226\207", Q_NULLPTR)); button_to_configuration->setText(QApplication::translate("hexo_GUIClass", "\351\205\215\347\275\256", Q_NULLPTR)); menu->setTitle(QApplication::translate("hexo_GUIClass", "\350\256\276\347\275\256", Q_NULLPTR)); menu_2->setTitle(QApplication::translate("hexo_GUIClass", "\345\205\263\344\272\216", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class hexo_GUIClass: public Ui_hexo_GUIClass {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_HEXO_GUI_H
for f in $(ls *.png) do convert $f -fx '(r+g+b)/3' -colorspace Gray $f done;
/* eslint-disable no-async-promise-executor */ const bcrypt = require('bcryptjs') const { pool } = require('../database') const { sendEmail } = require('../utils') const otplib = require('otplib') /** * * @param {*} param0 * @param {String} param0.username * @param {String} param0.password * @param {String} param0.full_name * @param {String} param0.admission_number * @param {String} param0.email * @param {String} param0.admission_year * @param {Number} param0.department * @param {Number} param0.course * @return {Promise} * */ function signup({ username, password, full_name: fullName, admission_number: admissionNumber, email, admission_year: admissionYear, department, course, }) { return new Promise(async (resolve, reject) => { bcrypt.genSalt(parseInt(process.env.SALT_ROUNDS), (error, salt) => { if (error) { return reject(error) } bcrypt.hash(password, salt, (error, hash) => { if (error) { return reject(error) } const secretOtp = otplib.authenticator.generateSecret() const otp = otplib.authenticator.generate(secretOtp) pool.query( `INSERT INTO users (username,secret,full_name,admission_number,email,admission_year,department,course,otp,otp_valid_upto) VALUES(?,?,?,?,?,?,?,?,?,NOW()+INTERVAL 1 DAY)`, [ username, hash, fullName, admissionNumber, email, admissionYear, department, course, otp, ], (error) => { if (error) { if (error.code === 'ER_DUP_ENTRY') { return reject( `A user with this username '${username}' already exists.` ) } return reject(error) } const subject = 'Email verification' const port = process.env.FRONTEND_PORT || 3000 const host = process.env.FRONTEND_HOST || 'localhost' const html = emailMessage(fullName, otp, port, host, username) sendEmail(email, subject, html) return resolve( 'Account created. Please activate your account using the OTP sent to your email address.' ) } ) }) }) }) } const emailMessage = (fullName, otp, port, host, username) => { return `<p>Hello ${fullName} !</p> <p>The OTP for verifying your email is ${otp}</p> <p>Please verify your email by visiting the following link</p> <a href='http://${host}:${port}/auth/verify-email?username=${username}'> Verify your email </a>` } module.exports = signup
import readXlsx as reader import datetime as datetime def processFeeds (hashExchangeRates,df): sumSymbol=0 sumBase=0 for index, row in df.iterrows(): date= row['Date'] pasta=row['Amount'] type=row['Type'] if (type=="Rollover Fee"): date_time_obj = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S') #get rates dayExchangeRate=hashExchangeRates[str(date_time_obj.date())] #print(pasta, date_time_obj.date(),dayExchangeRate ) sumSymbol= sumSymbol + pasta sumBase= sumBase + pasta/dayExchangeRate return [sumSymbol,sumBase]
def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver code to test above arr = [5, 3, 1, 8, 6] bubbleSort(arr) print ("Sorted array is:") for i in range(len(arr)): print ("%d" %arr[i]),
// In your users route file: const express = require('express'); const router = express.Router(); const users = require('../data/users.json'); // GET api/users router.get('/', (req, res) => { res.json(users); }); module.exports = router;
<filename>src/app/home/home.component.ts import { Component, OnInit } from '@angular/core'; import { group, trigger, style, transition, animate, keyframes, query, stagger } from '@angular/animations'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], animations: [ trigger('itemc', [ transition('* => *', [ query(':enter', style({ opacity: 0 }), { optional: true }), query(':enter', stagger('300ms', [ animate('.6s ease-in-out', keyframes([ style({ opacity: 0 }), style({ opacity: .5 }), style({ opacity: 1 }) ]))]), { optional: true }), query(':leave', stagger('300ms', [ animate('.6s ease-in-out', keyframes([ style({ opacity: 1 }), style({ opacity: .5 }), style({ opacity: 0 }) ]))]), { optional: true }) ]) ]) ] }) export class HomeComponent implements OnInit { count: number; goalText: string; items = []; constructor() { } updateCount() { this.count = this.items.length; } addItem() { this.items.push(this.goalText); this.goalText = ""; this.updateCount(); } removeItem(i) { this.items.splice(i, 1); this.updateCount(); } ngOnInit() { this.updateCount(); } }
<reponame>andreimcristof/go_starter package queue type PatientsQueue []*Patient // Push required by the heap.Interface func (pq *PatientsQueue) Push(patientData interface{}) { patient := patientData.(*Patient) patient.index = len(*pq) // required by the heap.Interface *pq = append(*pq, patient) } // Pop required by the heap.Interface func (pq *PatientsQueue) Pop() interface{} { currentQueue := *pq n := len(currentQueue) patient := currentQueue[n-1] patient.index = -1 // required by the heap *pq = currentQueue[0 : n-1] return patient } // Len required by sort.Interface func (pq *PatientsQueue) Len() int { return len(*pq) } // Swap required by the sort.Interface func (pq PatientsQueue) Swap(a, b int) { pq[a], pq[b] = pq[b], pq[a] pq[a].index = a pq[b].index = b } // Less required by the sort.Interface // we flip the comparer (to greater than) because we need // the comparer to sort by highest prio, not lowest func (pq PatientsQueue) Less(a, b int) bool { return pq[a].severity > pq[b].severity }
<filename>scr/hginvest.js //////////////////////////////////////////////////////////// PLACES.en.pro_id = `Program ID`; PLACES.en.pro_gemt = `Amount to invest {${_progMoney}}`; ////////////////////////////////////////////////////////////
import { combination } from "../../utils/util" class Code{ Code SpuId seqments = [] constructor(Code){ this.Code = Code this.splitCode() } splitCode(){ // 2$1-45#3-9#4-14 const SpuAndSpec = this.Code.split('$') this.SpuId = SpuAndSpec[0] const SpecArray = SpuAndSpec[1].split('#') //进行组合 组合的次数就是数组的长度 1个 两两 3选三 let length = SpecArray.length for(let i =1;i<=length;i++){ const result =combination(SpecArray,i) // 打印出来的结果是几个二维数组 [[],[],[]]... 三种选择组合的二维数组 let joinedResult= result.map(r=>{ return r.join('#') }) this.seqments= this.seqments.concat(joinedResult) } } } export{ Code }
<reponame>zk25796/bluejoe-openwebflow package org.openwebflow.mgr.ext; public interface ActivityPermissionManagerEx { /** * 删除所有权限定义信息 */ public abstract void removeAll() throws Exception; /** * 保存一条权限定义信息 */ public abstract void save(String processDefId, String taskDefinitionKey, String assignee, String[] candidateGroupIds, String[] candidateUserIds) throws Exception; }
import React from 'react'; import { Layout } from 'antd'; import '../less/index.less'; const Footer = () => { const { Footer } = Layout; return ( <Footer className="center padding-35"> Village Book Builders ©2021 | All Rights Reserved </Footer> ); }; export default Footer;
import React, { Component } from 'react'; import { Text, View } from 'react-native'; const jokes = [ 'What do you call a bear with no teeth? A gummy bear!', 'Why did the chicken go to the seance? To get to the other side.', 'Why did the scarecrow win an award? Because he was outstanding in his field.' ]; class App extends Component { state = { joke: '' }; componentDidMount() { this.setState({ joke: this.getRandomJoke() }); } getRandomJoke() { const { jokes } = this; const id = Math.floor(Math.random() * jokes.length); return jokes[id]; } render() { const { joke } = this.state; return ( <View> <Text>{joke}</Text> </View> ); } } export default App;
#!/usr/bin/env bash aws s3 mb s3://v24-bucket aws cloudformation package \ --template-file template.yaml \ --output-template-file v24-stack.yaml \ --s3-bucket v24-bucket aws cloudformation deploy \ --template-file v24-stack.yaml \ --capabilities CAPABILITY_IAM \ --stack-name v24-stack # Test aws s3 ls | grep v24-stack aws s3 ls s3://v24-stack-srcbucket-1gunmxomkmc9w aws s3 cp /tmp/image.png s3://v24-stack-srcbucket-1gunmxomkmc9w aws s3 ls s3://v24-stack-srcbucket-1gunmxomkmc9w aws s3 ls s3://v24-stack-destbucket-1nkok4h9mbcly aws s3 ls s3://v24-stack-srcbucket-1gunmxomkmc9w awslogs get /aws/lambda/v24-stack-CopyFile-7NUG9424IJLA # Clean-up aws logs describe-log-groups | grep v24 aws logs describe-log-streams \ --log-kgroup="/aws/lambda/v24-stack-CopyFile-7NUG9424IJLA" \ | grep logStreamName aws logs get-log-events --output text \ --log-group="/aws/lambda/v24-stack-CopyFile-7NUG9424IJLA" \ --log-stream-name='2018/01/*' \ aws cloudformation delete-stack --stack-name=v24-stack aws cloudformation describe-stack-events --stack-name v24-stack
#!/usr/bin/env bash # 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. set -x # shellcheck source=scripts/ci/_script_init.sh . "$( dirname "${BASH_SOURCE[0]}" )/_script_init.sh" export UPGRADE_TO_LATEST_REQUIREMENTS="false" # In case of CRON jobs on Travis we run builds without cache if [[ "${TRAVIS_EVENT_TYPE:=}" == "cron" ]]; then echo echo "Disabling cache for CRON jobs" echo export DOCKER_CACHE="no-cache" export PULL_BASE_IMAGES="true" export UPGRADE_TO_LATEST_REQUIREMENTS="true" fi build_ci_image_on_ci # We need newer version of six for Travis as they bundle 1.11.0 version sudo pip install pre-commit 'six~=1.14'
def getStockAction(data): ''' Args: data (list): The data of the stock Returns: buy (boolean): True if stock should be bought; False if stock should be sold ''' # Read data values open_price = data[0] high_price = data[1] low_price = data[2] close_price = data[3] # Variables used to determine buy/sell delta = abs(high_price - low_price) trend = close_price - open_price buy = False # True if stock should be bought; False if stock should be sold if trend > 0: if delta >= 0.1 * open_price: # Buy the stock buy = True else: if delta >= 0.2 * open_price: # Sell the stock buy = False return buy
import Vue from 'vue' import Vuex from 'vuex' import VuexI18n from 'vuex-i18n' // load vuex i18n module import app from './modules/app' import * as getters from './getters' import axios from 'axios' Vue.use(Vuex) const store = new Vuex.Store({ strict: true, // process.env.NODE_ENV !== 'production', getters, modules: { app, }, state: {}, mutations: {}, }) Vue.use(VuexI18n.plugin, store) export default new Vuex.Store({ state: { status: '', token: localStorage.getItem('token') || '', usernameid: localStorage.getItem('username') || '', name: localStorage.getItem('name') || '', }, mutations: { auth_request (state) { state.status = 'loading' }, auth_success (state, { token, usernameid }) { state.status = 'success' state.token = token state.usernameid = usernameid }, auth_error (state) { state.status = 'error' }, logout (state) { state.status = '' state.token = '' }, }, actions: { login ({ commit }, user) { return new Promise((resolve, reject) => { commit('auth_request') axios({ method: 'post', url: '/auth/GetToken', headers: {}, data: { username: user.email, // This is the body part password: <PASSWORD>, system: 'COMPRAS', }, }) .then(resp => { const token = resp.data.Token const usernameid = resp.data.Id const name = resp.data.name localStorage.setItem('token', token) console.log(token) localStorage.setItem('usernameid', usernameid) console.log(usernameid) localStorage.setItem('name', name) console.log(name) axios.defaults.headers.common['Authorization'] = token commit('auth_success', { token, usernameid }) resolve(resp) }) .catch(err => { commit('auth_error') localStorage.removeItem('token') reject(err) }) }) }, logout ({ commit }) { return new Promise((resolve, reject) => { commit('logout') localStorage.removeItem('token') localStorage.removeItem('usernameid') localStorage.removeItem('name') delete axios.defaults.headers.common['Authorization'] /* axios.get('/auth/Logout/') */ console.log('el token amiga' + localStorage.getItem('token')) resolve() .catch(err => { reject(err) console.log(err) }) }) }, }, getters: { isLoggedIn: state => !!state.token, authStatus: state => state.status, user: state => state.name, tokencito: state => state.token, userid: state => state.usernameid, }, })
let Fname = 'Prateek'; let Lname='Arora'; let fullName='<NAME>!'; console.log(Fname+" "+Lname);
import ActiveRecord from './ActiveRecord'; import Core from './Core'; import Collection from './Collection'; import Model from './Model'; import Request from './Http/Request'; import { IAttributes, ICachedResponse, ICachedResponses, ICollectionMeta, IDispatcher, IModelRequestOptions, IModelRequestQueryParams, IPagination, ISortOptions } from './Interfaces'; export { ActiveRecord, Core, Collection, IAttributes, ICachedResponse, ICachedResponses, ICollectionMeta, IDispatcher, IModelRequestOptions, IModelRequestQueryParams, IPagination, ISortOptions, Model, Request, };
<html> <body> <form action="" method="POST"> <input type="text" name="firstname" placeholder="First name"> <input type="text" name="lastname" placeholder="Last name"> <input type="submit" value="Submit"> </form> </body> </html>