content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
#!/usr/bin/env python3 """Runs kb-stopwatch.""" from kbstopwatch.main import main # Run it main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 10987, 82, 47823, 12, 11338, 8340, 526, 15931, 198, 198, 6738, 47823, 11338, 8340, 13, 12417, 1330, 1388, 628, 198, 2, 5660, 340, 198, 12417, 3419, 198 ]
2.657895
38
#!/usr/bin/env python # encoding: utf-8 import sys, os import numpy as np import bisect import scipy.io import bisect import math import h5py from nltk.corpus import wordnet as wn from nltk.corpus import wordnet_ic from basic.constant import ROOT_PATH from basic.common import makedirsforfile, checkToSkip, printStatus from basic.util import readImageSet from basic.annotationtable import readConcepts from util.simpleknn.bigfile import BigFile from instance_based.tagvote import * INFO = 'transduction_based.laplacian_tags' DEFAULT_RATIOCS = 0.9 if __name__ == "__main__": sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 11748, 25064, 11, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 47457, 478, 198, 11748, 629, 541, 88, 13, 952, 198, 11748, 47457, 4...
2.884615
208
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from numpy.random import RandomState from tensorflow.python.framework import dtypes from tensorflow.python.ops import random_ops import random """ Quarternion layers References: https://arxiv.org/pdf/1806.04418.pdf https://arxiv.org/pdf/1806.07789.pdf https://github.com/Orkis-Research/light-Recurrent-Neural-Networks https://github.com/Orkis-Research/light-Convolutional-Neural-Networks-for-End-to-End-Automatic-Speech-Recognition Some functions are direct ports from the Pytorch library. """ def quarternion_attention(a, b): """ Performs dot product attention between two quarternion sequences. a = bsz x al x dim b = bsz x bl x dim following: (rr' - xx' - yy' - zz') + (rx' + xr' + yz' - zy')i + (ry' - xz' + yr' + zx')j + (rz' + xy' - yx' + zr')k + the output should be one attention matrix for each component (r,i,j,k) """ print("light Attention!") print(a) print(b) al, bl = tf.shape(a)[2], tf.shape(b)[2] ar, ax, ay, az = tf.split(a, 4, axis=-1) br, bx, by, bz = tf.split(b, 4, axis=-1) r = tf.matmul(ar, br, transpose_b=True) - tf.matmul(ax, bx, transpose_b=True) - tf.matmul(ay, by, transpose_b=True) - tf.matmul(az, bz, transpose_b=True) i = tf.matmul(ar, bx, transpose_b=True) + tf.matmul(ax, br, transpose_b=True) + tf.matmul(ay, bz, transpose_b=True) - tf.matmul(az, by, transpose_b=True) j = tf.matmul(ar, by, transpose_b=True) - tf.matmul(ax, bz, transpose_b=True) + tf.matmul(ay, br, transpose_b=True) + tf.matmul(az, bx, transpose_b=True) k = tf.matmul(ar, bz, transpose_b=True) + tf.matmul(ax, by, transpose_b=True) - tf.matmul(ay, bx, transpose_b=True) + tf.matmul(az, br, transpose_b=True) return [r, i, j, k] def quarternion_dot_product_att(a, b): """ Wrapper for two sequences """ al = tf.shape(a)[1] bl = tf.shape(b)[1] # print(a) d = a.get_shape().as_list()[2] bsz = tf.shape(b)[0] a = tf.reshape(a, [-1, d]) a = tf.tile(a, [bl, 1]) b = tf.reshape(b, [-1, d]) b = tf.tile(b, [al, 1]) att = quarternion_dot(a, b) att = tf.reshape(att, [bsz, -1, al * bl]) att = tf.reduce_sum(att, 1) return tf.reshape(att, [-1, al * bl]) def quarternion_dot(q0, q1): """ Quarternion product between 2 quarternions returns same shape and acts like element-wise quarternion mul """ q1_r = get_r(q1) q1_i = get_i(q1) q1_j = get_j(q1) q1_k = get_k(q1) r_base = tf.multiply(q0, q1) r = get_r(r_base) - get_i(r_base) - get_j(r_base) - get_k(r_base) i_base = tf.multiply(q0, tf.concat([q1_i, q1_r, q1_k, q1_j], 1)) i = get_r(i_base) + get_i(i_base) + get_j(i_base) - get_k(i_base) j_base = tf.multiply(q0, tf.concat([q1_j, q1_k, q1_r, q1_i], 1)) j = get_r(j_base) - get_i(j_base) + get_j(j_base) + get_k(j_base) k_base = tf.multiply(q0, tf.concat([q1_k, q1_j, q1_i, q1_r], 1)) k = get_r(k_base) + get_i(k_base) - get_j(k_base) + get_k(k_base) return tf.concat([r, i, j, k], 1) def quarternion_concat(x, axis): """ Helpful if we have 2 quarternions in [r,i,j,k]. We can't simply concat them as it would mess the components. So in this case, we extract each component and concat them individually. """ output = [[] for i in range(4)] for _x in x: sp = tf.split(_x, 4, axis=axis) for i in range(4): output[i].append(sp[i]) final = [] for o in output: o = tf.concat(o, axis) final.append(o) return tf.concat(final, axis) def quarternion_ffn_3d(x, dim, name='', init=None, num_layers=1, activation=None, reuse=None): """ Quarternion Feed-forward layers to 3D input [bsz x seq_len x dim] returns same shape tensor with new projected dimension. """ print("QFFN layer..") _d = x.get_shape().as_list()[2] sq = tf.shape(x)[1] x = tf.reshape(x, [-1, _d]) x = quarternion_ffn(x, dim, name=name, init=init, num_layers=num_layers, activation=activation,reuse=reuse) x = tf.reshape(x, [-1, sq, dim]) return x def factorized_ffn_3d(x, dim, name='', init=None, num_layers=1, activation=None, reuse=None): """ 3D factorized FFN layer """ print("Factor Layer") _d = x.get_shape().as_list()[2] sq = tf.shape(x)[1] x = tf.reshape(x, [-1, _d]) x = factorized_ffn(x, dim, name=name, init=init, num_layers=num_layers, activation=activation,reuse=reuse) x = tf.reshape(x, [-1, sq, dim]) return x def factorized_ffn(x, dim, name='', init=None, num_layers=1, activation=None, reuse=None): """ Factorized FFN """ if(init is None): init = tf.contrib.layers.xavier_initializer() input_dim=x.get_shape().as_list()[2] k1 = tf.get_variable('factork1{}'.format(name), [input_dim], initializer=init) k2 = tf.get_variable('factork2{}'.format(name), [dim], initializer=init) W = tf.tensordot(k1, k2, axes=0) output = tf.matmul(x, W) if(activation): output = activation(output) return output def quarternion_ffn(x, dim, name='', init=None, num_layers=1, activation=None, reuse=None): """ Implements quarternion feed-forward layer x is [bsz x features] tensor """ if(init is None): init = tf.contrib.layers.xavier_initializer() # init = q_xavier_initializer() input_dim = x.get_shape().as_list()[1] // 4 with tf.variable_scope('Q{}'.format(name), reuse=reuse) as scope: kernel = tf.get_variable('quarternion', [input_dim, dim], initializer=init) hamilton = make_quarternion_mul(kernel) output = tf.matmul(x, hamilton) if(activation): output = activation(output) return output def make_random_mul(kernel, n=4, concat_dim=0, dual=False): """ input is dim/n x dim output is dim x dim generalization and parameterized hypercomplex product """ dim = kernel.get_shape().as_list()[1] dim2 = kernel.get_shape().as_list()[0] kernel = tf.reshape(kernel, [dim2, 1, 1, dim]) mix = tf.split(kernel, n, axis=-1) sdim = mix[0].get_shape().as_list()[-1] # dim//n x 1 x 1 x dim//n AM = tf.get_variable('A', [n, 1, n, n]) cat = tf.concat(mix, axis=1) # dim/n x n x 1 x dim/n cat = tf.tile(cat, [1, 1, n, 1]) # dim/n x n x n x dim/n cat = tf.transpose(cat, [1, 0, 2, 3]) # n x dim/n x n x dim/n if(dual==1): print("Using Dual..") BM = tf.get_variable('B', [n, 1, n, n]) AM *= tf.nn.sigmoid(BM) AM = tf.tile(AM, [1, dim2, 1, 1]) # n x dim/n x n x n cat = tf.matmul(AM, cat) # n x dim/n x n x dim/n output = tf.reshape(cat, [dim2 *n, dim]) return output def random_ffn_3d(x, dim, n=16, name='', init=None, num_layers=1, activation=None, reuse=None, dual=False): """ Implements random feed-forward layer x is [bsz x features] tensor """ print("R-FFN layer..n={} dual={}".format(n, dual)) _d = x.get_shape().as_list()[2] sq = tf.shape(x)[1] x = tf.reshape(x, [-1, _d]) print(x) x = random_ffn(x, dim, n=n, name=name, init=init, num_layers=num_layers, activation=activation, reuse=reuse, dual=dual) x = tf.reshape(x, [-1, sq, dim]) return x def random_ffn(x, dim, n=4, name='', init=None, num_layers=1, activation=None, reuse=None, dual=0): """ Implements random feed-forward layer x is [bsz x features] tensor """ if(init is None): init = tf.contrib.layers.xavier_initializer() # init = q_xavier_initializer() input_dim = x.get_shape().as_list()[1] // n with tf.variable_scope('R{}'.format(name), reuse=reuse) as scope: kernel = tf.get_variable('random', [input_dim, dim], initializer=init) hamilton = make_random_mul(kernel, n=n, dual=dual) output = tf.matmul(x, hamilton) if(activation): output = activation(output) return output def octonion_ffn_3d(x, dim, name='', init=None, num_layers=1, activation=None, reuse=None): """ Quarternion Feed-forward layers to 3D input [bsz x seq_len x dim] returns same shape tensor with new projected dimension. """ print("OFFN layer..") _d = x.get_shape().as_list()[2] sq = tf.shape(x)[1] x = tf.reshape(x, [-1, _d]) x = octonion_ffn(x, dim, name=name, init=init, num_layers=num_layers, activation=activation,reuse=reuse) x = tf.reshape(x, [-1, sq, dim]) return x
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 6738, ...
2.243561
3,572
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: hfc/protos/token/prover.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 from hfc.protos.token import expectations_pb2 as hfc_dot_protos_dot_token_dot_expectations__pb2 from hfc.protos.token import transaction_pb2 as hfc_dot_protos_dot_token_dot_transaction__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='hfc/protos/token/prover.proto', package='token', syntax='proto3', serialized_options=_b('\n#org.hyperledger.fabric.protos.tokenZ*github.com/hyperledger/fabric/protos/token'), serialized_pb=_b('\n\x1dhfc/protos/token/prover.proto\x12\x05token\x1a\x1fgoogle/protobuf/timestamp.proto\x1a#hfc/protos/token/expectations.proto\x1a\"hfc/protos/token/transaction.proto\"A\n\x0cTokenToIssue\x12\x11\n\trecipient\x18\x01 \x01(\x0c\x12\x0c\n\x04type\x18\x02 \x01(\t\x12\x10\n\x08quantity\x18\x03 \x01(\x04\"=\n\x16RecipientTransferShare\x12\x11\n\trecipient\x18\x01 \x01(\x0c\x12\x10\n\x08quantity\x18\x02 \x01(\x04\"I\n\x0bTokenOutput\x12\x1a\n\x02id\x18\x01 \x01(\x0b\x32\x0e.token.InputId\x12\x0c\n\x04type\x18\x02 \x01(\t\x12\x10\n\x08quantity\x18\x03 \x01(\x04\"3\n\rUnspentTokens\x12\"\n\x06tokens\x18\x01 \x03(\x0b\x32\x12.token.TokenOutput\"!\n\x0bListRequest\x12\x12\n\ncredential\x18\x01 \x01(\x0c\"Q\n\rImportRequest\x12\x12\n\ncredential\x18\x01 \x01(\x0c\x12,\n\x0ftokens_to_issue\x18\x02 \x03(\x0b\x32\x13.token.TokenToIssue\"w\n\x0fTransferRequest\x12\x12\n\ncredential\x18\x01 \x01(\x0c\x12!\n\ttoken_ids\x18\x02 \x03(\x0b\x32\x0e.token.InputId\x12-\n\x06shares\x18\x03 \x03(\x0b\x32\x1d.token.RecipientTransferShare\"b\n\rRedeemRequest\x12\x12\n\ncredential\x18\x01 \x01(\x0c\x12!\n\ttoken_ids\x18\x02 \x03(\x0b\x32\x0e.token.InputId\x12\x1a\n\x12quantity_to_redeem\x18\x03 \x01(\x04\">\n\x17\x41llowanceRecipientShare\x12\x11\n\trecipient\x18\x01 \x01(\x0c\x12\x10\n\x08quantity\x18\x02 \x01(\x04\"\x81\x01\n\x0e\x41pproveRequest\x12\x12\n\ncredential\x18\x01 \x01(\x0c\x12\x38\n\x10\x61llowance_shares\x18\x02 \x03(\x0b\x32\x1e.token.AllowanceRecipientShare\x12!\n\ttoken_ids\x18\x03 \x03(\x0b\x32\x0e.token.InputId\"y\n\x12\x45xpectationRequest\x12\x12\n\ncredential\x18\x01 \x01(\x0c\x12,\n\x0b\x65xpectation\x18\x02 \x01(\x0b\x32\x17.token.TokenExpectation\x12!\n\ttoken_ids\x18\x03 \x03(\x0b\x32\x0e.token.InputId\"\x82\x01\n\x06Header\x12-\n\ttimestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\nchannel_id\x18\x02 \x01(\t\x12\r\n\x05nonce\x18\x03 \x01(\x0c\x12\x0f\n\x07\x63reator\x18\x04 \x01(\x0c\x12\x15\n\rtls_cert_hash\x18\x05 \x01(\x0c\"\x98\x03\n\x07\x43ommand\x12\x1d\n\x06header\x18\x01 \x01(\x0b\x32\r.token.Header\x12.\n\x0eimport_request\x18\x02 \x01(\x0b\x32\x14.token.ImportRequestH\x00\x12\x32\n\x10transfer_request\x18\x03 \x01(\x0b\x32\x16.token.TransferRequestH\x00\x12*\n\x0clist_request\x18\x04 \x01(\x0b\x32\x12.token.ListRequestH\x00\x12.\n\x0eredeem_request\x18\x05 \x01(\x0b\x32\x14.token.RedeemRequestH\x00\x12\x30\n\x0f\x61pprove_request\x18\x06 \x01(\x0b\x32\x15.token.ApproveRequestH\x00\x12\x37\n\x15transfer_from_request\x18\x07 \x01(\x0b\x32\x16.token.TransferRequestH\x00\x12\x38\n\x13\x65xpectation_request\x18\x08 \x01(\x0b\x32\x19.token.ExpectationRequestH\x00\x42\t\n\x07payload\"3\n\rSignedCommand\x12\x0f\n\x07\x63ommand\x18\x01 \x01(\x0c\x12\x11\n\tsignature\x18\x02 \x01(\x0c\"m\n\x15\x43ommandResponseHeader\x12-\n\ttimestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x14\n\x0c\x63ommand_hash\x18\x02 \x01(\x0c\x12\x0f\n\x07\x63reator\x18\x03 \x01(\x0c\")\n\x05\x45rror\x12\x0f\n\x07message\x18\x01 \x01(\t\x12\x0f\n\x07payload\x18\x02 \x01(\x0c\"\xcd\x01\n\x0f\x43ommandResponse\x12,\n\x06header\x18\x01 \x01(\x0b\x32\x1c.token.CommandResponseHeader\x12\x1b\n\x03\x65rr\x18\x02 \x01(\x0b\x32\x0c.token.ErrorH\x00\x12\x34\n\x11token_transaction\x18\x03 \x01(\x0b\x32\x17.token.TokenTransactionH\x00\x12.\n\x0eunspent_tokens\x18\x04 \x01(\x0b\x32\x14.token.UnspentTokensH\x00\x42\t\n\x07payload\"<\n\x15SignedCommandResponse\x12\x10\n\x08response\x18\x01 \x01(\x0c\x12\x11\n\tsignature\x18\x02 \x01(\x0c\x32P\n\x06Prover\x12\x46\n\x0eProcessCommand\x12\x14.token.SignedCommand\x1a\x1c.token.SignedCommandResponse\"\x00\x42Q\n#org.hyperledger.fabric.protos.tokenZ*github.com/hyperledger/fabric/protos/tokenb\x06proto3') , dependencies=[google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,hfc_dot_protos_dot_token_dot_expectations__pb2.DESCRIPTOR,hfc_dot_protos_dot_token_dot_transaction__pb2.DESCRIPTOR,]) _TOKENTOISSUE = _descriptor.Descriptor( name='TokenToIssue', full_name='token.TokenToIssue', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='recipient', full_name='token.TokenToIssue.recipient', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='type', full_name='token.TokenToIssue.type', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='quantity', full_name='token.TokenToIssue.quantity', index=2, number=3, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=146, serialized_end=211, ) _RECIPIENTTRANSFERSHARE = _descriptor.Descriptor( name='RecipientTransferShare', full_name='token.RecipientTransferShare', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='recipient', full_name='token.RecipientTransferShare.recipient', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='quantity', full_name='token.RecipientTransferShare.quantity', index=1, number=2, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=213, serialized_end=274, ) _TOKENOUTPUT = _descriptor.Descriptor( name='TokenOutput', full_name='token.TokenOutput', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='token.TokenOutput.id', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='type', full_name='token.TokenOutput.type', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='quantity', full_name='token.TokenOutput.quantity', index=2, number=3, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=276, serialized_end=349, ) _UNSPENTTOKENS = _descriptor.Descriptor( name='UnspentTokens', full_name='token.UnspentTokens', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='tokens', full_name='token.UnspentTokens.tokens', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=351, serialized_end=402, ) _LISTREQUEST = _descriptor.Descriptor( name='ListRequest', full_name='token.ListRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='credential', full_name='token.ListRequest.credential', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=404, serialized_end=437, ) _IMPORTREQUEST = _descriptor.Descriptor( name='ImportRequest', full_name='token.ImportRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='credential', full_name='token.ImportRequest.credential', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='tokens_to_issue', full_name='token.ImportRequest.tokens_to_issue', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=439, serialized_end=520, ) _TRANSFERREQUEST = _descriptor.Descriptor( name='TransferRequest', full_name='token.TransferRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='credential', full_name='token.TransferRequest.credential', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='token_ids', full_name='token.TransferRequest.token_ids', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='shares', full_name='token.TransferRequest.shares', index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=522, serialized_end=641, ) _REDEEMREQUEST = _descriptor.Descriptor( name='RedeemRequest', full_name='token.RedeemRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='credential', full_name='token.RedeemRequest.credential', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='token_ids', full_name='token.RedeemRequest.token_ids', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='quantity_to_redeem', full_name='token.RedeemRequest.quantity_to_redeem', index=2, number=3, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=643, serialized_end=741, ) _ALLOWANCERECIPIENTSHARE = _descriptor.Descriptor( name='AllowanceRecipientShare', full_name='token.AllowanceRecipientShare', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='recipient', full_name='token.AllowanceRecipientShare.recipient', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='quantity', full_name='token.AllowanceRecipientShare.quantity', index=1, number=2, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=743, serialized_end=805, ) _APPROVEREQUEST = _descriptor.Descriptor( name='ApproveRequest', full_name='token.ApproveRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='credential', full_name='token.ApproveRequest.credential', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='allowance_shares', full_name='token.ApproveRequest.allowance_shares', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='token_ids', full_name='token.ApproveRequest.token_ids', index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=808, serialized_end=937, ) _EXPECTATIONREQUEST = _descriptor.Descriptor( name='ExpectationRequest', full_name='token.ExpectationRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='credential', full_name='token.ExpectationRequest.credential', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='expectation', full_name='token.ExpectationRequest.expectation', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='token_ids', full_name='token.ExpectationRequest.token_ids', index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=939, serialized_end=1060, ) _HEADER = _descriptor.Descriptor( name='Header', full_name='token.Header', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='timestamp', full_name='token.Header.timestamp', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='channel_id', full_name='token.Header.channel_id', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='nonce', full_name='token.Header.nonce', index=2, number=3, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='creator', full_name='token.Header.creator', index=3, number=4, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='tls_cert_hash', full_name='token.Header.tls_cert_hash', index=4, number=5, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1063, serialized_end=1193, ) _COMMAND = _descriptor.Descriptor( name='Command', full_name='token.Command', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='header', full_name='token.Command.header', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='import_request', full_name='token.Command.import_request', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='transfer_request', full_name='token.Command.transfer_request', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='list_request', full_name='token.Command.list_request', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='redeem_request', full_name='token.Command.redeem_request', index=4, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='approve_request', full_name='token.Command.approve_request', index=5, number=6, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='transfer_from_request', full_name='token.Command.transfer_from_request', index=6, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='expectation_request', full_name='token.Command.expectation_request', index=7, number=8, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='payload', full_name='token.Command.payload', index=0, containing_type=None, fields=[]), ], serialized_start=1196, serialized_end=1604, ) _SIGNEDCOMMAND = _descriptor.Descriptor( name='SignedCommand', full_name='token.SignedCommand', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='command', full_name='token.SignedCommand.command', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='signature', full_name='token.SignedCommand.signature', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1606, serialized_end=1657, ) _COMMANDRESPONSEHEADER = _descriptor.Descriptor( name='CommandResponseHeader', full_name='token.CommandResponseHeader', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='timestamp', full_name='token.CommandResponseHeader.timestamp', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='command_hash', full_name='token.CommandResponseHeader.command_hash', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='creator', full_name='token.CommandResponseHeader.creator', index=2, number=3, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1659, serialized_end=1768, ) _ERROR = _descriptor.Descriptor( name='Error', full_name='token.Error', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='message', full_name='token.Error.message', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='payload', full_name='token.Error.payload', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1770, serialized_end=1811, ) _COMMANDRESPONSE = _descriptor.Descriptor( name='CommandResponse', full_name='token.CommandResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='header', full_name='token.CommandResponse.header', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='err', full_name='token.CommandResponse.err', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='token_transaction', full_name='token.CommandResponse.token_transaction', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='unspent_tokens', full_name='token.CommandResponse.unspent_tokens', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='payload', full_name='token.CommandResponse.payload', index=0, containing_type=None, fields=[]), ], serialized_start=1814, serialized_end=2019, ) _SIGNEDCOMMANDRESPONSE = _descriptor.Descriptor( name='SignedCommandResponse', full_name='token.SignedCommandResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='response', full_name='token.SignedCommandResponse.response', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='signature', full_name='token.SignedCommandResponse.signature', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=2021, serialized_end=2081, ) _TOKENOUTPUT.fields_by_name['id'].message_type = hfc_dot_protos_dot_token_dot_transaction__pb2._INPUTID _UNSPENTTOKENS.fields_by_name['tokens'].message_type = _TOKENOUTPUT _IMPORTREQUEST.fields_by_name['tokens_to_issue'].message_type = _TOKENTOISSUE _TRANSFERREQUEST.fields_by_name['token_ids'].message_type = hfc_dot_protos_dot_token_dot_transaction__pb2._INPUTID _TRANSFERREQUEST.fields_by_name['shares'].message_type = _RECIPIENTTRANSFERSHARE _REDEEMREQUEST.fields_by_name['token_ids'].message_type = hfc_dot_protos_dot_token_dot_transaction__pb2._INPUTID _APPROVEREQUEST.fields_by_name['allowance_shares'].message_type = _ALLOWANCERECIPIENTSHARE _APPROVEREQUEST.fields_by_name['token_ids'].message_type = hfc_dot_protos_dot_token_dot_transaction__pb2._INPUTID _EXPECTATIONREQUEST.fields_by_name['expectation'].message_type = hfc_dot_protos_dot_token_dot_expectations__pb2._TOKENEXPECTATION _EXPECTATIONREQUEST.fields_by_name['token_ids'].message_type = hfc_dot_protos_dot_token_dot_transaction__pb2._INPUTID _HEADER.fields_by_name['timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP _COMMAND.fields_by_name['header'].message_type = _HEADER _COMMAND.fields_by_name['import_request'].message_type = _IMPORTREQUEST _COMMAND.fields_by_name['transfer_request'].message_type = _TRANSFERREQUEST _COMMAND.fields_by_name['list_request'].message_type = _LISTREQUEST _COMMAND.fields_by_name['redeem_request'].message_type = _REDEEMREQUEST _COMMAND.fields_by_name['approve_request'].message_type = _APPROVEREQUEST _COMMAND.fields_by_name['transfer_from_request'].message_type = _TRANSFERREQUEST _COMMAND.fields_by_name['expectation_request'].message_type = _EXPECTATIONREQUEST _COMMAND.oneofs_by_name['payload'].fields.append( _COMMAND.fields_by_name['import_request']) _COMMAND.fields_by_name['import_request'].containing_oneof = _COMMAND.oneofs_by_name['payload'] _COMMAND.oneofs_by_name['payload'].fields.append( _COMMAND.fields_by_name['transfer_request']) _COMMAND.fields_by_name['transfer_request'].containing_oneof = _COMMAND.oneofs_by_name['payload'] _COMMAND.oneofs_by_name['payload'].fields.append( _COMMAND.fields_by_name['list_request']) _COMMAND.fields_by_name['list_request'].containing_oneof = _COMMAND.oneofs_by_name['payload'] _COMMAND.oneofs_by_name['payload'].fields.append( _COMMAND.fields_by_name['redeem_request']) _COMMAND.fields_by_name['redeem_request'].containing_oneof = _COMMAND.oneofs_by_name['payload'] _COMMAND.oneofs_by_name['payload'].fields.append( _COMMAND.fields_by_name['approve_request']) _COMMAND.fields_by_name['approve_request'].containing_oneof = _COMMAND.oneofs_by_name['payload'] _COMMAND.oneofs_by_name['payload'].fields.append( _COMMAND.fields_by_name['transfer_from_request']) _COMMAND.fields_by_name['transfer_from_request'].containing_oneof = _COMMAND.oneofs_by_name['payload'] _COMMAND.oneofs_by_name['payload'].fields.append( _COMMAND.fields_by_name['expectation_request']) _COMMAND.fields_by_name['expectation_request'].containing_oneof = _COMMAND.oneofs_by_name['payload'] _COMMANDRESPONSEHEADER.fields_by_name['timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP _COMMANDRESPONSE.fields_by_name['header'].message_type = _COMMANDRESPONSEHEADER _COMMANDRESPONSE.fields_by_name['err'].message_type = _ERROR _COMMANDRESPONSE.fields_by_name['token_transaction'].message_type = hfc_dot_protos_dot_token_dot_transaction__pb2._TOKENTRANSACTION _COMMANDRESPONSE.fields_by_name['unspent_tokens'].message_type = _UNSPENTTOKENS _COMMANDRESPONSE.oneofs_by_name['payload'].fields.append( _COMMANDRESPONSE.fields_by_name['err']) _COMMANDRESPONSE.fields_by_name['err'].containing_oneof = _COMMANDRESPONSE.oneofs_by_name['payload'] _COMMANDRESPONSE.oneofs_by_name['payload'].fields.append( _COMMANDRESPONSE.fields_by_name['token_transaction']) _COMMANDRESPONSE.fields_by_name['token_transaction'].containing_oneof = _COMMANDRESPONSE.oneofs_by_name['payload'] _COMMANDRESPONSE.oneofs_by_name['payload'].fields.append( _COMMANDRESPONSE.fields_by_name['unspent_tokens']) _COMMANDRESPONSE.fields_by_name['unspent_tokens'].containing_oneof = _COMMANDRESPONSE.oneofs_by_name['payload'] DESCRIPTOR.message_types_by_name['TokenToIssue'] = _TOKENTOISSUE DESCRIPTOR.message_types_by_name['RecipientTransferShare'] = _RECIPIENTTRANSFERSHARE DESCRIPTOR.message_types_by_name['TokenOutput'] = _TOKENOUTPUT DESCRIPTOR.message_types_by_name['UnspentTokens'] = _UNSPENTTOKENS DESCRIPTOR.message_types_by_name['ListRequest'] = _LISTREQUEST DESCRIPTOR.message_types_by_name['ImportRequest'] = _IMPORTREQUEST DESCRIPTOR.message_types_by_name['TransferRequest'] = _TRANSFERREQUEST DESCRIPTOR.message_types_by_name['RedeemRequest'] = _REDEEMREQUEST DESCRIPTOR.message_types_by_name['AllowanceRecipientShare'] = _ALLOWANCERECIPIENTSHARE DESCRIPTOR.message_types_by_name['ApproveRequest'] = _APPROVEREQUEST DESCRIPTOR.message_types_by_name['ExpectationRequest'] = _EXPECTATIONREQUEST DESCRIPTOR.message_types_by_name['Header'] = _HEADER DESCRIPTOR.message_types_by_name['Command'] = _COMMAND DESCRIPTOR.message_types_by_name['SignedCommand'] = _SIGNEDCOMMAND DESCRIPTOR.message_types_by_name['CommandResponseHeader'] = _COMMANDRESPONSEHEADER DESCRIPTOR.message_types_by_name['Error'] = _ERROR DESCRIPTOR.message_types_by_name['CommandResponse'] = _COMMANDRESPONSE DESCRIPTOR.message_types_by_name['SignedCommandResponse'] = _SIGNEDCOMMANDRESPONSE _sym_db.RegisterFileDescriptor(DESCRIPTOR) TokenToIssue = _reflection.GeneratedProtocolMessageType('TokenToIssue', (_message.Message,), dict( DESCRIPTOR = _TOKENTOISSUE, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.TokenToIssue) )) _sym_db.RegisterMessage(TokenToIssue) RecipientTransferShare = _reflection.GeneratedProtocolMessageType('RecipientTransferShare', (_message.Message,), dict( DESCRIPTOR = _RECIPIENTTRANSFERSHARE, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.RecipientTransferShare) )) _sym_db.RegisterMessage(RecipientTransferShare) TokenOutput = _reflection.GeneratedProtocolMessageType('TokenOutput', (_message.Message,), dict( DESCRIPTOR = _TOKENOUTPUT, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.TokenOutput) )) _sym_db.RegisterMessage(TokenOutput) UnspentTokens = _reflection.GeneratedProtocolMessageType('UnspentTokens', (_message.Message,), dict( DESCRIPTOR = _UNSPENTTOKENS, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.UnspentTokens) )) _sym_db.RegisterMessage(UnspentTokens) ListRequest = _reflection.GeneratedProtocolMessageType('ListRequest', (_message.Message,), dict( DESCRIPTOR = _LISTREQUEST, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.ListRequest) )) _sym_db.RegisterMessage(ListRequest) ImportRequest = _reflection.GeneratedProtocolMessageType('ImportRequest', (_message.Message,), dict( DESCRIPTOR = _IMPORTREQUEST, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.ImportRequest) )) _sym_db.RegisterMessage(ImportRequest) TransferRequest = _reflection.GeneratedProtocolMessageType('TransferRequest', (_message.Message,), dict( DESCRIPTOR = _TRANSFERREQUEST, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.TransferRequest) )) _sym_db.RegisterMessage(TransferRequest) RedeemRequest = _reflection.GeneratedProtocolMessageType('RedeemRequest', (_message.Message,), dict( DESCRIPTOR = _REDEEMREQUEST, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.RedeemRequest) )) _sym_db.RegisterMessage(RedeemRequest) AllowanceRecipientShare = _reflection.GeneratedProtocolMessageType('AllowanceRecipientShare', (_message.Message,), dict( DESCRIPTOR = _ALLOWANCERECIPIENTSHARE, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.AllowanceRecipientShare) )) _sym_db.RegisterMessage(AllowanceRecipientShare) ApproveRequest = _reflection.GeneratedProtocolMessageType('ApproveRequest', (_message.Message,), dict( DESCRIPTOR = _APPROVEREQUEST, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.ApproveRequest) )) _sym_db.RegisterMessage(ApproveRequest) ExpectationRequest = _reflection.GeneratedProtocolMessageType('ExpectationRequest', (_message.Message,), dict( DESCRIPTOR = _EXPECTATIONREQUEST, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.ExpectationRequest) )) _sym_db.RegisterMessage(ExpectationRequest) Header = _reflection.GeneratedProtocolMessageType('Header', (_message.Message,), dict( DESCRIPTOR = _HEADER, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.Header) )) _sym_db.RegisterMessage(Header) Command = _reflection.GeneratedProtocolMessageType('Command', (_message.Message,), dict( DESCRIPTOR = _COMMAND, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.Command) )) _sym_db.RegisterMessage(Command) SignedCommand = _reflection.GeneratedProtocolMessageType('SignedCommand', (_message.Message,), dict( DESCRIPTOR = _SIGNEDCOMMAND, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.SignedCommand) )) _sym_db.RegisterMessage(SignedCommand) CommandResponseHeader = _reflection.GeneratedProtocolMessageType('CommandResponseHeader', (_message.Message,), dict( DESCRIPTOR = _COMMANDRESPONSEHEADER, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.CommandResponseHeader) )) _sym_db.RegisterMessage(CommandResponseHeader) Error = _reflection.GeneratedProtocolMessageType('Error', (_message.Message,), dict( DESCRIPTOR = _ERROR, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.Error) )) _sym_db.RegisterMessage(Error) CommandResponse = _reflection.GeneratedProtocolMessageType('CommandResponse', (_message.Message,), dict( DESCRIPTOR = _COMMANDRESPONSE, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.CommandResponse) )) _sym_db.RegisterMessage(CommandResponse) SignedCommandResponse = _reflection.GeneratedProtocolMessageType('SignedCommandResponse', (_message.Message,), dict( DESCRIPTOR = _SIGNEDCOMMANDRESPONSE, __module__ = 'hfc.protos.token.prover_pb2' # @@protoc_insertion_point(class_scope:token.SignedCommandResponse) )) _sym_db.RegisterMessage(SignedCommandResponse) DESCRIPTOR._options = None _PROVER = _descriptor.ServiceDescriptor( name='Prover', full_name='token.Prover', file=DESCRIPTOR, index=0, serialized_options=None, serialized_start=2083, serialized_end=2163, methods=[ _descriptor.MethodDescriptor( name='ProcessCommand', full_name='token.Prover.ProcessCommand', index=0, containing_service=None, input_type=_SIGNEDCOMMAND, output_type=_SIGNEDCOMMANDRESPONSE, serialized_options=None, ), ]) _sym_db.RegisterServiceDescriptor(_PROVER) DESCRIPTOR.services_by_name['Prover'] = _PROVER # @@protoc_insertion_point(module_scope)
[ 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 289, 16072, 14, 11235, 418, 14, 30001, 14, 1676, 332, 13, 1676, 1462, 198, 198, 11748, 25064, 198, 62, 65, 28, 17597, 13, 9641, 62, 10951...
2.442633
17,545
import json import requests from instagram_scraper.constants import BASE_URL, STORIES_UA, LOGIN_URL, LOGOUT_URL CHROME_WIN_UA = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'
[ 11748, 33918, 198, 198, 11748, 7007, 198, 198, 6738, 916, 6713, 62, 1416, 38545, 13, 9979, 1187, 1330, 49688, 62, 21886, 11, 46366, 11015, 62, 34970, 11, 41605, 1268, 62, 21886, 11, 41605, 12425, 62, 21886, 198, 198, 37846, 13649, 62, ...
2.541667
96
# Determining interface details with netfaces library # This script uses a number of functions to accomplish specific tasks # including get_networks, get_addresses, get_gateways and get_interfaces import netifaces import sys try: import netifaces except: sys.exit("[!] Install the netifaces library: pip install netifaces") gateways = {} network_ifaces={} # The second function identifies the gateways and return them as a dictionary # The third function identifies the addresses for each interface # This fourth fuction is actucally identifying the gateway IP from the dictionary provided # by the get_gateways function to the interface. gateways = get_gateways() network_ifaces = get_networks(gateways) print(network_ifaces)
[ 2, 360, 13221, 278, 7071, 3307, 351, 2010, 32186, 5888, 198, 2, 770, 4226, 3544, 257, 1271, 286, 5499, 284, 9989, 2176, 8861, 198, 2, 1390, 651, 62, 3262, 5225, 11, 651, 62, 2860, 16746, 11, 651, 62, 10494, 1322, 290, 651, 62, 384...
3.747475
198
from helpers import functions from flask import Flask, request, session, url_for, redirect, \ render_template, abort, g, flash, _app_ctx_stack from werkzeug import check_password_hash, generate_password_hash def login(): """Logs the user in.""" if g.user: return redirect(functions.url_for('/')) error = None if request.method == 'POST': user = functions.query_db('''select * from user where username = ?''', [request.form['username']], one=True) if user is None: error = 'Invalid username' elif not check_password_hash(user['pw_hash'], request.form['password']): error = 'Invalid password' else: flash('You were logged in') session['user_id'] = user['user_id'] return redirect(functions.url_for('/')) return render_template('login.html', error=error) def register(): """Registers the user.""" return render_template('register.html') def logout(): """Logs the user out.""" flash('You were logged out') session.pop('user_id', None) return redirect(functions.url_for('/public'))
[ 6738, 49385, 1330, 5499, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 6246, 11, 19016, 62, 1640, 11, 18941, 11, 3467, 198, 220, 220, 220, 220, 8543, 62, 28243, 11, 15614, 11, 308, 11, 7644, 11, 4808, 1324, 62, 49464, 62, 25558, 198,...
2.438017
484
#Embedded file name: /Users/versonator/Hudson/live/Projects/AppLive/Resources/MIDI Remote Scripts/MackieControl/ChannelStripController.py from itertools import chain from .MHControlComponent import * from _Generic.Devices import * class ChannelStripController(MHControlComponent): """ Controls all channel-strips of the Mackie Control and controller extensions (Mackie Control XTs) if available: Maps and controls the faders, VPots and the displays depending on the assignemnt modes (Vol_Pan, PlugIn, IO, Send) and edit and flip mode. stack_offset vs. strip_index vs. bank_channel_offset: When using multiple sets of channel strips (stacking them), we will still only have one ChannelStripController which rules them all. To identify and seperate them, the implementation uses 3 different kind of indices or offsets: - strip_index: is the index of a channel_strip within its controller box, so strip no 1 on an extension (XT) and strip number one on the 'main' Mackie will both have a strip_index of 1. We need to preserve this index, because every device (extension or main controller will use a unique MIDI port to send out its MIDI messages which uses the strip_index, encoded into the MIDI messages channel, to tell the hardware which channel on the controller is meant. - stack_offset: descibes how many channels are left to the device that a channel_strip belongs to. For example: You have 3 Mackies: First, a XT, then the main Mackie, then another XT. The first XT will have the stack_index 0, the main Mackie, the stack_index 8, because 8 faders are on present before it. The second XT has a stack_index of 16 - bank_cha_offset: this shifts all available channel strips within all the tracks that should be controlled. For example: If you have a song with 32 tracks, and a main Mackie Control + a XT on the right, then you want to shift the first fader of the main Mackie to Track 16, to be able to control Track 16 to 32. The master channel strip is hardcoded and not in the list of "normal" channel_strips, because its always mapped to the master_volume. """ def set_controller_extensions(self, left_extensions, right_extensions): """ Called from the main script (after all scripts where initialized), to let us know where and how many MackieControlXT are installed. There exists only one ChannelStripController, so we will take care about the extensions channel strips """ self.__left_extensions = left_extensions self.__right_extensions = right_extensions self.__channel_strips = [] stack_offset = 0 for le in left_extensions: for s in le.channel_strips(): self.__channel_strips.append(s) s.set_stack_offset(stack_offset) stack_offset += NUM_CHANNEL_STRIPS for s in self.__own_channel_strips: self.__channel_strips.append(s) s.set_stack_offset(stack_offset) stack_offset += NUM_CHANNEL_STRIPS for re in right_extensions: for s in re.channel_strips(): self.__channel_strips.append(s) s.set_stack_offset(stack_offset) stack_offset += NUM_CHANNEL_STRIPS for s in self.__channel_strips: s.set_channel_strip_controller(self) self.refresh_state() def request_rebuild_midi_map(self): """ Overridden to call also the extensions request_rebuild_midi_map""" MHControlComponent.request_rebuild_midi_map(self) for ex in self.__left_extensions + self.__right_extensions: ex.request_rebuild_midi_map() def toggle_meter_mode(self): """ called from the main script when the display toggle button was pressed """ self.__meters_enabled = not self.__meters_enabled self.__apply_meter_mode() def handle_vpot_rotation(self, strip_index, stack_offset, cc_value): """ forwarded to us by the channel_strips """ if self.__assignment_mode == CSM_IO: if cc_value >= 64: direction = -1 else: direction = 1 channel_strip = self.__channel_strips[stack_offset + strip_index] current_routing = self.__routing_target(channel_strip) available_routings = self.__available_routing_targets(channel_strip) if current_routing and available_routings: if current_routing in available_routings: i = list(available_routings).index(current_routing) if direction == 1: new_i = min(len(available_routings) - 1, i + direction) else: new_i = max(0, i + direction) new_routing = available_routings[new_i] elif len(available_routings): new_routing = available_routings[0] self.__set_routing_target(channel_strip, new_routing) elif self.__assignment_mode == CSM_PLUGINS: pass else: channel_strip = self.__channel_strips[stack_offset + strip_index] raise not channel_strip.assigned_track() or not channel_strip.assigned_track().has_audio_output or AssertionError('in every other mode, the midimap should handle the messages') def handle_fader_touch(self, strip_offset, stack_offset, touched): """ forwarded to us by the channel_strips """ self.__reassign_channel_strip_parameters(for_display_only=True) def handle_pressed_v_pot(self, strip_index, stack_offset): """ forwarded to us by the channel_strips """ if self.__assignment_mode == CSM_VOLPAN or self.__assignment_mode == CSM_SENDS or self.__assignment_mode == CSM_PLUGINS and self.__plugin_mode == PCM_PARAMETERS: if stack_offset + strip_index in range(0, len(self.__channel_strips)): param = self.__channel_strips[stack_offset + strip_index].v_pot_parameter() if param and param.is_enabled: if param.is_quantized: if param.value + 1 > param.max: param.value = param.min else: param.value = param.value + 1 else: param.value = param.default_value elif self.__assignment_mode == CSM_PLUGINS: if self.__plugin_mode == PCM_DEVICES: device_index = strip_index + stack_offset + self.__plugin_mode_offsets[PCM_DEVICES] if device_index >= 0 and device_index < len(self.song().view.selected_track.devices): if self.__chosen_plugin != None: self.__chosen_plugin.remove_parameters_listener(self.__on_parameter_list_of_chosen_plugin_changed) self.__chosen_plugin = self.song().view.selected_track.devices[device_index] self.__chosen_plugin != None and self.__chosen_plugin.add_parameters_listener(self.__on_parameter_list_of_chosen_plugin_changed) self.__reorder_parameters() self.__plugin_mode_offsets[PCM_PARAMETERS] = 0 self.__set_plugin_mode(PCM_PARAMETERS) def __strip_offset(self): """ return the bank_channel offset depending if we are in return mode or not """ if self.__view_returns: return self.__bank_cha_offset_returns else: return self.__bank_cha_offset def __controlled_num_of_tracks(self): """ return the number of tracks, depending on if we are in send_track mode or normal track mode """ if self.__view_returns: return len(self.song().return_tracks) else: return len(self.song().visible_tracks) def __send_parameter(self, strip_index, stack_index): """ Return the send parameter that is assigned to the given channel strip """ if not self.__assignment_mode == CSM_SENDS: raise AssertionError send_index = strip_index + stack_index + self.__send_mode_offset p = send_index < len(self.song().view.selected_track.mixer_device.sends) and self.song().view.selected_track.mixer_device.sends[send_index] return (p, p.name) return (None, None) def __plugin_parameter(self, strip_index, stack_index): """ Return the parameter that is assigned to the given channel strip """ if not self.__assignment_mode == CSM_PLUGINS: raise AssertionError return self.__plugin_mode == PCM_DEVICES and (None, None) elif not (self.__plugin_mode == PCM_PARAMETERS and self.__chosen_plugin): raise AssertionError parameters = self.__ordered_plugin_parameters parameter_index = strip_index + stack_index + self.__plugin_mode_offsets[PCM_PARAMETERS] if parameter_index >= 0 and parameter_index < len(parameters): return parameters[parameter_index] else: return (None, None) else: raise 0 or AssertionError def __can_switch_to_prev_page(self): """ return true if pressing the "next" button will have any effect """ if self.__assignment_mode == CSM_PLUGINS: return self.__plugin_mode_offsets[self.__plugin_mode] > 0 elif self.__assignment_mode == CSM_SENDS: return self.__send_mode_offset > 0 else: return False def __can_switch_to_next_page(self): """ return true if pressing the "prev" button will have any effect """ if self.__assignment_mode == CSM_PLUGINS: sel_track = self.song().view.selected_track if self.__plugin_mode == PCM_DEVICES: return self.__plugin_mode_offsets[PCM_DEVICES] + len(self.__channel_strips) < len(sel_track.devices) elif not (self.__plugin_mode == PCM_PARAMETERS and self.__chosen_plugin): raise AssertionError parameters = self.__ordered_plugin_parameters return self.__plugin_mode_offsets[PCM_PARAMETERS] + len(self.__channel_strips) < len(parameters) else: raise 0 or AssertionError elif self.__assignment_mode == CSM_SENDS: return self.__send_mode_offset + len(self.__channel_strips) < len(self.song().return_tracks) else: return False def __set_channel_offset(self, new_offset): """ Set and validate a new channel_strip offset, which shifts all available channel strips within all the available tracks or reutrn tracks """ if new_offset < 0: new_offset = 0 elif new_offset >= self.__controlled_num_of_tracks(): new_offset = self.__controlled_num_of_tracks() - 1 if self.__view_returns: self.__bank_cha_offset_returns = new_offset else: self.__bank_cha_offset = new_offset self.__main_display_controller.set_channel_offset(new_offset) self.__reassign_channel_strip_offsets() self.__reassign_channel_strip_parameters(for_display_only=False) self.__update_channel_strip_strings() self.request_rebuild_midi_map() def __set_plugin_mode(self, new_mode): """ Set a new plugin sub-mode, which can be: 1. Choosing the device to control (PCM_DEVICES) 2. Controlling the chosen devices parameters (PCM_PARAMETERS) """ if not (new_mode >= 0 and new_mode < PCM_NUMMODES): raise AssertionError if self.__plugin_mode != new_mode: self.__plugin_mode = new_mode self.__reassign_channel_strip_parameters(for_display_only=False) self.request_rebuild_midi_map() self.__plugin_mode == PCM_DEVICES and self.__update_vpot_leds_in_plugins_device_choose_mode() else: for plugin in self.__displayed_plugins: if plugin != None: plugin.remove_name_listener(self.__update_plugin_names) self.__displayed_plugins = [] self.__update_page_switch_leds() self.__update_flip_led() self.__update_page_switch_leds() def __switch_to_prev_page(self): """ Switch to the previous page in the non track strip modes (choosing plugs, or controlling devices) """ if self.__can_switch_to_prev_page(): if self.__assignment_mode == CSM_PLUGINS: self.__plugin_mode_offsets[self.__plugin_mode] -= len(self.__channel_strips) if self.__plugin_mode == PCM_DEVICES: self.__update_vpot_leds_in_plugins_device_choose_mode() elif self.__assignment_mode == CSM_SENDS: self.__send_mode_offset -= len(self.__channel_strips) self.__reassign_channel_strip_parameters(for_display_only=False) self.__update_channel_strip_strings() self.__update_page_switch_leds() self.request_rebuild_midi_map() def __switch_to_next_page(self): """ Switch to the next page in the non track strip modes (choosing plugs, or controlling devices) """ if self.__can_switch_to_next_page(): if self.__assignment_mode == CSM_PLUGINS: self.__plugin_mode_offsets[self.__plugin_mode] += len(self.__channel_strips) if self.__plugin_mode == PCM_DEVICES: self.__update_vpot_leds_in_plugins_device_choose_mode() elif self.__assignment_mode == CSM_SENDS: self.__send_mode_offset += len(self.__channel_strips) else: raise 0 or AssertionError self.__reassign_channel_strip_parameters(for_display_only=False) self.__update_channel_strip_strings() self.__update_page_switch_leds() self.request_rebuild_midi_map() def __switch_to_next_io_mode(self): """ Step through the available IO modes (In/OutPut//Main/Sub) """ self.__sub_mode_in_io_mode += 1 if self.__sub_mode_in_io_mode > CSM_IO_LAST_MODE: self.__sub_mode_in_io_mode = CSM_IO_FIRST_MODE def __reassign_channel_strip_offsets(self): """ Update the channel strips bank_channel offset """ for s in self.__channel_strips: s.set_bank_and_channel_offset(self.__strip_offset(), self.__view_returns, self.__within_track_added_or_deleted) def __reassign_channel_strip_parameters(self, for_display_only): """ Reevaluate all v-pot/fader -> parameter assignments """ display_parameters = [] for s in self.__channel_strips: vpot_param = (None, None) slider_param = (None, None) vpot_display_mode = VPOT_DISPLAY_SINGLE_DOT slider_display_mode = VPOT_DISPLAY_SINGLE_DOT if self.__assignment_mode == CSM_VOLPAN: if s.assigned_track() and s.assigned_track().has_audio_output: vpot_param = (s.assigned_track().mixer_device.panning, 'Pan') vpot_display_mode = VPOT_DISPLAY_BOOST_CUT slider_param = (s.assigned_track().mixer_device.volume, 'Volume') slider_display_mode = VPOT_DISPLAY_WRAP elif self.__assignment_mode == CSM_PLUGINS: vpot_param = self.__plugin_parameter(s.strip_index(), s.stack_offset()) vpot_display_mode = VPOT_DISPLAY_WRAP if s.assigned_track() and s.assigned_track().has_audio_output: slider_param = (s.assigned_track().mixer_device.volume, 'Volume') slider_display_mode = VPOT_DISPLAY_WRAP elif self.__assignment_mode == CSM_SENDS: vpot_param = self.__send_parameter(s.strip_index(), s.stack_offset()) vpot_display_mode = VPOT_DISPLAY_WRAP if s.assigned_track() and s.assigned_track().has_audio_output: slider_param = (s.assigned_track().mixer_device.volume, 'Volume') slider_display_mode = VPOT_DISPLAY_WRAP elif self.__assignment_mode == CSM_IO: if s.assigned_track() and s.assigned_track().has_audio_output: slider_param = (s.assigned_track().mixer_device.volume, 'Volume') if self.__flip and self.__can_flip(): if self.__any_slider_is_touched(): display_parameters.append(vpot_param) else: display_parameters.append(slider_param) if not for_display_only: s.set_v_pot_parameter(slider_param[0], slider_display_mode) s.set_fader_parameter(vpot_param[0]) else: if self.__any_slider_is_touched(): display_parameters.append(slider_param) else: display_parameters.append(vpot_param) if not for_display_only: s.set_v_pot_parameter(vpot_param[0], vpot_display_mode) s.set_fader_parameter(slider_param[0]) self.__main_display_controller.set_channel_offset(self.__strip_offset()) if len(display_parameters): self.__main_display_controller.set_parameters(display_parameters) def __apply_meter_mode(self): """ Update the meter mode in the displays and channel strips """ enabled = self.__meters_enabled and self.__assignment_mode is CSM_VOLPAN for s in self.__channel_strips: s.enable_meter_mode(enabled) self.__main_display_controller.enable_meters(enabled) def __toggle_flip(self): """ En/Disable V-Pot / Fader flipping """ if self.__can_flip(): self.__flip = not self.__flip self.__on_flip_changed() def __toggle_view_returns(self): """ Toggle if we want to control the return tracks or normal tracks """ self.__view_returns = not self.__view_returns self.__update_view_returns_mode() def __update_assignment_mode_leds(self): """ Show which assignment mode is currently active """ if self.__assignment_mode == CSM_IO: sid_on_switch = SID_ASSIGNMENT_IO elif self.__assignment_mode == CSM_SENDS: sid_on_switch = SID_ASSIGNMENT_SENDS elif self.__assignment_mode == CSM_VOLPAN: sid_on_switch = SID_ASSIGNMENT_PAN elif self.__assignment_mode == CSM_PLUGINS: sid_on_switch = SID_ASSIGNMENT_PLUG_INS else: raise 0 or AssertionError sid_on_switch = None for s in (SID_ASSIGNMENT_IO, SID_ASSIGNMENT_SENDS, SID_ASSIGNMENT_PAN, SID_ASSIGNMENT_PLUG_INS): if s == sid_on_switch: self.send_midi((NOTE_ON_STATUS, s, BUTTON_STATE_ON)) else: self.send_midi((NOTE_ON_STATUS, s, BUTTON_STATE_OFF)) def __update_assignment_display(self): """ Cryptically label the current assignment mode in the 2char display above the assignment buttons """ if self.__assignment_mode == CSM_VOLPAN: ass_string = ['P', 'N'] else: if self.__assignment_mode == CSM_PLUGINS or self.__assignment_mode == CSM_SENDS: ass_string = self.__last_attached_selected_track == self.song().master_track and ['M', 'A'] for t in self.song().return_tracks: if t == self.__last_attached_selected_track: ass_string = ['R', chr(ord('A') + list(self.song().return_tracks).index(t))] break for t in self.song().visible_tracks: if t == self.__last_attached_selected_track: ass_string = list('%.2d' % min(99, list(self.song().visible_tracks).index(t) + 1)) break if not ass_string: raise AssertionError elif self.__assignment_mode == CSM_IO: if self.__sub_mode_in_io_mode == CSM_IO_MODE_INPUT_MAIN: ass_string = ['I', "'"] elif self.__sub_mode_in_io_mode == CSM_IO_MODE_INPUT_SUB: ass_string = ['I', ','] elif self.__sub_mode_in_io_mode == CSM_IO_MODE_OUTPUT_MAIN: ass_string = ['0', "'"] elif self.__sub_mode_in_io_mode == CSM_IO_MODE_OUTPUT_SUB: ass_string = ['0', ','] else: raise 0 or AssertionError else: raise 0 or AssertionError self.send_midi((CC_STATUS, 75, g7_seg_led_conv_table[ass_string[0]])) self.send_midi((CC_STATUS, 74, g7_seg_led_conv_table[ass_string[1]])) def __update_page_switch_leds(self): """ visualize if the "prev" an "next" buttons can be pressed """ if self.__can_switch_to_prev_page(): self.send_midi((NOTE_ON_STATUS, SID_ASSIGNMENT_EQ, BUTTON_STATE_ON)) else: self.send_midi((NOTE_ON_STATUS, SID_ASSIGNMENT_EQ, BUTTON_STATE_OFF)) if self.__can_switch_to_next_page(): self.send_midi((NOTE_ON_STATUS, SID_ASSIGNMENT_DYNAMIC, BUTTON_STATE_ON)) else: self.send_midi((NOTE_ON_STATUS, SID_ASSIGNMENT_DYNAMIC, BUTTON_STATE_OFF)) def __update_vpot_leds_in_plugins_device_choose_mode(self): """ To be called in assignment mode CSM_PLUGINS, submode PCM_DEVICES only: This will enlighten all poties which can be pressed to choose a device for editing, and unlight all poties where pressing will have no effect """ raise self.__assignment_mode == CSM_PLUGINS or AssertionError raise self.__plugin_mode == PCM_DEVICES or AssertionError sel_track = self.song().view.selected_track count = 0 for s in self.__channel_strips: offset = self.__plugin_mode_offsets[self.__plugin_mode] if sel_track and offset + count >= 0 and offset + count < len(sel_track.devices): s.show_full_enlighted_poti() else: s.unlight_vpot_leds() count += 1 def __update_channel_strip_strings(self): """ In IO mode, collect all strings that will be visible in the main display manually """ if not self.__any_slider_is_touched(): if self.__assignment_mode == CSM_IO: targets = [] for s in self.__channel_strips: if self.__routing_target(s): targets.append(self.__routing_target(s)) else: targets.append('') self.__main_display_controller.set_channel_strip_strings(targets) elif self.__assignment_mode == CSM_PLUGINS and self.__plugin_mode == PCM_DEVICES: for plugin in self.__displayed_plugins: if plugin != None: plugin.remove_name_listener(self.__update_plugin_names) self.__displayed_plugins = [] sel_track = self.song().view.selected_track for i in range(len(self.__channel_strips)): device_index = i + self.__plugin_mode_offsets[PCM_DEVICES] if device_index >= 0 and device_index < len(sel_track.devices): sel_track.devices[device_index].add_name_listener(self.__update_plugin_names) self.__displayed_plugins.append(sel_track.devices[device_index]) else: self.__displayed_plugins.append(None) self.__update_plugin_names() def __update_view_returns_mode(self): """ Update the control return tracks LED """ if self.__view_returns: self.send_midi((NOTE_ON_STATUS, SID_FADERBANK_EDIT, BUTTON_STATE_ON)) else: self.send_midi((NOTE_ON_STATUS, SID_FADERBANK_EDIT, BUTTON_STATE_OFF)) self.__main_display_controller.set_show_return_track_names(self.__view_returns) self.__reassign_channel_strip_offsets() self.__reassign_channel_strip_parameters(for_display_only=False) self.request_rebuild_midi_map() def __on_selected_track_changed(self): """ Notifier, called as soon as the selected track has changed """ st = self.__last_attached_selected_track if st and st.devices_has_listener(self.__on_selected_device_chain_changed): st.remove_devices_listener(self.__on_selected_device_chain_changed) self.__last_attached_selected_track = self.song().view.selected_track st = self.__last_attached_selected_track if st: st.add_devices_listener(self.__on_selected_device_chain_changed) if self.__assignment_mode == CSM_PLUGINS: self.__plugin_mode_offsets = [ 0 for x in range(PCM_NUMMODES) ] if self.__chosen_plugin != None: self.__chosen_plugin.remove_parameters_listener(self.__on_parameter_list_of_chosen_plugin_changed) self.__chosen_plugin = None self.__ordered_plugin_parameters = [] self.__update_assignment_display() if self.__plugin_mode == PCM_DEVICES: self.__update_vpot_leds_in_plugins_device_choose_mode() else: self.__set_plugin_mode(PCM_DEVICES) elif self.__assignment_mode == CSM_SENDS: self.__reassign_channel_strip_parameters(for_display_only=False) self.__update_assignment_display() self.request_rebuild_midi_map() def __on_flip_changed(self): """ Update the flip button LED when the flip mode changed """ self.__update_flip_led() if self.__can_flip(): self.__update_assignment_display() self.__reassign_channel_strip_parameters(for_display_only=False) self.request_rebuild_midi_map() def __on_tracks_added_or_deleted(self): """ Notifier, called as soon as tracks where added, removed or moved """ self.__within_track_added_or_deleted = True for t in chain(self.song().visible_tracks, self.song().return_tracks): if not t.solo_has_listener(self.__update_rude_solo_led): t.add_solo_listener(self.__update_rude_solo_led) if not t.has_audio_output_has_listener(self.__on_any_tracks_output_type_changed): t.add_has_audio_output_listener(self.__on_any_tracks_output_type_changed) if self.__send_mode_offset >= len(self.song().return_tracks): self.__send_mode_offset = 0 self.__reassign_channel_strip_parameters(for_display_only=False) self.__update_channel_strip_strings() if self.__strip_offset() + len(self.__channel_strips) >= self.__controlled_num_of_tracks(): self.__set_channel_offset(max(0, self.__controlled_num_of_tracks() - len(self.__channel_strips))) self.__reassign_channel_strip_parameters(for_display_only=False) self.__update_channel_strip_strings() if self.__assignment_mode == CSM_SENDS: self.__update_page_switch_leds() self.refresh_state() self.__main_display_controller.refresh_state() self.__within_track_added_or_deleted = False self.request_rebuild_midi_map() def __on_any_tracks_output_type_changed(self): """ called as soon as any device chain has changed (devices where added/removed/swapped...) """ self.__reassign_channel_strip_parameters(for_display_only=False) self.request_rebuild_midi_map()
[ 2, 31567, 47238, 2393, 1438, 25, 1220, 14490, 14, 49589, 1352, 14, 39, 463, 1559, 14, 12583, 14, 16775, 82, 14, 4677, 18947, 14, 33236, 14, 44, 2389, 40, 21520, 12327, 82, 14, 44, 441, 494, 15988, 14, 29239, 1273, 5528, 22130, 13, ...
2.147581
13,125
nome = str(input('Digite o seu nome: ')) nom = nome.title() print('Silva' in nom)
[ 77, 462, 796, 965, 7, 15414, 10786, 19511, 578, 267, 384, 84, 299, 462, 25, 705, 4008, 198, 26601, 796, 299, 462, 13, 7839, 3419, 198, 4798, 10786, 15086, 6862, 6, 287, 4515, 8 ]
2.382353
34
print(insertionSort([55,3,2,5,6,75,4]))
[ 201, 198, 201, 198, 201, 198, 4798, 7, 28463, 295, 42758, 26933, 2816, 11, 18, 11, 17, 11, 20, 11, 21, 11, 2425, 11, 19, 60, 4008 ]
1.666667
27
#!/usr/bin/env python3 # encoding: utf-8 # # Copyright (c) 2010 Doug Hellmann. All rights reserved. # """ """ #end_pymotw_header import argparse parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-a', action='store_true') group.add_argument('-b', action='store_true') print(parser.parse_args())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 2, 198, 2, 15069, 357, 66, 8, 3050, 15115, 5783, 9038, 13, 220, 1439, 2489, 10395, 13, 198, 2, 198, 37811, 198, 37811, 198, 198, 2, 437, ...
2.8
125
#!/usr/bin/env python3 # === IMPORTS === import logging import os from flask import Flask from inovonics.cloud.datastore import InoRedis from inovonics.cloud.oauth import InoOAuth2Provider, oauth_register_handlers from inovonics.cloud.oauth import OAuthClients, OAuthClient, OAuthUsers, OAuthUser # === GLOBALS === REDIS_HOST = os.getenv('REDIS_HOST', 'localhost') REDIS_PORT = os.getenv('REDIS_PORT', 6379) REDIS_DB = os.getenv('REDIS_DB', 0) dstore = InoRedis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB) app = Flask(__name__) oauth = InoOAuth2Provider(app, dstore) oauth_register_handlers(app, oauth, token_path='/oauth/token', revoke_path='/oauth/revoke') # === FUNCTIONS === @app.before_first_request @app.route('/') @app.route('/protected/') @oauth.require_oauth('protected') # === CLASSES === # === MAIN === if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 24844, 30023, 33002, 24844, 198, 11748, 18931, 198, 11748, 28686, 198, 198, 6738, 42903, 1330, 46947, 198, 198, 6738, 287, 709, 38530, 13, 17721, 13, 19608, 459, 382, 1330, ...
2.555882
340
from otree.api import Currency as c, currency_range from . import views from ._builtin import Bot from .models import Constants from otree.api import SubmissionMustFail
[ 6738, 267, 21048, 13, 15042, 1330, 20113, 355, 269, 11, 7395, 62, 9521, 198, 6738, 764, 1330, 5009, 198, 6738, 47540, 18780, 259, 1330, 18579, 198, 6738, 764, 27530, 1330, 4757, 1187, 198, 6738, 267, 21048, 13, 15042, 1330, 42641, 34320...
3.866667
45
from transferfile import TransferFactory from pathlib import Path
[ 6738, 4351, 7753, 1330, 20558, 22810, 198, 6738, 3108, 8019, 1330, 10644, 628 ]
5.153846
13
''' Socket.IO server for testing CLI: python -m watchgod server.main [aiohttp|sanic|tornado|asgi] Test results: | connect | disconnect | event | background_task | Ctrl+C ---------+---------+------------+-------+-----------------|-------- aiohttp | O | O | O | X | O sanic | O | O | O | X | O tornado | O | O | O | O | O asgi | O | O | O | ! | O ''' import sys from servers.aiohttp_server import main as aiohttp_main from servers.asgi_server import main as asgi_main from servers.sanic_server import main as sanic_main from servers.tornado_server import main as tornado_main if __name__ == '__main__': main()
[ 7061, 6, 201, 198, 39105, 13, 9399, 4382, 329, 4856, 201, 198, 201, 198, 5097, 40, 25, 201, 198, 220, 21015, 532, 76, 2342, 25344, 4382, 13, 12417, 685, 64, 952, 4023, 91, 12807, 291, 91, 45910, 4533, 91, 292, 12397, 60, 201, 198,...
2.0375
400
import cv2 video_file_name = "" if __name__ == '__main__': FrameCapture(video_file_name)
[ 11748, 269, 85, 17, 220, 198, 198, 15588, 62, 7753, 62, 3672, 796, 13538, 198, 220, 220, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 220, 198, 220, 220, 220, 25184, 49630, 7, 15588, 62, 7753, 62, 3672, 8, 198 ]
2.302326
43
# Copyright 2016 Medical Research Council Harwell. # # 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. # # # @author Neil Horner <n.horner@har.mrc.ac.uk> """ TODO: don't duplicate the full array for each _get_* function """ import numpy as np import os import tempfile from PIL import Image from PyQt5 import QtCore from vpv.common import read_image, get_stage_and_modality, error_dialog from vpv.annotations.impc_xml import load_xml, get_annotator_id_and_date from vpv.annotations.annotations_model import centre_stage_options, PROCEDURE_METADATA, ANNOTATION_DONE_METADATA_FILE from .ImageVolume import ImageVolume from .HeatmapVolume import HeatmapVolume from .VectorVolume import VectorVolume from .ImageSeriesVolume import ImageSeriesVolume from .VirtualStackVolume import VirtualStackVolume import yaml class DataModel(QtCore.QObject): """ The model for our app """ data_changed_signal = QtCore.pyqtSignal() updating_started_signal = QtCore.pyqtSignal() updating_msg_signal = QtCore.pyqtSignal(str) updating_finished_signal = QtCore.pyqtSignal() def update_msg_slot(self, msg): """ Gets update messages from the different volume classes which are then propagated to the main window to display a progress message Parameters ---------- msg: str progress message """ self.update_msg_signal.emit(msg) def load_annotation(self, ann_path): """ Load annotations from an IMPC xml file. Parameters ---------- ann_path: str path to xml annotation file Returns ------- """ # Load in data from xml try: centerID, pipeline, project, doe, ex_id, spec_id, proc_id, \ simple_and_series_params, procedure_metadata = load_xml(ann_path) except IOError as e: print("Cannot read xml file {}\n".format(ann_path, e)) error_dialog(None, 'File read error', "Problem reading annotaitons file\n{}".format(ann_path)) return # try to find a corresponding procedure_metadata.yaml file ann_dir = os.path.split(ann_path)[0] procedure_metadata_file = os.path.join(ann_dir, PROCEDURE_METADATA) if not os.path.isfile(procedure_metadata_file): vol = None # Should also check if annotation options have been loaded else: vol_id = os.path.basename(ann_dir) # The annotation directory is the same name as the annotated volume vol = self._volumes.get(vol_id) if not vol: return "Could not load annotation: {}. Not able to find loaded volume with same id".format(vol_id) vol.annotations.clear() # Get the dict that contains the available options for a given center/stage annotation_date_param_id = get_annotator_id_and_date(proc_id)[1] ann_date = [x[1] for x in procedure_metadata if x[0] == annotation_date_param_id] ann_date = ann_date[0] vol.annotations.annotation_date = ann_date default_opts = centre_stage_options.opts stage = get_stage_and_modality(proc_id, centerID) ###################################### # This all needs moving into Annotations # Set the xml file path which is where it will get resaved to vol.annotations.saved_xml_fname = ann_path # Get all the simpleParameter entries form the xml file for xml_param, xml_data in simple_and_series_params.items(): option = xml_data['option'] xyz = xml_data.get('xyz') if xyz: x, y, z = [int(i) for i in xyz] else: x = y = z = None dims = vol.shape_xyz() # Some of the data needed to create an annotation object is not recorded in the XML output # So we need to load that from the center annotation options file for center, default_data in default_opts['centers'].items(): if default_data['short_name'] == centerID: params = default_data['procedures'][proc_id]['parameters'] for param_id, default_param_info in params.items(): if param_id == xml_param: name = default_param_info['name'] options = default_opts['available_options'][ default_param_info['options']] # available options for this parameter order = default_param_info['order'] is_mandatory = default_param_info['mandatory'] vol.annotations.add_impc_annotation(x, y, z, xml_param, name, options, option, stage, order, is_mandatory, dims) vol.annotations._load_done_status() # def load_annotation(self, ann_path): # """ # Load annotations from an IMPC xml file. # # Parameters # ---------- # ann_path: str # path to xml annotation file # # Returns # ------- # # """ # # Load in data from xml # centerID, pipeline, project, doe, ex_id, spec_id, proc_id, \ # simple_and_series_params, procedure_metadata = load_xml(ann_path) # # # try to find a corresponding procedure_metadata.yaml file # ann_dir = os.path.split(ann_path)[0] # procedure_metadata_file = os.path.join(ann_dir, PROCEDURE_METADATA) # if not os.path.isfile(procedure_metadata_file): # vol = None # Should also check if annotation options have been loaded # else: # vol_id = os.path.basename(ann_dir) # The annotation directory is the same name as the annotated volume # vol = self._volumes.get(vol_id) # # if vol: # # Get the dict that contains the available options for a given center/stage # default_opts = centre_stage_options.opts # stage = get_stage_from_proc_id(proc_id, centerID) # # # Get all the simpleParameter entries form the xml file # for xml_param, xml_data in simple_and_series_params.items(): # option = xml_data['option'] # xyz = xml_data.get('xyz') # if xyz: # x, y, z = [int(i) for i in xyz] # else: # x = y = z = None # dims = vol.shape_xyz() # # # Some of the data neded to crate an annotation object is not recorded in the XML output # # So we need to load that from the center annotation options file # for center, default_data in default_opts['centers'].items(): # if default_data['short_name'] == centerID: # params = default_data['stages'][stage]['parameters'] # # for param_id, default_param_info in params.items(): # if param_id == xml_param: # name = default_param_info['name'] # options = default_opts['available_options'][default_param_info['options']]# available options for this parameter # order = default_param_info['options'] # is_mandatory = default_param_info['mandatory'] # # vol.annotations.add_impc_annotation(x, y, z, xml_param, name, options, option, stage, # order, is_mandatory, dims) # # else: # return "Could not load annotation: {}. Not able to find loaded volume with same id".format(vol_id) # return None def add_volume(self, volpath, data_type, memory_map, fdr_thresholds=False) -> str: """ Load a volume into a subclass of a Volume object Parameters ---------- volpath: str data_type: str memory_map: bool fdr_thresholds: fdict q -> t statistic mappings {0.01: 3.4, 0.05:, 3.1} Returns ------- unique id of loaded image """ if data_type != 'virtual_stack': volpath = str(volpath) n = os.path.basename(volpath) unique_name = self.create_unique_name(n) else: n = os.path.basename(os.path.split(volpath[0])[0]) unique_name = self.create_unique_name(n) if data_type == 'heatmap': vol = HeatmapVolume(volpath, self, 'heatmap') if fdr_thresholds or fdr_thresholds is None: vol.fdr_thresholds = fdr_thresholds vol.name = unique_name self._data[vol.name] = vol elif data_type == 'vol': vol = ImageVolume(volpath, self, 'volume', memory_map) vol.name = unique_name self._volumes[vol.name] = vol elif data_type == 'virtual_stack': vol = VirtualStackVolume(volpath, self, 'virtual_stack', memory_map) vol.name = unique_name self._volumes[vol.name] = vol elif data_type == 'vector': vol = VectorVolume(volpath, self, 'vector') vol.name = unique_name self._vectors[vol.name] = vol self.id_counter += 1 self.data_changed_signal.emit() return unique_name def create_unique_name(self, name): """ Create a unique name for each volume. If it already exists, append a digit in a bracket to it :param name: :return: """ name = os.path.splitext(name)[0] if name not in self._volumes and name not in self._data and name not in self._vectors: return name else: for i in range(1, 100): new_name = '{}({})'.format(name, i) if new_name not in self._volumes and new_name not in self._data: return new_name def write_temporary_annotations_metadata(self): """ Returns ------- """ from os.path import join for id_, vol in self._volumes.items(): if vol.annotations.annotation_dir: # Check for previous done list done_file = join(vol.annotations.annotation_dir, ANNOTATION_DONE_METADATA_FILE) done_status = {} for ann in vol.annotations: done_status[ann.term] = ann.looked_at with open(done_file, 'w') as fh: fh.write(yaml.dump(done_status))
[ 2, 15069, 1584, 8366, 4992, 4281, 2113, 4053, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 1...
2.176957
5,199
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. # # Maintainer: Jonathan Lange <jml@twistedmatrix.com> import errno, sys, os, re, StringIO from twisted.internet.utils import suppressWarnings from twisted.python import failure from twisted.trial import unittest, runner, reporter, util from twisted.trial.test import erroneous class BrokenStream(object): """ Stream-ish object that raises a signal interrupt error. We use this to make sure that Trial still manages to write what it needs to write. """ written = False flushed = False class MockColorizer: """ Used by TestTreeReporter to make sure that output is colored correctly. """ supported = classmethod(supported)
[ 2, 15069, 357, 66, 8, 5878, 12, 15724, 40006, 24936, 46779, 13, 198, 2, 4091, 38559, 24290, 329, 3307, 13, 198, 2, 198, 2, 337, 2913, 10613, 25, 11232, 47579, 1279, 73, 4029, 31, 4246, 6347, 6759, 8609, 13, 785, 29, 628, 198, 1174...
3.436937
222
# Import Flask app object from project folder (For python this means from the __init__.py file) from project import app # Run flask app with debug on and listening on port 8000 app.run( debug=True, port=8000 )
[ 2, 17267, 46947, 598, 2134, 422, 1628, 9483, 357, 1890, 21015, 428, 1724, 422, 262, 11593, 15003, 834, 13, 9078, 2393, 8, 198, 6738, 1628, 1330, 598, 198, 198, 2, 5660, 42903, 598, 351, 14257, 319, 290, 8680, 319, 2493, 38055, 198, ...
3.460317
63
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: Prediction exercise fruits = ['Strawberry', 'Lemon', 'Orange', 'Raspberry', 'Cherry'] print(fruits[0]) print(fruits[3]) print(fruits[2]) print(fruits[len(fruits)-1]) print(fruits[1]) fruit = fruits[2+2] print(fruit) print(fruit[0]) orange = fruits[1] print(orange) lemon = fruits[1] print(lemon) # Additional question (on the same page) # A string is in fact a list of single character strings # The first index refers to the list element # The second index is applied to that element print(fruits[0][0]+fruits[1][0]+fruits[2][0])
[ 2, 8558, 25, 406, 4093, 50, 11361, 49983, 20389, 26701, 201, 198, 2, 7536, 25, 1737, 2864, 201, 198, 2, 6434, 25, 5689, 3594, 11, 14340, 2257, 201, 198, 2, 304, 25804, 25, 9061, 4234, 31, 30094, 301, 13, 494, 201, 198, 2, 32039, ...
2.687023
262
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Jan 4 07:43:40 2020 @author: lukemcculloch """ import numpy as np
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 7031, 2365, 220, 604, 8753, 25, 3559, 25, 1821, 12131, 198, 198, 31, 9800, 25, 300, 4649,...
2
76
from .vsr import VERSION __version__ = VERSION __author__ = 'Sameera Sandaruwan' __author_email__ = 'basameera@protonmail.com'
[ 6738, 764, 14259, 81, 1330, 44156, 2849, 198, 834, 9641, 834, 796, 44156, 2849, 198, 834, 9800, 834, 796, 705, 30556, 8607, 3837, 11493, 8149, 6, 198, 834, 9800, 62, 12888, 834, 796, 705, 12093, 480, 8607, 31, 1676, 1122, 4529, 13, ...
2.863636
44
from django.test import LiveServerTestCase from selenium import webdriver from django.urls import reverse from django.utils.translation import activate, gettext_lazy as _ from .creation_utils import create_user, create_post from simpleblog.models import Post if __name__ == '__main__': unittest.main()
[ 6738, 42625, 14208, 13, 9288, 1330, 7547, 10697, 14402, 20448, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 15155, 11, 651, 5239, ...
3.411111
90
# O(n) time | O(n) space # O(n) time | O(1) space
[ 2, 440, 7, 77, 8, 640, 930, 440, 7, 77, 8, 2272, 198, 198, 2, 440, 7, 77, 8, 640, 930, 440, 7, 16, 8, 2272, 198 ]
1.888889
27
#!/usr/bin/env python # -*- coding: utf-8 -*- #! 强制默认编码为utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') import urllib, urllib2, json, time from pprint import pprint from pdb import set_trace import requests from lxml import html from alfred.feedback import Feedback from config import service, addword, loginurl, username, pwd # 扇贝词典 if __name__ == '__main__': d = ShanbayDict() d.query(sys.argv[1]) d.output()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 0, 10263, 120, 118, 26344, 114, 165, 119, 246, 164, 106, 97, 163, 120, 244, 163, 254, 223, 10310, 118, 40477, 12...
2.265306
196
ODL_IP = "127.0.0.1" ODL_PORT = "8181" ODL_USER = "admin" ODL_PASS = "admin"
[ 3727, 43, 62, 4061, 796, 366, 16799, 13, 15, 13, 15, 13, 16, 1, 198, 3727, 43, 62, 15490, 796, 366, 23, 27057, 1, 198, 3727, 43, 62, 29904, 796, 366, 28482, 1, 198, 3727, 43, 62, 47924, 796, 366, 28482, 1, 628 ]
1.813953
43
import requests from nova_dveri_ru.data import USER_AGENT if __name__ == '__main__': url = 'https://nova-dveri.ru/mezhkomnatnye-dveri/ehkoshpon/il%20doors/dver-galleya-07-chern-yasen-svetlyj' out_html_file = 'galleya-07-chern-yasen-svetlyj.html' save_html_code(url, out_html_file)
[ 11748, 7007, 198, 198, 6738, 645, 6862, 62, 67, 332, 72, 62, 622, 13, 7890, 1330, 1294, 1137, 62, 4760, 3525, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 19016, 796, 705, 5450, 1378, ...
2.048276
145
# Copyright 2021 Jakub Kuczys (https://github.com/jack1142) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """User models""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Optional, final from ..bit_fields import Badges, UserFlags from ..enums import Presence, RelationshipStatus from .attachment import Attachment from .bases import Model, ParserData, StatefulModel, StatefulResource, field if TYPE_CHECKING: from ...events import UserUpdateEvent from ..state import State __all__ = ( "User", "BotInfo", "Relationship", "Status", "UserProfile", ) @final class Status(Model): """ Status() Represents a user's status. Attributes: text: The custom status text. presence: The user's presence. """ text: Optional[str] = field("text", default=None) # Users who have never changed their presence do not have the `presence`. # New users start with an Online presence, # so that's what we should use in such case. presence: Presence = field("presence", factory=True, default="Online") @final class Relationship(StatefulModel): """ Relationship() Represents the client user's relationship with other user. Attributes: user_id: The ID of the other user in this relation. status: The relationship's status. """ user_id: str = field("_id") status: RelationshipStatus = field("status", factory=True) @final class BotInfo(StatefulModel): """ BotInfo() Represents the information about a bot user. Attributes: owner_id: The ID of the bot owner. """ owner_id: str = field("owner") @classmethod @final class UserProfile(StatefulModel): """ UserProfile() Represents a profile of a user. Attributes: content: The profile content if provided. background: The profile background if provided. """ content: Optional[str] = field("content", default=None) background: Optional[Attachment] = field("background", factory=True, default=None) @classmethod @final class User(StatefulResource): """ User() Represents a user. Attributes: id: The user ID. username: The username. avatar: The user's avatar. relations: The user's relations. This is only present for the client user. badges: The user's badges. status: The user's status. relationship_status: The client user's relationship status with this user. online: Indicates whether the user is online. flags: The user flags. bot: The information about this bot, or `None` if this user is not a bot. profile: The user's profile. """ id: str = field("_id") username: str = field("username") avatar: Optional[Attachment] = field("avatar", factory=True, default=None) relations: Optional[dict[str, Relationship]] = field( "relations", factory=True, default=None ) badges: Badges = field("badges", factory=True, default=0) status: Status = field("status", factory=True, default_factory=dict) relationship_status: Optional[RelationshipStatus] = field( "relationship", factory=True, default=None ) online: bool = field("online") flags: UserFlags = field("flags", factory=True, default=0) bot: Optional[BotInfo] = field("bot", factory=True, default=None) profile: Optional[UserProfile] = field("profile", factory=True, default=None)
[ 2, 15069, 33448, 25845, 549, 509, 1229, 89, 893, 357, 5450, 1378, 12567, 13, 785, 14, 19650, 1157, 3682, 8, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407...
3.047292
1,311
from dataclasses import dataclass from profit.types.blockchain_format.sized_bytes import bytes32 from profit.util.ints import uint32 from profit.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 198, 6738, 7630, 13, 19199, 13, 9967, 7983, 62, 18982, 13, 13982, 62, 33661, 1330, 9881, 2624, 198, 6738, 7630, 13, 22602, 13, 29503, 1330, 20398, 2624, 198, 6738, 7630, 13, 22602, ...
3.432836
67
# Generated by h2py from \mssdk\include\winnt.h APPLICATION_ERROR_MASK = 536870912 ERROR_SEVERITY_SUCCESS = 0 ERROR_SEVERITY_INFORMATIONAL = 1073741824 ERROR_SEVERITY_WARNING = -2147483648 ERROR_SEVERITY_ERROR = -1073741824 MINCHAR = 128 MAXCHAR = 127 MINSHORT = 32768 MAXSHORT = 32767 MINLONG = -2147483648 MAXLONG = 2147483647 MAXBYTE = 255 MAXWORD = 65535 MAXDWORD = -1 LANG_NEUTRAL = 0 LANG_AFRIKAANS = 54 LANG_ALBANIAN = 28 LANG_ARABIC = 1 LANG_BASQUE = 45 LANG_BELARUSIAN = 35 LANG_BULGARIAN = 2 LANG_CATALAN = 3 LANG_CHINESE = 4 LANG_CROATIAN = 26 LANG_CZECH = 5 LANG_DANISH = 6 LANG_DUTCH = 19 LANG_ENGLISH = 9 LANG_ESTONIAN = 37 LANG_FAEROESE = 56 LANG_FARSI = 41 LANG_FINNISH = 11 LANG_FRENCH = 12 LANG_GERMAN = 7 LANG_GREEK = 8 LANG_HEBREW = 13 LANG_HINDI = 57 LANG_HUNGARIAN = 14 LANG_ICELANDIC = 15 LANG_INDONESIAN = 33 LANG_ITALIAN = 16 LANG_JAPANESE = 17 LANG_KOREAN = 18 LANG_LATVIAN = 38 LANG_LITHUANIAN = 39 LANG_MACEDONIAN = 47 LANG_MALAY = 62 LANG_NORWEGIAN = 20 LANG_POLISH = 21 LANG_PORTUGUESE = 22 LANG_ROMANIAN = 24 LANG_RUSSIAN = 25 LANG_SERBIAN = 26 LANG_SLOVAK = 27 LANG_SLOVENIAN = 36 LANG_SPANISH = 10 LANG_SWAHILI = 65 LANG_SWEDISH = 29 LANG_THAI = 30 LANG_TURKISH = 31 LANG_UKRAINIAN = 34 LANG_VIETNAMESE = 42 SUBLANG_NEUTRAL = 0 SUBLANG_DEFAULT = 1 SUBLANG_SYS_DEFAULT = 2 SUBLANG_ARABIC_SAUDI_ARABIA = 1 SUBLANG_ARABIC_IRAQ = 2 SUBLANG_ARABIC_EGYPT = 3 SUBLANG_ARABIC_LIBYA = 4 SUBLANG_ARABIC_ALGERIA = 5 SUBLANG_ARABIC_MOROCCO = 6 SUBLANG_ARABIC_TUNISIA = 7 SUBLANG_ARABIC_OMAN = 8 SUBLANG_ARABIC_YEMEN = 9 SUBLANG_ARABIC_SYRIA = 10 SUBLANG_ARABIC_JORDAN = 11 SUBLANG_ARABIC_LEBANON = 12 SUBLANG_ARABIC_KUWAIT = 13 SUBLANG_ARABIC_UAE = 14 SUBLANG_ARABIC_BAHRAIN = 15 SUBLANG_ARABIC_QATAR = 16 SUBLANG_CHINESE_TRADITIONAL = 1 SUBLANG_CHINESE_SIMPLIFIED = 2 SUBLANG_CHINESE_HONGKONG = 3 SUBLANG_CHINESE_SINGAPORE = 4 SUBLANG_CHINESE_MACAU = 5 SUBLANG_DUTCH = 1 SUBLANG_DUTCH_BELGIAN = 2 SUBLANG_ENGLISH_US = 1 SUBLANG_ENGLISH_UK = 2 SUBLANG_ENGLISH_AUS = 3 SUBLANG_ENGLISH_CAN = 4 SUBLANG_ENGLISH_NZ = 5 SUBLANG_ENGLISH_EIRE = 6 SUBLANG_ENGLISH_SOUTH_AFRICA = 7 SUBLANG_ENGLISH_JAMAICA = 8 SUBLANG_ENGLISH_CARIBBEAN = 9 SUBLANG_ENGLISH_BELIZE = 10 SUBLANG_ENGLISH_TRINIDAD = 11 SUBLANG_ENGLISH_ZIMBABWE = 12 SUBLANG_ENGLISH_PHILIPPINES = 13 SUBLANG_FRENCH = 1 SUBLANG_FRENCH_BELGIAN = 2 SUBLANG_FRENCH_CANADIAN = 3 SUBLANG_FRENCH_SWISS = 4 SUBLANG_FRENCH_LUXEMBOURG = 5 SUBLANG_FRENCH_MONACO = 6 SUBLANG_GERMAN = 1 SUBLANG_GERMAN_SWISS = 2 SUBLANG_GERMAN_AUSTRIAN = 3 SUBLANG_GERMAN_LUXEMBOURG = 4 SUBLANG_GERMAN_LIECHTENSTEIN = 5 SUBLANG_ITALIAN = 1 SUBLANG_ITALIAN_SWISS = 2 SUBLANG_KOREAN = 1 SUBLANG_KOREAN_JOHAB = 2 SUBLANG_LITHUANIAN = 1 SUBLANG_LITHUANIAN_CLASSIC = 2 SUBLANG_MALAY_MALAYSIA = 1 SUBLANG_MALAY_BRUNEI_DARUSSALAM = 2 SUBLANG_NORWEGIAN_BOKMAL = 1 SUBLANG_NORWEGIAN_NYNORSK = 2 SUBLANG_PORTUGUESE = 2 SUBLANG_PORTUGUESE_BRAZILIAN = 1 SUBLANG_SERBIAN_LATIN = 2 SUBLANG_SERBIAN_CYRILLIC = 3 SUBLANG_SPANISH = 1 SUBLANG_SPANISH_MEXICAN = 2 SUBLANG_SPANISH_MODERN = 3 SUBLANG_SPANISH_GUATEMALA = 4 SUBLANG_SPANISH_COSTA_RICA = 5 SUBLANG_SPANISH_PANAMA = 6 SUBLANG_SPANISH_DOMINICAN_REPUBLIC = 7 SUBLANG_SPANISH_VENEZUELA = 8 SUBLANG_SPANISH_COLOMBIA = 9 SUBLANG_SPANISH_PERU = 10 SUBLANG_SPANISH_ARGENTINA = 11 SUBLANG_SPANISH_ECUADOR = 12 SUBLANG_SPANISH_CHILE = 13 SUBLANG_SPANISH_URUGUAY = 14 SUBLANG_SPANISH_PARAGUAY = 15 SUBLANG_SPANISH_BOLIVIA = 16 SUBLANG_SPANISH_EL_SALVADOR = 17 SUBLANG_SPANISH_HONDURAS = 18 SUBLANG_SPANISH_NICARAGUA = 19 SUBLANG_SPANISH_PUERTO_RICO = 20 SUBLANG_SWEDISH = 1 SUBLANG_SWEDISH_FINLAND = 2 SORT_DEFAULT = 0 SORT_JAPANESE_XJIS = 0 SORT_JAPANESE_UNICODE = 1 SORT_CHINESE_BIG5 = 0 SORT_CHINESE_PRCP = 0 SORT_CHINESE_UNICODE = 1 SORT_CHINESE_PRC = 2 SORT_KOREAN_KSC = 0 SORT_KOREAN_UNICODE = 1 SORT_GERMAN_PHONE_BOOK = 1 NLS_VALID_LOCALE_MASK = 1048575 MAXIMUM_WAIT_OBJECTS = 64 MAXIMUM_SUSPEND_COUNT = MAXCHAR EXCEPTION_NONCONTINUABLE = 1 EXCEPTION_MAXIMUM_PARAMETERS = 15 PROCESS_TERMINATE = (1) PROCESS_CREATE_THREAD = (2) PROCESS_VM_OPERATION = (8) PROCESS_VM_READ = (16) PROCESS_VM_WRITE = (32) PROCESS_DUP_HANDLE = (64) PROCESS_CREATE_PROCESS = (128) PROCESS_SET_QUOTA = (256) PROCESS_SET_INFORMATION = (512) PROCESS_QUERY_INFORMATION = (1024) MAXIMUM_PROCESSORS = 32 THREAD_TERMINATE = (1) THREAD_SUSPEND_RESUME = (2) THREAD_GET_CONTEXT = (8) THREAD_SET_CONTEXT = (16) THREAD_SET_INFORMATION = (32) THREAD_QUERY_INFORMATION = (64) THREAD_SET_THREAD_TOKEN = (128) THREAD_IMPERSONATE = (256) THREAD_DIRECT_IMPERSONATION = (512) JOB_OBJECT_ASSIGN_PROCESS = (1) JOB_OBJECT_SET_ATTRIBUTES = (2) JOB_OBJECT_QUERY = (4) JOB_OBJECT_TERMINATE = (8) TLS_MINIMUM_AVAILABLE = 64 THREAD_BASE_PRIORITY_LOWRT = 15 THREAD_BASE_PRIORITY_MAX = 2 THREAD_BASE_PRIORITY_MIN = -2 THREAD_BASE_PRIORITY_IDLE = -15 JOB_OBJECT_LIMIT_WORKINGSET = 1 JOB_OBJECT_LIMIT_PROCESS_TIME = 2 JOB_OBJECT_LIMIT_JOB_TIME = 4 JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 8 JOB_OBJECT_LIMIT_AFFINITY = 16 JOB_OBJECT_LIMIT_PRIORITY_CLASS = 32 JOB_OBJECT_LIMIT_VALID_FLAGS = 63 EVENT_MODIFY_STATE = 2 MUTANT_QUERY_STATE = 1 SEMAPHORE_MODIFY_STATE = 2 TIME_ZONE_ID_UNKNOWN = 0 TIME_ZONE_ID_STANDARD = 1 TIME_ZONE_ID_DAYLIGHT = 2 PROCESSOR_INTEL_386 = 386 PROCESSOR_INTEL_486 = 486 PROCESSOR_INTEL_PENTIUM = 586 PROCESSOR_MIPS_R4000 = 4000 PROCESSOR_ALPHA_21064 = 21064 PROCESSOR_HITACHI_SH3 = 10003 PROCESSOR_HITACHI_SH3E = 10004 PROCESSOR_HITACHI_SH4 = 10005 PROCESSOR_MOTOROLA_821 = 821 PROCESSOR_ARM_7TDMI = 70001 PROCESSOR_ARCHITECTURE_INTEL = 0 PROCESSOR_ARCHITECTURE_MIPS = 1 PROCESSOR_ARCHITECTURE_ALPHA = 2 PROCESSOR_ARCHITECTURE_PPC = 3 PROCESSOR_ARCHITECTURE_SH = 4 PROCESSOR_ARCHITECTURE_ARM = 5 PROCESSOR_ARCHITECTURE_UNKNOWN = 65535 PF_FLOATING_POINT_PRECISION_ERRATA = 0 PF_FLOATING_POINT_EMULATED = 1 PF_COMPARE_EXCHANGE_DOUBLE = 2 PF_MMX_INSTRUCTIONS_AVAILABLE = 3 PF_PPC_MOVEMEM_64BIT_OK = 4 PF_ALPHA_BYTE_INSTRUCTIONS = 5 SECTION_QUERY = 1 SECTION_MAP_WRITE = 2 SECTION_MAP_READ = 4 SECTION_MAP_EXECUTE = 8 SECTION_EXTEND_SIZE = 16 PAGE_NOACCESS = 1 PAGE_READONLY = 2 PAGE_READWRITE = 4 PAGE_WRITECOPY = 8 PAGE_EXECUTE = 16 PAGE_EXECUTE_READ = 32 PAGE_EXECUTE_READWRITE = 64 PAGE_EXECUTE_WRITECOPY = 128 PAGE_GUARD = 256 PAGE_NOCACHE = 512 MEM_COMMIT = 4096 MEM_RESERVE = 8192 MEM_DECOMMIT = 16384 MEM_RELEASE = 32768 MEM_FREE = 65536 MEM_PRIVATE = 131072 MEM_MAPPED = 262144 MEM_RESET = 524288 MEM_TOP_DOWN = 1048576 MEM_4MB_PAGES = -2147483648 SEC_FILE = 8388608 SEC_IMAGE = 16777216 SEC_VLM = 33554432 SEC_RESERVE = 67108864 SEC_COMMIT = 134217728 SEC_NOCACHE = 268435456 MEM_IMAGE = SEC_IMAGE FILE_READ_DATA = ( 1 ) FILE_LIST_DIRECTORY = ( 1 ) FILE_WRITE_DATA = ( 2 ) FILE_ADD_FILE = ( 2 ) FILE_APPEND_DATA = ( 4 ) FILE_ADD_SUBDIRECTORY = ( 4 ) FILE_CREATE_PIPE_INSTANCE = ( 4 ) FILE_READ_EA = ( 8 ) FILE_WRITE_EA = ( 16 ) FILE_EXECUTE = ( 32 ) FILE_TRAVERSE = ( 32 ) FILE_DELETE_CHILD = ( 64 ) FILE_READ_ATTRIBUTES = ( 128 ) FILE_WRITE_ATTRIBUTES = ( 256 ) FILE_SHARE_READ = 1 FILE_SHARE_WRITE = 2 FILE_SHARE_DELETE = 4 FILE_ATTRIBUTE_READONLY = 1 FILE_ATTRIBUTE_HIDDEN = 2 FILE_ATTRIBUTE_SYSTEM = 4 FILE_ATTRIBUTE_DIRECTORY = 16 FILE_ATTRIBUTE_ARCHIVE = 32 FILE_ATTRIBUTE_ENCRYPTED = 64 FILE_ATTRIBUTE_NORMAL = 128 FILE_ATTRIBUTE_TEMPORARY = 256 FILE_ATTRIBUTE_SPARSE_FILE = 512 FILE_ATTRIBUTE_REPARSE_POINT = 1024 FILE_ATTRIBUTE_COMPRESSED = 2048 FILE_ATTRIBUTE_OFFLINE = 4096 FILE_NOTIFY_CHANGE_FILE_NAME = 1 FILE_NOTIFY_CHANGE_DIR_NAME = 2 FILE_NOTIFY_CHANGE_ATTRIBUTES = 4 FILE_NOTIFY_CHANGE_SIZE = 8 FILE_NOTIFY_CHANGE_LAST_WRITE = 16 FILE_NOTIFY_CHANGE_LAST_ACCESS = 32 FILE_NOTIFY_CHANGE_CREATION = 64 FILE_NOTIFY_CHANGE_SECURITY = 256 FILE_ACTION_ADDED = 1 FILE_ACTION_REMOVED = 2 FILE_ACTION_MODIFIED = 3 FILE_ACTION_RENAMED_OLD_NAME = 4 FILE_ACTION_RENAMED_NEW_NAME = 5 FILE_CASE_SENSITIVE_SEARCH = 1 FILE_CASE_PRESERVED_NAMES = 2 FILE_UNICODE_ON_DISK = 4 FILE_PERSISTENT_ACLS = 8 FILE_FILE_COMPRESSION = 16 FILE_VOLUME_QUOTAS = 32 FILE_SUPPORTS_SPARSE_FILES = 64 FILE_SUPPORTS_REPARSE_POINTS = 128 FILE_SUPPORTS_REMOTE_STORAGE = 256 FILE_VOLUME_IS_COMPRESSED = 32768 FILE_SUPPORTS_OBJECT_IDS = 65536 FILE_SUPPORTS_ENCRYPTION = 131072 MAXIMUM_REPARSE_DATA_BUFFER_SIZE = ( 16 * 1024 ) IO_REPARSE_TAG_RESERVED_ZERO = (0) IO_REPARSE_TAG_RESERVED_ONE = (1) IO_REPARSE_TAG_SYMBOLIC_LINK = (2) IO_REPARSE_TAG_NSS = (5) IO_REPARSE_TAG_FILTER_MANAGER = -2147483637 IO_REPARSE_TAG_DFS = -2147483638 IO_REPARSE_TAG_SIS = -2147483641 IO_REPARSE_TAG_MOUNT_POINT = -1610612733 IO_REPARSE_TAG_HSM = -1073741820 IO_REPARSE_TAG_NSSRECOVER = (8) IO_REPARSE_TAG_RESERVED_MS_RANGE = (256) IO_REPARSE_TAG_RESERVED_RANGE = IO_REPARSE_TAG_RESERVED_ONE IO_COMPLETION_MODIFY_STATE = 2 DUPLICATE_CLOSE_SOURCE = 1 DUPLICATE_SAME_ACCESS = 2 DELETE = (65536) READ_CONTROL = (131072) WRITE_DAC = (262144) WRITE_OWNER = (524288) SYNCHRONIZE = (1048576) STANDARD_RIGHTS_REQUIRED = (983040) STANDARD_RIGHTS_READ = (READ_CONTROL) STANDARD_RIGHTS_WRITE = (READ_CONTROL) STANDARD_RIGHTS_EXECUTE = (READ_CONTROL) STANDARD_RIGHTS_ALL = (2031616) SPECIFIC_RIGHTS_ALL = (65535) IO_COMPLETION_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3 ACCESS_SYSTEM_SECURITY = (16777216) MAXIMUM_ALLOWED = (33554432) GENERIC_READ = (-2147483648) GENERIC_WRITE = (1073741824) GENERIC_EXECUTE = (536870912) GENERIC_ALL = (268435456) # Included from pshpack4.h # Included from poppack.h SID_REVISION = (1) SID_MAX_SUB_AUTHORITIES = (15) SID_RECOMMENDED_SUB_AUTHORITIES = (1) SidTypeUser = 1 SidTypeGroup = 2 SidTypeDomain =3 SidTypeAlias = 4 SidTypeWellKnownGroup = 5 SidTypeDeletedAccount = 6 SidTypeInvalid = 7 SidTypeUnknown = 8 SECURITY_NULL_RID = (0) SECURITY_WORLD_RID = (0) SECURITY_LOCAL_RID = (0X00000000) SECURITY_CREATOR_OWNER_RID = (0) SECURITY_CREATOR_GROUP_RID = (1) SECURITY_CREATOR_OWNER_SERVER_RID = (2) SECURITY_CREATOR_GROUP_SERVER_RID = (3) SECURITY_DIALUP_RID = (1) SECURITY_NETWORK_RID = (2) SECURITY_BATCH_RID = (3) SECURITY_INTERACTIVE_RID = (4) SECURITY_SERVICE_RID = (6) SECURITY_ANONYMOUS_LOGON_RID = (7) SECURITY_PROXY_RID = (8) SECURITY_SERVER_LOGON_RID = (9) SECURITY_PRINCIPAL_SELF_RID = (10) SECURITY_AUTHENTICATED_USER_RID = (11) SECURITY_LOGON_IDS_RID = (5) SECURITY_LOGON_IDS_RID_COUNT = (3) SECURITY_LOCAL_SYSTEM_RID = (18) SECURITY_NT_NON_UNIQUE = (21) SECURITY_BUILTIN_DOMAIN_RID = (32) DOMAIN_USER_RID_ADMIN = (500) DOMAIN_USER_RID_GUEST = (501) DOMAIN_GROUP_RID_ADMINS = (512) DOMAIN_GROUP_RID_USERS = (513) DOMAIN_GROUP_RID_GUESTS = (514) DOMAIN_ALIAS_RID_ADMINS = (544) DOMAIN_ALIAS_RID_USERS = (545) DOMAIN_ALIAS_RID_GUESTS = (546) DOMAIN_ALIAS_RID_POWER_USERS = (547) DOMAIN_ALIAS_RID_ACCOUNT_OPS = (548) DOMAIN_ALIAS_RID_SYSTEM_OPS = (549) DOMAIN_ALIAS_RID_PRINT_OPS = (550) DOMAIN_ALIAS_RID_BACKUP_OPS = (551) DOMAIN_ALIAS_RID_REPLICATOR = (552) SE_GROUP_MANDATORY = (1) SE_GROUP_ENABLED_BY_DEFAULT = (2) SE_GROUP_ENABLED = (4) SE_GROUP_OWNER = (8) SE_GROUP_LOGON_ID = (-1073741824) ACL_REVISION = (2) ACL_REVISION_DS = (4) ACL_REVISION1 = (1) ACL_REVISION2 = (2) ACL_REVISION3 = (3) ACL_REVISION4 = (4) MAX_ACL_REVISION = ACL_REVISION4 ACCESS_MIN_MS_ACE_TYPE = (0) ACCESS_ALLOWED_ACE_TYPE = (0) ACCESS_DENIED_ACE_TYPE = (1) SYSTEM_AUDIT_ACE_TYPE = (2) SYSTEM_ALARM_ACE_TYPE = (3) ACCESS_MAX_MS_V2_ACE_TYPE = (3) ACCESS_ALLOWED_COMPOUND_ACE_TYPE = (4) ACCESS_MAX_MS_V3_ACE_TYPE = (4) ACCESS_MIN_MS_OBJECT_ACE_TYPE = (5) ACCESS_ALLOWED_OBJECT_ACE_TYPE = (5) ACCESS_DENIED_OBJECT_ACE_TYPE = (6) SYSTEM_AUDIT_OBJECT_ACE_TYPE = (7) SYSTEM_ALARM_OBJECT_ACE_TYPE = (8) ACCESS_MAX_MS_OBJECT_ACE_TYPE = (8) ACCESS_MAX_MS_V4_ACE_TYPE = (8) ACCESS_MAX_MS_ACE_TYPE = (8) OBJECT_INHERIT_ACE = (1) CONTAINER_INHERIT_ACE = (2) NO_PROPAGATE_INHERIT_ACE = (4) INHERIT_ONLY_ACE = (8) INHERITED_ACE = (16) VALID_INHERIT_FLAGS = (31) SUCCESSFUL_ACCESS_ACE_FLAG = (64) FAILED_ACCESS_ACE_FLAG = (128) ACE_OBJECT_TYPE_PRESENT = 1 ACE_INHERITED_OBJECT_TYPE_PRESENT = 2 SECURITY_DESCRIPTOR_REVISION = (1) SECURITY_DESCRIPTOR_REVISION1 = (1) SECURITY_DESCRIPTOR_MIN_LENGTH = (20) SE_OWNER_DEFAULTED = (1) SE_GROUP_DEFAULTED = (2) SE_DACL_PRESENT = (4) SE_DACL_DEFAULTED = (8) SE_SACL_PRESENT = (16) SE_SACL_DEFAULTED = (32) SE_DACL_AUTO_INHERIT_REQ = (256) SE_SACL_AUTO_INHERIT_REQ = (512) SE_DACL_AUTO_INHERITED = (1024) SE_SACL_AUTO_INHERITED = (2048) SE_DACL_PROTECTED = (4096) SE_SACL_PROTECTED = (8192) SE_SELF_RELATIVE = (32768) ACCESS_OBJECT_GUID = 0 ACCESS_PROPERTY_SET_GUID = 1 ACCESS_PROPERTY_GUID = 2 ACCESS_MAX_LEVEL = 4 AUDIT_ALLOW_NO_PRIVILEGE = 1 ACCESS_DS_SOURCE_A = "Directory Service" ACCESS_DS_OBJECT_TYPE_NAME_A = "Directory Service Object" SE_PRIVILEGE_ENABLED_BY_DEFAULT = (1) SE_PRIVILEGE_ENABLED = (2) SE_PRIVILEGE_USED_FOR_ACCESS = (-2147483648) PRIVILEGE_SET_ALL_NECESSARY = (1) SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege" SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege" SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege" SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege" SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege" SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege" SE_TCB_NAME = "SeTcbPrivilege" SE_SECURITY_NAME = "SeSecurityPrivilege" SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege" SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege" SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege" SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege" SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege" SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege" SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege" SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege" SE_BACKUP_NAME = "SeBackupPrivilege" SE_RESTORE_NAME = "SeRestorePrivilege" SE_SHUTDOWN_NAME = "SeShutdownPrivilege" SE_DEBUG_NAME = "SeDebugPrivilege" SE_AUDIT_NAME = "SeAuditPrivilege" SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege" SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege" SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege" TOKEN_ASSIGN_PRIMARY = (1) TOKEN_DUPLICATE = (2) TOKEN_IMPERSONATE = (4) TOKEN_QUERY = (8) TOKEN_QUERY_SOURCE = (16) TOKEN_ADJUST_PRIVILEGES = (32) TOKEN_ADJUST_GROUPS = (64) TOKEN_ADJUST_DEFAULT = (128) TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |\ TOKEN_ASSIGN_PRIMARY |\ TOKEN_DUPLICATE |\ TOKEN_IMPERSONATE |\ TOKEN_QUERY |\ TOKEN_QUERY_SOURCE |\ TOKEN_ADJUST_PRIVILEGES |\ TOKEN_ADJUST_GROUPS |\ TOKEN_ADJUST_DEFAULT) TOKEN_READ = (STANDARD_RIGHTS_READ |\ TOKEN_QUERY) TOKEN_WRITE = (STANDARD_RIGHTS_WRITE |\ TOKEN_ADJUST_PRIVILEGES |\ TOKEN_ADJUST_GROUPS |\ TOKEN_ADJUST_DEFAULT) TOKEN_EXECUTE = (STANDARD_RIGHTS_EXECUTE) TOKEN_SOURCE_LENGTH = 8 # Token types TokenPrimary = 1 TokenImpersonation = 2 TokenUser = 1 TokenGroups = 2 TokenPrivileges = 3 TokenOwner = 4 TokenPrimaryGroup = 5 TokenDefaultDacl = 6 TokenSource = 7 TokenType = 8 TokenImpersonationLevel = 9 TokenStatistics = 10 OWNER_SECURITY_INFORMATION = (0X00000001) GROUP_SECURITY_INFORMATION = (0X00000002) DACL_SECURITY_INFORMATION = (0X00000004) SACL_SECURITY_INFORMATION = (0X00000008) IMAGE_DOS_SIGNATURE = 23117 IMAGE_OS2_SIGNATURE = 17742 IMAGE_OS2_SIGNATURE_LE = 17740 IMAGE_VXD_SIGNATURE = 17740 IMAGE_NT_SIGNATURE = 17744 IMAGE_SIZEOF_FILE_HEADER = 20 IMAGE_FILE_RELOCS_STRIPPED = 1 IMAGE_FILE_EXECUTABLE_IMAGE = 2 IMAGE_FILE_LINE_NUMS_STRIPPED = 4 IMAGE_FILE_LOCAL_SYMS_STRIPPED = 8 IMAGE_FILE_AGGRESIVE_WS_TRIM = 16 IMAGE_FILE_LARGE_ADDRESS_AWARE = 32 IMAGE_FILE_BYTES_REVERSED_LO = 128 IMAGE_FILE_32BIT_MACHINE = 256 IMAGE_FILE_DEBUG_STRIPPED = 512 IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 1024 IMAGE_FILE_NET_RUN_FROM_SWAP = 2048 IMAGE_FILE_SYSTEM = 4096 IMAGE_FILE_DLL = 8192 IMAGE_FILE_UP_SYSTEM_ONLY = 16384 IMAGE_FILE_BYTES_REVERSED_HI = 32768 IMAGE_FILE_MACHINE_UNKNOWN = 0 IMAGE_FILE_MACHINE_I386 = 332 IMAGE_FILE_MACHINE_R3000 = 354 IMAGE_FILE_MACHINE_R4000 = 358 IMAGE_FILE_MACHINE_R10000 = 360 IMAGE_FILE_MACHINE_WCEMIPSV2 = 361 IMAGE_FILE_MACHINE_ALPHA = 388 IMAGE_FILE_MACHINE_POWERPC = 496 IMAGE_FILE_MACHINE_SH3 = 418 IMAGE_FILE_MACHINE_SH3E = 420 IMAGE_FILE_MACHINE_SH4 = 422 IMAGE_FILE_MACHINE_ARM = 448 IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16 IMAGE_SIZEOF_ROM_OPTIONAL_HEADER = 56 IMAGE_SIZEOF_STD_OPTIONAL_HEADER = 28 IMAGE_SIZEOF_NT_OPTIONAL_HEADER = 224 IMAGE_NT_OPTIONAL_HDR_MAGIC = 267 IMAGE_ROM_OPTIONAL_HDR_MAGIC = 263 IMAGE_SUBSYSTEM_UNKNOWN = 0 IMAGE_SUBSYSTEM_NATIVE = 1 IMAGE_SUBSYSTEM_WINDOWS_GUI = 2 IMAGE_SUBSYSTEM_WINDOWS_CUI = 3 IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 4 IMAGE_SUBSYSTEM_OS2_CUI = 5 IMAGE_SUBSYSTEM_POSIX_CUI = 7 IMAGE_SUBSYSTEM_RESERVED8 = 8 IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = 8192 IMAGE_DIRECTORY_ENTRY_EXPORT = 0 IMAGE_DIRECTORY_ENTRY_IMPORT = 1 IMAGE_DIRECTORY_ENTRY_RESOURCE = 2 IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3 IMAGE_DIRECTORY_ENTRY_SECURITY = 4 IMAGE_DIRECTORY_ENTRY_BASERELOC = 5 IMAGE_DIRECTORY_ENTRY_DEBUG = 6 IMAGE_DIRECTORY_ENTRY_COPYRIGHT = 7 IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8 IMAGE_DIRECTORY_ENTRY_TLS = 9 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11 IMAGE_DIRECTORY_ENTRY_IAT = 12 IMAGE_SIZEOF_SHORT_NAME = 8 IMAGE_SIZEOF_SECTION_HEADER = 40 IMAGE_SCN_TYPE_NO_PAD = 8 IMAGE_SCN_CNT_CODE = 32 IMAGE_SCN_CNT_INITIALIZED_DATA = 64 IMAGE_SCN_CNT_UNINITIALIZED_DATA = 128 IMAGE_SCN_LNK_OTHER = 256 IMAGE_SCN_LNK_INFO = 512 IMAGE_SCN_LNK_REMOVE = 2048 IMAGE_SCN_LNK_COMDAT = 4096 IMAGE_SCN_MEM_FARDATA = 32768 IMAGE_SCN_MEM_PURGEABLE = 131072 IMAGE_SCN_MEM_16BIT = 131072 IMAGE_SCN_MEM_LOCKED = 262144 IMAGE_SCN_MEM_PRELOAD = 524288 IMAGE_SCN_ALIGN_1BYTES = 1048576 IMAGE_SCN_ALIGN_2BYTES = 2097152 IMAGE_SCN_ALIGN_4BYTES = 3145728 IMAGE_SCN_ALIGN_8BYTES = 4194304 IMAGE_SCN_ALIGN_16BYTES = 5242880 IMAGE_SCN_ALIGN_32BYTES = 6291456 IMAGE_SCN_ALIGN_64BYTES = 7340032 IMAGE_SCN_LNK_NRELOC_OVFL = 16777216 IMAGE_SCN_MEM_DISCARDABLE = 33554432 IMAGE_SCN_MEM_NOT_CACHED = 67108864 IMAGE_SCN_MEM_NOT_PAGED = 134217728 IMAGE_SCN_MEM_SHARED = 268435456 IMAGE_SCN_MEM_EXECUTE = 536870912 IMAGE_SCN_MEM_READ = 1073741824 IMAGE_SCN_MEM_WRITE = -2147483648 IMAGE_SCN_SCALE_INDEX = 1 IMAGE_SIZEOF_SYMBOL = 18 IMAGE_SYM_TYPE_NULL = 0 IMAGE_SYM_TYPE_VOID = 1 IMAGE_SYM_TYPE_CHAR = 2 IMAGE_SYM_TYPE_SHORT = 3 IMAGE_SYM_TYPE_INT = 4 IMAGE_SYM_TYPE_LONG = 5 IMAGE_SYM_TYPE_FLOAT = 6 IMAGE_SYM_TYPE_DOUBLE = 7 IMAGE_SYM_TYPE_STRUCT = 8 IMAGE_SYM_TYPE_UNION = 9 IMAGE_SYM_TYPE_ENUM = 10 IMAGE_SYM_TYPE_MOE = 11 IMAGE_SYM_TYPE_BYTE = 12 IMAGE_SYM_TYPE_WORD = 13 IMAGE_SYM_TYPE_UINT = 14 IMAGE_SYM_TYPE_DWORD = 15 IMAGE_SYM_TYPE_PCODE = 32768 IMAGE_SYM_DTYPE_NULL = 0 IMAGE_SYM_DTYPE_POINTER = 1 IMAGE_SYM_DTYPE_FUNCTION = 2 IMAGE_SYM_DTYPE_ARRAY = 3 IMAGE_SYM_CLASS_NULL = 0 IMAGE_SYM_CLASS_AUTOMATIC = 1 IMAGE_SYM_CLASS_EXTERNAL = 2 IMAGE_SYM_CLASS_STATIC = 3 IMAGE_SYM_CLASS_REGISTER = 4 IMAGE_SYM_CLASS_EXTERNAL_DEF = 5 IMAGE_SYM_CLASS_LABEL = 6 IMAGE_SYM_CLASS_UNDEFINED_LABEL = 7 IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8 IMAGE_SYM_CLASS_ARGUMENT = 9 IMAGE_SYM_CLASS_STRUCT_TAG = 10 IMAGE_SYM_CLASS_MEMBER_OF_UNION = 11 IMAGE_SYM_CLASS_UNION_TAG = 12 IMAGE_SYM_CLASS_TYPE_DEFINITION = 13 IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14 IMAGE_SYM_CLASS_ENUM_TAG = 15 IMAGE_SYM_CLASS_MEMBER_OF_ENUM = 16 IMAGE_SYM_CLASS_REGISTER_PARAM = 17 IMAGE_SYM_CLASS_BIT_FIELD = 18 IMAGE_SYM_CLASS_FAR_EXTERNAL = 68 IMAGE_SYM_CLASS_BLOCK = 100 IMAGE_SYM_CLASS_FUNCTION = 101 IMAGE_SYM_CLASS_END_OF_STRUCT = 102 IMAGE_SYM_CLASS_FILE = 103 IMAGE_SYM_CLASS_SECTION = 104 IMAGE_SYM_CLASS_WEAK_EXTERNAL = 105 N_BTMASK = 15 N_TMASK = 48 N_TMASK1 = 192 N_TMASK2 = 240 N_BTSHFT = 4 N_TSHIFT = 2 IMAGE_SIZEOF_AUX_SYMBOL = 18 IMAGE_COMDAT_SELECT_NODUPLICATES = 1 IMAGE_COMDAT_SELECT_ANY = 2 IMAGE_COMDAT_SELECT_SAME_SIZE = 3 IMAGE_COMDAT_SELECT_EXACT_MATCH = 4 IMAGE_COMDAT_SELECT_ASSOCIATIVE = 5 IMAGE_COMDAT_SELECT_LARGEST = 6 IMAGE_COMDAT_SELECT_NEWEST = 7 IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = 1 IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = 2 IMAGE_WEAK_EXTERN_SEARCH_ALIAS = 3 IMAGE_SIZEOF_RELOCATION = 10 IMAGE_REL_I386_ABSOLUTE = 0 IMAGE_REL_I386_DIR16 = 1 IMAGE_REL_I386_REL16 = 2 IMAGE_REL_I386_DIR32 = 6 IMAGE_REL_I386_DIR32NB = 7 IMAGE_REL_I386_SEG12 = 9 IMAGE_REL_I386_SECTION = 10 IMAGE_REL_I386_SECREL = 11 IMAGE_REL_I386_REL32 = 20 IMAGE_REL_MIPS_ABSOLUTE = 0 IMAGE_REL_MIPS_REFHALF = 1 IMAGE_REL_MIPS_REFWORD = 2 IMAGE_REL_MIPS_JMPADDR = 3 IMAGE_REL_MIPS_REFHI = 4 IMAGE_REL_MIPS_REFLO = 5 IMAGE_REL_MIPS_GPREL = 6 IMAGE_REL_MIPS_LITERAL = 7 IMAGE_REL_MIPS_SECTION = 10 IMAGE_REL_MIPS_SECREL = 11 IMAGE_REL_MIPS_SECRELLO = 12 IMAGE_REL_MIPS_SECRELHI = 13 IMAGE_REL_MIPS_REFWORDNB = 34 IMAGE_REL_MIPS_PAIR = 37 IMAGE_REL_ALPHA_ABSOLUTE = 0 IMAGE_REL_ALPHA_REFLONG = 1 IMAGE_REL_ALPHA_REFQUAD = 2 IMAGE_REL_ALPHA_GPREL32 = 3 IMAGE_REL_ALPHA_LITERAL = 4 IMAGE_REL_ALPHA_LITUSE = 5 IMAGE_REL_ALPHA_GPDISP = 6 IMAGE_REL_ALPHA_BRADDR = 7 IMAGE_REL_ALPHA_HINT = 8 IMAGE_REL_ALPHA_INLINE_REFLONG = 9 IMAGE_REL_ALPHA_REFHI = 10 IMAGE_REL_ALPHA_REFLO = 11 IMAGE_REL_ALPHA_PAIR = 12 IMAGE_REL_ALPHA_MATCH = 13 IMAGE_REL_ALPHA_SECTION = 14 IMAGE_REL_ALPHA_SECREL = 15 IMAGE_REL_ALPHA_REFLONGNB = 16 IMAGE_REL_ALPHA_SECRELLO = 17 IMAGE_REL_ALPHA_SECRELHI = 18 IMAGE_REL_PPC_ABSOLUTE = 0 IMAGE_REL_PPC_ADDR64 = 1 IMAGE_REL_PPC_ADDR32 = 2 IMAGE_REL_PPC_ADDR24 = 3 IMAGE_REL_PPC_ADDR16 = 4 IMAGE_REL_PPC_ADDR14 = 5 IMAGE_REL_PPC_REL24 = 6 IMAGE_REL_PPC_REL14 = 7 IMAGE_REL_PPC_TOCREL16 = 8 IMAGE_REL_PPC_TOCREL14 = 9 IMAGE_REL_PPC_ADDR32NB = 10 IMAGE_REL_PPC_SECREL = 11 IMAGE_REL_PPC_SECTION = 12 IMAGE_REL_PPC_IFGLUE = 13 IMAGE_REL_PPC_IMGLUE = 14 IMAGE_REL_PPC_SECREL16 = 15 IMAGE_REL_PPC_REFHI = 16 IMAGE_REL_PPC_REFLO = 17 IMAGE_REL_PPC_PAIR = 18 IMAGE_REL_PPC_SECRELLO = 19 IMAGE_REL_PPC_SECRELHI = 20 IMAGE_REL_PPC_TYPEMASK = 255 IMAGE_REL_PPC_NEG = 256 IMAGE_REL_PPC_BRTAKEN = 512 IMAGE_REL_PPC_BRNTAKEN = 1024 IMAGE_REL_PPC_TOCDEFN = 2048 IMAGE_REL_SH3_ABSOLUTE = 0 IMAGE_REL_SH3_DIRECT16 = 1 IMAGE_REL_SH3_DIRECT32 = 2 IMAGE_REL_SH3_DIRECT8 = 3 IMAGE_REL_SH3_DIRECT8_WORD = 4 IMAGE_REL_SH3_DIRECT8_LONG = 5 IMAGE_REL_SH3_DIRECT4 = 6 IMAGE_REL_SH3_DIRECT4_WORD = 7 IMAGE_REL_SH3_DIRECT4_LONG = 8 IMAGE_REL_SH3_PCREL8_WORD = 9 IMAGE_REL_SH3_PCREL8_LONG = 10 IMAGE_REL_SH3_PCREL12_WORD = 11 IMAGE_REL_SH3_STARTOF_SECTION = 12 IMAGE_REL_SH3_SIZEOF_SECTION = 13 IMAGE_REL_SH3_SECTION = 14 IMAGE_REL_SH3_SECREL = 15 IMAGE_REL_SH3_DIRECT32_NB = 16 IMAGE_SIZEOF_LINENUMBER = 6 IMAGE_SIZEOF_BASE_RELOCATION = 8 IMAGE_REL_BASED_ABSOLUTE = 0 IMAGE_REL_BASED_HIGH = 1 IMAGE_REL_BASED_LOW = 2 IMAGE_REL_BASED_HIGHLOW = 3 IMAGE_REL_BASED_HIGHADJ = 4 IMAGE_REL_BASED_MIPS_JMPADDR = 5 IMAGE_REL_BASED_SECTION = 6 IMAGE_REL_BASED_REL32 = 7 IMAGE_ARCHIVE_START_SIZE = 8 IMAGE_ARCHIVE_START = "!<arch>\n" IMAGE_ARCHIVE_END = "`\n" IMAGE_ARCHIVE_PAD = "\n" IMAGE_ARCHIVE_LINKER_MEMBER = "/ " IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR = 60 IMAGE_ORDINAL_FLAG = -2147483648 IMAGE_RESOURCE_NAME_IS_STRING = -2147483648 IMAGE_RESOURCE_DATA_IS_DIRECTORY = -2147483648 IMAGE_DEBUG_TYPE_UNKNOWN = 0 IMAGE_DEBUG_TYPE_COFF = 1 IMAGE_DEBUG_TYPE_CODEVIEW = 2 IMAGE_DEBUG_TYPE_FPO = 3 IMAGE_DEBUG_TYPE_MISC = 4 IMAGE_DEBUG_TYPE_EXCEPTION = 5 IMAGE_DEBUG_TYPE_FIXUP = 6 IMAGE_DEBUG_TYPE_OMAP_TO_SRC = 7 IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = 8 IMAGE_DEBUG_TYPE_BORLAND = 9 FRAME_FPO = 0 FRAME_TRAP = 1 FRAME_TSS = 2 FRAME_NONFPO = 3 SIZEOF_RFPO_DATA = 16 IMAGE_DEBUG_MISC_EXENAME = 1 IMAGE_SEPARATE_DEBUG_SIGNATURE = 18756 IMAGE_SEPARATE_DEBUG_FLAGS_MASK = 32768 IMAGE_SEPARATE_DEBUG_MISMATCH = 32768 # Included from string.h _NLSCMPERROR = 2147483647 NULL = 0 HEAP_NO_SERIALIZE = 1 HEAP_GROWABLE = 2 HEAP_GENERATE_EXCEPTIONS = 4 HEAP_ZERO_MEMORY = 8 HEAP_REALLOC_IN_PLACE_ONLY = 16 HEAP_TAIL_CHECKING_ENABLED = 32 HEAP_FREE_CHECKING_ENABLED = 64 HEAP_DISABLE_COALESCE_ON_FREE = 128 HEAP_CREATE_ALIGN_16 = 65536 HEAP_CREATE_ENABLE_TRACING = 131072 HEAP_MAXIMUM_TAG = 4095 HEAP_PSEUDO_TAG_FLAG = 32768 HEAP_TAG_SHIFT = 16 IS_TEXT_UNICODE_ASCII16 = 1 IS_TEXT_UNICODE_REVERSE_ASCII16 = 16 IS_TEXT_UNICODE_STATISTICS = 2 IS_TEXT_UNICODE_REVERSE_STATISTICS = 32 IS_TEXT_UNICODE_CONTROLS = 4 IS_TEXT_UNICODE_REVERSE_CONTROLS = 64 IS_TEXT_UNICODE_SIGNATURE = 8 IS_TEXT_UNICODE_REVERSE_SIGNATURE = 128 IS_TEXT_UNICODE_ILLEGAL_CHARS = 256 IS_TEXT_UNICODE_ODD_LENGTH = 512 IS_TEXT_UNICODE_DBCS_LEADBYTE = 1024 IS_TEXT_UNICODE_NULL_BYTES = 4096 IS_TEXT_UNICODE_UNICODE_MASK = 15 IS_TEXT_UNICODE_REVERSE_MASK = 240 IS_TEXT_UNICODE_NOT_UNICODE_MASK = 3840 IS_TEXT_UNICODE_NOT_ASCII_MASK = 61440 COMPRESSION_FORMAT_NONE = (0) COMPRESSION_FORMAT_DEFAULT = (1) COMPRESSION_FORMAT_LZNT1 = (2) COMPRESSION_ENGINE_STANDARD = (0) COMPRESSION_ENGINE_MAXIMUM = (256) MESSAGE_RESOURCE_UNICODE = 1 RTL_CRITSECT_TYPE = 0 RTL_RESOURCE_TYPE = 1 SEF_DACL_AUTO_INHERIT = 1 SEF_SACL_AUTO_INHERIT = 2 SEF_DEFAULT_DESCRIPTOR_FOR_OBJECT = 4 SEF_AVOID_PRIVILEGE_CHECK = 8 DLL_PROCESS_ATTACH = 1 DLL_THREAD_ATTACH = 2 DLL_THREAD_DETACH = 3 DLL_PROCESS_DETACH = 0 EVENTLOG_SEQUENTIAL_READ = 0X0001 EVENTLOG_SEEK_READ = 0X0002 EVENTLOG_FORWARDS_READ = 0X0004 EVENTLOG_BACKWARDS_READ = 0X0008 EVENTLOG_SUCCESS = 0X0000 EVENTLOG_ERROR_TYPE = 1 EVENTLOG_WARNING_TYPE = 2 EVENTLOG_INFORMATION_TYPE = 4 EVENTLOG_AUDIT_SUCCESS = 8 EVENTLOG_AUDIT_FAILURE = 16 EVENTLOG_START_PAIRED_EVENT = 1 EVENTLOG_END_PAIRED_EVENT = 2 EVENTLOG_END_ALL_PAIRED_EVENTS = 4 EVENTLOG_PAIRED_EVENT_ACTIVE = 8 EVENTLOG_PAIRED_EVENT_INACTIVE = 16 KEY_QUERY_VALUE = (1) KEY_SET_VALUE = (2) KEY_CREATE_SUB_KEY = (4) KEY_ENUMERATE_SUB_KEYS = (8) KEY_NOTIFY = (16) KEY_CREATE_LINK = (32) KEY_READ = ((STANDARD_RIGHTS_READ |\ KEY_QUERY_VALUE |\ KEY_ENUMERATE_SUB_KEYS |\ KEY_NOTIFY) \ & \ (~SYNCHRONIZE)) KEY_WRITE = ((STANDARD_RIGHTS_WRITE |\ KEY_SET_VALUE |\ KEY_CREATE_SUB_KEY) \ & \ (~SYNCHRONIZE)) KEY_EXECUTE = ((KEY_READ) \ & \ (~SYNCHRONIZE)) KEY_ALL_ACCESS = ((STANDARD_RIGHTS_ALL |\ KEY_QUERY_VALUE |\ KEY_SET_VALUE |\ KEY_CREATE_SUB_KEY |\ KEY_ENUMERATE_SUB_KEYS |\ KEY_NOTIFY |\ KEY_CREATE_LINK) \ & \ (~SYNCHRONIZE)) REG_OPTION_RESERVED = (0) REG_OPTION_NON_VOLATILE = (0) REG_OPTION_VOLATILE = (1) REG_OPTION_CREATE_LINK = (2) REG_OPTION_BACKUP_RESTORE = (4) REG_OPTION_OPEN_LINK = (8) REG_LEGAL_OPTION = \ (REG_OPTION_RESERVED |\ REG_OPTION_NON_VOLATILE |\ REG_OPTION_VOLATILE |\ REG_OPTION_CREATE_LINK |\ REG_OPTION_BACKUP_RESTORE |\ REG_OPTION_OPEN_LINK) REG_CREATED_NEW_KEY = (1) REG_OPENED_EXISTING_KEY = (2) REG_WHOLE_HIVE_VOLATILE = (1) REG_REFRESH_HIVE = (2) REG_NO_LAZY_FLUSH = (4) REG_NOTIFY_CHANGE_NAME = (1) REG_NOTIFY_CHANGE_ATTRIBUTES = (2) REG_NOTIFY_CHANGE_LAST_SET = (4) REG_NOTIFY_CHANGE_SECURITY = (8) REG_LEGAL_CHANGE_FILTER = \ (REG_NOTIFY_CHANGE_NAME |\ REG_NOTIFY_CHANGE_ATTRIBUTES |\ REG_NOTIFY_CHANGE_LAST_SET |\ REG_NOTIFY_CHANGE_SECURITY) REG_NONE = ( 0 ) REG_SZ = ( 1 ) REG_EXPAND_SZ = ( 2 ) REG_BINARY = ( 3 ) REG_DWORD = ( 4 ) REG_DWORD_LITTLE_ENDIAN = ( 4 ) REG_DWORD_BIG_ENDIAN = ( 5 ) REG_LINK = ( 6 ) REG_MULTI_SZ = ( 7 ) REG_RESOURCE_LIST = ( 8 ) REG_FULL_RESOURCE_DESCRIPTOR = ( 9 ) REG_RESOURCE_REQUIREMENTS_LIST = ( 10 ) SERVICE_KERNEL_DRIVER = 1 SERVICE_FILE_SYSTEM_DRIVER = 2 SERVICE_ADAPTER = 4 SERVICE_RECOGNIZER_DRIVER = 8 SERVICE_DRIVER = (SERVICE_KERNEL_DRIVER | \ SERVICE_FILE_SYSTEM_DRIVER | \ SERVICE_RECOGNIZER_DRIVER) SERVICE_WIN32_OWN_PROCESS = 16 SERVICE_WIN32_SHARE_PROCESS = 32 SERVICE_WIN32 = (SERVICE_WIN32_OWN_PROCESS | \ SERVICE_WIN32_SHARE_PROCESS) SERVICE_INTERACTIVE_PROCESS = 256 SERVICE_TYPE_ALL = (SERVICE_WIN32 | \ SERVICE_ADAPTER | \ SERVICE_DRIVER | \ SERVICE_INTERACTIVE_PROCESS) SERVICE_BOOT_START = 0 SERVICE_SYSTEM_START = 1 SERVICE_AUTO_START = 2 SERVICE_DEMAND_START = 3 SERVICE_DISABLED = 4 SERVICE_ERROR_IGNORE = 0 SERVICE_ERROR_NORMAL = 1 SERVICE_ERROR_SEVERE = 2 SERVICE_ERROR_CRITICAL = 3 TAPE_ERASE_SHORT = 0 TAPE_ERASE_LONG = 1 TAPE_LOAD = 0 TAPE_UNLOAD = 1 TAPE_TENSION = 2 TAPE_LOCK = 3 TAPE_UNLOCK = 4 TAPE_FORMAT = 5 TAPE_SETMARKS = 0 TAPE_FILEMARKS = 1 TAPE_SHORT_FILEMARKS = 2 TAPE_LONG_FILEMARKS = 3 TAPE_ABSOLUTE_POSITION = 0 TAPE_LOGICAL_POSITION = 1 TAPE_PSEUDO_LOGICAL_POSITION = 2 TAPE_REWIND = 0 TAPE_ABSOLUTE_BLOCK = 1 TAPE_LOGICAL_BLOCK = 2 TAPE_PSEUDO_LOGICAL_BLOCK = 3 TAPE_SPACE_END_OF_DATA = 4 TAPE_SPACE_RELATIVE_BLOCKS = 5 TAPE_SPACE_FILEMARKS = 6 TAPE_SPACE_SEQUENTIAL_FMKS = 7 TAPE_SPACE_SETMARKS = 8 TAPE_SPACE_SEQUENTIAL_SMKS = 9 TAPE_DRIVE_FIXED = 1 TAPE_DRIVE_SELECT = 2 TAPE_DRIVE_INITIATOR = 4 TAPE_DRIVE_ERASE_SHORT = 16 TAPE_DRIVE_ERASE_LONG = 32 TAPE_DRIVE_ERASE_BOP_ONLY = 64 TAPE_DRIVE_ERASE_IMMEDIATE = 128 TAPE_DRIVE_TAPE_CAPACITY = 256 TAPE_DRIVE_TAPE_REMAINING = 512 TAPE_DRIVE_FIXED_BLOCK = 1024 TAPE_DRIVE_VARIABLE_BLOCK = 2048 TAPE_DRIVE_WRITE_PROTECT = 4096 TAPE_DRIVE_EOT_WZ_SIZE = 8192 TAPE_DRIVE_ECC = 65536 TAPE_DRIVE_COMPRESSION = 131072 TAPE_DRIVE_PADDING = 262144 TAPE_DRIVE_REPORT_SMKS = 524288 TAPE_DRIVE_GET_ABSOLUTE_BLK = 1048576 TAPE_DRIVE_GET_LOGICAL_BLK = 2097152 TAPE_DRIVE_SET_EOT_WZ_SIZE = 4194304 TAPE_DRIVE_EJECT_MEDIA = 16777216 TAPE_DRIVE_RESERVED_BIT = -2147483648 TAPE_DRIVE_LOAD_UNLOAD = -2147483647 TAPE_DRIVE_TENSION = -2147483646 TAPE_DRIVE_LOCK_UNLOCK = -2147483644 TAPE_DRIVE_REWIND_IMMEDIATE = -2147483640 TAPE_DRIVE_SET_BLOCK_SIZE = -2147483632 TAPE_DRIVE_LOAD_UNLD_IMMED = -2147483616 TAPE_DRIVE_TENSION_IMMED = -2147483584 TAPE_DRIVE_LOCK_UNLK_IMMED = -2147483520 TAPE_DRIVE_SET_ECC = -2147483392 TAPE_DRIVE_SET_COMPRESSION = -2147483136 TAPE_DRIVE_SET_PADDING = -2147482624 TAPE_DRIVE_SET_REPORT_SMKS = -2147481600 TAPE_DRIVE_ABSOLUTE_BLK = -2147479552 TAPE_DRIVE_ABS_BLK_IMMED = -2147475456 TAPE_DRIVE_LOGICAL_BLK = -2147467264 TAPE_DRIVE_LOG_BLK_IMMED = -2147450880 TAPE_DRIVE_END_OF_DATA = -2147418112 TAPE_DRIVE_RELATIVE_BLKS = -2147352576 TAPE_DRIVE_FILEMARKS = -2147221504 TAPE_DRIVE_SEQUENTIAL_FMKS = -2146959360 TAPE_DRIVE_SETMARKS = -2146435072 TAPE_DRIVE_SEQUENTIAL_SMKS = -2145386496 TAPE_DRIVE_REVERSE_POSITION = -2143289344 TAPE_DRIVE_SPACE_IMMEDIATE = -2139095040 TAPE_DRIVE_WRITE_SETMARKS = -2130706432 TAPE_DRIVE_WRITE_FILEMARKS = -2113929216 TAPE_DRIVE_WRITE_SHORT_FMKS = -2080374784 TAPE_DRIVE_WRITE_LONG_FMKS = -2013265920 TAPE_DRIVE_WRITE_MARK_IMMED = -1879048192 TAPE_DRIVE_FORMAT = -1610612736 TAPE_DRIVE_FORMAT_IMMEDIATE = -1073741824 TAPE_DRIVE_HIGH_FEATURES = -2147483648 TAPE_FIXED_PARTITIONS = 0 TAPE_SELECT_PARTITIONS = 1 TAPE_INITIATOR_PARTITIONS = 2
[ 2, 2980, 515, 416, 289, 17, 9078, 422, 3467, 76, 824, 34388, 59, 17256, 59, 5404, 429, 13, 71, 201, 198, 201, 198, 2969, 31484, 6234, 62, 24908, 62, 31180, 42, 796, 642, 27412, 31495, 1065, 201, 198, 24908, 62, 5188, 5959, 9050, 6...
1.877983
17,473
# -*- encoding: utf-8 -*- """ Exceptions for EsiPy related errors """ class APIException(Exception): """ Exception for SSO related errors """
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 1475, 11755, 329, 8678, 72, 20519, 3519, 8563, 37227, 201, 198, 201, 198, 201, 198, 4871, 7824, 16922, 7, 16922, 2599, 201, 198, 220, 220, 220, 37227, 35528,...
2.961538
52
# coding=utf-8 # Author: Jianghan LI # Question: 599.Minimum_Index_Sum_of_Two_Lists # Date: 2017-05-30, 0 wrong try from collections import Counter s = Solution() print s.findRestaurant(["Shogun", "Tapioca Express", "Burger King", "KFC"], ["KFC", "Shogun", "Burger King"])
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 6434, 25, 40922, 6064, 24653, 198, 2, 18233, 25, 642, 2079, 13, 44046, 62, 15732, 62, 13065, 62, 1659, 62, 7571, 62, 43, 1023, 198, 2, 7536, 25, 2177, 12, 2713, 12, 1270, 11, 657, 2642, 1949,...
2.742574
101
"""Test awesomeversion.""" import json import pytest from awesomeversion import ( AwesomeVersion, AwesomeVersionStrategy, AwesomeVersionStrategyException, ) def test_awesomeversion(): """Test awesomeversion.""" version = AwesomeVersion("2020.12.1") assert not version.beta version = AwesomeVersion("2020.12.1a0") assert version.alpha version = AwesomeVersion("2020.12.1b0") assert version.beta version = AwesomeVersion("2020.12.1dev0") assert version.dev version = AwesomeVersion("2020.12.1d0") assert version.dev version = AwesomeVersion("2020.12.1rc0") assert version.release_candidate assert version.prefix is None version = AwesomeVersion("v2020.12.1rc0") assert version.prefix == "v" version2 = AwesomeVersion(version) assert version == version2 assert str(version) == str(version2) assert str(version) == "v2020.12.1rc0" assert version.string == "2020.12.1rc0" assert repr(version) == "<AwesomeVersion CalVer '2020.12.1rc0'>" assert AwesomeVersion("1.0.0-beta.2").modifier == "beta.2" assert AwesomeVersion("2020.2.0b1").modifier_type == "b" with AwesomeVersion("20.12.0") as current: with AwesomeVersion("20.12.1") as upstream: assert upstream > current def test_serialization(): """Test to and from JSON serialization.""" version = AwesomeVersion("20.12.1") dumps = json.dumps({"version": version}) assert dumps == '{"version": "20.12.1"}' assert json.loads(dumps)["version"] == version.string test_data = [ ("2020.12.1b0"), ("2020.12.1"), ("2021.2.0.dev20210118"), ] @pytest.mark.parametrize("version", test_data) def test_nesting(version): """Test nesting AwesomeVersion objects.""" obj = AwesomeVersion(version) assert obj.string == version assert str(obj) == version assert AwesomeVersion(obj) == AwesomeVersion(version) assert AwesomeVersion(obj).string == AwesomeVersion(version) assert str(AwesomeVersion(obj)) == AwesomeVersion(version) assert AwesomeVersion(obj) == version assert AwesomeVersion(obj).string == version assert str(AwesomeVersion(obj)) == version assert ( AwesomeVersion( AwesomeVersion(AwesomeVersion(AwesomeVersion(AwesomeVersion(obj)))) ) == version ) assert ( AwesomeVersion( AwesomeVersion(AwesomeVersion(AwesomeVersion(AwesomeVersion(obj)))) ).string == version ) assert str( ( AwesomeVersion( AwesomeVersion(AwesomeVersion(AwesomeVersion(AwesomeVersion(obj)))) ) ) == version ) def test_ensure_strategy(caplog): """test ensure_strategy.""" obj = AwesomeVersion("1.0.0", AwesomeVersionStrategy.SEMVER) assert obj.strategy == AwesomeVersionStrategy.SEMVER obj = AwesomeVersion( "1.0.0", [AwesomeVersionStrategy.SEMVER, AwesomeVersionStrategy.SPECIALCONTAINER], ) assert obj.strategy in [ AwesomeVersionStrategy.SEMVER, AwesomeVersionStrategy.SPECIALCONTAINER, ] with pytest.raises(AwesomeVersionStrategyException): AwesomeVersion("1", AwesomeVersionStrategy.SEMVER) with pytest.raises(AwesomeVersionStrategyException): AwesomeVersion( "1", [AwesomeVersionStrategy.SEMVER, AwesomeVersionStrategy.SPECIALCONTAINER], ) obj = AwesomeVersion.ensure_strategy("1.0.0", AwesomeVersionStrategy.SEMVER) assert ( "Using AwesomeVersion.ensure_strategy(version, strategy) is deprecated" in caplog.text )
[ 37811, 14402, 7427, 9641, 526, 15931, 198, 11748, 33918, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 7427, 9641, 1330, 357, 198, 220, 220, 220, 25020, 14815, 11, 198, 220, 220, 220, 25020, 14815, 13290, 4338, 11, 198, 220, 220, 220, ...
2.646931
1,385
# Generated by Django 2.2.5 on 2019-11-02 11:35 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 20, 319, 13130, 12, 1157, 12, 2999, 1367, 25, 2327, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import re import os from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse from scrapy.utils.response import get_base_url from scrapy.utils.url import urljoin_rfc import csv from product_spiders.items import Product, ProductLoader
[ 11748, 302, 198, 11748, 28686, 198, 198, 6738, 15881, 88, 13, 2777, 1304, 1330, 7308, 41294, 198, 6738, 15881, 88, 13, 19738, 273, 1330, 367, 20369, 55, 15235, 17563, 273, 198, 6738, 15881, 88, 13, 4023, 1330, 19390, 11, 367, 20369, 3...
3.433333
90
# -*- python -*- # This software was produced by NIST, an agency of the U.S. government, # and by statute is not subject to copyright in the United States. # Recipients of this software assume all responsibilities associated # with its operation, modification and maintenance. However, to # facilitate maintenance we ask that before distributing modified # versions of this software, you first contact the authors at # oof_manager@nist.gov. # Example of an all-Python property, using the PyPropertyWrapper # mechanism to route callbacks through to Python routines contained # here. # Casting of flux and field to the "most-derived" class via the # PythonExportable mechanism is thinkable, but probably not actually # necessary. The property knows its field and flux as derived types # at construction/initialization time, and can get the appropriate # iterators from them, rather than from the passed-in arguments to # fluxmatrix, fluxrhs, etc. Those it can just use for comparison, # to detect which field is currently presenting its fluxmatrix. from ooflib.SWIG.engine import fieldindex from ooflib.SWIG.engine import outputval from ooflib.SWIG.engine import planarity from ooflib.SWIG.engine import pypropertywrapper from ooflib.SWIG.engine import symmmatrix from ooflib.SWIG.engine.property.elasticity import cijkl from ooflib.common import debug from ooflib.engine import propertyregistration from ooflib.engine import problem Displacement = problem.Displacement Stress = problem.Stress # This property has a simple repr, with no parameters. propertyregistration.PropertyRegistration('PyProperty', TestProp, "fruitproperty.pyproperty", 1000, params=[], fields=[Displacement], fluxes=[Stress], outputs=["Energy", "Strain"], propertyType="Elasticity")
[ 2, 532, 9, 12, 21015, 532, 9, 12, 198, 198, 2, 770, 3788, 373, 4635, 416, 399, 8808, 11, 281, 4086, 286, 262, 471, 13, 50, 13, 1230, 11, 198, 2, 290, 416, 14195, 318, 407, 2426, 284, 6634, 287, 262, 1578, 1829, 13, 198, 2, 3...
2.675607
783
# Copyright 2021, Google LLC. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utils for distributed mean estimation.""" import numpy as np import tensorflow as tf from distributed_dp.modular_clipping_factory import modular_clip_by_value def generate_client_data(d, n, l2_norm=1): """Sample `n` of `d`-dim vectors on the l2 ball with radius `l2_norm`. Args: d: The dimension of the client vector. n: The number of clients. l2_norm: The L2 norm of the sampled vector. Returns: A list of `n` np.array each with shape (d,). """ vectors = np.random.normal(size=(n, d)) unit_vectors = vectors / np.linalg.norm(vectors, axis=-1, keepdims=True) scaled_vectors = unit_vectors * l2_norm # Cast to float32 as TF implementations use float32. return list(scaled_vectors.astype(np.float32)) def compute_dp_average(client_data, dp_query, is_compressed, bits): """Aggregate client data with DPQuery's interface and take average.""" global_state = dp_query.initial_global_state() sample_params = dp_query.derive_sample_params(global_state) client_template = tf.zeros_like(client_data[0]) sample_state = dp_query.initial_sample_state(client_template) if is_compressed: # Achieve compression via modular clipping. Upper bound is exclusive. clip_lo, clip_hi = -(2**(bits - 1)), 2**(bits - 1) # 1. Client pre-processing stage. for x in client_data: record = tf.convert_to_tensor(x) prep_record = dp_query.preprocess_record(sample_params, record) # Client applies modular clip on the preprocessed record. prep_record = modular_clip_by_value(prep_record, clip_lo, clip_hi) sample_state = dp_query.accumulate_preprocessed_record( sample_state, prep_record) # 2. Server applies modular clip on the aggregate. sample_state = modular_clip_by_value(sample_state, clip_lo, clip_hi) else: for x in client_data: record = tf.convert_to_tensor(x) sample_state = dp_query.accumulate_record( sample_params, sample_state, record=record) # Apply server post-processing. agg_result, _ = dp_query.get_noised_result(sample_state, global_state) # The agg_result should have the same input type as client_data. assert agg_result.shape == client_data[0].shape assert agg_result.dtype == client_data[0].dtype # Take the average on the aggregate. return agg_result / len(client_data)
[ 2, 15069, 33448, 11, 3012, 11419, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 1...
2.977642
984
# -*- coding: utf-8 -*- # Copyright 2012 Loris Corazza, Sakis Christakidis # # 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. from p2ner.abstract.interface import Interface from cPickle import loads
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 220, 220, 15069, 2321, 26068, 271, 2744, 1031, 4496, 11, 13231, 271, 1951, 461, 29207, 198, 2, 198, 2, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, ...
3.382075
212
"""Initial migrate Revision ID: 8580b5c0888c Revises: Create Date: 2017-11-02 23:42:58.243681 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '8580b5c0888c' down_revision = None branch_labels = None depends_on = None
[ 37811, 24243, 32492, 198, 198, 18009, 1166, 4522, 25, 7600, 1795, 65, 20, 66, 2919, 3459, 66, 198, 18009, 2696, 25, 220, 198, 16447, 7536, 25, 2177, 12, 1157, 12, 2999, 2242, 25, 3682, 25, 3365, 13, 1731, 2623, 6659, 198, 198, 37811...
2.607477
107
from ._base import * from .soccer import SoccerModel from .soccerObjectDetector import SoccerObjectDetector
[ 6738, 47540, 8692, 1330, 1635, 198, 6738, 764, 35634, 2189, 1330, 15872, 17633, 198, 6738, 764, 35634, 2189, 10267, 11242, 9250, 1330, 15872, 10267, 11242, 9250, 198 ]
4
27
# Compute potential scale reduction factor (Rhat) using rhat function of kanga, which is rhat of arviz # %% Load packages import arviz as az import numpy as np # %% Define function for computing univariate Rhat based on arviz # x is a numpy array of 3 dimensions, (chain, MC iteration, parameter) # %% Read chains chains = np.array([np.genfromtxt('chain'+str(i+1).zfill(2)+'.csv', delimiter=',') for i in range(4)]) # %% Compute Rhat using rank method # The output of rhat in kanga coincides with the output of Rhat in rstan # See # https://mc-stan.org/rstan/reference/Rhat.html rhat_rank = uni_arviz_rhat(chains, method='rank') print('Rhat based on rank method: {}'.format(rhat_rank))
[ 2, 3082, 1133, 2785, 5046, 7741, 5766, 357, 49, 5183, 8, 1262, 374, 5183, 2163, 286, 479, 16484, 11, 543, 318, 374, 5183, 286, 610, 85, 528, 198, 198, 2, 43313, 8778, 10392, 198, 198, 11748, 610, 85, 528, 355, 35560, 198, 11748, 2...
2.982833
233
"""Helpers: Information: read_hacs_manifest.""" import json # pylint: disable=missing-docstring import os from custom_components.hacs.helpers.functions.information import read_hacs_manifest from custom_components.hacs.share import get_hacs
[ 37811, 12621, 19276, 25, 6188, 25, 1100, 62, 71, 16436, 62, 805, 8409, 526, 15931, 198, 11748, 33918, 198, 198, 2, 279, 2645, 600, 25, 15560, 28, 45688, 12, 15390, 8841, 198, 11748, 28686, 198, 198, 6738, 2183, 62, 5589, 3906, 13, 7...
3.128205
78
"""Pieces used in Capture The Flag (Ctf) game."""
[ 37811, 48223, 728, 973, 287, 31793, 383, 19762, 357, 34, 27110, 8, 983, 526, 15931, 628, 198 ]
3.058824
17
"""The main idea of CE (Cross Entropy) is to maintain a distribution of possible solution, and update this distribution accordingly. Preliminary investigation showed that applicability of CE to RL problems is restricted severly by the phenomenon that the distribution concentrates to a single point too fast. To prevent this issue, noise is added to the previous stddev/variance update calculation. We implement two algorithms cem, the Cross-Entropy Method (CEM) with noise [1] and Proportional Cross-Entropy (PCEM) [2]. CEM is implemented with decreasing variance noise variance + max(5 - t / 10, 0), where t is the iteration step PCEM is implemented the same as CEM except we adjust the weights, evaluations of f as follows: M = max(weights) m = min(weights) weights = (weight - m) / (M - m + eps) where eps is a very small value to avoid division by 0 An issue with CEM is it might not optimize the actual objective. PCEM helps with this. References: [1] Learning Tetris with the Noisy Cross-Entropy Method (Szita, Lorincz 2006) [2] The Cross-Entropy Method Optimizes for Quantiles (Goschin, Weinstein, Littman 2013) """ from __future__ import absolute_import from __future__ import print_function from __future__ import division from six.moves import range import gym import numpy as np import logging import argparse # only two possible actions 0 or 1 def do_rollout(agent, env, num_steps, render=False): """ Performs actions for num_steps on the environment based on the agents current params """ total_rew = 0 ob = env.reset() for t in range(num_steps): a = agent.act(ob) (ob, reward, done, _) = env.step(a) total_rew += reward if render and t%3==0: env.render() if done: break return total_rew, t+1 # mean and std are 1D array of size d if __name__ == '__main__': logger = logging.getLogger() logger.setLevel(logging.INFO) parser = argparse.ArgumentParser() parser.add_argument('--seed', default=0, type=int, help='random seed') parser.add_argument('--iters', default=50, type=int, help='number of iterations') parser.add_argument('--samples', default=30, type=int, help='number of samples CEM algorithm chooses from on each iter') parser.add_argument('--num_steps', default=200, type=int, help='number of steps/actions in the rollout') parser.add_argument('--top_frac', default=0.2, type=float, help='percentage of top samples used to calculate mean and variance of next iteration') parser.add_argument('--algorithm', default='cem', type=str, choices=['pcem', 'cem']) parser.add_argument('--outdir', default='CartPole-v0-cem', type=str, help='output directory where results are saved (/tmp/ prefixed)') parser.add_argument('--render', action='store_true', help='show rendered results during training') parser.add_argument('--upload', action='store_true', help='upload results via OpenAI API') args = parser.parse_args() print(args) np.random.seed(args.seed) env = gym.make('CartPole-v0') num_steps = args.num_steps ef = None if args.algorithm == 'cem': ef = cem else: ef = pcem outdir = '/tmp/' + args.outdir env.monitor.start(outdir, force=True) f = evaluation_func(BinaryActionLinearPolicy, env, num_steps) # params for cem params = dict(n_iters=args.iters, n_samples=args.samples, top_frac=args.top_frac) u = np.random.randn(env.observation_space.shape[0]+1) var = np.square(np.ones_like(u) * 0.1) for (i, data) in enumerate(ef(f, u, var, **params)): print("Iteration {}. Episode mean reward: {}".format(i, data['y_mean'])) agent = BinaryActionLinearPolicy(data['theta_mean']) if args.render: do_rollout(agent, env, num_steps, render=True) env.monitor.close() # make sure to setup your OPENAI_GYM_API_KEY environment variable if args.upload: gym.upload(outdir, algorithm_id=args.algorithm)
[ 37811, 464, 1388, 2126, 286, 18671, 357, 21544, 7232, 28338, 8, 318, 284, 5529, 257, 6082, 198, 1659, 1744, 4610, 11, 290, 4296, 428, 6082, 16062, 13, 198, 198, 47, 2411, 38429, 3645, 3751, 326, 2161, 1799, 286, 18671, 284, 45715, 276...
2.869192
1,399
""" Michael duPont - michael@mdupont.com avwx_api.views - Routes and views for the Quart application """ # pylint: disable=W0702 # library from quart import Response, jsonify # module from avwx_api import app # Static Web Pages @app.route("/") @app.route("/home") async def home() -> Response: """Returns static home page""" return await app.send_static_file("html/home.html") @app.route("/ping") def ping() -> Response: """Send empty 200 ping response""" return Response(None, 200) # API Routing Errors @app.route("/api") async def no_report() -> Response: """Returns no report msg""" return jsonify({"error": "No report type given"}), 400 @app.route("/api/metar") @app.route("/api/taf") async def no_station() -> Response: """Returns no station msg""" return jsonify({"error": "No station given"}), 400
[ 37811, 198, 13256, 7043, 48039, 532, 285, 40302, 31, 76, 646, 79, 756, 13, 785, 198, 615, 49345, 62, 15042, 13, 33571, 532, 39602, 274, 290, 5009, 329, 262, 48748, 3586, 198, 37811, 198, 198, 2, 279, 2645, 600, 25, 15560, 28, 54, ...
2.904437
293
""" Base mutual information estimators. """ from numpy import sum, sqrt, isnan, exp, mean, eye, ones, dot, cumsum, \ hstack, newaxis, maximum, prod, abs, arange, log from numpy.linalg import norm from scipy.spatial.distance import pdist, squareform from scipy.special import factorial from scipy.linalg import det from scipy.sparse.linalg import eigsh from ite.cost.x_initialization import InitX, InitEtaKernel from ite.cost.x_verification import VerCompSubspaceDims, \ VerSubspaceNumberIsK,\ VerOneDSubspaces from ite.shared import compute_dcov_dcorr_statistics, median_heuristic,\ copula_transformation, compute_matrix_r_kcca_kgv from ite.cost.x_kernel import Kernel class BIDistCov(InitX, VerCompSubspaceDims, VerSubspaceNumberIsK): """ Distance covariance estimator using pairwise distances. Partial initialization comes from 'InitX', verification is from 'VerCompSubspaceDims' and 'VerSubspaceNumber' (see 'ite.cost.x_initialization.py', 'ite.cost.x_verification.py'). """ def __init__(self, mult=True, alpha=1): """ Initialize the estimator. Parameters ---------- mult : bool, optional 'True': multiplicative constant relevant (needed) in the estimation. 'False': estimation up to 'proportionality'. (default is True) alpha : float, optional Parameter of the distance covariance: 0 < alpha < 2 (default is 1). Examples -------- >>> import ite >>> co1 = ite.cost.BIDistCov() >>> co2 = ite.cost.BIDistCov(alpha = 1.2) """ # initialize with 'InitX': super().__init__(mult=mult) # other attribute: if alpha <= 0 or alpha >= 2: raise Exception('0 < alpha < 2 is needed for this estimator!') self.alpha = alpha def estimation(self, y, ds): """ Estimate distance covariance. Parameters ---------- y : (number of samples, dimension)-ndarray One row of y corresponds to one sample. ds : int vector Dimensions of the individual subspaces in y; ds[i] = i^th subspace dimension. len(ds) = 2. Returns ------- i : float Estimated distance covariance. References ---------- Gabor J. Szekely and Maria L. Rizzo. Brownian distance covariance. The Annals of Applied Statistics, 3:1236-1265, 2009. Gabor J. Szekely, Maria L. Rizzo, and Nail K. Bakirov. Measuring and testing dependence by correlation of distances. The Annals of Statistics, 35:2769-2794, 2007. Examples -------- i = co.estimation(y,ds) """ # verification: self.verification_compatible_subspace_dimensions(y, ds) self.verification_subspace_number_is_k(ds, 2) num_of_samples = y.shape[0] # number of samples a = compute_dcov_dcorr_statistics(y[:, :ds[0]], self.alpha) b = compute_dcov_dcorr_statistics(y[:, ds[0]:], self.alpha) i = sqrt(sum(a*b)) / num_of_samples return i class BIDistCorr(InitX, VerCompSubspaceDims, VerSubspaceNumberIsK): """ Distance correlation estimator using pairwise distances. Partial initialization comes from 'InitX', verification is from 'VerCompSubspaceDims' and 'VerSubspaceNumber' (see 'ite.cost.x_initialization.py', 'ite.cost.x_verification.py'). """ def __init__(self, mult=True, alpha=1): """ Initialize the estimator. Parameters ---------- mult : bool, optional 'True': multiplicative constant relevant (needed) in the estimation. 'False': estimation up to 'proportionality'. (default is True) alpha : float, optional Parameter of the distance covariance: 0 < alpha < 2 (default is 1). Examples -------- >>> import ite >>> co1 = ite.cost.BIDistCorr() >>> co2 = ite.cost.BIDistCorr(alpha = 1.2) """ # initialize with 'InitX': super().__init__(mult=mult) # other attribute: if alpha <= 0 or alpha >= 2: raise Exception('0 < alpha < 2 is needed for this estimator!') self.alpha = alpha def estimation(self, y, ds): """ Estimate distance correlation. Parameters ---------- y : (number of samples, dimension)-ndarray One row of y corresponds to one sample. ds : int vector Dimensions of the individual subspaces in y; ds[i] = i^th subspace dimension. len(ds) = 2. Returns ------- i : float Estimated distance correlation. References ---------- Gabor J. Szekely and Maria L. Rizzo. Brownian distance covariance. The Annals of Applied Statistics, 3:1236-1265, 2009. Gabor J. Szekely, Maria L. Rizzo, and Nail K. Bakirov. Measuring and testing dependence by correlation of distances. The Annals of Statistics, 35:2769-2794, 2007. Examples -------- i = co.estimation(y,ds) """ # verification: self.verification_compatible_subspace_dimensions(y, ds) self.verification_subspace_number_is_k(ds, 2) a = compute_dcov_dcorr_statistics(y[:, :ds[0]], self.alpha) b = compute_dcov_dcorr_statistics(y[:, ds[0]:], self.alpha) n = sum(a*b) # numerator d1 = sum(a**2) # denumerator-1 (without sqrt) d2 = sum(b**2) # denumerator-2 (without sqrt) if (d1 * d2) == 0: # >=1 of the random variables is constant i = 0 else: i = n / sqrt(d1 * d2) # <A,B> / sqrt(<A,A><B,B>) i = sqrt(i) return i class BI3WayJoint(InitX, VerCompSubspaceDims, VerSubspaceNumberIsK): """ Joint dependency from the mean embedding of the 'joint minus the product of the marginals'. Partial initialization comes from 'InitX', verification is from 'VerCompSubspaceDims' and 'VerSubspaceNumber' (see 'ite.cost.x_initialization.py', 'ite.cost.x_verification.py'). """ def __init__(self, mult=True, sigma1=0.1, sigma2=0.1, sigma3=0.1): """ Initialize the estimator. Parameters ---------- mult : bool, optional 'True': multiplicative constant relevant (needed) in the estimation. 'False': estimation up to 'proportionality'. (default is True) sigma1 : float, optional Std in the RBF kernel on the first subspace (default is sigma1 = 0.1). sigma1 = nan means 'use median heuristic'. sigma2 : float, optional Std in the RBF kernel on the second subspace (default is sigma2 = 0.1). sigma2 = nan means 'use median heuristic'. sigma3 : float, optional Std in the RBF kernel on the third subspace (default is sigma3 = 0.1). sigma3 = nan means 'use median heuristic'. Examples -------- >>> from numpy import nan >>> import ite >>> co1 = ite.cost.BI3WayJoint() >>> co2 = ite.cost.BI3WayJoint(sigma1=0.1,sigma2=0.1,sigma3=0.1) >>> co3 = ite.cost.BI3WayJoint(sigma1=nan,sigma2=nan,sigma3=nan) """ # initialize with 'InitX': super().__init__(mult=mult) # other attributes: self.sigma1, self.sigma2, self.sigma3 = sigma1, sigma2, sigma3 def estimation(self, y, ds): """ Estimate joint dependency. Parameters ---------- y : (number of samples, dimension)-ndarray One row of y corresponds to one sample. ds : int vector Dimensions of the individual subspaces in y; ds[i] = i^th subspace dimension. len(ds) = 3. Returns ------- i : float Estimated joint dependency. References ---------- Dino Sejdinovic, Arthur Gretton, and Wicher Bergsma. A kernel test for three-variable interactions. In Advances in Neural Information Processing Systems (NIPS), pages 1124-1132, 2013. (Lancaster three-variable interaction based dependency index). Henry Oliver Lancaster. The Chi-squared Distribution. John Wiley and Sons Inc, 1969. (Lancaster interaction) Examples -------- i = co.estimation(y,ds) """ # verification: self.verification_compatible_subspace_dimensions(y, ds) self.verification_subspace_number_is_k(ds, 3) # Gram matrices (k1,k2,k3): sigma1, sigma2, sigma3 = self.sigma1, self.sigma2, self.sigma3 # k1 (set co.sigma1 using median heuristic, if needed): if isnan(sigma1): sigma1 = median_heuristic(y[:, 0:ds[0]]) k1 = squareform(pdist(y[:, 0:ds[0]])) k1 = exp(-k1**2 / (2 * sigma1**2)) # k2 (set co.sigma2 using median heuristic, if needed): if isnan(sigma2): sigma2 = median_heuristic(y[:, ds[0]:ds[0]+ds[1]]) k2 = squareform(pdist(y[:, ds[0]:ds[0]+ds[1]])) k2 = exp(-k2**2 / (2 * sigma2**2)) # k3 (set co.sigma3 using median heuristic, if needed): if isnan(sigma3): sigma3 = median_heuristic(y[:, ds[0]+ds[1]:]) k3 = squareform(pdist(y[:, ds[0]+ds[1]:], 'euclidean')) k3 = exp(-k3**2 / (2 * sigma3**2)) prod_of_ks = k1 * k2 * k3 # Hadamard product term1 = mean(prod_of_ks) term2 = -2 * mean(mean(k1, axis=1) * mean(k2, axis=1) * mean(k3, axis=1)) term3 = mean(k1) * mean(k2) * mean(k3) i = term1 + term2 + term3 return i class BI3WayLancaster(InitX, VerCompSubspaceDims, VerSubspaceNumberIsK): """ Estimate the Lancaster three-variable interaction measure. Partial initialization comes from 'InitX', verification is from 'VerCompSubspaceDims' and 'VerSubspaceNumber' (see 'ite.cost.x_initialization.py', 'ite.cost.x_verification.py'). """ def __init__(self, mult=True, sigma1=0.1, sigma2=0.1, sigma3=0.1): """ Initialize the estimator. Parameters ---------- mult : bool, optional 'True': multiplicative constant relevant (needed) in the estimation. 'False': estimation up to 'proportionality'. (default is True) sigma1 : float, optional Std in the RBF kernel on the first subspace (default is sigma1 = 0.1). sigma1 = nan means 'use median heuristic'. sigma2 : float, optional Std in the RBF kernel on the second subspace (default is sigma2 = 0.1). sigma2 = nan means 'use median heuristic'. sigma3 : float, optional Std in the RBF kernel on the third subspace (default is sigma3 = 0.1). sigma3 = nan means 'use median heuristic'. Examples -------- >>> from numpy import nan >>> import ite >>> co1 = ite.cost.BI3WayLancaster() >>> co2 = ite.cost.BI3WayLancaster(sigma1=0.1, sigma2=0.1,\ sigma3=0.1) >>> co3 = ite.cost.BI3WayLancaster(sigma1=nan, sigma2=nan,\ sigma3=nan) """ # initialize with 'InitX': super().__init__(mult=mult) # other attributes: self.sigma1, self.sigma2, self.sigma3 = sigma1, sigma2, sigma3 def estimation(self, y, ds): """ Estimate Lancaster three-variable interaction measure. Parameters ---------- y : (number of samples, dimension)-ndarray One row of y corresponds to one sample. ds : int vector Dimensions of the individual subspaces in y; ds[i] = i^th subspace dimension. len(ds) = 3. Returns ------- i : float Estimated Lancaster three-variable interaction measure. References ---------- Dino Sejdinovic, Arthur Gretton, and Wicher Bergsma. A kernel test for three-variable interactions. In Advances in Neural Information Processing Systems (NIPS), pages 1124-1132, 2013. (Lancaster three-variable interaction based dependency index). Henry Oliver Lancaster. The Chi-squared Distribution. John Wiley and Sons Inc, 1969. (Lancaster interaction) Examples -------- i = co.estimation(y,ds) """ # verification: self.verification_compatible_subspace_dimensions(y, ds) self.verification_subspace_number_is_k(ds, 3) num_of_samples = y.shape[0] # number of samples # Gram matrices (k1,k2,k3): sigma1, sigma2, sigma3 = self.sigma1, self.sigma2, self.sigma3 # k1 (set co.sigma1 using median heuristic, if needed): if isnan(sigma1): sigma1 = median_heuristic(y[:, 0:ds[0]]) k1 = squareform(pdist(y[:, 0:ds[0]])) k1 = exp(-k1**2 / (2 * sigma1**2)) # k2 (set co.sigma2 using median heuristic, if needed): if isnan(sigma2): sigma2 = median_heuristic(y[:, ds[0]:ds[0]+ds[1]]) k2 = squareform(pdist(y[:, ds[0]:ds[0]+ds[1]])) k2 = exp(-k2**2 / (2 * sigma2**2)) # k3 set co.sigma3 using median heuristic, if needed(): if isnan(sigma3): sigma3 = median_heuristic(y[:, ds[0]+ds[1]:]) k3 = squareform(pdist(y[:, ds[0]+ds[1]:])) k3 = exp(-k3**2 / (2 * sigma3**2)) # centering of k1, k2, k3: h = eye(num_of_samples) -\ ones((num_of_samples, num_of_samples)) / num_of_samples k1 = dot(dot(h, k1), h) k2 = dot(dot(h, k2), h) k3 = dot(dot(h, k3), h) i = mean(k1 * k2 * k3) return i class BIHSIC_IChol(InitEtaKernel, VerCompSubspaceDims): """ Estimate HSIC using incomplete Cholesky decomposition. HSIC refers to Hilbert-Schmidt Independence Criterion. Partial initialization comes from 'InitEtaKernel', verification is from 'VerCompSubspaceDims' (see 'ite.cost.x_initialization.py', 'ite.cost.x_verification.py'). Notes ----- The current implementation uses the same kernel an all the subspaces: k = k_1 = ... = k_M, where y = [y^1;...;y^M]. Examples -------- >>> from ite.cost.x_kernel import Kernel >>> import ite >>> co1 = ite.cost.BIHSIC_IChol() >>> co2 = ite.cost.BIHSIC_IChol(eta=1e-3) >>> k = Kernel({'name': 'RBF','sigma': 1}) >>> co3 = ite.cost.BIHSIC_IChol(kernel=k, eta=1e-3) """ def estimation(self, y, ds): """ Estimate HSIC. Parameters ---------- y : (number of samples, dimension)-ndarray One row of y corresponds to one sample. ds : int vector Dimensions of the individual subspaces in y; ds[i] = i^th subspace dimension. Returns ------- i : float Estimated value of HSIC. References ---------- Arthur Gretton, Olivier Bousquet, Alexander Smola and Bernhard Scholkopf. Measuring Statistical Dependence with Hilbert-Schmidt Norms. International Conference on Algorithmic Learnng Theory (ALT), 63-78, 2005. Alain Berlinet and Christine Thomas-Agnan. Reproducing Kernel Hilbert Spaces in Probability and Statistics. Kluwer, 2004. (mean embedding) Examples -------- i = co.estimation(y,ds) """ # verification: self.verification_compatible_subspace_dimensions(y, ds) # initialization: num_of_samples = y.shape[0] # number of samples num_of_subspaces = len(ds) # Step-1 (g1, g2, ...): # 0,d_1,d_1+d_2,...,d_1+...+d_{M-1}; starting indices of the # subspaces: cum_ds = cumsum(hstack((0, ds[:-1]))) gs = list() for m in range(num_of_subspaces): idx = range(cum_ds[m], cum_ds[m] + ds[m]) g = self.kernel.ichol(y[:, idx], num_of_samples * self.eta) g = g - mean(g, axis=0) # center the Gram matrix: dot(g,g.T) gs.append(g) # Step-2 (g1, g2, ... -> i): i = 0 for i1 in range(num_of_subspaces-1): # i1 = 0:M-2 for i2 in range(i1+1, num_of_subspaces): # i2 = i1+1:M-1 i += norm(dot(gs[i2].T, gs[i1]))**2 # norm = Frob. norm i /= num_of_samples**2 return i class BIHoeffding(InitX, VerOneDSubspaces, VerCompSubspaceDims): """ Estimate the multivariate version of Hoeffding's Phi. Partial initialization comes from 'InitX', verification is from 'VerCompSubspaceDims' and 'VerSubspaceNumber' (see 'ite.cost.x_initialization.py', 'ite.cost.x_verification.py'). """ def __init__(self, mult=True, small_sample_adjustment=True): """ Initialize the estimator. Parameters ---------- mult : bool, optional 'True': multiplicative constant relevant (needed) in the estimation. 'False': estimation up to 'proportionality'. (default is True) small_sample_adjustment: boolean, optional Whether we want small-sample adjustment. Examples -------- >>> import ite >>> co1 = ite.cost.BIHoeffding() >>> co2 = ite.cost.BIHoeffding(small_sample_adjustment=False) """ # initialize with 'InitX': super().__init__(mult=mult) # other attributes: self.small_sample_adjustment = small_sample_adjustment def estimation(self, y, ds): """ Estimate multivariate version of Hoeffding's Phi. Parameters ---------- y : (number of samples, dimension)-ndarray One row of y corresponds to one sample. ds : int vector Dimensions of the individual subspaces in y; ds[i] = i^th subspace dimension = 1 for this estimator. Returns ------- i : float Estimated value of the multivariate version of Hoeffding's Phi. References ---------- Sandra Gaiser, Martin Ruppert, Friedrich Schmid. A multivariate version of Hoeffding's Phi-Square. Journal of Multivariate Analysis. 101: pages 2571-2586, 2010. Examples -------- i = co.estimation(y,ds) """ # verification: self.verification_compatible_subspace_dimensions(y, ds) self.verification_one_dimensional_subspaces(ds) num_of_samples, dim = y.shape u = copula_transformation(y) # term1: m = 1 - maximum(u[:, 0][:, newaxis], u[:, 0]) for i in range(1, dim): m *= 1 - maximum(u[:, i][:, newaxis], u[:, i]) term1 = mean(m) # term2: if self.small_sample_adjustment: term2 = \ - mean(prod(1 - u**2 - (1 - u) / num_of_samples, axis=1)) / \ (2**(dim - 1)) else: term2 = - mean(prod(1 - u**2, axis=1)) / (2 ** (dim - 1)) # term3: if self.small_sample_adjustment: term3 = \ ((num_of_samples - 1) * (2 * num_of_samples-1) / (3 * 2 * num_of_samples**2))**dim else: term3 = 1 / 3**dim i = term1 + term2 + term3 if self.mult: if self.small_sample_adjustment: t1 = \ sum((1 - arange(1, num_of_samples) / num_of_samples)**dim * (2*arange(1, num_of_samples) - 1)) \ / num_of_samples**2 t2 = \ -2 * mean(((num_of_samples * (num_of_samples - 1) - arange(1, num_of_samples+1) * arange(num_of_samples)) / (2 * num_of_samples ** 2))**dim) t3 = term3 inv_hd = t1 + t2 + t3 # 1 / h(d, n) else: inv_hd = \ 2 / ((dim + 1) * (dim + 2)) - factorial(dim) / \ (2 ** dim * prod(arange(dim + 1) + 1 / 2)) + \ 1 / 3 ** dim # 1 / h(d)s i /= inv_hd i = sqrt(abs(i)) return i class BIKGV(InitEtaKernel, VerCompSubspaceDims): """ Estimate kernel generalized variance (KGV). Partial initialization comes from 'InitEtaKernel', verification is from 'VerCompSubspaceDims' (see 'ite.cost.x_initialization.py', 'ite.cost.x_verification.py'). """ def __init__(self, mult=True, kernel=Kernel(), eta=1e-2, kappa=0.01): """ Initialize the estimator. Parameters ---------- mult : bool, optional 'True': multiplicative constant relevant (needed) in the estimation. 'False': estimation up to 'proportionality'. (default is True) kernel : Kernel, optional For examples, see 'ite.cost.x_kernel.Kernel' eta : float, >0, optional It is used to control the quality of the incomplete Cholesky decomposition based Gram matrix approximation. Smaller 'eta' means larger sized Gram factor and better approximation. (default is 1e-2) kappa: float, >0 Regularization parameter. Examples -------- >>> import ite >>> from ite.cost.x_kernel import Kernel >>> co1 = ite.cost.BIKGV() >>> co2 = ite.cost.BIKGV(eta=1e-4) >>> co3 = ite.cost.BIKGV(eta=1e-4, kappa=0.02) >>> k = Kernel({'name': 'RBF', 'sigma': 0.3}) >>> co4 = ite.cost.BIKGV(eta=1e-4, kernel=k) """ # initialize with 'InitEtaKernel': super().__init__(mult=mult, kernel=kernel, eta=eta) # other attributes: self.kappa = kappa def estimation(self, y, ds): """ Estimate KGV. Parameters ---------- y : (number of samples, dimension)-ndarray One row of y corresponds to one sample. ds : int vector Dimensions of the individual subspaces in y; ds[i] = i^th subspace dimension. Returns ------- i : float Estimated value of KGV. References ---------- Francis Bach, Michael I. Jordan. Kernel Independent Component Analysis. Journal of Machine Learning Research, 3: 1-48, 2002. Francis Bach, Michael I. Jordan. Learning graphical models with Mercer kernels. International Conference on Neural Information Processing Systems (NIPS), pages 1033-1040, 2002. Examples -------- i = co.estimation(y,ds) """ # verification: self.verification_compatible_subspace_dimensions(y, ds) num_of_samples = y.shape[0] tol = num_of_samples * self.eta r = compute_matrix_r_kcca_kgv(y, ds, self.kernel, tol, self.kappa) i = -log(det(r)) / 2 return i class BIKCCA(InitEtaKernel, VerCompSubspaceDims): """ Kernel canonical correlation analysis (KCCA) based estimator. Partial initialization comes from 'InitEtaKernel', verification is from 'VerCompSubspaceDims' (see 'ite.cost.x_initialization.py', 'ite.cost.x_verification.py'). """ def __init__(self, mult=True, kernel=Kernel(), eta=1e-2, kappa=0.01): """ Initialize the estimator. Parameters ---------- mult : bool, optional 'True': multiplicative constant relevant (needed) in the estimation. 'False': estimation up to 'proportionality'. (default is True) kernel : Kernel, optional For examples, see 'ite.cost.x_kernel.Kernel' eta : float, >0, optional It is used to control the quality of the incomplete Cholesky decomposition based Gram matrix approximation. Smaller 'eta' means larger sized Gram factor and better approximation. (default is 1e-2) kappa: float, >0 Regularization parameter. Examples -------- >>> import ite >>> from ite.cost.x_kernel import Kernel >>> co1 = ite.cost.BIKCCA() >>> co2 = ite.cost.BIKCCA(eta=1e-4) >>> co3 = ite.cost.BIKCCA(eta=1e-4, kappa=0.02) >>> k = Kernel({'name': 'RBF', 'sigma': 0.3}) >>> co4 = ite.cost.BIKCCA(eta=1e-4, kernel=k) """ # initialize with 'InitEtaKernel': super().__init__(mult=mult, kernel=kernel, eta=eta) # other attributes: self.kappa = kappa def estimation(self, y, ds): """ Estimate KCCA. Parameters ---------- y : (number of samples, dimension)-ndarray One row of y corresponds to one sample. ds : int vector Dimensions of the individual subspaces in y; ds[i] = i^th subspace dimension. Returns ------- i : float Estimated value of KCCA. References ---------- Francis Bach, Michael I. Jordan. Learning graphical models with Mercer kernels. International Conference on Neural Information Processing Systems (NIPS), pages 1033-1040, 2002. Examples -------- i = co.estimation(y,ds) """ # verification: self.verification_compatible_subspace_dimensions(y, ds) num_of_samples = y.shape[0] tol = num_of_samples * self.eta r = compute_matrix_r_kcca_kgv(y, ds, self.kernel, tol, self.kappa) eig_min = eigsh(r, k=1, which='SM')[0][0] i = -log(eig_min) / 2 return i
[ 37811, 7308, 13584, 1321, 3959, 2024, 13, 37227, 198, 198, 6738, 299, 32152, 1330, 2160, 11, 19862, 17034, 11, 2125, 272, 11, 1033, 11, 1612, 11, 4151, 11, 3392, 11, 16605, 11, 269, 5700, 388, 11, 3467, 198, 220, 220, 220, 220, 220,...
2.048492
13,198
#! python3 print("Task 17.3") import requests from plotly.graph_objs import Bar from plotly import offline def get_response(): """Make an api call, and return the response.""" url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' headers = {'Accept': 'application/vnd.github.v3+json'} r = requests.get(url, headers=headers) return r def get_repo_dicts(r): """Return a set of dicts representing the most popular repositories.""" response_dict = r.json() repo_dicts = response_dict['items'] return repo_dicts def get_project_data(repo_dicts): """Return data needed for each project in visualization.""" repo_links, stars, labels = [], [], [] for repo_dict in repo_dicts: repo_name = repo_dict['name'] repo_url = repo_dict['html_url'] repo_link = f"<a href='{repo_url}'>{repo_name}</a>" repo_links.append(repo_link) stars.append(repo_dict['stargazers_count']) owner = repo_dict['owner']['login'] description = repo_dict['description'] label = f"{owner}<br />{description}" labels.append(label) return repo_links, stars, labels def make_visualization(repo_links, stars, labels): """Generate the visualization of most commented articles.""" data = [{ 'type': 'bar', 'x': repo_links, 'y': stars, 'hovertext': labels, 'marker': { 'color': 'rgb(255, 0, 0)', 'line': {'width': 2, 'color': 'rgb(250, 200, 0)'} }, 'opacity': 0.6, }] my_layout = { 'title': 'Most-Starred Python Projects on GitHub', 'titlefont': {'size': 20}, 'xaxis': { 'title': 'Repository', 'titlefont': {'size': 18}, 'tickfont': {'size': 14}, }, 'yaxis': { 'title': 'Stars', 'titlefont': {'size': 18}, 'tickfont': {'size': 14}, }, } fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='python_repos.html') if __name__ == '__main__': r = get_response() repo_dicts = get_repo_dicts(r) repo_links, stars, labels = get_project_data(repo_dicts) make_visualization(repo_links, stars, labels)
[ 2, 0, 21015, 18, 198, 198, 4798, 7203, 25714, 1596, 13, 18, 4943, 198, 198, 11748, 7007, 198, 198, 6738, 7110, 306, 13, 34960, 62, 672, 8457, 1330, 2409, 198, 6738, 7110, 306, 1330, 18043, 198, 198, 4299, 651, 62, 26209, 33529, 198,...
2.252234
1,007
"""Custom exceptions for this package""" class JerseyError(Exception): """Basic exception for this package""" pass
[ 37811, 15022, 13269, 329, 428, 5301, 37811, 198, 198, 4871, 8221, 12331, 7, 16922, 2599, 198, 220, 220, 220, 37227, 26416, 6631, 329, 428, 5301, 37811, 198, 220, 220, 220, 1208, 198 ]
3.875
32
# influenced by https://www.reddit.com/r/adventofcode/comments/a3kr4r/2018_day_6_solutions/eb7385m/ import itertools from collections import defaultdict, Counter if __name__ == "__main__": with open("6.txt") as f: points = f.readlines() points = [tuple(int(i) for i in l.split(",")) for l in points] print("Part 1: {}".format(part1(points))) print("Part 2: {}".format(part2(points)))
[ 2, 12824, 416, 3740, 1378, 2503, 13, 10748, 13, 785, 14, 81, 14, 324, 1151, 1659, 8189, 14, 15944, 14, 64, 18, 38584, 19, 81, 14, 7908, 62, 820, 62, 21, 62, 82, 14191, 14, 1765, 22, 27203, 76, 14, 198, 198, 11748, 340, 861, 10...
2.571429
161
"""Grammar and methods for parsing the configuration file""" from .printing import PybnfError, print1 from .config import Configuration from string import punctuation import logging import pyparsing as pp import re logger = logging.getLogger(__name__) numkeys_int = ['verbosity', 'parallel_count', 'delete_old_files', 'population_size', 'smoothing', 'max_iterations', 'num_to_output', 'output_every', 'islands', 'migrate_every', 'num_to_migrate', 'init_size', 'local_min_limit', 'reserve_size', 'burn_in', 'sample_every', 'output_hist_every', 'hist_bins', 'refine', 'simplex_max_iterations', 'wall_time_sim', 'wall_time_gen', 'verbosity', 'exchange_every', 'backup_every', 'bootstrap', 'crossover_number', 'ind_var_rounding', 'local_objective_eval', 'reps_per_beta', 'save_best_data', 'parallelize_models', 'adaptive', 'continue_run'] numkeys_float = ['min_objective', 'cognitive', 'social', 'particle_weight', 'particle_weight_final', 'adaptive_n_max', 'adaptive_n_stop', 'adaptive_abs_tol', 'adaptive_rel_tol', 'mutation_rate', 'mutation_factor', 'stop_tolerance', 'step_size', 'simplex_step', 'simplex_log_step', 'simplex_reflection', 'simplex_expansion', 'simplex_contraction', 'simplex_shrink', 'cooling', 'beta_max', 'bootstrap_max_obj', 'simplex_stop_tol', 'v_stop', 'gamma_prob', 'zeta', 'lambda', 'constraint_scale', 'neg_bin_r', 'stablizingCov'] multnumkeys = ['credible_intervals', 'beta', 'beta_range', 'starting_params'] b_var_def_keys = ['uniform_var', 'loguniform_var'] var_def_keys = ['lognormal_var', 'normal_var'] var_def_keys_1or2nums = ['var', 'logvar'] strkeylist = ['bng_command', 'output_dir', 'fit_type', 'objfunc', 'initialization', 'cluster_type', 'scheduler_node', 'scheduler_file', 'de_strategy', 'sbml_integrator', 'simulation_dir'] multstrkeys = ['worker_nodes', 'postprocess', 'output_trajectory', 'output_noise_trajectory'] dictkeys = ['time_course', 'param_scan'] punctuation_safe = re.sub('[:,]', '', punctuation) def parse_normalization_def(s): """ Parse the complicated normalization grammar If the grammar is specified incorrectly, it will end up calling something invalid the normalization type or the exp file, and this error will be caught later. :param s: The string following the equals sign in the normalization key :return: What to write in the config dictionary: A string, or a dictionary {expfile: string} or {expfile: (string, index_list)} or {expfile: (string, name_list)} """ def parse_range(x): """Parse a string as a set of numbers like 10,""" result = [] for part in x.split(','): if '-' in part: a, b = part.split('-') a, b = int(a), int(b) result.extend(range(a, b + 1)) else: a = int(part) result.append(a) return result # Remove all spaces s = re.sub('\s', '', s) if ':' in s: # List of exp files res = dict() i = s.index(':') normtype = s[:i] explist = s[i+1:] exps = re.split(r',(?![^()]*\))', explist) # Dark magic: split on commas that aren't inside parentheses # Achievement unlocked: Use 16 punctuation marks in a row for e in exps: if e[0] == '(' and e[-1] == ')': # It's an exp in parentheses with column-wise specs pair = e[1:-1].split(':') if len(pair) == 1: res[pair[0]] = normtype elif len(pair) == 2: e, cols = pair if re.match('^[\d,\-]+$', cols): col_nums = parse_range(cols) res[e] = (normtype, col_nums) else: col_names = cols.split(',') res[e] = (normtype, col_names) else: raise PybnfError("Parsing normalization key - the item '%s' has too many colons in it" % e) else: # It's just an exp res[e] = normtype return res else: # Single string for all return s
[ 37811, 38, 859, 3876, 290, 5050, 329, 32096, 262, 8398, 2393, 37811, 628, 198, 6738, 764, 4798, 278, 1330, 9485, 9374, 69, 12331, 11, 3601, 16, 198, 6738, 764, 11250, 1330, 28373, 198, 198, 6738, 4731, 1330, 21025, 2288, 198, 198, 117...
2.159463
2,013
from typing import Dict, Any import torch from torch import nn from torch.utils.data import DataLoader from torch import optim from torch.optim.lr_scheduler import _LRScheduler from ..core.callback import Callback from ..core.state import State from ..utils.torch import get_available_device
[ 6738, 19720, 1330, 360, 713, 11, 4377, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 6738, 28034, 1330, 6436, 198, 6738, 28034, 13, 40085, 13, 14050, 62, 1416, ...
3.641975
81
import numpy as np import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import requests import time import os from selenium.webdriver.common.by import By import re import time from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.linear_model import RidgeCV from sklearn.linear_model import LassoCV from sklearn.pipeline import make_pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.model_selection import KFold from sklearn.preprocessing import StandardScaler from sklearn.linear_model import Ridge from sklearn.linear_model import Lasso from sklearn.model_selection import cross_val_score from sklearn.metrics import mean_squared_error import scipy.stats as stats PATH_RS = '/Users/jadams/ds/metis/baseball_lin_regression/data/processed_df/rookie_stats.csv' PATH_S = '/Users/jadams/ds/metis/baseball_lin_regression/data/processed_df/salary.csv' def count_awards(s): ''' Counts the numebr of awards from baseballreference.com where the awards are listed in CSV format s: CSV string of awards return: int (count of awards) ''' awards = 0 s = str(s) if len(s) > 0: awards = s.count(',')+1 return awards def get_player_data(html, year, name): ''' Parses a player page on baseballreference.com, builds and writes a data frame to the data directory. html: html scrapped from baseballreference.com year: rookie year of the player name: name of the player return: writes a data frame to data/ directory ''' soup_players = BeautifulSoup(html, 'lxml') # Get position position = soup_players.find('p') position = position.contents[2].strip() if position in 'Pitcher': return None # Get the debut for identification in case duplicate name debut = soup_players.find('a', {'href': re.compile('=debut')}) debut = debut.contents # Get batting stats batting = soup_players.find('table',{'id':'batting_standard'}) batting_tbl_list = pd.read_html(str(batting)) batting_df = batting_tbl_list[0] batting_df = batting_df[:-1] rookie_stats = batting_df[(batting_df.Year == str(year))] rookie_stats = rookie_stats[(~rookie_stats.Tm.str.contains('-min'))] rookie_stats = rookie_stats[rookie_stats.Tm != 'TOT'] columns = ['Year', 'Age', 'Tm', 'Lg', 'G', 'PA', 'AB', 'R','H', 'SB','BA','HR','TB','2B','3B','RBI','BB','SO','Awards'] rookie_stats = rookie_stats.loc[:, columns] rookie_stats = rookie_stats[rookie_stats.Lg.str.contains(r'[A,N]L$')] rookie_stats['position'] = position rookie_stats['name'] = name rookie_stats['debut'] = debut * rookie_stats.shape[0] rookie_stats.Year = rookie_stats.Year.astype(int) rookie_stats.debut = pd.to_datetime(rookie_stats.debut, format='%B %d, %Y') rookie_stats.loc[rookie_stats.Awards.isnull(),'Awards'] = '' rookie_stats['award_count'] = rookie_stats.Awards.apply(count_awards) with open(PATH_RS, 'a') as f: rookie_stats.to_csv(f, header=False) def build_rookie_table(rookie_pages): ''' Builds a master data set of all rookie players using the rookie summary page on baseballreference.com rookie_pages: pd.DataFrame containing [html, year] return: pd.DataFrame() ['Name','Debut','Age','Tm','rookie_year'] ''' rookie_df = pd.DataFrame(columns=['Name','Debut','Age','Tm','rookie_year']) rookie_dfs = [] for i in rookie_pages.year.values: # scrape the rookie batters (includes pitchers if PA) soup_pages = BeautifulSoup(rookie_pages.html[i], 'lxml') batting = soup_pages.find('table',{'id':'misc_batting'}) batting_df = pd.read_html(str(batting)) # add Name, Debut, Age, Tm, and rookie_year year_df = batting_df[0].loc[:,['Name','Debut','Age','Tm']] year_df['rookie_year'] = [i] * batting_df[0].shape[0] year_df.rookie_year = year_df.rookie_year.astype(int) rookie_dfs.append(year_df) #= rookie_df.append(year_df) # Combine the rookie_dfs rookie_df = pd.concat(rookie_dfs) # Strip HOF indicator from name rookie_df.Name = rookie_df.Name.str.replace('HOF','') rookie_df[rookie_df.Name.str.contains('HOF')] rookie_df.Name = rookie_df.Name.str.strip() # Make Debut a date time rookie_df.Debut = rookie_df.Debut.astype('datetime64') return rookie_df def get_player_salary(html, year, name, ind): ''' Parses a player's page on baseballrefernce.com and builds a data frame of their salary data html: player page from baseballreference.com year: rookie year name: player name ind: index to build a unique identfier return: appends to /data/salary.csv ''' salary_soup = BeautifulSoup(html, 'lxml') salary_html = salary_soup.find('table',{'id':'br-salaries'}) if salary_html is None: return None salary_tables_lst = pd.read_html(str(salary_html)) salary_df = salary_tables_lst[0] salary_df = salary_df[~salary_df.Year.isnull()] salary_df = salary_df[salary_df.Year.str.contains(r'[1-2]\d{3}$')] salary_df['name'] = [name] * salary_df.shape[0] salary_df['UID'] = [ind] * salary_df.shape[0] salary_df['rookie_year'] = [year] * salary_df.shape[0] salary_df.Salary = (salary_df.Salary .str.replace('$','') .str.replace(',','') .str.replace('*','') ) salary_df.loc[salary_df.Salary == '', 'Salary'] = np.nan salary_df.Salary = salary_df.Salary.astype(float) salary_df.Age = salary_df.Age.astype(float) if salary_df.SrvTm.dtype != 'float64': salary_df.loc[salary_df.SrvTm == '?','SrvTm'] = np.nan salary_df.SrvTm = salary_df.SrvTm.astype(float) if ind == 1: salary_df.to_csv(PATH_S) else: with open(PATH_S, 'a') as f: salary_df.to_csv(f, header=False) def run_models(X_train, y_train, name, results = None, cv=10, alphas=[10**a for a in range(-2,5)]): ''' Method to quickly run all models with different feature sets. Runs: OLS, Standard Scaler + LassoCV, and PolynomialFeatures + Standard Scaler + LassoCV X_train: training feature set y_train: training actuals name: name of the type of run (used for comparing different feature sets) results: data frame to hold the results if varying the feature set cv: number of n-fold cross validations alphas: range of alpha values for CV return: pd.DataFrame of the MSE results ''' # capture the results for the feature set model_results = pd.Series(name=name) # Perform 10-fold cross-validation linear regression model. lin_model = LinearRegression() scores = cross_val_score(lin_model, X_train, y_train, cv=cv, scoring='neg_mean_squared_error') model_results['linear model - cv10'] = np.mean(-scores) # Now perform a n-fold cross validation cv_lasso = make_pipeline(StandardScaler(), LassoCV(cv=cv, alphas=alphas, tol=0.001)) cv_lasso.fit(X_train, y_train) model_results['lasso cv - ' + str(cv_lasso.get_params()['lassocv'].alpha_)] = mean_mse_Lasso(cv_lasso, 'lassocv') # Now 2-5 degree polynomial features and perform a n-fold cross validation. for degrees in range(2,6): cv_lasso_poly = make_pipeline(PolynomialFeatures(degrees), StandardScaler(), LassoCV(cv=cv, alphas=alphas,tol=0.001)) cv_lasso_poly.fit(X_train, y_train) model_results['lasso poly ' + str(degrees) + ' cv - ' + str(cv_lasso_poly.get_params()['lassocv'].alpha_)] = mean_mse_Lasso(cv_lasso_poly, 'lassocv') if results is None: results = pd.DataFrame(model_results) else: results = pd.concat([results, pd.DataFrame(model_results)], axis=1, sort=True) return results def mean_mse_Lasso(model,name): ''' Calcualtes the MSE of an n-fold CV from LassoCV model model: sklearn model or pipeline name: name of the lassocv model return float64 (mean MSE) ''' mse = model.get_params()[name].mse_path_ alphas = model.get_params()[name].alphas_ mse_df = pd.DataFrame(data=mse, index=alphas) return mse_df.loc[model.get_params()[name].alpha_].mean()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 13083, ...
2.460406
3,397
import sys feature_map_basic = { "avg_length":"the average length", "avg_basic_words":"the ratio of basic words (pre-defied by a dictionary)", "avg_lexical_richness":"the lexical diversity", "avg_gender_bias_word_male":"the average ratio of male words", "avg_gender_bias_word_female":"the average ratio of female words", "avg_gender_bias_single_name_male":"the average ratio of male names", "avg_gender_bias_single_name_female":"the average ratio of female names", "avg_gender_bias_name_male":"the average ratio of male names", "avg_gender_bias_name_female": "the average ratio of female names", "avg_span_length_of_ner_tags": "the average of entity length", "avg_eCon_of_ner_tags": "the average of entity's label consistency (defined in the paper: Interpretable Multi-dataset Evaluation for Named Entity Recognition)", "avg_eFre_of_ner_tags":"the average of entity frequency", "avg_density":"the average density (measures to what extent a summary covers the content in the source text)", "avg_coverage":"the average of coverage (measures to what extent a summary covers the content in the source text)", "avg_compression": "the average of compression (measures the compression ratio from the source text to the generated summary)", "avg_repetition": "the average of repetition (measures the rate of repeated segments in summaries. The segments are instantiated as trigrams)", "avg_novelty": "the average of novelty (the proportion of segments in the summaries that have not appeared in source documents. The segments are instantiated as bigrams)", "avg_copy_length": "the average of copy_length (the average length of segments in summary copied from source document)", } feature_map_basic2 = {"divide":"fraction", "minus":"difference", "add":"addition",} # Usage & Test Cases: # feature_name = "background_train_avg_gender_bias_single_name_male" # feature_name = "bleu_question_situation_avg_test" # feature_name = "question_length_divide_situation_avg_validation_length" # feature_name = "avg_span_length_of_ner_tags_test" # feature_name = "avg_eCon_of_ner_tags_validation" # feature_name = "avg_compression_of_test_highlights_and_article" # feature_name = "avg_copy_length_of_test_highlights_and_article" # feature_name = "premise_length_add_hypothesis_avg_validation_length" # feature_name = "premise_length_divide_hypothesis_avg_train_length" # feature_name = "bleu_question_context_avg_train" # feature_name = "question_length_divide_context_avg_validation_length" # # print(get_feature_description(feature_name))
[ 11748, 25064, 628, 198, 198, 30053, 62, 8899, 62, 35487, 796, 1391, 198, 220, 220, 220, 366, 615, 70, 62, 13664, 2404, 1169, 2811, 4129, 1600, 198, 220, 220, 220, 366, 615, 70, 62, 35487, 62, 10879, 2404, 1169, 8064, 286, 4096, 2456...
3.032073
873
from typing import List from wt.ids import BaseId from wt.fields.links._obj import Link
[ 6738, 19720, 1330, 7343, 198, 198, 6738, 266, 83, 13, 2340, 1330, 7308, 7390, 198, 6738, 266, 83, 13, 25747, 13, 28751, 13557, 26801, 1330, 7502, 628 ]
3.333333
27
fileName = 'test.txt' linebreak = '\n' items = [['a,99,22'], ['b,34,dd'], ['c,5,21']] writeItemsToFile(items) items = getItemsFromFile() print(items)
[ 7753, 5376, 796, 705, 9288, 13, 14116, 6, 198, 1370, 9032, 796, 705, 59, 77, 6, 198, 198, 23814, 796, 16410, 6, 64, 11, 2079, 11, 1828, 6, 4357, 37250, 65, 11, 2682, 11, 1860, 6, 4357, 37250, 66, 11, 20, 11, 2481, 6, 11907, 19...
2.253731
67
__________________________________________________________________________________________________ sample 56 ms submission # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None __________________________________________________________________________________________________ sample 17372 kb submission # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None __________________________________________________________________________________________________
[ 27193, 10221, 834, 198, 39873, 7265, 13845, 14498, 198, 2, 30396, 329, 257, 13934, 5509, 10139, 13, 198, 2, 1398, 12200, 19667, 25, 198, 2, 220, 220, 220, 220, 825, 11593, 15003, 834, 7, 944, 11, 2124, 2599, 198, 2, 220, 220, 220, ...
3.884393
173
from epics import caput, caget from math import inf, nan from IEX_29id.utils.exp import CheckBranch from IEX_29id.utils.misc import read_dict from bluesky import plan_stubs as bps import logging from ophyd import EpicsMotor, EpicsSignal, PVPositionerPC, EpicsSignalRO, Signal from ophyd import Component, Device from apstools.devices import EpicsDescriptionMixin # busy_record = Component(EpicsSignalRO, "29idKappa:Kappa_busy", done_value=0,kind='omitted') ## Instantiate pseudo motors slits = _My4Slits("29idb:Slit",name="motors") #--------------------------- Old Functions ----------------------------# # def slit(val): # """ # Sets the exit slits: # ARPES = 0 < x < 300 um # Kappa = 0 < x < 1000 um # """ # SetExitSlit(val) # def SetSlit1A(Hsize,Vsize,Hcenter,Vcenter,q=None): # """move slits 1A: Hsize x Vsize centered at (Hcenter,Vcenter)""" # caput("29idb:Slit1Hsync.PROC",1) # make sure slits are in sink with real motors # caput("29idb:Slit1Vsync.PROC",1) # caput("29idb:Slit1Hsize.VAL", Hsize) # caput("29idb:Slit1Vsize.VAL", Vsize) # caput("29idb:Slit1Hcenter.VAL",Hcenter) # caput("29idb:Slit1Vcenter.VAL",Vcenter) # if not q: # print("Slit-1A = ("+str(round(Hsize,3))+"x"+str(round(Vsize,3))+") @ ("+str(Hcenter)+","+str(Vcenter)+")") # def SetSlit2B(Hsize,Vsize,Hcenter,Vcenter,q=None): # caput("29idb:Slit2Hsync.PROC",1) # caput("29idb:Slit2Vsync.PROC",1) # caput("29idb:Slit2Hsize.VAL", Hsize) # caput("29idb:Slit2Vsize.VAL", Vsize) # caput("29idb:Slit2Hcenter.VAL",Hcenter) # caput("29idb:Slit2Vcenter.VAL",Vcenter) # if not q: # print("Slit-2B = ("+str(Hsize)+"x"+str(Vsize)+") @ ("+str(Hcenter)+","+str(Vcenter)+")") # def SetSlit3C(size): # caput("29idb:Slit3CFit.A",size) # print("Slit-3C =",size,"um") # def SetSlit3D(size,position=None): # if position == None: # position=round(caget('29idb:Slit4Vt2.D'),2) # caput("29idb:Slit4Vcenter.VAL") # caput("29idb:Slit4Vsize.VAL",size,wait=True,timeout=18000) # print("Slit-3D =",size,"um") # def SetSlit_BL(c2B=1,c1A=1,q=None): # RBV=caget("29idmono:ENERGY_MON") # GRT=caget("29idmono:GRT_DENSITY") # hv=max(RBV,500) # hv=min(RBV,2000) # c=4.2/2.2 # if GRT==1200: # GRT='MEG' # V=0.65 # set to 65% of RR calculation for both grt => cf 2016_2_summary # elif GRT==2400: # GRT='HEG' # V=0.65*c # set to 65% of RR calculation (no longer 80%) => cf 2016_2_summary # try: # slit_position=read_dict(FileName='Dict_Slit.txt') # except KeyError: # print("Unable to read dictionary") # return # V2center= slit_position[GRT]['S2V'] # H2center= slit_position[GRT]['S2H'] # V1center= slit_position[GRT]['S1V'] # H1center= slit_position[GRT]['S1H'] # Size1A=( Aperture_Fit(hv,1)[0]*c1A, Aperture_Fit(hv,1)[1]*c1A ) # Size2B=( Aperture_Fit(hv,2)[0]*c2B, round(Aperture_Fit(hv,2)[1]*c2B*V,3)) # SetSlit1A (Size1A[0],Size1A[1],H1center,V1center,q) # standard operating # SetSlit2B(Size2B[0],Size2B[1],H2center,V2center,q) # def SetExitSlit(size): # branch=CheckBranch() # if branch == "c": # SetSlit3C(size) # elif branch == "d": # SetSlit3D(size) # def Slit3C_Fit(size): # K0=-36.383 # K1=0.16473 # K2=-0.00070276 # K3=8.4346e-06 # K4=-5.6215e-08 # K5=1.8223e-10 # K6=-2.2635e-13 # motor=K0+K1*size+K2*size**2+K3*size**3+K4*size**4+K5*size**5+K6*size**6 # return motor # def Slit_Coef(n): # if n == 1: # pv='29id:k_slit1A' # #Redshifted x (H): # H0=2.3325 # H1=-.000936 # H2=2.4e-7 # #Redshifted z (V): # V0=2.3935 # V1=-.0013442 # V2=3.18e-7 # if n == 2: # pv='29id:k_slit2B' # #Redshifted x (H): # H0=3.61 # H1=-0.00186 # H2=5.2e-7 # #Redshifted z (V): # V0=6.8075 # V1=-0.003929 # V2=9.5e-7 # K=H0,H1,H2,V0,V1,V2 # return pv,K # def Aperture_Fit(hv,n): # K=Slit_Coef(n)[1] # sizeH=K[0]+K[1]*hv+K[2]*hv*hv # sizeV=K[3]+K[4]*hv+K[5]*hv*hv # return [round(sizeH,3),round(sizeV,3)] # # SetSlits: # def SetSlit(n,Hsize=None,Vsize=None,Hcenter=0,Vcenter=0,q=None): # if n == 1: # if Hsize in [inf,nan,None]: Hsize=4.5 # if Vsize in [inf,nan,None]: Vsize=4.5 # SetSlit1A(Hsize,Vsize,Hcenter,Vcenter,q=None) # elif n == 2: # if Hsize in [inf,nan,None]: Hsize=6 # if Vsize in [inf,nan,None]: Vsize=8 # SetSlit2B(Hsize,Vsize,Hcenter,Vcenter,q=None) # else: # print('Not a valid slit number')
[ 6738, 2462, 873, 1330, 1451, 315, 11, 269, 363, 316, 198, 6738, 10688, 1330, 1167, 11, 15709, 198, 6738, 314, 6369, 62, 1959, 312, 13, 26791, 13, 11201, 1330, 6822, 33, 25642, 198, 6738, 314, 6369, 62, 1959, 312, 13, 26791, 13, 4437...
1.809721
2,654
import os import unittest from vcr_unittest import VCRTestCase import getnet from getnet import NotFound from getnet.services.base import ResponseList from getnet.services.customers import Service, Customer from tests.getnet.services.customers.test_customer import sample if __name__ == "__main__": unittest.main()
[ 11748, 28686, 198, 11748, 555, 715, 395, 198, 198, 6738, 410, 6098, 62, 403, 715, 395, 1330, 569, 9419, 14402, 20448, 198, 198, 11748, 651, 3262, 198, 6738, 651, 3262, 1330, 1892, 21077, 198, 6738, 651, 3262, 13, 30416, 13, 8692, 1330...
3.272727
99
import psutil import json mem = psutil.virtual_memory() result = { "_Total": mem.total } print(json.dumps(result))
[ 11748, 26692, 22602, 198, 11748, 33918, 198, 198, 11883, 796, 26692, 22602, 13, 32844, 62, 31673, 3419, 198, 20274, 796, 1391, 45434, 14957, 1298, 1066, 13, 23350, 1782, 198, 4798, 7, 17752, 13, 67, 8142, 7, 20274, 4008, 198 ]
2.974359
39
import typing from random import randint, random as random_range from PIL import ImageFilter, Image from pixelsort.sorting import lightness def edge(image: Image.Image, lower_threshold: float, **_) -> typing.List[typing.List[int]]: """Performs an edge detection, which is used to define intervals. Tweak threshold with threshold.""" edge_data = image.filter(ImageFilter.FIND_EDGES).convert('RGBA').load() intervals = [] for y in range(image.size[1]): intervals.append([]) flag = True for x in range(image.size[0]): if lightness(edge_data[x, y]) < lower_threshold * 255: flag = True elif flag: intervals[y].append(x) flag = False return intervals def threshold(image: Image.Image, lower_threshold: float, upper_threshold: float, **_) -> typing.List[typing.List[int]]: """Intervals defined by lightness thresholds; only pixels with a lightness between the upper and lower thresholds are sorted.""" intervals = [] image_data = image.load() for y in range(image.size[1]): intervals.append([]) for x in range(image.size[0]): level = lightness(image_data[x, y]) if level < lower_threshold * 255 or level > upper_threshold * 255: intervals[y].append(x) return intervals def random(image, char_length, **_) -> typing.List[typing.List[int]]: """Randomly generate intervals. Distribution of widths is linear by default. Interval widths can be scaled using char_length.""" intervals = [] for y in range(image.size[1]): intervals.append([]) x = 0 while True: x += int(char_length * random_range()) if x > image.size[0]: break else: intervals[y].append(x) return intervals def waves(image, char_length, **_) -> typing.List[typing.List[int]]: """Intervals are waves of nearly uniform widths. Control width of waves with char_length.""" intervals = [] for y in range(image.size[1]): intervals.append([]) x = 0 while True: x += char_length + randint(0, 10) if x > image.size[0]: break else: intervals[y].append(x) return intervals def file_mask(image, interval_image, **_) -> typing.List[typing.List[int]]: """Intervals taken from another specified input image. Must be black and white, and the same size as the input image.""" intervals = [] data = interval_image.load() for y in range(image.size[1]): intervals.append([]) flag = True for x in range(image.size[0]): if data[x, y]: flag = True elif flag: intervals[y].append(x) flag = False return intervals def file_edges(image, interval_image, lower_threshold, **_) -> typing.List[typing.List[int]]: """Intervals defined by performing edge detection on the file specified by -f. Must be the same size as the input image.""" edge_data = interval_image.filter( ImageFilter.FIND_EDGES).convert('RGBA').load() intervals = [] for y in range(image.size[1]): intervals.append([]) flag = True for x in range(image.size[0]): if lightness(edge_data[x, y]) < lower_threshold * 255: flag = True elif flag: intervals[y].append(x) flag = False return intervals def none(image, **_) -> typing.List[typing.List[int]]: """Sort whole rows, only stopping at image borders.""" intervals = [] for y in range(image.size[1]): intervals.append([]) return intervals choices = { "random": random, "threshold": threshold, "edges": edge, "waves": waves, "file": file_mask, "file-edges": file_edges, "none": none }
[ 11748, 19720, 198, 6738, 4738, 1330, 43720, 600, 11, 4738, 355, 4738, 62, 9521, 198, 198, 6738, 350, 4146, 1330, 7412, 22417, 11, 7412, 198, 198, 6738, 17848, 419, 13, 82, 24707, 1330, 1657, 1108, 628, 198, 4299, 5743, 7, 9060, 25, ...
2.361144
1,678
import django from django.conf import settings from django.utils.decorators import classonlymethod from django.views.generic import CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import PermissionRequiredMixin from django.http.response import JsonResponse from django.template.response import TemplateResponse from django.core.exceptions import ImproperlyConfigured from .fields import ForeignKeyWidget, ManyToManyWidget if django.VERSION >= (2, 0): from django.urls import path, include else: from django.conf.urls import url, include
[ 11748, 42625, 14208, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 26791, 13, 12501, 273, 2024, 1330, 1398, 8807, 24396, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 13610, 7680, 11, 10133, 7680, 11,...
3.55625
160
print("Enter 'q' at any time to quit.\n") while True: try: x = input("\nGive me a number: ") if x == 'q': break x = int(x) y = input("Give me another number: ") if y == 'q': break y = int(y) except ValueError: print("Sorry, I really needed a number.") else: sum = x + y print("The sum of " + str(x) + " and " + str(y) + " is " + str(sum) + ".")
[ 4798, 7203, 17469, 705, 80, 6, 379, 597, 640, 284, 11238, 13, 59, 77, 4943, 198, 198, 4514, 6407, 25, 198, 220, 220, 220, 1949, 25, 198, 220, 220, 220, 220, 220, 220, 220, 2124, 796, 5128, 7203, 59, 77, 23318, 502, 257, 1271, 25...
1.965665
233
#!/usr/bin/env python3 import sys import cdsapi year= sys.argv[1] month= sys.argv[2] c = cdsapi.Client() c.retrieve( 'efas-historical', { 'format': 'grib', 'origin': 'ecmwf', 'simulation_version': 'version_3_5', 'variable': [ 'soil_depth', 'volumetric_soil_moisture', ], 'model_levels': 'soil_levels', 'soil_level': [ '1', '2', '3', ], 'hyear': year, 'hmonth': month, 'hday': [ '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', ] }, '/home/smartmet/data/efas-ana-%s.grib'%(year))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 25064, 198, 11748, 269, 9310, 15042, 198, 1941, 28, 25064, 13, 853, 85, 58, 16, 60, 198, 8424, 28, 25064, 13, 853, 85, 58, 17, 60, 198, 198, 66, 796, 269, 9310, 15042, ...
1.320151
1,062
from . import settings class Block: """Minecraft PI block description. Can be sent to Minecraft.setBlock/s""" def __iter__(self): """Allows a Block to be sent whenever id [and data] is needed""" if self.nbt is not None: return iter((self.id, self.data, self.nbt)) else: return iter((self.id, self.data)) AIR = Block(0) STONE = Block(1) GRASS = Block(2) DIRT = Block(3) COBBLESTONE = Block(4) WOOD_PLANKS = Block(5) SAPLING = Block(6) BEDROCK = Block(7) WATER_FLOWING = Block(8) WATER = WATER_FLOWING WATER_STATIONARY = Block(9) LAVA_FLOWING = Block(10) LAVA = LAVA_FLOWING LAVA_STATIONARY = Block(11) SAND = Block(12) GRAVEL = Block(13) GOLD_ORE = Block(14) IRON_ORE = Block(15) COAL_ORE = Block(16) WOOD = Block(17) LEAVES = Block(18) GLASS = Block(20) LAPIS_LAZULI_ORE = Block(21) LAPIS_LAZULI_BLOCK = Block(22) SANDSTONE = Block(24) BED = Block(26) COBWEB = Block(30) GRASS_TALL = Block(31) WOOL = Block(35) FLOWER_YELLOW = Block(37) FLOWER_CYAN = Block(38) MUSHROOM_BROWN = Block(39) MUSHROOM_RED = Block(40) GOLD_BLOCK = Block(41) IRON_BLOCK = Block(42) STONE_SLAB_DOUBLE = Block(43) STONE_SLAB = Block(44) BRICK_BLOCK = Block(45) TNT = Block(46) BOOKSHELF = Block(47) MOSS_STONE = Block(48) OBSIDIAN = Block(49) TORCH = Block(50) FIRE = Block(51) STAIRS_WOOD = Block(53) CHEST = Block(54) DIAMOND_ORE = Block(56) DIAMOND_BLOCK = Block(57) CRAFTING_TABLE = Block(58) FARMLAND = Block(60) FURNACE_INACTIVE = Block(61) FURNACE_ACTIVE = Block(62) DOOR_WOOD = Block(64) LADDER = Block(65) STAIRS_COBBLESTONE = Block(67) DOOR_IRON = Block(71) REDSTONE_ORE = Block(73) STONE_BUTTON = Block(77) SNOW = Block(78) ICE = Block(79) SNOW_BLOCK = Block(80) CACTUS = Block(81) CLAY = Block(82) SUGAR_CANE = Block(83) FENCE = Block(85) GLOWSTONE_BLOCK = Block(89) BEDROCK_INVISIBLE = Block(95) if settings.isPE: STAINED_GLASS = WOOL else: STAINED_GLASS = Block(95) STONE_BRICK = Block(98) GLASS_PANE = Block(102) MELON = Block(103) FENCE_GATE = Block(107) WOOD_BUTTON = Block(143) REDSTONE_BLOCK = Block(152) QUARTZ_BLOCK = Block(155) if settings.isPE: HARDENED_CLAY_STAINED = WOOL else: HARDENED_CLAY_STAINED = Block(159) if settings.isPE: SEA_LANTERN = Block(246) # glowing obsidian else: SEA_LANTERN = Block(169) CARPET = Block(171) COAL_BLOCK = Block(173) if settings.isPE: GLOWING_OBSIDIAN = Block(246) NETHER_REACTOR_CORE = Block(247) REDSTONE_LAMP_INACTIVE = OBSIDIAN REDSTONE_LAMP_ACTIVE = GLOWING_OBSIDIAN else: GLOWING_OBSIDIAN = SEA_LANTERN NETHER_REACTOR_CORE = SEA_LANTERN REDSTONE_LAMP_INACTIVE = Block(123) REDSTONE_LAMP_ACTIVE = Block(124) SUNFLOWER = Block(175,0) LILAC = Block(175,1) DOUBLE_TALLGRASS = Block(175,2) LARGE_FERN = Block(175,3) ROSE_BUSH = Block(175,4) PEONY = Block(175,5) WOOL_WHITE = Block(WOOL.id, 0) WOOL_ORANGE = Block(WOOL.id, 1) WOOL_MAGENTA = Block(WOOL.id, 2) WOOL_LIGHT_BLUE = Block(WOOL.id, 3) WOOL_YELLOW = Block(WOOL.id, 4) WOOL_LIME = Block(WOOL.id, 5) WOOL_PINK = Block(WOOL.id, 6) WOOL_GRAY = Block(WOOL.id, 7) WOOL_LIGHT_GRAY = Block(WOOL.id, 8) WOOL_CYAN = Block(WOOL.id, 9) WOOL_PURPLE = Block(WOOL.id, 10) WOOL_BLUE = Block(WOOL.id, 11) WOOL_BROWN = Block(WOOL.id, 12) WOOL_GREEN = Block(WOOL.id, 13) WOOL_RED = Block(WOOL.id, 14) WOOL_BLACK = Block(WOOL.id, 15) CARPET_WHITE = Block(CARPET.id, 0) CARPET_ORANGE = Block(CARPET.id, 1) CARPET_MAGENTA = Block(CARPET.id, 2) CARPET_LIGHT_BLUE = Block(CARPET.id, 3) CARPET_YELLOW = Block(CARPET.id, 4) CARPET_LIME = Block(CARPET.id, 5) CARPET_PINK = Block(CARPET.id, 6) CARPET_GRAY = Block(CARPET.id, 7) CARPET_LIGHT_GRAY = Block(CARPET.id, 8) CARPET_CYAN = Block(CARPET.id, 9) CARPET_PURPLE = Block(CARPET.id, 10) CARPET_BLUE = Block(CARPET.id, 11) CARPET_BROWN = Block(CARPET.id, 12) CARPET_GREEN = Block(CARPET.id, 13) CARPET_RED = Block(CARPET.id, 14) CARPET_BLACK = Block(CARPET.id, 15) STAINED_GLASS_WHITE = Block(STAINED_GLASS.id, 0) STAINED_GLASS_ORANGE = Block(STAINED_GLASS.id, 1) STAINED_GLASS_MAGENTA = Block(STAINED_GLASS.id, 2) STAINED_GLASS_LIGHT_BLUE = Block(STAINED_GLASS.id, 3) STAINED_GLASS_YELLOW = Block(STAINED_GLASS.id, 4) STAINED_GLASS_LIME = Block(STAINED_GLASS.id, 5) STAINED_GLASS_PINK = Block(STAINED_GLASS.id, 6) STAINED_GLASS_GRAY = Block(STAINED_GLASS.id, 7) STAINED_GLASS_LIGHT_GRAY = Block(STAINED_GLASS.id, 8) STAINED_GLASS_CYAN = Block(STAINED_GLASS.id, 9) STAINED_GLASS_PURPLE = Block(STAINED_GLASS.id, 10) STAINED_GLASS_BLUE = Block(STAINED_GLASS.id, 11) STAINED_GLASS_BROWN = Block(STAINED_GLASS.id, 12) STAINED_GLASS_GREEN = Block(STAINED_GLASS.id, 13) STAINED_GLASS_RED = Block(STAINED_GLASS.id, 14) STAINED_GLASS_BLACK = Block(STAINED_GLASS.id, 15) HARDENED_CLAY_STAINED_WHITE = Block(HARDENED_CLAY_STAINED.id, 0) HARDENED_CLAY_STAINED_ORANGE = Block(HARDENED_CLAY_STAINED.id, 1) HARDENED_CLAY_STAINED_MAGENTA = Block(HARDENED_CLAY_STAINED.id, 2) HARDENED_CLAY_STAINED_LIGHT_BLUE = Block(HARDENED_CLAY_STAINED.id, 3) HARDENED_CLAY_STAINED_YELLOW = Block(HARDENED_CLAY_STAINED.id, 4) HARDENED_CLAY_STAINED_LIME = Block(HARDENED_CLAY_STAINED.id, 5) HARDENED_CLAY_STAINED_PINK = Block(HARDENED_CLAY_STAINED.id, 6) HARDENED_CLAY_STAINED_GRAY = Block(HARDENED_CLAY_STAINED.id, 7) HARDENED_CLAY_STAINED_LIGHT_GRAY = Block(HARDENED_CLAY_STAINED.id, 8) HARDENED_CLAY_STAINED_CYAN = Block(HARDENED_CLAY_STAINED.id, 9) HARDENED_CLAY_STAINED_PURPLE = Block(HARDENED_CLAY_STAINED.id, 10) HARDENED_CLAY_STAINED_BLUE = Block(HARDENED_CLAY_STAINED.id, 11) HARDENED_CLAY_STAINED_BROWN = Block(HARDENED_CLAY_STAINED.id, 12) HARDENED_CLAY_STAINED_GREEN = Block(HARDENED_CLAY_STAINED.id, 13) HARDENED_CLAY_STAINED_RED = Block(HARDENED_CLAY_STAINED.id, 14) HARDENED_CLAY_STAINED_BLACK = Block(HARDENED_CLAY_STAINED.id, 15) LEAVES_OAK_DECAYABLE = Block(LEAVES.id, 0) LEAVES_SPRUCE_DECAYABLE = Block(LEAVES.id, 1) LEAVES_BIRCH_DECAYABLE = Block(LEAVES.id, 2) LEAVES_JUNGLE_DECAYABLE = Block(LEAVES.id, 3) LEAVES_OAK_PERMANENT = Block(LEAVES.id, 4) LEAVES_SPRUCE_PERMANENT = Block(LEAVES.id, 5) LEAVES_BIRCH_PERMANENT = Block(LEAVES.id, 6) LEAVES_JUNGLE_PERMANENT = Block(LEAVES.id, 7) if settings.isPE: LEAVES_ACACIA_DECAYABLE = Block(161,0) LEAVES_DARK_OAK_DECAYABLE = Block(161,1) LEAVES_ACACIA_PERMANENT = Block(161,2) LEAVES_DARK_OAK_PERMANENT = Block(161,3) else: LEAVES_ACACIA_DECAYABLE = LEAVES_OAK_DECAYABLE LEAVES_DARK_OAK_DECAYABLE = LEAVES_JUNGLE_DECAYABLE LEAVES_ACACIA_PERMANENT = LEAVES_OAK_PERMANENT LEAVES_DARK_OAK_PERMANENT = LEAVES_JUNGLE_PERMANENT
[ 6738, 764, 1330, 6460, 198, 198, 4871, 9726, 25, 198, 220, 220, 220, 37227, 39194, 30434, 2512, 6764, 13, 1680, 307, 1908, 284, 24609, 13, 2617, 12235, 14, 82, 37811, 628, 220, 220, 220, 825, 11593, 2676, 834, 7, 944, 2599, 198, 220...
1.844175
3,966
#Write a function shorten(text, n) to process a text, # omitting the n most frequently occurring words of the text. # How readable is it? import nltk def shorten(text, n): """Delete the most frequent n words from a text (list of words)""" assert isinstance(text, list), "The text should be a list of words" most_frequent_words = set(w for (w,f) in nltk.FreqDist(text).most_common(n)) return [w for w in text if w not in most_frequent_words] text = "to be or not to be that is the question".split() out = "or not that is the question".split() print(text) print (shorten(text,0)) print (shorten(text,1)) print (shorten(text,1)) print (shorten(text,2)) ##print shorten("to be or not to be that is the question", 2) #Write a list comprehension that sorts a list of WordNet synsets #for proximity to a given synset. #For example, given the synsets minke_whale.n.01, orca.n.01, novel.n.01, # and tortoise.n.01, sort them according to their shortest_path_distance() # from right_whale.n.01 from nltk.corpus import wordnet as wn whales = [wn.synset(s) for s in "minke_whale.n.01, orca.n.01, novel.n.01, tortoise.n.01".split(', ')] print (whales) def semantic_sort(sslist,ss): """return a list of synsets, sorted by similarity to another synset""" sim = [(ss.shortest_path_distance(s), s) for s in sslist] return [s for (sm, s) in sorted(sim)] print (semantic_sort(whales, wn.synset('right_whale.n.01'))) def semantic_sort1(sslist,ss): """return a list of synsets, sorted by similarity to another synset""" return sorted(sslist, key=lambda x: ss.shortest_path_distance(x)) print (semantic_sort1(whales, wn.synset('right_whale.n.01'))) # Write a function that takes a list of words (containing duplicates) # and returns a list of words (with no duplicates) sorted by # decreasing frequency. # E.g. if the input list contained 10 instances of the word table and # 9 instances of the word chair, then table would appear before chair # in the output list. def dec_freq(liszt): """take a list and returns a list of types in decreasing frequency""" return list(nltk.FreqDist(liszt).keys()) # Write a program to sort words by length. # print (sorted(text, key=lambda x:len(x))) print (sorted(text, key=len))
[ 2, 16594, 257, 2163, 45381, 7, 5239, 11, 299, 8, 284, 1429, 257, 2420, 11, 198, 2, 267, 16138, 262, 299, 749, 6777, 14963, 2456, 286, 262, 2420, 13, 198, 2, 1374, 31744, 318, 340, 30, 198, 11748, 299, 2528, 74, 198, 198, 4299, 4...
2.825279
807
import time from config import singleton, Logger from elasticsearch import Elasticsearch from elasticsearch.helpers import bulk from datetime import datetime from numpy import long log = Logger().logger @singleton
[ 11748, 640, 201, 198, 6738, 4566, 1330, 2060, 1122, 11, 5972, 1362, 201, 198, 6738, 27468, 12947, 1330, 48567, 12947, 201, 198, 6738, 27468, 12947, 13, 16794, 364, 1330, 11963, 201, 198, 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 673...
3.267606
71
from django.urls import reverse, reverse_lazy from django.utils.translation import gettext_lazy as _ from arctic.generics import ( CreateView, DeleteView, ListView, UpdateView, ) from .forms import {{ camel_case_app_name }}Form from .models import {{ camel_case_app_name }} class {{ camel_case_app_name }}ListView(ListView): model = {{ camel_case_app_name }} fields = '__all__' permission_required = 'view_{{ app_name }}' # Delete and detail action link action_links = [ ("detail", "{{ app_name}}:detail", "fa-edit"), ("delete", "{{ app_name}}:delete", "fa-trash"), ] # tool link to create tool_links = [ (_("Create {{ app_name }}"), "{{ app_name }}:create", "fa-plus"), ] # Some optional fields # paginate_by = 10 # ordering_fields = ['field_name1', ..] # search_fields = ['field_name', ...] # allowed_exports = ["csv"] class {{ camel_case_app_name }}CreateView(CreateView): model = {{ camel_case_app_name }} form_class = {{ camel_case_app_name }}Form permission_required = 'add_{{ app_name }}' class {{ camel_case_app_name }}UpdateView(UpdateView): model = {{ camel_case_app_name }} form_class = {{ camel_case_app_name }}Form permission_required = 'change_{{ app_name }}' success_url = reverse_lazy('{{app_name}}:list') actions = [ (_("Cancel"), "cancel"), (_("Save"), "submit"), ] class {{ camel_case_app_name }}DeleteView(DeleteView): model = {{ camel_case_app_name }} success_url = reverse_lazy('{{app_name}}:list') permission_required = 'delete_{{ app_name }}'
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 11, 9575, 62, 75, 12582, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 651, 5239, 62, 75, 12582, 355, 4808, 198, 198, 6738, 610, 11048, 13, 8612, 873, 1330, 357, 198, 220, 220, 22...
2.61563
627
import re from base64 import urlsafe_b64encode from os import urandom from typing import cast from unittest import TestCase from unittest.mock import MagicMock from ipaddress import IPv4Network from flask import Flask from sipa.backends import Backends, DataSource, Dormitory, InitContextCallable
[ 11748, 302, 198, 6738, 2779, 2414, 1330, 2956, 7278, 8635, 62, 65, 2414, 268, 8189, 198, 6738, 28686, 1330, 2956, 3749, 198, 6738, 19720, 1330, 3350, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 555, 715, 395, 13, 76, 735, ...
3.541176
85
#!/usr/bin/env python """ This script takes a JSON dictionary containing traditional chinese characters as keys, and the simplified equivalents as values. It then outputs a header file appropriate for inclusion. The header output file contains an array, `Cn_T2S` which can be used as ``` simpChr = Cn_T2S[tradChr]; ``` the variable Cn_T2S_MinChr contains the smallest key in the dictionary, whereas Cn_T2S_MaxChr contains the largest key in the dictionary. """ import json import datetime import sys from argparse import ArgumentParser ap = ArgumentParser() ap.add_argument('-f', '--file', help='Chinese map file', required=True) ap.add_argument('-o', '--output', help='Where to place the output C source') options = ap.parse_args() with open(options.file, 'r') as fp: txt = json.load(fp) if options.output is None or ap.output == '-': ofp = sys.stdout else: ofp = open(ap.output, 'w') CP_MIN = 0xffffffff CP_MAX = 0x00 for k in txt: v = ord(k) if v > CP_MAX: CP_MAX = v if v < CP_MIN: CP_MIN = v ofp.write(''' /** * Generated by {script} on {date} * */ #include <stdint.h> static const uint16_t Cn_T2S_MinChr = {cp_min}; static const uint16_t Cn_T2S_MaxChr = {cp_max}; static uint16_t Cn_T2S[{cap}]={{ '''.format( script=' '.join(sys.argv), date=datetime.datetime.now(), cp_min=CP_MIN, cp_max=CP_MAX, cap=CP_MAX+1)) num_items = 0 ITEMS_PER_LINE = 5 for trad, simp in txt.items(): ix = ord(trad) val = ord(simp) ofp.write(' [0x{:X}]=0x{:X},'.format(ix, val)) num_items += 1 if num_items >= ITEMS_PER_LINE: ofp.write('\n') num_items = 0 ofp.write('};\n') ofp.flush()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 1212, 4226, 2753, 257, 19449, 22155, 7268, 4569, 442, 3762, 3435, 198, 292, 8251, 11, 290, 262, 27009, 40255, 355, 3815, 13, 632, 788, 23862, 257, 13639, 2393, 198, 13...
2.348006
727
# -*- coding: utf-8 -*- # @COPYRIGHT_begin # # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland # # 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. # # @COPYRIGHT_end """@package src.cm.views.user.network @author Maciej Nabożny <mn@mnabozny.pl> Database model describing public ip addresses, which could be mapped on vm ip lease (Lease entity). Attached ips are redirected by nodes, on which vm are running. This is done by one-to-one NAT (SNAT+DNAT) """ import subprocess from django.db import models from cm.utils import log from cm.utils.exception import CMException
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 34, 3185, 38162, 9947, 62, 27471, 198, 2, 198, 2, 15069, 685, 10333, 12, 4967, 60, 5136, 286, 19229, 23123, 40468, 11, 509, 17716, 322, 11, 12873, 198, 2, 1...
3.284866
337
from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.generics import ListAPIView from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from blog.models import BlogPost from blog.utils import validate_uuid4 from blog.serializers import ( BlogPostSerializer, BlogPostUpdateSerializer, BlogPostCreateSerializer, ) @api_view(["GET"]) @permission_classes((IsAuthenticated,)) @authentication_classes([TokenAuthentication]) @api_view(["POST"]) @permission_classes((IsAuthenticated,)) @api_view(["PUT"]) @permission_classes((IsAuthenticated,)) @api_view(["DELETE"]) @permission_classes((IsAuthenticated,)) @api_view(["GET"]) @permission_classes((IsAuthenticated,)) @api_view(['GET', ]) @permission_classes((IsAuthenticated,))
[ 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 13, 41299, 3299, 1330, 29130, 47649, 3299, 198, 6738, 1334, 62, 30604, 13, 12501, 273, 2024, 1330, 40391, 62, 1177, 11, 7170, 62, 37724, 11, 18239, 62, 37724, 198, 6738, 1...
3.390476
315
""" crypto.cipher.aes_cbc AES_CBC Encryption Algorithm Copyright (c) 2002 by Paul A. Lambert Read LICENSE.txt for license information. 2002-06-14 """ from crypto.cipher.aes import AES from crypto.cipher.cbc import CBC from crypto.cipher.base import BlockCipher, padWithPadLen, noPadding class AES_CBC(CBC): """ AES encryption in CBC feedback mode """
[ 37811, 21473, 13, 66, 10803, 13, 64, 274, 62, 66, 15630, 628, 220, 220, 220, 34329, 62, 29208, 14711, 13168, 978, 42289, 628, 220, 220, 220, 15069, 357, 66, 8, 6244, 416, 3362, 317, 13, 36978, 198, 220, 220, 220, 4149, 38559, 24290,...
2.960938
128
import time from threading import Thread from typing import List from fpakman.util.cache import Cache
[ 11748, 640, 198, 6738, 4704, 278, 1330, 14122, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 277, 41091, 805, 13, 22602, 13, 23870, 1330, 34088, 628, 198 ]
3.888889
27
#!/usr/bin/env python3 import sys import json from util.aoc import file_to_day from util.input import load_data if __name__ == "__main__": test = len(sys.argv) > 1 and sys.argv[1] == "test" main(test)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 25064, 198, 11748, 33918, 198, 198, 6738, 7736, 13, 64, 420, 1330, 2393, 62, 1462, 62, 820, 198, 6738, 7736, 13, 15414, 1330, 3440, 62, 7890, 628, 628, 628, 628, 198,...
2.460674
89
import os import fsspec import numpy as np from PIL import Image from PIL import ImageDraw
[ 11748, 28686, 198, 11748, 277, 824, 43106, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 350, 4146, 1330, 7412, 25302, 628, 628, 628 ]
3.233333
30
from django.urls import re_path from . import views urlpatterns = [ re_path(r'^action/', views.action_view), re_path(r'^append-block/', views.append_block_view), re_path(r'^edit-block/', views.edit_block_view), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 302, 62, 6978, 198, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 302, 62, 6978, 7, 81, 6, 61, 2673, 14, 3256, 5009, 13, 2673, 62, 1177, 828, 198, 22...
2.414894
94
from __future__ import annotations import json from base64 import b64decode, b64encode from copy import deepcopy as dp from io import BytesIO from random import randrange from string import digits as strdigits from typing import Generator, IO from . import utils from .common import Cipher, Crypter from .exceptions import FileTypeMismatchError from .standardciphers import StreamedAESWithModeECB __all__ = ['NCM', 'NCMRC4Cipher'] class NCM(Crypter): """读写网易云音乐 NCM 格式的文件。 读取: >>> ncmfile = NCM('./test1.ncm') >>> data = ncmfile.read() 写入: >>> ncmfile.write(b'Writted bytes') 创建、写入并保存: >>> new_ncmfile = NCM() # 随机生成一个密钥 >>> with open('./metal.flac', 'rb') as f: # 写入未加密的文件数据 ... new_ncmfile.write(f.read()) >>> new_ncmfile.save('./result.ncm') >>> """ @staticmethod @staticmethod @staticmethod def __init__(self, filething: utils.FileThing | None = None, **kwargs ) -> None: """读写网易云音乐 NCM 格式的文件。 Args: filething (file): 源 NCM 文件的路径或文件对象;留空则视为创建一个空 NCM 文件 Keyword Args: key (bytes): 加/解密数据所需的密钥;留空则会随机生成一个 所有未知的关键字参数都会被忽略。 """ if filething is None: self._raw = BytesIO() self._name = None key: bytes | None = kwargs.get('key', None) if key is not None: self._cipher: NCMRC4Cipher = NCMRC4Cipher(key) else: # 如果没有指定密钥,也没有指定文件,那么随机生成一个长度等于 111 或 113 的密钥 key_left = utils.gen_random_string( randrange(27, 30), strdigits ).encode() key_right = b'E7fT49x7dof9OKCgg9cdvhEuezy3iZCL1nFvBFd1T4uSktAJKmwZXsijPbijliionVUXXg9plTbXEclAE9Lb' self._cipher = NCMRC4Cipher(key_left + key_right) self._tagdata = {} self.coverdata = b'' else: super().__init__(filething, **kwargs) def load(self, filething: utils.FileThing, **kwargs ) -> None: """将一个 NCM 文件加载到当前 NCM 对象中。 Args: filething (file): 源 NCM 文件的路径或文件对象 Keyword Args: skip_tagdata (bool): 加载文件时跳过加载标签信息和封面数据,默认为 ``False`` Raises: FileTypeMismatchError: ``filething`` 不是一个 NCM 格式文件 所有未知的关键字参数都会被忽略。 """ skip_tagdata: bool = kwargs.get('skip_tagdata', False) if utils.is_filepath(filething): fileobj: IO[bytes] = open(filething, 'rb') # type: ignore self._name = fileobj.name else: fileobj: IO[bytes] = filething # type: ignore self._name = None utils.verify_fileobj_readable(fileobj, bytes) utils.verify_fileobj_seekable(fileobj) fileobj.seek(0, 0) file_header = fileobj.read(10) for header in self.file_headers(): if file_header.startswith(header): break else: raise FileTypeMismatchError('not a NCM file: bad file header') # 获取加密的主密钥数据 encrypted_masterkey_len = int.from_bytes(fileobj.read(4), 'little') encrypted_masterkey = bytes(b ^ 0x64 for b in fileobj.read(encrypted_masterkey_len)) masterkey_cipher = StreamedAESWithModeECB(self.core_key()) masterkey = masterkey_cipher.decrypt(encrypted_masterkey)[17:] # 去除密钥开头的 b'neteasecloudmusic' # 获取加密的标签信息 raw_encrypted_tagdata_len = int.from_bytes(fileobj.read(4), 'little') tagdata = {} if skip_tagdata: fileobj.seek(raw_encrypted_tagdata_len, 1) else: raw_encrypted_tagdata = bytes( b ^ 0x63 for b in fileobj.read(raw_encrypted_tagdata_len) ) encrypted_tagdata = b64decode(raw_encrypted_tagdata[22:], validate=True) # 在 b64decode 之前,去除原始数据开头的 b"163 key(Don't modify):" identifier = raw_encrypted_tagdata tagdata_cipher = StreamedAESWithModeECB(self.meta_key()) tagdata.update(json.loads(tagdata_cipher.decrypt(encrypted_tagdata)[6:])) # 在 JSON 反序列化之前,去除字节串开头的 b'music:' tagdata['identifier'] = identifier.decode() fileobj.seek(5, 1) # 获取封面数据 cover_alloc = int.from_bytes(fileobj.read(4), 'little') coverdata = b'' if skip_tagdata: fileobj.seek(cover_alloc, 1) else: cover_size = int.from_bytes(fileobj.read(4), 'little') if cover_size: coverdata = fileobj.read(cover_size) fileobj.seek(cover_alloc - cover_size, 1) # 将以上步骤所得信息,连同加密音频数据设置为属性 self._tagdata = tagdata self.coverdata = coverdata self._cipher: NCMRC4Cipher = NCMRC4Cipher(masterkey) self._raw = BytesIO(fileobj.read()) def save(self, filething: utils.FileThing | None = None, **kwargs ) -> None: """将当前 NCM 对象保存为一个 NCM 格式文件。 Args: filething (file): 目标 NCM 文件的路径或文件对象, 留空则尝试使用 ``self.name``;如果两者都为空, 抛出 ``ValueError`` Keyword Args: tagdata (dict): 向目标文件写入的标签信息;留空则使用 ``self.tagdata`` coverdata (bytes): 向目标文件写入的封面数据;留空则使用 ``self.coverdata`` Raises: ValueError: 同时缺少参数 ``filething`` 和属性 ``self.name`` 所有未知的关键字参数都会被忽略。 """ tagdata: dict | None = kwargs.get('tagdata', None) coverdata: bytes | None = kwargs.get('coverdata', None) if filething: if utils.is_filepath(filething): fileobj: IO[bytes] = open(filething, 'wb') # type: ignore else: fileobj: IO[bytes] = filething # type: ignore utils.verify_fileobj_writable(fileobj, bytes) elif self._name: fileobj: IO[bytes] = open(self._name, 'wb') else: raise ValueError('missing filepath or fileobj') if tagdata is None: tagdata = dp(self._tagdata) else: tagdata = dp(tagdata) if coverdata is None: coverdata = bytes(self.coverdata) fileobj.seek(0, 0) fileobj.write(b'CTENFDAM\x00\x00') # 加密并写入主密钥 masterkey = b'neteasecloudmusic' + self._cipher.key masterkey_cipher = StreamedAESWithModeECB(self.core_key()) encrypted_masterkey = bytes(b ^ 0x64 for b in masterkey_cipher.encrypt(masterkey)) fileobj.write(len(encrypted_masterkey).to_bytes(4, 'little')) fileobj.write(encrypted_masterkey) # 加密并写入标签信息 tagdata.pop('identifier', None) plain_tagdata = b'music:' + json.dumps(tagdata).encode() tagdata_cipher = StreamedAESWithModeECB(self.meta_key()) encrypted_tagdata = tagdata_cipher.encrypt(plain_tagdata) raw_encrypted_tagdata = bytes(b ^ 0x63 for b in b"163 key(Don't modify):" + b64encode(encrypted_tagdata)) fileobj.write(len(raw_encrypted_tagdata).to_bytes(4, 'little')) fileobj.write(raw_encrypted_tagdata) fileobj.seek(5, 1) # 写入封面数据 cover_alloc = len(coverdata) cover_size = cover_alloc fileobj.write(cover_alloc.to_bytes(4, 'little')) fileobj.write(cover_size.to_bytes(4, 'little')) fileobj.write(coverdata) # 写入加密的音频数据 self._raw.seek(0, 0) fileobj.write(self._raw.read()) if utils.is_filepath(filething): fileobj.close() @property
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 33918, 198, 6738, 2779, 2414, 1330, 275, 2414, 12501, 1098, 11, 275, 2414, 268, 8189, 198, 6738, 4866, 1330, 2769, 30073, 355, 288, 79, 198, 6738, 33245, 1330, 2750, 4879, 9399, 198...
1.663578
4,533
from . import base from . import data from . import envs from . import nets from . import prob from . import sche from . import patch from . import utils
[ 6738, 764, 1330, 2779, 198, 6738, 764, 1330, 1366, 198, 6738, 764, 1330, 551, 14259, 198, 6738, 764, 1330, 31720, 198, 6738, 764, 1330, 1861, 198, 6738, 764, 1330, 3897, 198, 6738, 764, 1330, 8529, 198, 6738, 764, 1330, 3384, 4487 ]
3.731707
41
from datetime import timedelta SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:root@127.0.0.1:3306/mine_blog" SQLALCHEMY_TRACK_MODIFICATIONS = True JWT_SECRET_KEY = 'jwt_secret' JWT_AUTH_URL_RULE = '/api/v1/auth' JWT_EXPIRATION_DELTA = timedelta(seconds=12000) SYS_UPLOAD_PATH = '/home/laowang/gitwarehouse/mine_blog/application/static/img/' GITHUB_OAUTH = { 'CLIENT_ID': 'f9fa118d12389497686b', 'CLIENT_SECRET': 'a67149f74ce50c1e95c2d9bdeba7bbd579eb8d45', 'AUTHORIZE_PATH': 'https://github.com/login/oauth/authorize', 'ACCESS_TOKEN_PATH': 'https://github.com/login/oauth/access_token', 'USER_MESSAGE_PATH': 'https://api.github.com/user', } TENCENT_OAUTH = { 'secret_id': '', 'secret_key': '', 'region': '', 'bucket': '' }
[ 6738, 4818, 8079, 1330, 28805, 12514, 198, 198, 17861, 1847, 3398, 3620, 56, 62, 35, 1404, 6242, 11159, 62, 47269, 796, 366, 28744, 13976, 10, 79, 4948, 893, 13976, 1378, 15763, 25, 15763, 31, 16799, 13, 15, 13, 15, 13, 16, 25, 18, ...
2.132022
356
# Generated by Django 3.1.4 on 2020-12-17 12:05 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 19, 319, 12131, 12, 1065, 12, 1558, 1105, 25, 2713, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
# To run this, download the BeautifulSoup zip file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, "html.parser") total = 0 count = 0 # Retrieve all of the span tags tags = soup('span') for tag in tags: # Look at the parts of a tag number = int(tag.contents[0]) total += number count += 1 print("Sum:", total) print("Count:", count)
[ 2, 1675, 1057, 428, 11, 4321, 262, 23762, 50, 10486, 19974, 2393, 201, 198, 2, 2638, 1378, 2503, 13, 9078, 19, 68, 13, 785, 14, 8189, 18, 14, 1443, 19, 13, 13344, 201, 198, 2, 290, 555, 13344, 340, 287, 262, 976, 8619, 355, 428,...
2.656716
268
""" Donate to Createor : { just follow me on github and star to this project } """ # complement this fields
[ 37811, 198, 3987, 378, 284, 13610, 273, 1058, 1391, 655, 1061, 502, 319, 33084, 220, 198, 197, 197, 220, 220, 220, 220, 290, 3491, 284, 428, 1628, 1782, 628, 198, 37811, 628, 198, 2, 16829, 428, 7032, 198, 197, 198, 197, 198, 197 ]
2.906977
43
import discord from discord.ext import commands import asyncpg import datetime from dotenv import load_dotenv import os load_dotenv('.env') INITIAL_EXTENSIONS = [ 'cogs.dev', 'cogs.events', 'cogs.fun', 'cogs.games', 'cogs.help', 'cogs.image', 'cogs.mod', 'cogs.utility' ] bot = PizzaHat() if __name__ == '__main__': bot.run()
[ 11748, 36446, 201, 198, 6738, 36446, 13, 2302, 1330, 9729, 201, 198, 11748, 30351, 6024, 201, 198, 11748, 4818, 8079, 201, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 201, 198, 11748, 28686, 201, 198, 201, 198, 2220, 62, 2651...
2.120219
183
"""The WaveBlocks Project The basic common algorithms for evaluation Hagedorn basis functions of the old kind. @author: R. Bourquin @copyright: Copyright (C) 2016 R. Bourquin @license: Modified BSD License """ from numpy import complexfloating, dot, vstack, zeros, conjugate from scipy import sqrt from scipy.linalg import det, inv from WaveBlocksND.HagedornBasisEvaluationCommon import HagedornBasisEvaluationCommon __all__ = ["HagedornBasisEvaluationPhi"] class HagedornBasisEvaluationPhi(HagedornBasisEvaluationCommon): r""" """ def evaluate_basis_at(self, grid, component, *, prefactor=False): r"""Evaluate the basis functions :math:`\phi_k` recursively at the given nodes :math:`\gamma`. :param grid: The grid :math:`\Gamma` containing the nodes :math:`\gamma`. :type grid: A class having a :py:meth:`get_nodes(...)` method. :param component: The index :math:`i` of a single component :math:`\Phi_i` to evaluate. :param prefactor: Whether to include a factor of :math:`\frac{1}{\sqrt{\det(Q)}}`. :type prefactor: Boolean, default is ``False``. :return: A two-dimensional ndarray :math:`H` of shape :math:`(|\mathfrak{K}_i|, |\Gamma|)` where the entry :math:`H[\mu(k), i]` is the value of :math:`\phi_k(\gamma_i)`. """ D = self._dimension bas = self._basis_shapes[component] bs = self._basis_sizes[component] # The grid grid = self._grid_wrap(grid) nodes = grid.get_nodes() nn = grid.get_number_nodes(overall=True) # Allocate the storage array phi = zeros((bs, nn), dtype=complexfloating) # Precompute some constants Pi = self.get_parameters(component=component) q, p, Q, P, _ = Pi Qinv = inv(Q) Qbar = conjugate(Q) QQ = dot(Qinv, Qbar) # Compute the ground state phi_0 via direct evaluation mu0 = bas[tuple(D * [0])] phi[mu0, :] = self._evaluate_phi0(component, nodes, prefactor=False) # Compute all higher order states phi_k via recursion for d in range(D): # Iterator for all valid index vectors k indices = bas.get_node_iterator(mode="chain", direction=d) for k in indices: # Current index vector ki = vstack(k) # Access predecessors phim = zeros((D, nn), dtype=complexfloating) for j, kpj in bas.get_neighbours(k, selection="backward"): mukpj = bas[kpj] phim[j, :] = phi[mukpj, :] # Compute 3-term recursion p1 = (nodes - q) * phi[bas[k], :] p2 = sqrt(ki) * phim t1 = sqrt(2.0 / self._eps**2) * dot(Qinv[d, :], p1) t2 = dot(QQ[d, :], p2) # Find multi-index where to store the result kped = bas.get_neighbours(k, selection="forward", direction=d) # Did we find this k? if len(kped) > 0: kped = kped[0] # Store computed value phi[bas[kped[1]], :] = (t1 - t2) / sqrt(ki[d] + 1.0) if prefactor is True: phi = phi / self._get_sqrt(component)(det(Q)) return phi def slim_recursion(self, grid, component, *, prefactor=False): r"""Evaluate the Hagedorn wavepacket :math:`\Psi` at the given nodes :math:`\gamma`. This routine is a slim version compared to the full basis evaluation. At every moment we store only the data we really need to compute the next step until we hit the highest order basis functions. :param grid: The grid :math:`\Gamma` containing the nodes :math:`\gamma`. :type grid: A class having a :py:meth:`get_nodes(...)` method. :param component: The index :math:`i` of a single component :math:`\Phi_i` to evaluate. :param prefactor: Whether to include a factor of :math:`\frac{1}{\sqrt{\det(Q)}}`. :type prefactor: Boolean, default is ``False``. :return: A list of arrays or a single array containing the values of the :math:`\Phi_i` at the nodes :math:`\gamma`. Note that this function does not include the global phase :math:`\exp(\frac{i S}{\varepsilon^2})`. """ D = self._dimension # Precompute some constants Pi = self.get_parameters(component=component) q, p, Q, P, _ = Pi Qinv = inv(Q) Qbar = conjugate(Q) QQ = dot(Qinv, Qbar) # The basis shape bas = self._basis_shapes[component] Z = tuple(D * [0]) # Book keeping todo = [] newtodo = [Z] olddelete = [] delete = [] tmp = {} # The grid nodes grid = self._grid_wrap(grid) nn = grid.get_number_nodes(overall=True) nodes = grid.get_nodes() # Evaluate phi0 tmp[Z] = self._evaluate_phi0(component, nodes, prefactor=False) psi = self._coefficients[component][bas[Z], 0] * tmp[Z] # Iterate for higher order states while len(newtodo) != 0: # Delete results that never will be used again for d in olddelete: del tmp[d] # Exchange queues todo = newtodo newtodo = [] olddelete = delete delete = [] # Compute new results for k in todo: # Center stencil at node k ki = vstack(k) # Access predecessors phim = zeros((D, nn), dtype=complexfloating) for j, kpj in bas.get_neighbours(k, selection="backward"): phim[j, :] = tmp[kpj] # Compute the neighbours for d, n in bas.get_neighbours(k, selection="forward"): if n not in tmp.keys(): # Compute 3-term recursion p1 = (nodes - q) * tmp[k] p2 = sqrt(ki) * phim t1 = sqrt(2.0 / self._eps**2) * dot(Qinv[d, :], p1) t2 = dot(QQ[d, :], p2) # Store computed value tmp[n] = (t1 - t2) / sqrt(ki[d] + 1.0) # And update the result psi = psi + self._coefficients[component][bas[n], 0] * tmp[n] newtodo.append(n) delete.append(k) if prefactor is True: psi = psi / self._get_sqrt(component)(det(Q)) return psi
[ 37811, 464, 17084, 45356, 4935, 198, 198, 464, 4096, 2219, 16113, 329, 12660, 367, 1886, 1211, 4308, 5499, 198, 1659, 262, 1468, 1611, 13, 198, 198, 31, 9800, 25, 371, 13, 20576, 21915, 198, 31, 22163, 4766, 25, 15069, 357, 34, 8, 1...
2.014191
3,312
from datetime import datetime from django.db import models from django.conf import settings from django.core.validators import MaxValueValidator, MinValueValidator from django.db.models.signals import post_save from django.dispatch import receiver from serverConfig.models.gestionParams import GestionParam from gestion.models.client import Client from computedfields.models import ComputedFieldsModel, computed
[ 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 201, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 201, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 201, 198, 6738, 42625, 14208, 13, 7295, 13, 12102, 2024, 1330, 5436, 11395, 47139, 13...
3.516393
122
# Simple PyPong in Python 3 import turtle window = turtle.Screen() window.title("PyPong by Grantlee11") window.bgcolor("black") window.setup(width = 800, height = 600) window.tracer(0) # Score scoreA = 0 scoreB = 0 # Paddle A paddleA = turtle.Turtle() paddleA.speed(0) paddleA.shape("square") paddleA.color("white") paddleA.shapesize(stretch_wid = 5, stretch_len = 1) paddleA.penup() paddleA.goto(-350, 0) # Paddle B paddleB = turtle.Turtle() paddleB.speed(0) paddleB.shape("square") paddleB.color("white") paddleB.shapesize(stretch_wid = 5, stretch_len = 1) paddleB.penup() paddleB.goto(350, 0) # Ball ball = turtle.Turtle() ball.speed(0) ball.shape("square") ball.color("white") ball.penup() ball.goto(0, 0) # These numbers are computer specific, if you use this code you may need to change this on your computer as it controls the speed of the ball ball.dx = 0.1 ball.dy = 0.1 # Pen pen = turtle.Turtle() pen.speed(0) pen.color("white") pen.penup() pen.hideturtle() pen.goto(0, 260) pen.write("Player A: 0 Player B: 0", align = "center", font = ("Courier", 24, "normal")) # Functions # Keyboard binding window.listen() window.onkeypress(paddleAUp, "w") window.onkeypress(paddleADown, "s") window.onkeypress(paddleBUp, "Up") window.onkeypress(paddleBDown, "Down") # Main game loop while True: window.update() # Move the ball ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) # Border checking if ball.ycor() > 290: ball.sety(290) ball.dy *= -1 if ball.ycor() < -290: ball.sety(-290) ball.dy *= -1 if ball.xcor() > 390: ball.goto(0, 0) ball.dx *= -1 scoreA += 1 pen.clear() pen.write("Player A: {} Player B: {}".format(scoreA, scoreB), align = "center", font = ("Courier", 24, "normal")) if ball.xcor() < -390: ball.goto(0, 0) ball.dx *= -1 scoreB += 1 pen.clear() pen.write("Player A: {} Player B: {}".format(scoreA, scoreB), align = "center", font = ("Courier", 24, "normal")) # Paddle and ball collisions if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddleB.ycor() + 40 and ball.ycor() > paddleB.ycor() - 40): ball.setx(340) ball.dx *= -1 if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddleA.ycor() + 40 and ball.ycor() > paddleA.ycor() - 40): ball.setx(-340) ball.dx *= -1
[ 2, 17427, 9485, 47, 506, 287, 11361, 513, 198, 198, 11748, 28699, 198, 198, 17497, 796, 28699, 13, 23901, 3419, 198, 17497, 13, 7839, 7203, 20519, 47, 506, 416, 12181, 7197, 1157, 4943, 198, 17497, 13, 35904, 8043, 7203, 13424, 4943, ...
2.262295
1,098
import unittest from wasmtime import *
[ 11748, 555, 715, 395, 198, 198, 6738, 373, 76, 2435, 1330, 1635, 628 ]
3.153846
13
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # Copyright (c) 2015, dNeural.com # # 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. # # Except as contained in this notice, the name of dNeural and or its trademarks # (and among others NullNude) shall not be used in advertising or otherwise to # promote the sale, use or other dealings in this Software without prior # written authorization from dNeural. from nullnude import Nullnude api_key = 'your_api_key' api_secret = 'your_api_secret' images = [ 'https://nullnude.com/wp-content/uploads/2016/01/vintage_porn_1.jpg', 'https://nullnude.com/wp-content/uploads/2016/01/vintage_porn_2.jpg', 'https://nullnude.com/wp-content/uploads/2016/01/vintage_porn_3.jpg', '../bird.jpg' ] # Create the NullNude SDK interface nullnude = Nullnude(api_key, api_secret) # Call the Nullnude servers to check for nudity. You can either pass a public URL or a local path. for image in images: output = nullnude.moderate.image(image) print ('url: %s moderated as: %s' % (output.url, output.moderated_url))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 66, 8, 1853, 11, 288, 8199, 1523, 13, 785, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 1...
3.288431
631
import FWCore.ParameterSet.Config as cms from DQMOffline.Trigger.RazorMonitor_cff import * from DQMOffline.Trigger.VBFSUSYMonitor_cff import * from DQMOffline.Trigger.LepHTMonitor_cff import * from DQMOffline.Trigger.susyHLTEleCaloJets_cff import * from DQMOffline.Trigger.SoftMuHardJetMETSUSYMonitor_cff import * from DQMOffline.Trigger.TopMonitor_cfi import hltTOPmonitoring # muon double_soft_muon_muonpt = hltTOPmonitoring.clone() double_soft_muon_muonpt.FolderName = cms.string('HLT/SUSY/SOS/Muon/') # Selections double_soft_muon_muonpt.nmuons = cms.uint32(2) double_soft_muon_muonpt.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_muonpt.HTcut = cms.double(60) double_soft_muon_muonpt.enableMETPlot = True double_soft_muon_muonpt.metSelection =cms.string('pt>150') double_soft_muon_muonpt.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_muonpt.MHTcut = cms.double(150) double_soft_muon_muonpt.invMassUppercut = cms.double(50) double_soft_muon_muonpt.invMassLowercut = cms.double(10) # Binning double_soft_muon_muonpt.histoPSet.muPtBinning =cms.vdouble(0,2,5,7,10,12,15,17,20,25,30,50) double_soft_muon_muonpt.histoPSet.muPtBinning2D =cms.vdouble(0,2,5,7,10,12,15,17,20,25,30,50) # Triggers double_soft_muon_muonpt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DZ_PFMET50_PFMHT60_v*') double_soft_muon_muonpt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_PFMET140_PFMHT140_v*') # met double_soft_muon_metpt = hltTOPmonitoring.clone() double_soft_muon_metpt.FolderName = cms.string('HLT/SUSY/SOS/MET/') # Selections double_soft_muon_metpt.nmuons = cms.uint32(2) double_soft_muon_metpt.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_metpt.HTcut = cms.double(60) double_soft_muon_metpt.muoSelection =cms.string('pt>18 & abs(eta)<2.4') double_soft_muon_metpt.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_metpt.MHTcut = cms.double(150) double_soft_muon_metpt.invMassUppercut = cms.double(50) double_soft_muon_metpt.invMassLowercut = cms.double(10) double_soft_muon_metpt.enableMETPlot = True # Binning double_soft_muon_metpt.histoPSet.metPSet =cms.PSet(nbins=cms.uint32(50),xmin=cms.double(50),xmax=cms.double(300) ) # Triggers double_soft_muon_metpt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DZ_PFMET50_PFMHT60_v*') double_soft_muon_metpt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_v*') # inv Mass double_soft_muon_mll = hltTOPmonitoring.clone() double_soft_muon_mll.FolderName = cms.string('HLT/SUSY/SOS/Mll/') # Selections double_soft_muon_mll.nmuons = cms.uint32(2) double_soft_muon_mll.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_mll.HTcut = cms.double(60) double_soft_muon_mll.muoSelection =cms.string('pt>10 & abs(eta)<2.4') double_soft_muon_mll.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_mll.MHTcut = cms.double(150) double_soft_muon_mll.enableMETPlot = True double_soft_muon_mll.metSelection = cms.string('pt>150') # Binning double_soft_muon_mll.histoPSet.invMassVariableBinning =cms.vdouble(8,12,15,20,25,30,35,40,45,47,50,60) # Triggers double_soft_muon_mll.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DZ_PFMET50_PFMHT60_v*') double_soft_muon_mll.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Dimuon12_Upsilon_eta1p5_v*') # mht double_soft_muon_mhtpt = hltTOPmonitoring.clone() double_soft_muon_mhtpt.FolderName = cms.string('HLT/SUSY/SOS/MHT/') # Selections double_soft_muon_mhtpt.nmuons = cms.uint32(2) double_soft_muon_mhtpt.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_mhtpt.HTcut = cms.double(60) double_soft_muon_mhtpt.muoSelection =cms.string('pt>18 & abs(eta)<2.0') double_soft_muon_mhtpt.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_mhtpt.enableMETPlot = True double_soft_muon_mhtpt.metSelection = cms.string('pt>150') double_soft_muon_mhtpt.invMassUppercut = cms.double(50) double_soft_muon_mhtpt.invMassLowercut = cms.double(10) # Binning double_soft_muon_mhtpt.histoPSet.MHTVariableBinning =cms.vdouble(50,60,70,80,90,100,110,120,130,150,200,300) # Triggers double_soft_muon_mhtpt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DZ_PFMET50_PFMHT60_v*') double_soft_muon_mhtpt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_v*') # backup1, met double_soft_muon_backup_70_metpt = hltTOPmonitoring.clone() double_soft_muon_backup_70_metpt.FolderName = cms.string('HLT/SUSY/SOS/backup70/MET/') # Selections double_soft_muon_backup_70_metpt.nmuons = cms.uint32(2) double_soft_muon_backup_70_metpt.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_backup_70_metpt.HTcut = cms.double(60) double_soft_muon_backup_70_metpt.muoSelection =cms.string('pt>18 & abs(eta)<2.4') double_soft_muon_backup_70_metpt.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_backup_70_metpt.MHTcut = cms.double(150) double_soft_muon_backup_70_metpt.invMassUppercut = cms.double(50) double_soft_muon_backup_70_metpt.invMassLowercut = cms.double(10) double_soft_muon_backup_70_metpt.enableMETPlot = True # Binning double_soft_muon_backup_70_metpt.histoPSet.metPSet =cms.PSet(nbins=cms.uint32(50),xmin=cms.double(50),xmax=cms.double(300) ) # Triggers double_soft_muon_backup_70_metpt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DZ_PFMET70_PFMHT70_v*') double_soft_muon_backup_70_metpt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_v*') # backup1, mht double_soft_muon_backup_70_mhtpt = hltTOPmonitoring.clone() double_soft_muon_backup_70_mhtpt.FolderName = cms.string('HLT/SUSY/SOS/backup70/MHT/') # Selections double_soft_muon_backup_70_mhtpt.nmuons = cms.uint32(2) double_soft_muon_backup_70_mhtpt.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_backup_70_mhtpt.HTcut = cms.double(60) double_soft_muon_backup_70_mhtpt.muoSelection =cms.string('pt>18 & abs(eta)<2.0') double_soft_muon_backup_70_mhtpt.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_backup_70_mhtpt.enableMETPlot = True double_soft_muon_backup_70_mhtpt.metSelection = cms.string('pt>150') double_soft_muon_backup_70_mhtpt.invMassUppercut = cms.double(50) double_soft_muon_backup_70_mhtpt.invMassLowercut = cms.double(10) # Binning double_soft_muon_backup_70_mhtpt.histoPSet.MHTVariableBinning =cms.vdouble(50,60,70,80,90,100,110,120,130,150,200,300) # Triggers double_soft_muon_backup_70_mhtpt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DZ_PFMET70_PFMHT70_v*') double_soft_muon_backup_70_mhtpt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_v*') # backup2, met double_soft_muon_backup_90_metpt = hltTOPmonitoring.clone() double_soft_muon_backup_90_metpt.FolderName = cms.string('HLT/SUSY/SOS/backup90/MET/') # Selections double_soft_muon_backup_90_metpt.nmuons = cms.uint32(2) double_soft_muon_backup_90_metpt.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_backup_90_metpt.HTcut = cms.double(60) double_soft_muon_backup_90_metpt.muoSelection =cms.string('pt>18 & abs(eta)<2.4') double_soft_muon_backup_90_metpt.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_backup_90_metpt.MHTcut = cms.double(150) double_soft_muon_backup_90_metpt.invMassUppercut = cms.double(50) double_soft_muon_backup_90_metpt.invMassLowercut = cms.double(10) double_soft_muon_backup_90_metpt.enableMETPlot = True # Binning double_soft_muon_backup_90_metpt.histoPSet.metPSet =cms.PSet(nbins=cms.uint32(50),xmin=cms.double(50),xmax=cms.double(300) ) # Triggers double_soft_muon_backup_90_metpt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DZ_PFMET90_PFMHT90_v*') double_soft_muon_backup_90_metpt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_v*') # backup2, mht double_soft_muon_backup_90_mhtpt = hltTOPmonitoring.clone() double_soft_muon_backup_90_mhtpt.FolderName = cms.string('HLT/SUSY/SOS/backup90/MHT/') # Selections double_soft_muon_backup_90_mhtpt.nmuons = cms.uint32(2) double_soft_muon_backup_90_mhtpt.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_backup_90_mhtpt.HTcut = cms.double(60) double_soft_muon_backup_90_mhtpt.muoSelection =cms.string('pt>18 & abs(eta)<2.0') double_soft_muon_backup_90_mhtpt.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_backup_90_mhtpt.enableMETPlot = True double_soft_muon_backup_90_mhtpt.metSelection = cms.string('pt>150') double_soft_muon_backup_90_mhtpt.invMassUppercut = cms.double(50) double_soft_muon_backup_90_mhtpt.invMassLowercut = cms.double(10) # Binning double_soft_muon_backup_90_mhtpt.histoPSet.MHTVariableBinning =cms.vdouble(50,60,70,80,90,100,110,120,130,150,200,300) # Triggers double_soft_muon_backup_90_mhtpt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DZ_PFMET90_PFMHT90_v*') double_soft_muon_backup_90_mhtpt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_v*') # triple muon triple_muon_mupt = hltTOPmonitoring.clone() triple_muon_mupt.FolderName = cms.string('HLT/SUSY/SOS/TripleMu/Muon') # Selections triple_muon_mupt.nmuons = cms.uint32(3) triple_muon_mupt.muoSelection =cms.string('isGlobalMuon()') triple_muon_mupt.invMassUppercut = cms.double(50) triple_muon_mupt.invMassLowercut = cms.double(10) triple_muon_mupt.invMassCutInAllMuPairs=cms.bool(True) # Triggers triple_muon_mupt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_TripleMu_5_3_3_Mass3p8to60_DZ_v*') triple_muon_mupt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Trimuon5_3p5_2_Upsilon_Muon_v*') # triplemu dca triple_muon_dca_mupt = hltTOPmonitoring.clone() triple_muon_dca_mupt.FolderName = cms.string('HLT/SUSY/SOS/TripleMu/DCA/Muon') # Selections triple_muon_dca_mupt.nmuons = cms.uint32(3) triple_muon_dca_mupt.muoSelection =cms.string('isGlobalMuon()') triple_muon_dca_mupt.invMassUppercut = cms.double(50) triple_muon_dca_mupt.invMassLowercut = cms.double(10) triple_muon_dca_mupt.invMassCutInAllMuPairs=cms.bool(True) # Triggers triple_muon_dca_mupt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_TripleMu_5_3_3_Mass3p8to60_DCA_v*') triple_muon_dca_mupt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Trimuon5_3p5_2_Upsilon_Muon_v*') # MuonEG susyMuEGMonitoring = hltTOPmonitoring.clone() susyMuEGMonitoring.FolderName = cms.string('HLT/SUSY/MuonEG/') susyMuEGMonitoring.nmuons = cms.uint32(1) susyMuEGMonitoring.nphotons = cms.uint32(1) susyMuEGMonitoring.nelectrons = cms.uint32(0) susyMuEGMonitoring.njets = cms.uint32(0) susyMuEGMonitoring.enablePhotonPlot = cms.bool(True) susyMuEGMonitoring.muoSelection = cms.string('pt>26 & abs(eta)<2.1 & isPFMuon & isGlobalMuon & isTrackerMuon & numberOfMatches>1 & innerTrack.hitPattern.trackerLayersWithMeasurement>5 & innerTrack.hitPattern.numberOfValidPixelHits>0 & globalTrack.hitPattern.numberOfValidMuonHits>0 & globalTrack.normalizedChi2<10 & (pfIsolationR04.sumChargedHadronPt + max(pfIsolationR04.sumNeutralHadronEt + pfIsolationR04.sumPhotonEt - (pfIsolationR04.sumPUPt)/2.,0.) )/pt<0.15') susyMuEGMonitoring.phoSelection = cms.string('(pt > 30 && abs(eta)<1.4442 && hadTowOverEm<0.0597 && full5x5_sigmaIetaIeta()<0.01031 && chargedHadronIso<1.295 && neutralHadronIso < 5.931+0.0163*pt+0.000014*pt*pt && photonIso < 6.641+0.0034*pt) || (pt > 30 && abs(eta)>1.4442 && hadTowOverEm<0.0481 && full5x5_sigmaIetaIeta()<0.03013 && chargedHadronIso<1.011 && neutralHadronIso < 1.715+0.0163*pt+0.000014*pt*pt && photonIso < 3.863+0.0034*pt)') susyMuEGMonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Mu17_Photon30_IsoCaloId*') susyMuEGMonitoring.denGenericTriggerEventPSet.hltPaths = cms.vstring('') # muon dca double_soft_muon_dca_muonpt = hltTOPmonitoring.clone() double_soft_muon_dca_muonpt.FolderName = cms.string('HLT/SUSY/SOS/DCA/Muon/') # Selections double_soft_muon_dca_muonpt.nmuons = cms.uint32(2) double_soft_muon_dca_muonpt.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_dca_muonpt.HTcut = cms.double(60) double_soft_muon_dca_muonpt.enableMETPlot = True double_soft_muon_dca_muonpt.metSelection =cms.string('pt>150') double_soft_muon_dca_muonpt.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_dca_muonpt.MHTcut = cms.double(150) double_soft_muon_dca_muonpt.invMassUppercut = cms.double(50) double_soft_muon_dca_muonpt.invMassLowercut = cms.double(10) # Binning double_soft_muon_dca_muonpt.histoPSet.muPtBinning =cms.vdouble(0,2,5,7,10,12,15,17,20,25,30,50) double_soft_muon_dca_muonpt.histoPSet.muPtBinning2D =cms.vdouble(0,2,5,7,10,12,15,17,20,25,30,50) # Triggers double_soft_muon_dca_muonpt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DCA_PFMET50_PFMHT60_v*') double_soft_muon_dca_muonpt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_PFMET140_PFMHT140_v*') # met double_soft_muon_dca_metpt = hltTOPmonitoring.clone() double_soft_muon_dca_metpt.FolderName = cms.string('HLT/SUSY/SOS/DCA/MET/') # Selections double_soft_muon_dca_metpt.nmuons = cms.uint32(2) double_soft_muon_dca_metpt.HTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_dca_metpt.HTcut = cms.double(60) double_soft_muon_dca_metpt.muoSelection =cms.string('pt>18 & abs(eta)<2.4') double_soft_muon_dca_metpt.MHTdefinition = cms.string('pt>30 & abs(eta)<2.4') double_soft_muon_dca_metpt.MHTcut = cms.double(150) double_soft_muon_dca_metpt.invMassUppercut = cms.double(50) double_soft_muon_dca_metpt.invMassLowercut = cms.double(10) double_soft_muon_dca_metpt.enableMETPlot = True # Binning double_soft_muon_dca_metpt.histoPSet.metPSet =cms.PSet(nbins=cms.uint32(50),xmin=cms.double(50),xmax=cms.double(300) ) # Triggers double_soft_muon_dca_metpt.numGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_DoubleMu3_DCA_PFMET50_PFMHT60_v*') double_soft_muon_dca_metpt.denGenericTriggerEventPSet.hltPaths = cms.vstring('HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_v*') susyMonitorHLT = cms.Sequence( susyHLTRazorMonitoring + susyHLTVBFMonitoring + LepHTMonitor + susyHLTEleCaloJets + double_soft_muon_muonpt + double_soft_muon_metpt + double_soft_muon_mhtpt + double_soft_muon_mll + double_soft_muon_backup_70_metpt + double_soft_muon_backup_70_mhtpt + double_soft_muon_backup_90_metpt + double_soft_muon_backup_90_mhtpt + triple_muon_mupt + triple_muon_dca_mupt + susyMuEGMonitoring + double_soft_muon_dca_muonpt + double_soft_muon_dca_metpt + susyHLTSoftMuHardJetMETMonitoring ) susHLTDQMSourceExtra = cms.Sequence( )
[ 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 198, 6738, 360, 48, 44, 28657, 13, 48344, 13, 49, 17725, 35479, 62, 66, 487, 1330, 1635, 198, 6738, 360, 48, 44, 28657, 13, 48344, 13, 44526, 10652, 2937, 56, 3547...
2.073204
7,363
from flask import Flask, redirect, url_for, request, render_template, make_response, session, send_from_directory, send_file import uuid import datetime import io import grpc import prototype_pb2_grpc import prototype_pb2 import base64 import json from prometheus_client import Counter, start_http_server import os app = Flask(__name__) app.config["DEBUG"] = False REQUESTS = Counter('http_requests_total', 'Total number of requests to this API.') PICTURES_CONN_STRING = os.environ['PICTURES'] SPECS_CONN_STRING = os.environ['SPECS'] CART_CONN_STRING = os.environ['CART'] CHECKOUT_CONN_STRING = os.environ['CHECKOUT'] @app.route('/') @app.route('/addproduct', methods = ['POST']) @app.route('/addtocart',methods = ['POST']) @app.route('/listcart',methods = ['GET']) @app.route('/checkoutcart',methods = ['GET']) @app.route('/listcheckouts', methods = ['GET']) @app.route('/addproduct',methods = ['GET']) @app.route('/listproducts', methods = ['GET']) @app.route('/checkout', methods = ['GET']) @app.route('/logout/') @app.route('/images/<productid>') if __name__ == '__main__': print(PICTURES_CONN_STRING) print(SPECS_CONN_STRING) print(CART_CONN_STRING) print(CHECKOUT_CONN_STRING) start_http_server(8000) app.run('0.0.0.0', port=80)
[ 6738, 42903, 1330, 46947, 11, 18941, 11, 19016, 62, 1640, 11, 2581, 11, 8543, 62, 28243, 11, 787, 62, 26209, 11, 6246, 11, 3758, 62, 6738, 62, 34945, 11, 3758, 62, 7753, 198, 11748, 334, 27112, 198, 11748, 4818, 8079, 198, 11748, 33...
2.597959
490
import asyncio import json import os from threading import Timer name = "Help" description = """ Module for displaying help modules: prints all modules help *module*: prints help for a Module """ metadata = {} functions = { "modules": Modules, "help": Help }
[ 11748, 30351, 952, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 4704, 278, 1330, 5045, 263, 198, 198, 3672, 796, 366, 22087, 1, 198, 11213, 796, 37227, 198, 26796, 329, 19407, 1037, 198, 198, 18170, 25, 20842, 477, 13103, 198, 16794...
3.235294
85
#!/usr/bin/env python # -*- coding: utf-8
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 628 ]
2.15
20
from absgridworld import AbsGridworld class WindyGridworld(AbsGridworld): """Class representing a windy girdworld""" def __init__(self, schema: list, actions: list, stepPenalty: float, columnToWindMap: dict) -> None: """ Description ---------- Constructor used for processing the schema into the internal gridworld representation that all concrete gridworld implementations would use. Parameters ---------- schema : list The schema used actions : list A list of all possible actions that can be taken stepPenalty : float The penalty for taking an action columnToWindMap : dict Maps the column to the wind value to be experienced """ super().__init__(schema, actions) self.stepPenalty = stepPenalty self.columnToWindMap = columnToWindMap """OVERLOADED METHODS"""
[ 6738, 2352, 25928, 6894, 1330, 13051, 41339, 6894, 628, 198, 4871, 3086, 88, 41339, 6894, 7, 24849, 41339, 6894, 2599, 198, 220, 220, 220, 37227, 9487, 10200, 257, 2344, 88, 308, 1447, 6894, 37811, 628, 220, 220, 220, 825, 11593, 15003,...
2.661064
357
from django.db import models # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 13610, 534, 4981, 994, 13 ]
3.733333
15
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- 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. """ from __future__ import absolute_import import pytest from datahub.access.tests import db_helper @pytest.fixture(scope="session") def django_db_setup(): """Avoid creating/setting up the test database""" pass @pytest.fixture @pytest.fixture @pytest.fixture @pytest.fixture @pytest.fixture @pytest.fixture @pytest.fixture
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 24893, 1087, 318, 10607, 284, 1104, 262, 1280, 2723, 2055, 416, 1642, 347, 42, 12, 33, 11159, 5525, 241, 251, 165, 110, 116, 161, 253, 118, 163, 94, 222, ...
3.337864
515
# -*- coding: utf-8 -*- """ Created on Thu Nov 11 17:47:46 2021 @author: vlad-eusebiu.baciu@vub.be """ import pyqtgraph as pg import sys import logo_qrc import ctypes from PyQt5 import QtWidgets, uic from pyqtgraph import PlotWidget from application1 import App1_Gui from application2 import App2_Gui if __name__ == '__main__': main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 5267, 1367, 1596, 25, 2857, 25, 3510, 33448, 198, 198, 31, 9800, 25, 410, 9435, 12, 68, 1904, 8482, 84, 13, 65, 330, 16115, 31, 85, 54...
2.559701
134
from random import randint,uniform from math import ceil from my_or_tools import newSolver, ObjVal, SolVal
[ 198, 6738, 4738, 1330, 43720, 600, 11, 403, 6933, 198, 6738, 10688, 1330, 2906, 346, 198, 198, 6738, 616, 62, 273, 62, 31391, 1330, 649, 50, 14375, 11, 38764, 7762, 11, 4294, 7762, 198 ]
3.205882
34
# coding: utf8 # Author: Wing Yung Chan (~wy) # Date: 2017 #non-abundant sums # N is non-abundant if the sum of its proper divisors is <= N # prop(N) = Set{1 <= i < N | N % i == 0} print(problem23())
[ 2, 19617, 25, 3384, 69, 23, 198, 2, 6434, 25, 13405, 575, 2150, 18704, 31034, 21768, 8, 198, 2, 7536, 25, 2177, 198, 198, 2, 13159, 12, 397, 917, 415, 21784, 198, 198, 2, 399, 318, 1729, 12, 397, 917, 415, 611, 262, 2160, 286, ...
2.481928
83
# start_scheduler_marker_0 import csv from datetime import datetime import requests from dagster import get_dagster_logger, job, op, repository, schedule @op @job # end_scheduler_marker_0 # start_scheduler_marker_1 @schedule( cron_schedule="45 6 * * *", job=hello_cereal_job, execution_timezone="US/Central", ) # end_scheduler_marker_1 # start_scheduler_marker_2 @repository # end_scheduler_marker_2 # start_scheduler_marker_3 # end_scheduler_marker_3 # start_scheduler_marker_4 @schedule( cron_schedule="45 6 * * *", job=hello_cereal_job, execution_timezone="US/Central", should_execute=weekday_filter, ) # end_scheduler_marker_4
[ 2, 923, 62, 1416, 704, 18173, 62, 4102, 263, 62, 15, 198, 11748, 269, 21370, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 7007, 198, 6738, 48924, 1706, 1330, 651, 62, 67, 363, 1706, 62, 6404, 1362, 11, 1693, 11, 1034, ...
2.346021
289
import pickle import re import copy import numpy as np import pandas as pd from torch import nn import torch from counterfit.core.targets import Target class MovieReviewsSentimentLSTM(nn.Module): """pre-trained LSTM model on 25 epochs for building sentiment analysis model on IMDB movies review dataset. """ def forward(self, x, hidden): """Forward process of LSTM model Args: x ([tensor]): training data/batch_first Returns: Last sigmoid output and hidden state """ batch_size = x.size(0) # embeddings and lstm_out # shape: Batch x Sequence x Feature since batch_first = True embeds = self.embedding(x) lstm_out, hidden = self.lstm(embeds, hidden) lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim) # dropout and fully connected layer out = self.dropout(lstm_out) out = self.fc(out) # sigmoid function sig_out = self.sig(out) # reshape to be batch_size first sig_out = sig_out.view(batch_size, -1) sig_out = sig_out[:, -1] # get last batch of labels return sig_out, hidden class MovieReviewsTarget(Target): """Defining movie reviews target which is responsible for predicting the scores for a given input and convert scores to labels. """ target_data_type = "text" target_name = "movie_reviews" target_endpoint = f"movie_reviews_sentiment_analysis.pt" target_input_shape = (1,) target_output_classes = [0, 1] target_classifier = "blackbox" sample_input_path = f"movie-reviews-scores-full.csv" vocab_file = f"movie-reviews-vocab.pkl" X = [] def load(self): """[summary] """ self.data = pd.read_csv(self.fullpath(self.sample_input_path)) print(f"\n[+] Total Movie Reviews: {len(self.data)}\n") self._load_x() self.vocab = self._load_vocab() self.model = self._load_model() def _load_x(self): """[summary] """ # Append input reviews to X list for idx in range(len(self.data)): self.X.append(self.data['review'][idx]) def _load_vocab(self): """[summary] Returns: [type]: [description] """ # Load vocabulary file; 1000 most occurence words with open(self.fullpath(self.vocab_file), 'rb') as fp: vocab = pickle.load(fp) return vocab def preprocess_string(self, s): """[summary] Args: s ([type]): [description] Returns: [type]: [description] """ # Remove all non-word characters (everything except numbers and letters) s = re.sub(r"[^\w\s]", '', s) # Replace all runs of whitespaces with no space s = re.sub(r"\s+", '', s) # replace digits with no space s = re.sub(r"\d", '', s) return s def _load_model(self): """[summary] Returns: [type]: [description] """ # Load the LST model that's already trained no_layers = 2 vocab_size = len(self.vocab) + 1 # extra 1 for padding purpose embedding_dim = 64 output_dim = 1 hidden_dim = 256 model = MovieReviewsSentimentLSTM( no_layers, vocab_size, hidden_dim, embedding_dim, output_dim, drop_prob=0.5) model.load_state_dict(copy.deepcopy( torch.load(self.fullpath(self.target_endpoint), 'cpu'))) model.eval() return model def predict(self, x): """This function takes list of input texts. For example., ["how are you?"] Args: x (list): [input_text] Returns: final_prob_scores: [[0.98, 0.02]] 0.98 probability score represents the sentence tone is positive and 0.02 score represents """ final_prob_scores = [] for text in x: word_seq = np.array([self.vocab[self.preprocess_string(word)] for word in text.split() if self.preprocess_string(word) in self.vocab.keys()]) word_seq = np.expand_dims(word_seq, axis=0) pad = torch.from_numpy(self.padding_(word_seq, 500)) inputs = pad.to('cpu') batch_size = 1 h = self.model.init_hidden(batch_size) h = tuple([each.data for each in h]) output, h = self.model(inputs, h) probability = output.item() final_prob_scores.append([probability, 1.0-probability]) return final_prob_scores # this must produce a list of class probabilities
[ 11748, 2298, 293, 198, 11748, 302, 198, 11748, 4866, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 28034, 1330, 299, 77, 198, 11748, 28034, 198, 198, 6738, 3753, 11147, 13, 7295, 13, 83, 853...
2.196328
2,124