content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" Copyright (c) 2016-2019 Keith Sterling http://www.keithsterling.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. """ from programy.utils.logging.ylogger import YLogger from programy.storage.factory import StorageFactory from programy.config.brain.braintree import BrainBraintreeConfiguration
[ 37811, 198, 15269, 357, 66, 8, 1584, 12, 23344, 14926, 23647, 2638, 1378, 2503, 13, 365, 342, 1706, 1359, 13, 785, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 3788, 29...
3.959627
322
# -*- coding: utf-8 -*- # # This file is part of REANA. # Copyright (C) 2018 CERN. # # REANA is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """REANA-Commons module to manage AMQP connections on REANA.""" import json import logging from kombu import Connection, Exchange, Queue from .config import ( MQ_CONNECTION_STRING, MQ_DEFAULT_EXCHANGE, MQ_DEFAULT_FORMAT, MQ_DEFAULT_QUEUES, MQ_PRODUCER_MAX_RETRIES, )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 4526, 31574, 13, 198, 2, 15069, 357, 34, 8, 2864, 327, 28778, 13, 198, 2, 198, 2, 4526, 31574, 318, 1479, 3788, 26, 345, 460, ...
2.642857
196
from sqlalchemy import ( BigInteger, Column, DateTime, Text, String, Integer, ) from sqlalchemy.sql.functions import current_timestamp from model.base import BaseObject
[ 6738, 44161, 282, 26599, 1330, 357, 198, 220, 220, 220, 4403, 46541, 11, 198, 220, 220, 220, 29201, 11, 198, 220, 220, 220, 7536, 7575, 11, 198, 220, 220, 220, 8255, 11, 198, 220, 220, 220, 10903, 11, 198, 220, 220, 220, 34142, 11...
2.722222
72
from drae import search
[ 6738, 28841, 68, 1330, 2989, 198 ]
4
6
"""The tests for the Template select platform.""" import pytest from homeassistant import setup from homeassistant.components.input_select import ( ATTR_OPTION as INPUT_SELECT_ATTR_OPTION, ATTR_OPTIONS as INPUT_SELECT_ATTR_OPTIONS, DOMAIN as INPUT_SELECT_DOMAIN, SERVICE_SELECT_OPTION as INPUT_SELECT_SERVICE_SELECT_OPTION, SERVICE_SET_OPTIONS, ) from homeassistant.components.select.const import ( ATTR_OPTION as SELECT_ATTR_OPTION, ATTR_OPTIONS as SELECT_ATTR_OPTIONS, DOMAIN as SELECT_DOMAIN, SERVICE_SELECT_OPTION as SELECT_SERVICE_SELECT_OPTION, ) from homeassistant.const import ATTR_ICON, CONF_ENTITY_ID, STATE_UNKNOWN from homeassistant.core import Context from homeassistant.helpers.entity_registry import async_get from tests.common import ( assert_setup_component, async_capture_events, async_mock_service, ) _TEST_SELECT = "select.template_select" # Represent for select's current_option _OPTION_INPUT_SELECT = "input_select.option" async def test_missing_optional_config(hass, calls): """Test: missing optional template is ok.""" with assert_setup_component(1, "template"): assert await setup.async_setup_component( hass, "template", { "template": { "select": { "state": "{{ 'a' }}", "select_option": {"service": "script.select_option"}, "options": "{{ ['a', 'b'] }}", } } }, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() _verify(hass, "a", ["a", "b"]) def _verify(hass, expected_current_option, expected_options, entity_name=_TEST_SELECT): """Verify select's state.""" state = hass.states.get(entity_name) attributes = state.attributes assert state.state == str(expected_current_option) assert attributes.get(SELECT_ATTR_OPTIONS) == expected_options
[ 37811, 464, 5254, 329, 262, 37350, 2922, 3859, 526, 15931, 198, 11748, 12972, 9288, 198, 198, 6738, 1363, 562, 10167, 1330, 9058, 198, 6738, 1363, 562, 10167, 13, 5589, 3906, 13, 15414, 62, 19738, 1330, 357, 198, 220, 220, 220, 5161, ...
2.353418
863
import os import random import string import base64 from django.utils import timezone from django.contrib.auth.hashers import make_password, check_password from django.test import TestCase from parameterized import parameterized from core.models import Module, EntryPoint, ExternalAuthorizationSession, User AUTHORIZATION_MODULE_LIST = ["ihna", "google", "mailru"]
[ 11748, 28686, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 2779, 2414, 198, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 10134, 7084, 1330, 787, 62, 28712, 11, 2198, 62,...
3.653465
101
from rhombus.lib.utils import get_dbhandler from rhombus.lib.tags import * from cmsfix.models.node import Node import re # the pattern below is either # ///123 # <<MacroName>> # [[MacroName]] pattern = re.compile('///(\d+)|///\{([\w-]+)\}|\&lt\;\&lt\;(.+)\&gt\;\&gt\;|\[\[(.+)\]\]') # syntax for Macro is: # [[MacroName|option1|option2|option3]] def postrender(buffer, node, request): """ return a new buffer """ dbh = get_dbhandler() nb = '' start_pos = 0 for m in pattern.finditer(buffer): nb += buffer[start_pos:m.start()] group = m.group() print(group) if group.startswith('///'): nb += node_link(group, dbh) elif group.startswith('[['): nb += run_macro(group, node, dbh, request) else: nb += '{{ ERR: macro pattern unprocessed }}' start_pos = m.end() nb += buffer[start_pos:] return nb def postedit(content, node): """ post edit the content, return a new modified content """ dbh = get_dbhandler() nc = '' start_pos = 0 for m in pattern.finditer(content): nc += content[start_pos:m.start()] group = m.group() if group.startswith('///'): if group[3] != '{': # convert to UUID node = dbh.get_node_by_id(int(group[3:])) nc += ('///{' + str(node.uuid) + '}' if node else group) else: nc += group else: nc += group start_pos = m.end() nc += content[start_pos:] return nc _MACROS_ = {} ## -- MACRO -- ## ## all macro functions should return either html or literal objects ##
[ 198, 6738, 9529, 2381, 385, 13, 8019, 13, 26791, 1330, 651, 62, 9945, 30281, 198, 6738, 9529, 2381, 385, 13, 8019, 13, 31499, 1330, 1635, 198, 6738, 269, 907, 13049, 13, 27530, 13, 17440, 1330, 19081, 198, 11748, 302, 198, 198, 2, 2...
2.12798
797
''' #;+ #; NAME: #; sdss.qso #; Version 1.1 #; #; PURPOSE: #; Class for SDSS QSO #; 2015 Written by JXP #;- #;------------------------------------------------------------------------------ ''' # Import libraries import numpy as np import os from astropy.table import QTable, Column from astropy.coordinates import SkyCoord from astropy import units as u from astropy.units import Quantity from xastropy.obs import radec as xor from xastropy.xutils import xdebug as xdb
[ 7061, 6, 198, 2, 26, 10, 220, 198, 2, 26, 36751, 25, 198, 2, 26, 45647, 824, 13, 80, 568, 198, 2, 26, 220, 220, 220, 10628, 352, 13, 16, 198, 2, 26, 198, 2, 26, 33079, 48933, 25, 198, 2, 26, 220, 220, 5016, 329, 311, 5258,...
3.050633
158
name = "module" from .module import func
[ 3672, 796, 366, 21412, 1, 198, 6738, 764, 21412, 1330, 25439, 198 ]
3.416667
12
import unittest import numpy as np from openmdao.utils.assert_utils import assert_near_equal from wisdem.optimization_drivers.dakota_driver import DakotaOptimizer try: import dakota except ImportError: dakota = None if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 201, 198, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 6738, 1280, 9132, 5488, 13, 26791, 13, 30493, 62, 26791, 1330, 6818, 62, 40093, 62, 40496, 201, 198, 6738, 266, 9409, 368, 13, 40085, 1634, ...
2.504274
117
#-*- coding: utf-8 -*- #! /usr/bin/env python ''' #------------------------------------------------------------ filename: lab4_runTFCurveFitting.py This is an example for linear regression in tensorflow Which is a curve fitting example written by Jaewook Kang @ Aug 2017 #------------------------------------------------------------ ''' from os import getcwd import math from IPython import display from matplotlib import cm from matplotlib import gridspec import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import metrics import tensorflow as tf from tensorflow.contrib.learn.python.learn import learn_io # from __future__ import print_function # Preparing data set ================================================ from tensorflow.examples.tutorials.mnist import input_data # generation of sinusoid data set total_size = 5000 training_size = 4000 validation_size = total_size - training_size xsize = 50 # the size of single x_data x_data = np.zeros([xsize, total_size]) cos_x = np.zeros([xsize, total_size]) mag = 1.0 phase_rad = np.pi/4 rad_freq = np.pi / 2.0 for i in range(total_size): x_data[:,i] = np.linspace(-4,4,xsize) cos_x = np.cos(rad_freq*x_data + phase_rad) noise_var = 0.01 noise = np.sqrt(noise_var) * np.random.randn(xsize,total_size) y_clean = cos_x y_data = y_clean + noise x_training_data = x_data[:,0:training_size] y_training_data = y_data[:,0:training_size] x_validation_data = x_data[:,training_size:-1] y_validation_data = y_data[:,training_size:-1] # signal plot # hfig1= plt.figure(1,figsize=[10,10]) # plt.plot(cos_x[:,1],color='b',label='clean') # plt.plot(y_data[:,1],color='r',label='noisy') # plt.legend() # configure training parameters ===================================== learning_rate = 0.01 training_epochs = 20 batch_size = 100 display_step = 1 # computational TF graph construction ================================ ##---------------- Define graph nodes ------------------- # tf Graph data input holder # (x,y) : input / output of prediction model # which will be feeded by training data in the TF graph computation # (a,b,c,d) : model parameters # which will be learned from training data in the TF graph computation x = tf.placeholder(tf.float32, [xsize,None]) y = tf.placeholder(tf.float32, [xsize,None]) # Set model weights which is calculated in the TF graph a = tf.Variable(1.) # initialization by 1 b = tf.Variable(1.) c = tf.Variable(1.) d = tf.Variable(1.) print ('TF graph nodes are defined') ##--------------------- Define function ----------------- # define relationshitp btw instance data x and label data y # define optimizer used in the learning phase # define cost function for optimization # Construct model pred_y = c*tf.cos(a*x+b)+d # Minimize error using MSE function cost = tf.reduce_mean(tf.reduce_sum( tf.square(y - pred_y) , reduction_indices=1), name="mse") # Gradient Descent # optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) print ('Functions in TF graph are ready') ## Performance evaluation model ========================_y=========== # y : data output # pred_y: prediction output by model, a x^3 + b x^2 + c x + d correct_prediction = cost # Calculate error rate using data -------------- # where # tf_reduce_mean(input_tensor, axis) : reduce dimension of tensor by computing the mean of elements # # 'x' is [[1., 1.] # [2., 2.]] # tf.reduce_mean(x) ==> 1.5 # tf.reduce_mean(x, 0) ==> [1.5, 1.5] # tf.reduce_mean(x, 1) ==> [1., 2.] accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) error_rate_training = np.zeros(training_epochs) error_rate_validation = np.zeros(training_epochs) # Launch the graph (execution) ======================================== # Initializing the variables init = tf.global_variables_initializer() ## -------------------- Learning iteration start -------------------- with tf.Session() as sess: sess.run(init) # this for variable use # Training cycle for epoch in range(training_epochs): # iteration loop avg_cost = 0. total_batch = int(training_size/batch_size) # # Loop over all batches for i in range(total_batch): # batch loop data_start_index = i * batch_size data_end_index = (i + 1) * batch_size # feed traing data -------------------------- batch_xs = x_training_data[:,data_start_index:data_end_index] batch_ys = y_training_data[:,data_start_index:data_end_index] #---------------------------------------------- # Run optimization op (backprop) and cost op (to get loss value) # feedign training data _, local_batch_cost = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys}) # Compute average loss avg_cost += local_batch_cost / total_batch # print ("At %d-th batch in %d-epoch, avg_cost = %f" % (i,epoch,avg_cost) ) # Display logs per epoch step if (epoch+1) % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost/batch_size)) batch_xs = x_training_data batch_ys = y_training_data error_rate_training[epoch] = accuracy.eval({x: batch_xs, y: batch_ys},session=sess)/training_size error_rate_validation[epoch] = accuracy.eval({x: x_validation_data, y: y_validation_data},session=sess)/validation_size print("Training set MSE:", error_rate_training[epoch]) print("Validation set MSE:", error_rate_validation[epoch]) print("--------------------------------------------") print("Optimization Finished!") pred_a = sess.run(a) pred_b = sess.run(b) pred_c = sess.run(c) pred_d = sess.run(d) hfig1 = plt.figure(1,figsize=(10,10)) epoch_index = np.array([elem for elem in range(training_epochs)]) plt.plot(epoch_index,error_rate_training,label='Training data',color='r',marker='o') plt.plot(epoch_index,error_rate_validation,label='Validation data',color='b',marker='x') plt.legend() plt.title('MSE of prediction:') plt.xlabel('Iteration epoch') plt.ylabel('MSE') hfig2 = plt.figure(2,figsize=(10,10)) pred_y = pred_c * np.cos(pred_a * x_data[:,0] + pred_b) +pred_d plt.plot(x_validation_data[:,0],y_validation_data[:,0],label='noisy data',color='b',marker='*') plt.plot(x_validation_data[:,0], pred_y,label='prediction',color='r') plt.legend() plt.title('A line fitting example:') plt.xlabel('X data') plt.ylabel('Y data') # FIG_SAVE_DIR = getcwd() + '/figs/' # hfig1.savefig(FIG_SAVE_DIR + 'runExample_TFLogisticReg_aymeric_ErrRate.png') # hfig1.clear()
[ 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 7061, 6, 198, 2, 47232, 10541, 198, 220, 29472, 25, 2248, 19, 62, 5143, 51, 4851, 333, 303, 37, 2535, 13, 9078, ...
2.618738
2,615
# coding=utf-8 from app.route.stats.processor import * from app.api.base.base_router import BaseRouter from app.api.base import base_name as names
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 598, 13, 38629, 13, 34242, 13, 41341, 1330, 1635, 198, 6738, 598, 13, 15042, 13, 8692, 13, 8692, 62, 472, 353, 1330, 7308, 49, 39605, 198, 6738, 598, 13, 15042, 13, 8692, 1330, 2779, 62, 367...
3.148936
47
from Bio import TogoWS import argparse import sys import os if __name__ == '__main__': ## description - Text to display before the argument help (default: none) parser=argparse.ArgumentParser(description='mbmeth') parser.add_argument("-i", '--input', help="Input list") parser.add_argument("-s", '--species', help="species") options = parser.parse_args(args=None if sys.argv[1:] else ['--help']) summary(options)
[ 6738, 16024, 1330, 309, 24076, 19416, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 22492, 6764, 532, 8255, 284, 3359, 878, 262, 45...
2.97973
148
# coding=utf8
[ 2, 19617, 28, 40477, 23, 628 ]
2.5
6
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### # pylint: disable=invalid-name """Various utils that should be used during migrations and migrations tests because the AiiDA ORM cannot be used.""" import datetime import errno import os import re import numpy from aiida.common import json ISOFORMAT_DATETIME_REGEX = re.compile(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+(\+\d{2}:\d{2})?$') def ensure_repository_folder_created(uuid): """Make sure that the repository sub folder for the node with the given UUID exists or create it. :param uuid: UUID of the node """ dirpath = get_node_repository_sub_folder(uuid) try: os.makedirs(dirpath) except OSError as exception: if exception.errno != errno.EEXIST: raise def put_object_from_string(uuid, name, content): """Write a file with the given content in the repository sub folder of the given node. :param uuid: UUID of the node :param name: name to use for the file :param content: the content to write to the file """ ensure_repository_folder_created(uuid) filepath = os.path.join(get_node_repository_sub_folder(uuid), name) with open(filepath, 'w', encoding='utf-8') as handle: handle.write(content) def get_object_from_repository(uuid, name): """Return the content of a file with the given name in the repository sub folder of the given node. :param uuid: UUID of the node :param name: name to use for the file """ filepath = os.path.join(get_node_repository_sub_folder(uuid), name) with open(filepath) as handle: return handle.read() def get_node_repository_sub_folder(uuid): """Return the absolute path to the sub folder `path` within the repository of the node with the given UUID. :param uuid: UUID of the node :return: absolute path to node repository folder, i.e `/some/path/repository/node/12/ab/c123134-a123/path` """ from aiida.manage.configuration import get_profile uuid = str(uuid) repo_dirpath = os.path.join(get_profile().repository_path, 'repository') node_dirpath = os.path.join(repo_dirpath, 'node', uuid[:2], uuid[2:4], uuid[4:], 'path') return node_dirpath def get_numpy_array_absolute_path(uuid, name): """Return the absolute path of a numpy array with the given name in the repository of the node with the given uuid. :param uuid: the UUID of the node :param name: the name of the numpy array :return: the absolute path of the numpy array file """ return os.path.join(get_node_repository_sub_folder(uuid), name + '.npy') def store_numpy_array_in_repository(uuid, name, array): """Store a numpy array in the repository folder of a node. :param uuid: the node UUID :param name: the name under which to store the array :param array: the numpy array to store """ ensure_repository_folder_created(uuid) filepath = get_numpy_array_absolute_path(uuid, name) with open(filepath, 'wb') as handle: numpy.save(handle, array) def delete_numpy_array_from_repository(uuid, name): """Delete the numpy array with a given name from the repository corresponding to a node with a given uuid. :param uuid: the UUID of the node :param name: the name of the numpy array """ filepath = get_numpy_array_absolute_path(uuid, name) try: os.remove(filepath) except (IOError, OSError): pass def load_numpy_array_from_repository(uuid, name): """Load and return a numpy array from the repository folder of a node. :param uuid: the node UUID :param name: the name under which to store the array :return: the numpy array """ filepath = get_numpy_array_absolute_path(uuid, name) return numpy.load(filepath) def recursive_datetime_to_isoformat(value): """Convert all datetime objects in the given value to string representations in ISO format. :param value: a mapping, sequence or single value optionally containing datetime objects """ if isinstance(value, list): return [recursive_datetime_to_isoformat(_) for _ in value] if isinstance(value, dict): return dict((key, recursive_datetime_to_isoformat(val)) for key, val in value.items()) if isinstance(value, datetime.datetime): return value.isoformat() return value def dumps_json(dictionary): """Transforms all datetime object into isoformat and then returns the JSON.""" return json.dumps(recursive_datetime_to_isoformat(dictionary))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 29113, 29113, 7804, 21017, 198, 2, 15069, 357, 66, 828, 383, 317, 4178, 5631, 1074, 13, 1439, 2489, 10395, 13, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.706942
1,887
__all__ = ["transformers", "vision"] from .transformers import * from .vision import *
[ 834, 439, 834, 796, 14631, 35636, 364, 1600, 366, 10178, 8973, 198, 198, 6738, 764, 35636, 364, 1330, 1635, 198, 6738, 764, 10178, 1330, 1635, 198 ]
3.384615
26
# This sample tests the checker's ability to enforce # type invariance for type arguments. # pyright: strict from typing import Dict, Union foo: Dict[Union[int, str], str] = {} bar: Dict[str, str] = {} # This should generate an error because # both type parameters for Dict are invariant, # and str isn't assignable to Union[int, str]. foo = bar
[ 2, 770, 6291, 5254, 262, 2198, 263, 338, 2694, 284, 4605, 198, 2, 2099, 25275, 590, 329, 2099, 7159, 13, 198, 198, 2, 279, 4766, 25, 7646, 198, 198, 6738, 19720, 1330, 360, 713, 11, 4479, 198, 198, 21943, 25, 360, 713, 58, 38176, ...
3.301887
106
how_many_snakes = 1 snake_string = """ Welcome to Python3! ____ / . .\\ \\ ---< \\ / __________/ / -=:___________/ <3, Juno """ print(snake_string * how_many_snakes)
[ 4919, 62, 21834, 62, 16184, 1124, 796, 352, 198, 16184, 539, 62, 8841, 796, 37227, 198, 14618, 284, 11361, 18, 0, 628, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1427, 198, 220, 220, 220, 220, 220, 220, 220, ...
1.821138
123
from flask import Flask from flask import render_template, redirect, session, request app = Flask(__name__) app.secret_key = 'ThisIsSecret' app.run(debug=True)
[ 6738, 42903, 1330, 46947, 198, 6738, 42903, 1330, 8543, 62, 28243, 11, 18941, 11, 6246, 11, 2581, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 198, 1324, 13, 21078, 62, 2539, 796, 705, 1212, 3792, 23725, 6, 198, 198, 1324,...
3.24
50
# -*- coding:utf-8 -*- """ Description: Inventory Class Usage: from neo.Network.Inventory import Inventory """ from neo.IO.MemoryStream import MemoryStream from neocore.IO.BinaryWriter import BinaryWriter
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 37811, 198, 11828, 25, 198, 220, 220, 220, 35772, 5016, 198, 28350, 25, 198, 220, 220, 220, 422, 19102, 13, 26245, 13, 818, 17158, 1330, 35772, 198, 37811, 198, 198, 6738, ...
3.208955
67
""" Copyright (C) 2021 Clariteia SL This file is part of minos framework. Minos framework can not be copied and/or distributed without the express permission of Clariteia SL. """ import unittest from minos.api_gateway.common import ( EmptyMinosModelSequenceException, MinosAttributeValidationException, MinosConfigDefaultAlreadySetException, MinosConfigException, MinosException, MinosMalformedAttributeException, MinosModelAttributeException, MinosModelException, MinosParseAttributeException, MinosRepositoryAggregateNotFoundException, MinosRepositoryDeletedAggregateException, MinosRepositoryException, MinosRepositoryManuallySetAggregateIdException, MinosRepositoryManuallySetAggregateVersionException, MinosRepositoryNonProvidedException, MinosRepositoryUnknownActionException, MinosReqAttributeException, MinosTypeAttributeException, MultiTypeMinosModelSequenceException, ) if __name__ == "__main__": unittest.main()
[ 37811, 198, 15269, 357, 34, 8, 33448, 15420, 578, 544, 12419, 198, 198, 1212, 2393, 318, 636, 286, 949, 418, 9355, 13, 198, 198, 9452, 418, 9355, 460, 407, 307, 18984, 290, 14, 273, 9387, 1231, 262, 4911, 7170, 286, 15420, 578, 544,...
3.213376
314
# coding: utf-8 # quote from kmaiya/HQAutomator # import time import json import requests import webbrowser questions = [] if __name__ == '__main__': main()
[ 2, 19617, 25, 3384, 69, 12, 23, 201, 198, 2, 9577, 422, 10571, 1872, 3972, 14, 41275, 38062, 1352, 201, 198, 2, 220, 201, 198, 201, 198, 11748, 640, 201, 198, 11748, 33918, 201, 198, 11748, 7007, 201, 198, 11748, 3992, 40259, 201, ...
2.329114
79
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: TensorflowModel.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper 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 from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='TensorflowModel.proto', package='ai.eloquent', syntax='proto3', serialized_pb=_b('\n\x15TensorflowModel.proto\x12\x0b\x61i.eloquent\"\x8f\x01\n\x0fTensorflowModel\x12\x18\n\x10serialized_graph\x18\x01 \x01(\x0c\x12.\n\x0ctoken_mapper\x18\x02 \x01(\x0b\x32\x18.ai.eloquent.TokenMapper\x12\x16\n\x0etrain_set_size\x18\x04 \x01(\x03\x12\x1a\n\x12train_set_positive\x18\x05 \x01(\x03\"\x80\x01\n\x0cTokenMapping\x12+\n\x04type\x18\x01 \x01(\x0e\x32\x1d.ai.eloquent.TokenMappingType\x12\r\n\x05regex\x18\x02 \x01(\t\x12\x10\n\x08num_hash\x18\x03 \x01(\x05\x12\x12\n\ndebug_base\x18\x04 \x01(\t\x12\x0e\n\x06tokens\x18\x05 \x03(\t\"\x9d\x01\n\x0bTokenMapper\x12\x30\n\rtoken_mapping\x18\x01 \x03(\x0b\x32\x19.ai.eloquent.TokenMapping\x12.\n\x0bunk_mapping\x18\x02 \x03(\x0b\x32\x19.ai.eloquent.TokenMapping\x12,\n\x07vectors\x18\x03 \x03(\x0b\x32\x1b.ai.eloquent.TunedEmbedding\"\x1f\n\x0eTunedEmbedding\x12\r\n\x05value\x18\x01 \x03(\x02\"\xf0\x03\n\x1aTensorflowModelPerformance\x12\x0f\n\x07\x64\x65v_set\x18\x01 \x03(\t\x12\x0f\n\x07version\x18\x02 \x01(\x03\x12\x17\n\x0f\x64\x65v_set_version\x18\x03 \x01(\x03\x12\x16\n\x0etrain_set_size\x18\x04 \x01(\x03\x12\x1d\n\x15train_set_total_votes\x18\x05 \x01(\x03\x12\x14\n\x0c\x64\x65v_set_size\x18\x06 \x01(\x03\x12\x1b\n\x13\x64\x65v_set_total_votes\x18\x07 \x01(\x03\x12\x12\n\nbest_epoch\x18\x08 \x01(\x05\x12\x0f\n\x07\x64ropout\x18\t \x01(\x02\x12\x13\n\x0brandom_seed\x18\n \x01(\x05\x12\x12\n\nhidden_dim\x18\x0b \x01(\x05\x12\x15\n\rtrue_positive\x18\x0c \x01(\x03\x12\x16\n\x0e\x66\x61lse_positive\x18\r \x01(\x03\x12\x16\n\x0e\x66\x61lse_negative\x18\x0e \x01(\x03\x12\x15\n\rtrue_negative\x18\x0f \x01(\x03\x12\x11\n\tprecision\x18\x10 \x01(\x02\x12\x0e\n\x06recall\x18\x11 \x01(\x02\x12\n\n\x02\x66\x31\x18\x12 \x01(\x02\x12\x10\n\x08\x61\x63\x63uracy\x18\x13 \x01(\x02\x12@\n\x08\x65xamples\x18\x14 \x03(\x0b\x32..ai.eloquent.TensorflowModelPerformanceExample\"S\n!TensorflowModelPerformanceExample\x12\r\n\x05input\x18\x01 \x03(\t\x12\x0f\n\x07guesses\x18\x02 \x03(\x02\x12\x0e\n\x06labels\x18\x03 \x03(\x05*2\n\x10TokenMappingType\x12\t\n\x05REGEX\x10\x00\x12\x08\n\x04HASH\x10\x01\x12\t\n\x05TOKEN\x10\x02\x42)\n\x10\x61i.eloquent.dataB\x15TensorflowModelProtosb\x06proto3') ) _TOKENMAPPINGTYPE = _descriptor.EnumDescriptor( name='TokenMappingType', full_name='ai.eloquent.TokenMappingType', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='REGEX', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='HASH', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='TOKEN', index=2, number=2, options=None, type=None), ], containing_type=None, options=None, serialized_start=1092, serialized_end=1142, ) _sym_db.RegisterEnumDescriptor(_TOKENMAPPINGTYPE) TokenMappingType = enum_type_wrapper.EnumTypeWrapper(_TOKENMAPPINGTYPE) REGEX = 0 HASH = 1 TOKEN = 2 _TENSORFLOWMODEL = _descriptor.Descriptor( name='TensorflowModel', full_name='ai.eloquent.TensorflowModel', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='serialized_graph', full_name='ai.eloquent.TensorflowModel.serialized_graph', 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, options=None), _descriptor.FieldDescriptor( name='token_mapper', full_name='ai.eloquent.TensorflowModel.token_mapper', 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, options=None), _descriptor.FieldDescriptor( name='train_set_size', full_name='ai.eloquent.TensorflowModel.train_set_size', index=2, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='train_set_positive', full_name='ai.eloquent.TensorflowModel.train_set_positive', index=3, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=39, serialized_end=182, ) _TOKENMAPPING = _descriptor.Descriptor( name='TokenMapping', full_name='ai.eloquent.TokenMapping', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='type', full_name='ai.eloquent.TokenMapping.type', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='regex', full_name='ai.eloquent.TokenMapping.regex', 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, options=None), _descriptor.FieldDescriptor( name='num_hash', full_name='ai.eloquent.TokenMapping.num_hash', index=2, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='debug_base', full_name='ai.eloquent.TokenMapping.debug_base', index=3, number=4, 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, options=None), _descriptor.FieldDescriptor( name='tokens', full_name='ai.eloquent.TokenMapping.tokens', index=4, number=5, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=185, serialized_end=313, ) _TOKENMAPPER = _descriptor.Descriptor( name='TokenMapper', full_name='ai.eloquent.TokenMapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='token_mapping', full_name='ai.eloquent.TokenMapper.token_mapping', 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, options=None), _descriptor.FieldDescriptor( name='unk_mapping', full_name='ai.eloquent.TokenMapper.unk_mapping', 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, options=None), _descriptor.FieldDescriptor( name='vectors', full_name='ai.eloquent.TokenMapper.vectors', 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, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=316, serialized_end=473, ) _TUNEDEMBEDDING = _descriptor.Descriptor( name='TunedEmbedding', full_name='ai.eloquent.TunedEmbedding', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='value', full_name='ai.eloquent.TunedEmbedding.value', index=0, number=1, type=2, cpp_type=6, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=475, serialized_end=506, ) _TENSORFLOWMODELPERFORMANCE = _descriptor.Descriptor( name='TensorflowModelPerformance', full_name='ai.eloquent.TensorflowModelPerformance', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='dev_set', full_name='ai.eloquent.TensorflowModelPerformance.dev_set', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='version', full_name='ai.eloquent.TensorflowModelPerformance.version', index=1, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='dev_set_version', full_name='ai.eloquent.TensorflowModelPerformance.dev_set_version', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='train_set_size', full_name='ai.eloquent.TensorflowModelPerformance.train_set_size', index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='train_set_total_votes', full_name='ai.eloquent.TensorflowModelPerformance.train_set_total_votes', index=4, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='dev_set_size', full_name='ai.eloquent.TensorflowModelPerformance.dev_set_size', index=5, number=6, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='dev_set_total_votes', full_name='ai.eloquent.TensorflowModelPerformance.dev_set_total_votes', index=6, number=7, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='best_epoch', full_name='ai.eloquent.TensorflowModelPerformance.best_epoch', index=7, number=8, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='dropout', full_name='ai.eloquent.TensorflowModelPerformance.dropout', index=8, number=9, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='random_seed', full_name='ai.eloquent.TensorflowModelPerformance.random_seed', index=9, number=10, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='hidden_dim', full_name='ai.eloquent.TensorflowModelPerformance.hidden_dim', index=10, number=11, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='true_positive', full_name='ai.eloquent.TensorflowModelPerformance.true_positive', index=11, number=12, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='false_positive', full_name='ai.eloquent.TensorflowModelPerformance.false_positive', index=12, number=13, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='false_negative', full_name='ai.eloquent.TensorflowModelPerformance.false_negative', index=13, number=14, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='true_negative', full_name='ai.eloquent.TensorflowModelPerformance.true_negative', index=14, number=15, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='precision', full_name='ai.eloquent.TensorflowModelPerformance.precision', index=15, number=16, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='recall', full_name='ai.eloquent.TensorflowModelPerformance.recall', index=16, number=17, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='f1', full_name='ai.eloquent.TensorflowModelPerformance.f1', index=17, number=18, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='accuracy', full_name='ai.eloquent.TensorflowModelPerformance.accuracy', index=18, number=19, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='examples', full_name='ai.eloquent.TensorflowModelPerformance.examples', index=19, number=20, 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, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=509, serialized_end=1005, ) _TENSORFLOWMODELPERFORMANCEEXAMPLE = _descriptor.Descriptor( name='TensorflowModelPerformanceExample', full_name='ai.eloquent.TensorflowModelPerformanceExample', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='input', full_name='ai.eloquent.TensorflowModelPerformanceExample.input', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='guesses', full_name='ai.eloquent.TensorflowModelPerformanceExample.guesses', index=1, number=2, type=2, cpp_type=6, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='labels', full_name='ai.eloquent.TensorflowModelPerformanceExample.labels', index=2, number=3, type=5, cpp_type=1, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1007, serialized_end=1090, ) _TENSORFLOWMODEL.fields_by_name['token_mapper'].message_type = _TOKENMAPPER _TOKENMAPPING.fields_by_name['type'].enum_type = _TOKENMAPPINGTYPE _TOKENMAPPER.fields_by_name['token_mapping'].message_type = _TOKENMAPPING _TOKENMAPPER.fields_by_name['unk_mapping'].message_type = _TOKENMAPPING _TOKENMAPPER.fields_by_name['vectors'].message_type = _TUNEDEMBEDDING _TENSORFLOWMODELPERFORMANCE.fields_by_name['examples'].message_type = _TENSORFLOWMODELPERFORMANCEEXAMPLE DESCRIPTOR.message_types_by_name['TensorflowModel'] = _TENSORFLOWMODEL DESCRIPTOR.message_types_by_name['TokenMapping'] = _TOKENMAPPING DESCRIPTOR.message_types_by_name['TokenMapper'] = _TOKENMAPPER DESCRIPTOR.message_types_by_name['TunedEmbedding'] = _TUNEDEMBEDDING DESCRIPTOR.message_types_by_name['TensorflowModelPerformance'] = _TENSORFLOWMODELPERFORMANCE DESCRIPTOR.message_types_by_name['TensorflowModelPerformanceExample'] = _TENSORFLOWMODELPERFORMANCEEXAMPLE DESCRIPTOR.enum_types_by_name['TokenMappingType'] = _TOKENMAPPINGTYPE _sym_db.RegisterFileDescriptor(DESCRIPTOR) TensorflowModel = _reflection.GeneratedProtocolMessageType('TensorflowModel', (_message.Message,), dict( DESCRIPTOR = _TENSORFLOWMODEL, __module__ = 'TensorflowModel_pb2' # @@protoc_insertion_point(class_scope:ai.eloquent.TensorflowModel) )) _sym_db.RegisterMessage(TensorflowModel) TokenMapping = _reflection.GeneratedProtocolMessageType('TokenMapping', (_message.Message,), dict( DESCRIPTOR = _TOKENMAPPING, __module__ = 'TensorflowModel_pb2' # @@protoc_insertion_point(class_scope:ai.eloquent.TokenMapping) )) _sym_db.RegisterMessage(TokenMapping) TokenMapper = _reflection.GeneratedProtocolMessageType('TokenMapper', (_message.Message,), dict( DESCRIPTOR = _TOKENMAPPER, __module__ = 'TensorflowModel_pb2' # @@protoc_insertion_point(class_scope:ai.eloquent.TokenMapper) )) _sym_db.RegisterMessage(TokenMapper) TunedEmbedding = _reflection.GeneratedProtocolMessageType('TunedEmbedding', (_message.Message,), dict( DESCRIPTOR = _TUNEDEMBEDDING, __module__ = 'TensorflowModel_pb2' # @@protoc_insertion_point(class_scope:ai.eloquent.TunedEmbedding) )) _sym_db.RegisterMessage(TunedEmbedding) TensorflowModelPerformance = _reflection.GeneratedProtocolMessageType('TensorflowModelPerformance', (_message.Message,), dict( DESCRIPTOR = _TENSORFLOWMODELPERFORMANCE, __module__ = 'TensorflowModel_pb2' # @@protoc_insertion_point(class_scope:ai.eloquent.TensorflowModelPerformance) )) _sym_db.RegisterMessage(TensorflowModelPerformance) TensorflowModelPerformanceExample = _reflection.GeneratedProtocolMessageType('TensorflowModelPerformanceExample', (_message.Message,), dict( DESCRIPTOR = _TENSORFLOWMODELPERFORMANCEEXAMPLE, __module__ = 'TensorflowModel_pb2' # @@protoc_insertion_point(class_scope:ai.eloquent.TensorflowModelPerformanceExample) )) _sym_db.RegisterMessage(TensorflowModelPerformanceExample) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\020ai.eloquent.dataB\025TensorflowModelProtos')) # @@protoc_insertion_point(module_scope)
[ 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 309, 22854, 11125, 17633, 13, 1676, 1462, 198, 198, 11748, 25064, 198, 62, 65, 28, 17597, 13, 9641, 62, 10951, 58, 15, 60, 27, 18, 290, ...
2.351882
9,327
"""Classes representing color entries and mappings.""" # ============================================================================= # IMPORTS # ============================================================================= from __future__ import annotations # Standard Library import re from typing import TYPE_CHECKING, Optional, Tuple if TYPE_CHECKING: import hou # ============================================================================= # CLASSES # ============================================================================= class StyleRule: """This class represents a color application bound to a name. :param name: The rule's name. :param color: The rule's color. :param color_type: The rule's color type. :param shape: The rule's shape. :param file_path: The path to the definition file. :return: """ # ------------------------------------------------------------------------- # SPECIAL METHODS # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # NON-PUBLIC METHODS # ------------------------------------------------------------------------- def _get_typed_color_value(self) -> Tuple[float]: """Get the appropriately typed color values. :return: The color value in the correct type. """ to_func = getattr(self.color, self.color_type.lower()) return to_func() # ------------------------------------------------------------------------- # PROPERTIES # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # METHODS # ------------------------------------------------------------------------- def apply_to_node(self, node: hou.Node): """Apply styling to a node. :param node: Node to apply to :return: """ if self.color is not None: node.setColor(self.color) if self.shape is not None: node.setUserData("nodeshape", self.shape) class ConstantRule: """This class represents a style application bound to a named constant. :param name: The rule's name. :param constant_name: The constant name. :param file_path: The path to the definition file. :return: """ # ------------------------------------------------------------------------- # SPECIAL METHODS # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # PROPERTIES # -------------------------------------------------------------------------
[ 37811, 9487, 274, 10200, 3124, 12784, 290, 285, 39242, 526, 15931, 198, 198, 2, 38093, 25609, 198, 2, 30023, 33002, 198, 2, 38093, 25609, 198, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 2, 8997, 10074, 198, 11748, 302, 198, ...
4.174174
666
import math import numpy as np # return an array K of size (d_max, d_max, N, N), K[i][j] is kernel value of depth i + 1 with first j layers fixed # return an array K of size (N, N), depth d_max, first fix_dep layers fixed
[ 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 198, 2, 1441, 281, 7177, 509, 286, 2546, 357, 67, 62, 9806, 11, 288, 62, 9806, 11, 399, 11, 399, 828, 509, 58, 72, 7131, 73, 60, 318, 9720, 1988, 286, 6795, 1312, 1343, 352, ...
2.986667
75
import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer, PorterStemmer from nltk.tokenize import sent_tokenize , word_tokenize import glob import re import os import numpy as np import sys nltk.download('stopwords') nltk.download('punkt') Stopwords = set(stopwords.words('english')) all_words = [] dict_global = {} file_folder = 'main/documents/*' idx = 1 files_with_index = {} for file in glob.glob(file_folder): fname = file file = open(file , "r") text = file.read() text = remove_special_characters(text) text = re.sub(re.compile('\d'),'',text) sentences = sent_tokenize(text) words = word_tokenize(text) words = [word for word in words if len(words)>1] words = [word.lower() for word in words] words = [word for word in words if word not in Stopwords] dict_global.update(finding_all_unique_words_and_freq(words)) files_with_index[idx] = os.path.basename(fname) idx = idx + 1 unique_words_all = set(dict_global.keys())
[ 11748, 299, 2528, 74, 198, 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330, 2245, 10879, 198, 6738, 299, 2528, 74, 13, 927, 1330, 9678, 7934, 43, 368, 6759, 7509, 11, 20890, 1273, 368, 647, 198, 6738, 299, 2528, 74, 13, 30001, 1096, ...
2.631854
383
# Copyright 2017 Ricardo Garcia Silva # # 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. """Implements the OSEO DescribeResultAccess operation""" from __future__ import absolute_import import logging import datetime as dt from django.core.exceptions import ObjectDoesNotExist import pytz import pyxb import pyxb.bundles.opengis.oseo_1_0 as oseo from .. import errors from .. import models from ..models import Order from .. import utilities logger = logging.getLogger(__name__) def describe_result_access(request, user): """Implements the OSEO DescribeResultAccess operation. This operation returns the location of the order items that are ready to be downloaded by the user. The DescribeResultAccess operation only reports on the availability of order items that specify onlineDataAccess as their delivery option. Parameters ---------- request: oseo.DescribeResultAccess The incoming request user: django.contrib.auth.User The django user that placed the request Returns ------- response: oseo.SubmitAck The response SubmitAck instance """ try: order = Order.objects.get(id=request.orderId) except ObjectDoesNotExist: raise errors.InvalidOrderIdentifierError() if order.user != user: raise errors.AuthorizationFailedError completed_items = get_order_completed_items(order, request.subFunction) logger.debug("completed_items: {}".format(completed_items)) order.last_describe_result_access_request = dt.datetime.now(pytz.utc) order.save() response = oseo.DescribeResultAccessResponse(status='success') item_id = None for item in completed_items: iut = oseo.ItemURLType() iut.itemId = item_id or item.item_specification.item_id iut.productId = oseo.ProductIdType( identifier=item.identifier, ) iut.productId.collectionId = utilities.get_collection_identifier( item.item_specification.collection) iut.itemAddress = oseo.OnLineAccessAddressType() iut.itemAddress.ResourceAddress = pyxb.BIND() iut.itemAddress.ResourceAddress.URL = item.url iut.expirationDate = item.expires_on response.URLs.append(iut) return response def get_order_completed_items(order, behaviour): """Get the completed order items for product orders. Parameters ---------- order: oseoserver.models.Order The order for which completed items are to be returned behaviour: str Either 'allReady' or 'nextReady', as defined in the OSEO specification Returns -------- list The completed order items for this order """ batches = order.batches.all() all_complete = [] for batch in batches: complete_items = get_batch_completed_items(batch, behaviour) all_complete.extend(complete_items) return all_complete
[ 2, 15069, 2177, 38847, 18555, 23720, 198, 2, 198, 2, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 220, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
2.914624
1,183
# -*- coding: utf-8 -*- # python Threading import time from functools import wraps from threading import Thread def async_call(fn): """() Args: :fn(function): Return: :wrapper(function): """ return wrapper def async_pool(pool_links): """ Args: :pool_links(int): Returns: :sub_wrapper(function): """ return sub_wrapper def async_retry(retry_times, space_time): """ call pool Args: :retry_times(int): """ return sub_wrapper # # @async_call # def sleep2andprint(): # time.sleep(2) # print('22222222') # @async_pool(pool_links=5) # def pools(): # time.sleep(1) # print('hehe') # @async_retry(retry_times=3, space_time=1) # def check(): # a = 1 # b = '2' # print(a + b) # def check_all(): # print('async_call') # print('111111') # sleep2andprint() # print('333333') # print('333322222') # print('async_pool') # pools() # print('5hehe') # print('async_retry') # check() # print('') # print(check.__name__) # print(sleep2andprint.__name__) # print(pools.__name__) # check_all()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 21015, 14122, 278, 198, 11748, 640, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 6738, 4704, 278, 1330, 14122, 628, 198, 4299, 30351, 62, 13345, 7, 22184, 2599, 198...
2.077193
570
if __name__ == '__main__': p = Person() eu = Person(name='marcio') wes = Person(eu, name='Wesley') print(p.cumprimentar()) print(p.year) # Atributo de instancia print(p.name) # Atributo de dados for filhos in wes.children: print(filhos.year) p.sobre = 'eu' print(p.sobre) del p.sobre print(p.__dict__) print(p.olhos) print(eu.olhos) print(p.metodo_estatico(), eu.metodo_estatico()) print(p.metodo_classe(), eu.metodo_classe())
[ 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 279, 796, 7755, 3419, 198, 220, 220, 220, 304, 84, 796, 7755, 7, 3672, 11639, 3876, 66, 952, 11537, 198, 220, 220, 220, 266, 274, 796, 7755, 7...
2.004016
249
"""Test combined function.""" from cmatools.combine.combine import combined def test_combined(): """Test of combined function""" assert combined() == "this hello cma"
[ 37811, 14402, 5929, 2163, 526, 15931, 198, 198, 6738, 269, 6759, 10141, 13, 24011, 500, 13, 24011, 500, 1330, 5929, 628, 198, 4299, 1332, 62, 24011, 1389, 33529, 198, 220, 220, 220, 37227, 14402, 286, 5929, 2163, 37811, 628, 220, 220, ...
3.377358
53
"""Enhancement to reformat `top_events_X` from match in order to reformat and put it back to be able to use in alert message. New format: top_events_keys_XXX -- contains array of corresponding key values defined in `top_count_keys`, where `XXX` key from `top_count_keys` array. top_events_values_XXX -- contains array of corresponding counts. Example: Original: {"top_events_KEY.NAME":{"key_value1": 10, "key_value2": 20}} Reformatted: { "top_events_keys_KEY.NAME":["key_value1", "key_value2"] "top_events_values_KEY.NAME":[10, 20] } Can be used in the rule like: top_count_keys: - 'KEY.NAME' match_enhancements: - 'elastalert_modules.top_count_keys_enhancement.Enhancement' alert_text_args: - top_events_keys_KEY.NAME[0] """ from elastalert.enhancements import BaseEnhancement
[ 37811, 35476, 590, 434, 284, 4975, 265, 4600, 4852, 62, 31534, 62, 55, 63, 198, 198, 6738, 2872, 287, 1502, 284, 4975, 265, 290, 1234, 340, 198, 1891, 284, 307, 1498, 284, 779, 287, 7995, 3275, 13, 198, 3791, 5794, 25, 198, 198, 4...
2.798635
293
import numpy import chainer import chainer.functions as F import chainer.links as L from chainer import reporter embed_init = chainer.initializers.Uniform(.25) def block_embed(embed, x, dropout=0.): """Embedding function followed by convolution Args: embed (callable): A :func:`~chainer.functions.embed_id` function or :class:`~chainer.links.EmbedID` link. x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable, which is a :math:`(B, L)`-shaped int array. Its first dimension :math:`(B)` is assumed to be the *minibatch dimension*. The second dimension :math:`(L)` is the length of padded sentences. dropout (float): Dropout ratio. Returns: ~chainer.Variable: Output variable. A float array with shape of :math:`(B, N, L, 1)`. :math:`(N)` is the number of dimensions of word embedding. """ e = embed(x) e = F.dropout(e, ratio=dropout) e = F.transpose(e, (0, 2, 1)) e = e[:, :, :, None] return e
[ 11748, 299, 32152, 198, 198, 11748, 6333, 263, 198, 11748, 6333, 263, 13, 12543, 2733, 355, 376, 198, 11748, 6333, 263, 13, 28751, 355, 406, 198, 6738, 6333, 263, 1330, 9095, 198, 198, 20521, 62, 15003, 796, 6333, 263, 13, 36733, 1134...
2.322105
475
from flask_login import UserMixin
[ 6738, 42903, 62, 38235, 1330, 11787, 35608, 259, 628 ]
3.888889
9
""" matmul autotvm [batch,in_dim] x [in_dim,out_dim] search_matmul_config(batch,in_dim,out_dim,num_trials): input: batch,in_dim,out_dim,num_trials [batch,in_dim] x [in_dim,out_dim] num_trials: num of trials, default: 1000 output: log (json format) use autotvm to search configs for the matmul lookup_matmul_config(): find a proper matmul config note: trade off kernel's performance and grid & block size launch_matmul_from_config(config): input: config (json string) usage: 1. use search_matmul_config(batch,in_dim,out_dim,num_trials) to search configs 2. use lookup_matmul_config() to get a proper config 3. write the config (in json format) to "matmul_config.json" 4. use launch_matmul_from_config("matmul_config.json") to print the matmul kernel code """ import numpy as np import tvm import logging import sys from tvm import autotvm import topi import json import os from topi.util import get_const_tuple import tensorflow as tf flags = tf.flags flags.DEFINE_string("input_path", "", "path of input file") flags.DEFINE_string("autotvm_log", "../autotvm_logs/all_tuned_tilling_dense_nn.1000.log", "path of autotvm tuning log") flags.DEFINE_string("tvm_profile_log", "/tmp/tvm_profile.log", "path of tvm profile") flags.DEFINE_string("output_path", "", "path of output file") FLAGS = flags.FLAGS output_log_file = "matmul_nn_autotvm_select_result.log" if os.path.exists(output_log_file): os.remove(output_log_file) lookup_matmul_config(4, 256, 256, output_log_file) lookup_matmul_config(16, 256, 256, output_log_file) dot_ops = extract_ops_from_log() topi_ops = generate_db_topi_ops(dot_ops, output_log_file) with open(FLAGS.output_path, 'w') as fout: json.dump(topi_ops, fout) os.remove(output_log_file)
[ 37811, 198, 6759, 76, 377, 1960, 313, 14761, 198, 198, 58, 43501, 11, 259, 62, 27740, 60, 2124, 685, 259, 62, 27740, 11, 448, 62, 27740, 60, 198, 198, 12947, 62, 6759, 76, 377, 62, 11250, 7, 43501, 11, 259, 62, 27740, 11, 448, 6...
2.493844
731
from django.contrib import admin from .models import ActivityLog, ReviewActionReasonLog from olympia.reviewers.models import ReviewActionReason admin.site.register(ActivityLog, ActivityLogAdmin) admin.site.register(ReviewActionReasonLog, ReviewActionReasonLogAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 764, 27530, 1330, 24641, 11187, 11, 6602, 12502, 45008, 11187, 198, 6738, 267, 6760, 544, 13, 19023, 364, 13, 27530, 1330, 6602, 12502, 45008, 628, 628, 198, 28482, 13, 156...
3.871429
70
import subprocess import sys import time import os ############################# # COLORING YOUR SHELL # ############################# R = "\033[1;31m" # B = "\033[1;34m" # Y = "\033[1;33m" # G = "\033[1;32m" # RS = "\033[0m" # W = "\033[1;37m" # ############################# os.system("clear") print(" ") print(R + "[" + G + "User Summary " + R + "]" + RS) print(""" Shows extra information about IPv6 addresses, such as embedded MAC or IPv4 addresses when available. Some IP address formats encode extra information; for example some IPv6 addresses encode an IPv4 address or MAC address script can decode these address formats: IPv4-compatible IPv6 addresses, IPv4-mapped IPv6 addresses, Teredo IPv6 addresses, 6to4 IPv6 addresses, IPv6 addresses using an EUI-64 interface ID, IPv4-embedded IPv6 addresses, ISATAP Modified EUI-64 IPv6 addresses. IPv4-translated IPv6 addresses and See RFC 4291 for general IPv6 addressing architecture and the definitions of some terms. """) print(" ") webb = input("" + RS + "[" + B + "ENTER TARGET " + R + "WEBSITE " + Y + "IP" + RS + "]" + G + ": " + RS) subprocess.check_call(['nmap', '-sV', '-sC', webb])
[ 11748, 850, 14681, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 28686, 198, 198, 14468, 7804, 4242, 2, 198, 2, 220, 220, 220, 20444, 1581, 2751, 16592, 6006, 23304, 220, 220, 220, 1303, 198, 14468, 7804, 4242, 2, 198, 49, 796, 3708...
2.671642
469
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest import os import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities.upgrade_checkpoint import upgrade_checkpoint
[ 2, 15069, 383, 9485, 15884, 354, 12469, 1074, 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...
3.77561
205
import oneflow.experimental as flow from oneflow.experimental import optim import oneflow.experimental.nn as nn from utils.dataset import * from utils.tensor_utils import * from models.rnn_model import RNN import argparse import time import math import numpy as np flow.env.init() flow.enable_eager_execution() # refer to: https://blog.csdn.net/Nin7a/article/details/107631078 n_iters = 100000 print_every = 500 plot_every = 1000 learning_rate = ( 0.005 # If you set this too high, it might explode. If too low, it might not learn ) # decrease learning rate if loss goes to NaN, increase learnig rate if it learns too slow if __name__ == "__main__": args = _parse_args() main(args)
[ 11748, 530, 11125, 13, 23100, 9134, 355, 5202, 198, 6738, 530, 11125, 13, 23100, 9134, 1330, 6436, 198, 11748, 530, 11125, 13, 23100, 9134, 13, 20471, 355, 299, 77, 198, 198, 6738, 3384, 4487, 13, 19608, 292, 316, 1330, 1635, 198, 673...
2.978992
238
import json import os from ..metaflow_config import DATASTORE_LOCAL_DIR, DATASTORE_SYSROOT_LOCAL from .datastore_storage import CloseAfterUse, DataStoreStorage from .exceptions import DataException
[ 11748, 33918, 198, 11748, 28686, 198, 198, 6738, 11485, 4164, 1878, 9319, 62, 11250, 1330, 360, 1404, 11262, 6965, 62, 29701, 1847, 62, 34720, 11, 360, 1404, 11262, 6965, 62, 23060, 12562, 46, 2394, 62, 29701, 1847, 198, 6738, 764, 1960...
3.225806
62
from __future__ import division, print_function from scipy.spatial.distance import euclidean from numpy import mean from pdb import set_trace
[ 6738, 11593, 37443, 834, 1330, 7297, 11, 3601, 62, 8818, 198, 6738, 629, 541, 88, 13, 2777, 34961, 13, 30246, 1330, 304, 36616, 485, 272, 198, 6738, 299, 32152, 1330, 1612, 198, 6738, 279, 9945, 1330, 900, 62, 40546 ]
3.615385
39
''' pip3 install BeautifulSoup4 pip3 install pypinyin ''' import requests import re import os import shutil from bs4 import BeautifulSoup from util import Profile, write_poem def read_poem_list(page): ''' Read poem list @param page:int @return (poem_list:Profile[], has_next_page:Boolean) ''' page_url = 'http://www.chinapoesy.com/XianDaiList_' + str(page) + '.html' response = requests.get(page_url) if response.status_code is not 200: return ([], False) text = response.text soup = BeautifulSoup(text, features='lxml') # profiles main_table = soup.find('table', id='DDlTangPoesy') td_ = main_table.find_all('td') poet_list = [] for td in td_: poem = parse_poem_profile_td(td) if poem is not None: poet_list.append(poem) img_neg = soup.find('img', src='/Images/Pager/nextn.gif') return (poet_list, img_neg is not None) main()
[ 198, 7061, 6, 198, 220, 220, 220, 7347, 18, 2721, 23762, 50, 10486, 19, 198, 220, 220, 220, 7347, 18, 2721, 279, 4464, 3541, 259, 198, 7061, 6, 198, 198, 11748, 7007, 198, 11748, 302, 198, 11748, 28686, 198, 11748, 4423, 346, 198, ...
2.33012
415
# Copyright 2020 D-Wave Systems Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from dwave.cloud.client import Client from dwave.cloud.solver import Solver from dwave.cloud.events import add_handler
[ 2, 15069, 12131, 360, 12, 39709, 11998, 3457, 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...
3.764398
191
''' Neural networks. Forward propagation in an already trained network in TensorFlow 2.0-2.1 (to use the network for classification). TF 2.0: Option 0 takes 0.08 sec. Option 1 takes 0.08 sec. Option 6 takes 0.08 sec. Option 2 takes 4.7 sec. Option 3 takes 1.6 sec. Option 4 takes 5.2 sec. Option 5 takes 0.08 sec. Option 7 takes 0.06 sec. If pred_digit = tf.map_fn(lambda x: ...) is used, then it's much slower: Option 0 takes 1.75 sec. Option 1 takes 1.75 sec. Option 6 takes 1.8 sec. Option 2 takes 6.1 sec. Option 3 takes 3.1 sec. Option 4 takes 6.3 sec. Option 5 takes 1.8 sec. Option 7 takes 1.8 sec. TF 2.1: option==2, 3, 4, 5, 7 work; options 0, 1 and 6 fail with "AttributeError: 'RepeatedCompositeFieldContainer' object has no attribute 'append'" (But mine hasn't installed properly.) Option 2 takes 4.5 sec. Option 3 takes 1.5 sec. Option 4 takes 4.4 sec. Option 5 takes 0.08 sec. Option 7 takes 0.06 sec. If pred_digit = tf.map_fn(lambda x: ...) is used, then it's much slower: Option 2 takes 5.7-6.1 sec. Option 3 takes 3.1 sec. Option 4 takes 5.7-6 sec. Option 5 takes 1.8 sec. Option 7 takes 1.8 sec. Be careful: According to tf.keras.layers.Dense (https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense): output = activation(dot(input, kernel) + bias) The kernel matrix multiplies from right! (And the inputs are seen as a row vector.) This is why I have to transpose the loaded network parameters Theta1 and Theta2. Earlier, according to r1.15 tf.layers.dense documentation (https://www.tensorflow.org/api_docs/python/tf/layers/dense): outputs = activation(inputs*kernel + bias) [In version for Tensorflow 1.x, there used to be two independent choices in program flow: Option 1 is with tf.layers.Input() Option 2 is without tf.layers.Input() Option a processes single inputs (single images), takes 1.5 sec Option b does batch processing of all images at once, takes 0.3 sec ] Bence Mlykti 09-19/03/2018, 27/01-07/02, 28/02/2020 ''' import numpy as np import scipy.io # to open Matlab's .mat files import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt import time ### User input ### option = 7 # {0, 1, ..., 7} ### End of input ### # The network parameters are here for info, they are not actually used. input_layer_size = 400 # 20x20 Input Images of Digits hidden_layer_size = 25 # 25 hidden units num_labels = 10 # 10 labels, from 1 to 10 # (note that we have mapped "0" to label 10) # =========== Part 1: Loading [and Visualizing] Data ============= data = scipy.io.loadmat('../machine-learning-ex3/ex3/ex3data1.mat') X = data['X'] y = data['y'] y = y % 10 # Transforming 10 to 0, which is its original meaning. # ================ Part 2: Loading Pameters ================ # In this part of the exercise, we load the pre-initialized # neural network parameters. params = scipy.io.loadmat('../machine-learning-ex3/ex3/ex3weights.mat') Theta1 = params['Theta1'] # Theta1 has size 25 x 401 Theta2 = params['Theta2'] # Theta2 has size 10 x 26 tf.keras.backend.clear_session() start_time = time.time() # ================= Part 3: Implement Predict ================= # After training a neural network, we would like to use it to predict # the labels. You will now implement the "predict" function to use the # neural network to predict the labels of the training set. This lets # you compute the training set accuracy. # Difference between tf.data.Dataset.from_tensors and tf.data.Dataset.from_tensor_slices: https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices # from_tensors reads all data at once; from_tensor_slices reads line by line, which is preferable for huge datasets # With from_tensors, you'd also need to pull out each row from the tensor somehow. # https://towardsdatascience.com/how-to-use-dataset-in-tensorflow-c758ef9e4428 # https://www.tensorflow.org/programmers_guide/datasets#consuming_numpy_arrays # To narrow computation to a subset of data for quick testing: #X, y = X[1990:2010,:], y[1990:2010,:] if option==2 or option==3: dataset = tf.data.Dataset.from_tensor_slices(X) else: dataset = tf.data.Dataset.from_tensor_slices(X).batch(X.shape[0]) #dataset = tf.data.Dataset.from_tensor_slices(X).batch(64) # this is about the same speed as .batch(X.shape[0]) #dataset = tf.data.Dataset.from_tensor_slices(X).batch(1) # this also works but it is 1.5x-4x slower # It also works with tf.keras.initializers.Constant() in place of tf.constant_initializer because these are only aliases: https://www.tensorflow.org/api_docs/python/tf/constant_initializer . if option==0: model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(Theta1.shape[0], activation='sigmoid', use_bias=True, kernel_initializer=tf.constant_initializer(Theta1[:,1:].T), bias_initializer=tf.constant_initializer(Theta1[:,0]), input_shape=[X.shape[1]])) model.add(tf.keras.layers.Dense(Theta2.shape[0], activation='sigmoid', use_bias=True, kernel_initializer=tf.constant_initializer(Theta2[:,1:].T), bias_initializer=tf.constant_initializer(Theta2[:,0]))) # One doesn't even need the second sigmoid activation function because it is monotone increasing and doesn't change the ordering for argmax. pred = model.predict(dataset) elif option==1: # input_shape=[X.shape[1]] could be left out below layers = [tf.keras.layers.Dense(Theta1.shape[0], kernel_initializer=tf.constant_initializer(Theta1[:,1:].T), bias_initializer=tf.constant_initializer(Theta1[:,0]), activation='sigmoid', input_shape=[X.shape[1]]), tf.keras.layers.Dense(Theta2.shape[0], kernel_initializer=tf.constant_initializer(Theta2[:,1:].T), bias_initializer=tf.constant_initializer(Theta2[:,0]), activation='sigmoid')] # One doesn't even need the second sigmoid activation function because it is monotone increasing and doesn't change the ordering for argmax. # This doesn't work as tf.constant_initializer() doesn't take Tensors as input. #layers = [tf.keras.layers.Dense(Theta1.shape[0], kernel_initializer= tf.constant_initializer(tf.transpose(Theta1[:,1:])), bias_initializer=tf.constant_initializer(Theta1[:,0]), activation='sigmoid'), # tf.keras.layers.Dense(Theta2.shape[0], kernel_initializer= tf.constant_initializer(tf.transpose(Theta2[:,1:])), bias_initializer=tf.constant_initializer(Theta2[:,0]), activation='sigmoid')] # This doesn't work: ValueError: Could not interpret initializer identifier: tf.Tensor(...) #layers = [tf.keras.layers.Dense(Theta1.shape[0], kernel_initializer=tf.transpose(Theta1[:,1:]), bias_initializer=Theta1[:,0], activation='sigmoid'), # tf.keras.layers.Dense(Theta2.shape[0], kernel_initializer=tf.transpose(Theta2[:,1:]), bias_initializer=Theta2[:,0], activation='sigmoid')] model = tf.keras.Sequential(layers) #model = tf.keras.models.Sequential(layers) # This is just an alias of previous. #model.build() # not necessary pred = model.predict(dataset) elif option==6: model = NNModel(Theta1, Theta2) pred = model.predict(dataset) elif option in [2, 3, 4, 5]: if option==2: pred = [] for entry in dataset: #pred.append(evaluation(tf.constant(Theta1.T), tf.constant(Theta2.T), entry.numpy().reshape((1,-1)))) # numpy reshape might be faster than tf.reshape pred.append(evaluation(tf.constant(Theta1.T), tf.constant(Theta2.T), tf.reshape(entry, (1,-1)))) # doing it in TF #pred = np.concatenate(pred, axis=0) # this also works pred = tf.concat(pred, axis=0) elif option==3: pred = dataset.map(lambda x: evaluation(tf.constant(Theta1.T), tf.constant(Theta2.T), tf.reshape(x, [1,-1]))) #pred = dataset.map(lambda x: evaluation(tf.constant(Theta1.T), tf.constant(Theta2.T), x)) # This doesn't work. pred = tf.concat([entry for entry in pred], axis=0) elif option==4: pred = [] for batch in dataset: for entry in batch: pred.append(evaluation(tf.constant(Theta1.T), tf.constant(Theta2.T), tf.reshape(entry, (1,-1)))) pred = tf.concat(pred, axis=0) else: # option==5 pred = dataset.map(lambda x: evaluation(tf.constant(Theta1.T), tf.constant(Theta2.T), x)) #pred = dataset.map(lambda x: evaluation(tf.constant(Theta1.T), tf.constant(Theta2.T), tf.reshape(x, [-1,400]))) # This works, in same time. pred = tf.concat([entry for entry in pred], axis=0) else: # option==7 pred = dataset.map(lambda x: evaluation2(tf.constant(Theta1[:,1:].T), tf.constant(Theta1[:,0]), tf.constant(Theta2[:,1:].T), tf.constant(Theta2[:,0].T), x)) #pred = dataset.map(lambda x: evaluation2(tf.constant(Theta1[:,1:].T), tf.constant(Theta1[:,0]), tf.constant(Theta2[:,1:].T), tf.constant(Theta2[:,0].T), tf.reshape(x, [-1,400]))) # This works, in same time. pred = tf.concat([entry for entry in pred], axis=0) # It does not work in this simplest form: #pred = evaluation2(tf.constant(Theta1[:,1:].T), tf.constant(Theta1[:,0]), tf.constant(Theta2[:,1:].T), tf.constant(Theta2[:,0].T), dataset) #tf.print(pred) # The output layer (pred) has 10 units, for digits 1,2,...,9,0. After taking argmax, you have to map the result of argmax, 0,1,2,...,9 to the required 1,2,...,9,0. pred_digit = (tf.argmax(pred, axis=1) + 1) % 10 #pred_digit = tf.map_fn(lambda x: (tf.argmax(x, axis=0, output_type=tf.int32)+1) % 10, pred, dtype=tf.int32) # This is rather slow! pred_np = pred_digit.numpy().reshape(-1,1) print('\nTraining Set Accuracy: {0:.2f}%.'.format(np.mean(pred_np == y) * 100)) print('Expected training error value on complete Training Set (approx.): 97.5%.') print('\nTime elapsed: {:.2f} sec'.format(time.time() - start_time)) print() if option in [0, 1, 6]: tf.print(model.summary()) # This provides interesting output. plt.scatter(np.arange(len(y)), y, label='Ground truth') plt.scatter(np.arange(len(y)), pred_np, marker=".", c='r', label='Prediction') plt.xlabel('Sample ID') plt.ylabel('Digit') plt.legend() plt.show()
[ 7061, 6, 198, 8199, 1523, 7686, 13, 19530, 43594, 287, 281, 1541, 8776, 3127, 287, 309, 22854, 37535, 362, 13, 15, 12, 17, 13, 16, 357, 1462, 779, 262, 3127, 329, 17923, 737, 198, 198, 10234, 362, 13, 15, 25, 198, 19722, 657, 2753...
2.646534
3,808
from django.db import models from django.db.models.deletion import CASCADE from django.contrib.auth.models import User from cloudinary.models import CloudinaryField # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, 1330, 35106, 34, 19266, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 6279, 3219, 13, ...
3.509091
55
from odoo import SUPERUSER_ID, api from odoo.tools.sql import column_exists def _migrate_purchase_request_to_property(env): """Create properties for all products with the flag set on all companies""" env.cr.execute("select id, coalesce(purchase_request, False) from product_template") values = dict(env.cr.fetchall()) for company in env["res.company"].with_context(active_test=False).search([]): env["ir.property"].with_context(force_company=company.id).set_multi( "purchase_request", "product.template", values, False, ) env.cr.execute("alter table product_template drop column purchase_request")
[ 6738, 16298, 2238, 1330, 33088, 29904, 62, 2389, 11, 40391, 198, 6738, 16298, 2238, 13, 31391, 13, 25410, 1330, 5721, 62, 1069, 1023, 628, 198, 198, 4299, 4808, 76, 42175, 62, 79, 18737, 62, 25927, 62, 1462, 62, 26745, 7, 24330, 2599,...
2.936652
221
# coding=UTF-8 """Server stuff.""" from __future__ import print_function from cfy import (create_server, create_ssh_key, attach_ssh_key, wait_for_state, wait_for_cond, create_nic, attach_nic, get_resource, get_server_status, start_server, stop_server, delete_resource) import socket import errno from cloudify import ctx from cloudify.decorators import operation from cloudify.exceptions import NonRecoverableError from cfy.helpers import (with_fco_api, with_exceptions_handled) from resttypes import enums, cobjects from paramiko import SSHClient, AutoAddPolicy import spur import spur.ssh from time import sleep from subprocess import call from fabric.api import settings, run import os RT = enums.ResourceType PROP_RESOURCE_ID = 'resource_id' PROP_USE_EXISTING = 'use_existing' PROP_IMAGE = 'image' PROP_VDC = 'vdc' PROP_NET = 'network' PROP_SERVER_PO = 'server_type' PROP_CPU_COUNT = 'cpu_count' PROP_RAM_AMOUNT = 'ram_amount' PROP_MANAGER_KEY = 'manager_key' PROP_PRIVATE_KEYS = 'private_keys' PROP_PUBLIC_KEYS = 'public_keys' RPROP_UUID = 'uuid' RPROP_DISKS = 'disks' RPROP_NIC = 'nic' RPROP_NICS = 'nics' RPROP_IP = 'ip' RPROP_USER = 'username' RPROP_PASS = 'password'
[ 2, 19617, 28, 48504, 12, 23, 198, 198, 37811, 10697, 3404, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 269, 24928, 1330, 357, 17953, 62, 15388, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220...
2.201923
624
# coding: utf-8 """ markdown2dita ~~~~~~~~~~~~~ A markdown to dita-ot conversion tool written in pure python. Uses mistune to parse the markdown. """ from __future__ import print_function import argparse import sys import mistune __version__ = '0.3' __author__ = 'Matt Carabine <matt.carabine@gmail.com>' __all__ = ['Renderer', 'Markdown', 'markdown', 'escape'] def escape(text, quote=False, smart_amp=True): return mistune.escape(text, quote=quote, smart_amp=smart_amp) def _parse_args(args): parser = argparse.ArgumentParser(description='markdown2dita - a markdown ' 'to dita-ot CLI conversion tool.') parser.add_argument('-i', '--input-file', help='input markdown file to be converted.' 'If omitted, input is taken from stdin.') parser.add_argument('-o', '--output-file', help='output file for the converted dita content.' 'If omitted, output is sent to stdout.') return parser.parse_args(args) def markdown(text, escape=True, **kwargs): return Markdown(escape=escape, **kwargs)(text) def main(): parsed_args = _parse_args(sys.argv[1:]) if parsed_args.input_file: input_str = open(parsed_args.input_file, 'r').read() elif not sys.stdin.isatty(): input_str = ''.join(line for line in sys.stdin) else: print('No input file specified and unable to read input on stdin.\n' "Use the '-h' or '--help' flag to see usage information", file=sys.stderr) exit(1) markdown = Markdown() dita_output = markdown(input_str) if parsed_args.output_file: with open(parsed_args.output_file, 'w') as output_file: output_file.write(dita_output) else: print(dita_output) if __name__ == '__main__': main()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 37811, 198, 220, 220, 220, 1317, 2902, 17, 5266, 64, 198, 220, 220, 220, 220, 15116, 8728, 93, 198, 220, 220, 220, 317, 1317, 2902, 284, 288, 5350, 12, 313, 11315, 2891, 3194, 287, 5899, 21015,...
2.284689
836
import pytest import os from helpers.cluster import ClickHouseCluster SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) cluster = ClickHouseCluster(__file__) node = cluster.add_instance('node', main_configs=["configs/first.crt", "configs/first.key", "configs/second.crt", "configs/second.key", "configs/cert.xml"]) def change_config_to_key(name): ''' * Generate config with certificate/key name from args. * Reload config. ''' node.exec_in_container(["bash", "-c" , """cat > /etc/clickhouse-server/config.d/cert.xml << EOF <?xml version="1.0"?> <clickhouse> <https_port>8443</https_port> <openSSL> <server> <certificateFile>/etc/clickhouse-server/config.d/{cur_name}.crt</certificateFile> <privateKeyFile>/etc/clickhouse-server/config.d/{cur_name}.key</privateKeyFile> <loadDefaultCAFile>true</loadDefaultCAFile> <cacheSessions>true</cacheSessions> <disableProtocols>sslv2,sslv3</disableProtocols> <preferServerCiphers>true</preferServerCiphers> </server> </openSSL> </clickhouse> EOF""".format(cur_name=name)]) node.query("SYSTEM RELOAD CONFIG") def test_first_than_second_cert(): ''' Consistently set first key and check that only it will be accepted, then repeat same for second key. ''' # Set first key change_config_to_key('first') # Command with correct certificate assert node.exec_in_container(['curl', '--silent', '--cacert', '/etc/clickhouse-server/config.d/{cur_name}.crt'.format(cur_name='first'), 'https://localhost:8443/']) == 'Ok.\n' # Command with wrong certificate # This command don't use option '-k', so it will lead to error while execution. # That's why except will always work try: node.exec_in_container(['curl', '--silent', '--cacert', '/etc/clickhouse-server/config.d/{cur_name}.crt'.format(cur_name='second'), 'https://localhost:8443/']) assert False except: assert True # Change to other key change_config_to_key('second') # Command with correct certificate assert node.exec_in_container(['curl', '--silent', '--cacert', '/etc/clickhouse-server/config.d/{cur_name}.crt'.format(cur_name='second'), 'https://localhost:8443/']) == 'Ok.\n' # Command with wrong certificate # Same as previous try: node.exec_in_container(['curl', '--silent', '--cacert', '/etc/clickhouse-server/config.d/{cur_name}.crt'.format(cur_name='first'), 'https://localhost:8443/']) assert False except: assert True
[ 11748, 12972, 9288, 198, 11748, 28686, 198, 6738, 49385, 13, 565, 5819, 1330, 6914, 18102, 2601, 5819, 198, 198, 6173, 46023, 62, 34720, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 5305, 6978, 7, 834, 7753, 834, 4008,...
2.264396
1,233
import flingclient as fc from flingclient.rest import ApiException from datetime import datetime # Per default the dockerized fling service runs on localhost:3000 In case you # run your own instance, change the base url configuration = fc.Configuration(host="http://localhost:3000") # Every call, with the exception of `/api/auth`, is has to be authorized by a # bearer token. Get a token by authenticating as admin and set it into the # configuration. All subsequent calls will send this token in the header as # `Authorization: Bearer <token> header` admin_user = input("Username: ") admin_password = input("Password: ") authenticate(admin_user, admin_password) with fc.ApiClient(configuration) as api_client: # Create a new fling fling_client = fc.FlingApi(api_client) fling = fc.Fling(name="A Fling from Python", auth_code="secret", direct_download=False, allow_upload=True, expiration_time=datetime(2099, 12, 12)) fling = fling_client.post_fling() print(f"Created a new fling: {fling}") #
[ 11748, 781, 278, 16366, 355, 277, 66, 198, 6738, 781, 278, 16366, 13, 2118, 1330, 5949, 72, 16922, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 2, 2448, 4277, 262, 36253, 1143, 781, 278, 2139, 4539, 319, 1957, 4774, 25, 23924, ...
3.014368
348
import tensorflow.compat.v1 as tf import os import tqdm GCS_BUCKET = 'gs://ptt5-1' TENSORBOARD_LOGS_LOCAL = '../logs_tensorboard' os.makedirs(TENSORBOARD_LOGS_LOCAL, exist_ok=True) # where to look for events files - experiment names base_paths = [ # Main initial experiments - all weights are updated 'small_standard_vocab', 'base_standard_vocab', 'large_standard_vocab', 'small_custom_sentencepiece_vocab', 'base_custom_sentencepiece_vocab', 'large_custom_sentencepiece_vocab', # Only embeddings are updated 'small_embeddings_only_standard_vocab', 'base_embeddings_only_standard_vocab', 'large_embeddings_only_standard_vocab', 'small_embeddings_only_custom_sentencepiece_vocab', 'base_embeddings_only_custom_sentencepiece_vocab', 'large_embeddings_only_custom_sentencepiece_vocab', # Double batch size for large (128 = 64 * 2) 'large_batchsize_128_custom_sentencepiece_vocab', 'large_batchsize_128_standard_vocab', ] # all paths have the scructure for base_path in base_paths: size = base_path.split('_')[0] full_path = os.path.join(GCS_BUCKET, base_path, 'models', size) download_dir = os.path.join(TENSORBOARD_LOGS_LOCAL, base_path) if not os.path.exists(download_dir): os.makedirs(download_dir, exist_ok=True) print(f'Downloading files from {full_path} to {download_dir}') for file in tqdm.tqdm(tf.gfile.Glob(os.path.join(full_path, "events.*"))): tf.gfile.Copy(file, os.path.join(download_dir, os.path.basename(file)), overwrite=False) else: print(f'{base_path} logs already download. Delete folder' f'{download_dir} and run script to download again')
[ 11748, 11192, 273, 11125, 13, 5589, 265, 13, 85, 16, 355, 48700, 198, 11748, 28686, 198, 11748, 256, 80, 36020, 198, 198, 38, 7902, 62, 33, 16696, 2767, 796, 705, 14542, 1378, 457, 83, 20, 12, 16, 6, 198, 51, 16938, 1581, 8202, 97...
2.249689
805
import base64 import requests
[ 11748, 2779, 2414, 198, 11748, 7007, 628 ]
4.428571
7
import logging import re from celery import shared_task from django.conf import settings from django.db.models import Q from django.shortcuts import get_object_or_404 from django.template.loader import get_template from django.urls import reverse from django.utils import timezone from architecture_tool_django.utils.confluence_wrapper import ( MyConfluence, tiny_to_page_id, ) from .models import Node logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 11748, 302, 198, 198, 6738, 18725, 1924, 1330, 4888, 62, 35943, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 1195, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, ...
3.20979
143
from crosswalk.authentication import AuthenticatedView from crosswalk.models import Domain, Entity from crosswalk.serializers import EntitySerializer from crosswalk.utils import import_class from django.core.exceptions import ObjectDoesNotExist from rest_framework import status from rest_framework.response import Response
[ 6738, 3272, 11152, 13, 41299, 3299, 1330, 31885, 3474, 7680, 198, 6738, 3272, 11152, 13, 27530, 1330, 20021, 11, 20885, 198, 6738, 3272, 11152, 13, 46911, 11341, 1330, 20885, 32634, 7509, 198, 6738, 3272, 11152, 13, 26791, 1330, 1330, 62,...
4.452055
73
from fastapi import FastAPI, Response, WebSocket, WebSocketDisconnect from threading import Thread from .server import Server from .errors import HoistExistsError from .error import Error from .version import __version__ from .flask_wrapper import HTML import uvicorn from typing import List, Callable from fastapi.responses import HTMLResponse, JSONResponse
[ 6738, 3049, 15042, 1330, 12549, 17614, 11, 18261, 11, 5313, 39105, 11, 5313, 39105, 7279, 8443, 198, 6738, 4704, 278, 1330, 14122, 198, 6738, 764, 15388, 1330, 9652, 198, 6738, 764, 48277, 1330, 9544, 396, 3109, 1023, 12331, 198, 6738, ...
4.079545
88
# This file is executed on every boot (including wake-boot from deepsleep) # 2017-1210 PePo send timestamp and temperature (Celsius) to MQTT-server on BBB # 2017-1105 PePo add _isLocal: sensor data to serial port (False) of stored in file (True) # 2017-0819 PePo add sensor, led and print to serial port # 2017-0811 PePo updated: no debug, disable webrepl, # source: https://youtu.be/yGKZOwzGePY - Tony D! MP ESP8266 HTTP examples print('main.py executing...') # connect to a personal Wifi network --------- import wifinetwork as wifi # TODO: JSON config-file with ssid:ww entry/entries #wifi.connectTo("PePoDevNet", wifi.readPasswordFrom('pepodevnet.txt')) print('Wifi: connect to PePoDevNet...') wifi.connectTo("PePoDevNet") # set the time from nptime --------- #print('TODO: get current time from the web...') print('getting time from the web...') import nptime print('... UTC time:', nptime.settime()) #print('\tTODO -local time') # --- SUMMERTIME or not (=WINTERTIME) --------------- _isSummerTime = False print('... Summertime:', _isSummerTime) # temperature --------- import class_ds18b20 #get sensor at GPIO14 ds = class_ds18b20.DS18B20(14) # --- location --------------- _LOCATION = 'studyroom' #7-segment display import tm1637 from machine import Pin import math # create tm tm = tm1637.TM1637(clk=Pin(5), dio=Pin(4)) #print('tm: ', tm) # helper function: returns temperature-record as string #''' store data in file temperature.txt # default: 1 measuremtn per 30 seconds # send data to MQTT-server #main run() - by-default 1 measurement per 30 seconds # go ahead and start getting, sending/storing the sensor data if __name__ == "__main__": run(60.0) # 1 measurement per minute
[ 2, 770, 2393, 318, 10945, 319, 790, 6297, 357, 8201, 7765, 12, 18769, 422, 2769, 42832, 8, 201, 198, 2, 2177, 12, 1065, 940, 2631, 18833, 3758, 41033, 290, 5951, 357, 34, 32495, 8, 284, 337, 48, 15751, 12, 15388, 319, 12597, 33, 2...
2.859935
614
#!/usr/bin/python3 lines = open("inputs/07.in", "r").readlines() for i,line in enumerate(lines): lines[i] = line.split("\n")[0] l = lines.copy(); wires = {} run() print("Part 1: " + str(wires["a"])) lines = l wires = {"b": wires["a"]} run() print("Part 2: " + str(wires["a"]))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 6615, 796, 1280, 7203, 15414, 82, 14, 2998, 13, 259, 1600, 366, 81, 11074, 961, 6615, 3419, 198, 1640, 1312, 11, 1370, 287, 27056, 378, 7, 6615, 2599, 198, 220, 220, 220, 3951, 58, 72...
2.244094
127
import socket import time import numpy # This script sends a message to the board, at IP address and port given by # server_address, using User Datagram Protocol (UDP). The board should be # programmed to echo back UDP packets sent to it. The time taken for num_samples # echoes is measured. # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = ('192.168.0.59', 7) sock.bind(('', 7)) message = 'this is a message of length 80 chars. asdfghjklasdfghjklasdfghjklasdfghjkl ++++'.encode() num_samples = 500 times = [] try: # Send data print('Sending "{}"'.format(message)) print('Measuring time taken for {} echoes'.format(num_samples)) total_time = 0 for i in range(num_samples): t0 = time.perf_counter() sent = sock.sendto(message, server_address) # Receive response data, server = sock.recvfrom(4096) t1 = time.perf_counter() dt = t1 - t0 total_time += dt #print('received "{}"'.format(data)) times.append(dt) f = open('times', 'a') try: f.write('\n') for i in range(num_samples): f.write('{},'.format(times[i])) finally: f.close() times_array = numpy.array(times) print('Took {} seconds for {} samples'.format(total_time, num_samples)) print('Average echo time: {} seconds'.format(numpy.average(times_array))) print('Standard deviation: {} seconds'.format(numpy.std(times_array))) print('Maximum: {} seconds, Minimum: {} seconds'.format(numpy.amax(times_array), numpy.amin(times_array))) finally: print('Closing socket') sock.close()
[ 11748, 17802, 198, 11748, 640, 198, 11748, 299, 32152, 198, 198, 2, 770, 4226, 12800, 257, 3275, 284, 262, 3096, 11, 379, 6101, 2209, 290, 2493, 1813, 416, 198, 2, 4382, 62, 21975, 11, 1262, 11787, 16092, 6713, 20497, 357, 52, 6322, ...
2.544479
652
#!/usr/bin/env python # # This file is part of the Emotions project. The complete source code is # available at https://github.com/luigivieira/emotions. # # Copyright (c) 2016-2017, Luiz Carlos Vieira (http://www.luiz.vieira.nom.br) # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys import argparse import cv2 import numpy as np from collections import OrderedDict from datetime import datetime, timedelta from faces import FaceDetector from data import FaceData from gabor import GaborBank from emotions import EmotionsDetector #--------------------------------------------- #--------------------------------------------- def main(argv): """ Main entry of this script. Parameters ------ argv: list of str Arguments received from the command line. """ # Parse the command line args = parseCommandLine(argv) # Loads the video or starts the webcam if args.source == 'cam': video = cv2.VideoCapture(args.id) if not video.isOpened(): print('Error opening webcam of id {}'.format(args.id)) sys.exit(-1) fps = 0 frameCount = 0 sourceName = 'Webcam #{}'.format(args.id) else: video = cv2.VideoCapture(args.file) if not video.isOpened(): print('Error opening video file {}'.format(args.file)) sys.exit(-1) fps = int(video.get(cv2.CAP_PROP_FPS)) frameCount = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) sourceName = args.file # Force HD resolution (if the video was not recorded in this resolution or # if the camera does not support it, the frames will be stretched to fit it) # The intention is just to standardize the input (and make the help window # work as intended) video.set(cv2.CAP_PROP_FRAME_WIDTH, 1280); video.set(cv2.CAP_PROP_FRAME_HEIGHT, 720); # Create the helper class data = VideoData() # Text settings font = cv2.FONT_HERSHEY_SIMPLEX scale = 1 thick = 1 glow = 3 * thick # Color settings color = (255, 255, 255) paused = False frameNum = 0 # Process the video input while True: if not paused: start = datetime.now() ret, img = video.read() if ret: frame = img.copy() else: paused = True drawInfo(frame, frameNum, frameCount, paused, fps, args.source) data.detect(frame) data.draw(frame) cv2.imshow(sourceName, frame) if paused: key = cv2.waitKey(0) else: end = datetime.now() delta = (end - start) if fps != 0: delay = int(max(1, ((1 / fps) - delta.total_seconds()) * 1000)) else: delay = 1 key = cv2.waitKey(delay) if key == ord('q') or key == ord('Q') or key == 27: break elif key == ord('p') or key == ord('P'): paused = not paused elif args.source == 'video' and (key == ord('r') or key == ord('R')): frameNum = 0 video.set(cv2.CAP_PROP_POS_FRAMES, frameNum) elif args.source == 'video' and paused and key == 2424832: # Left key frameNum -= 1 if frameNum < 0: frameNum = 0 video.set(cv2.CAP_PROP_POS_FRAMES, frameNum) elif args.source == 'video' and paused and key == 2555904: # Right key frameNum += 1 if frameNum >= frameCount: frameNum = frameCount - 1 elif args.source == 'video' and key == 2162688: # Pageup key frameNum -= (fps * 10) if frameNum < 0: frameNum = 0 video.set(cv2.CAP_PROP_POS_FRAMES, frameNum) elif args.source == 'video' and key == 2228224: # Pagedown key frameNum += (fps * 10) if frameNum >= frameCount: frameNum = frameCount - 1 video.set(cv2.CAP_PROP_POS_FRAMES, frameNum) elif key == 7340032: # F1 showHelp(sourceName, frame.shape) if not paused: frameNum += 1 video.release() cv2.destroyAllWindows() #--------------------------------------------- def drawInfo(frame, frameNum, frameCount, paused, fps, source): """ Draws text info related to the given frame number into the frame image. Parameters ---------- image: numpy.ndarray Image data where to draw the text info. frameNum: int Number of the frame of which to drawn the text info. frameCount: int Number total of frames in the video. paused: bool Indication if the video is paused or not. fps: int Frame rate (in frames per second) of the video for time calculation. source: str Source of the input images (either "video" or "cam"). """ # Font settings font = cv2.FONT_HERSHEY_SIMPLEX scale = 0.5 thick = 1 glow = 3 * thick # Color settings black = (0, 0, 0) yellow = (0, 255, 255) # Print the current frame number and timestamp if source == 'video': text = 'Frame: {:d}/{:d} {}'.format(frameNum, frameCount - 1, '(paused)' if paused else '') else: text = 'Frame: {:d} {}'.format(frameNum, '(paused)' if paused else '') size, _ = cv2.getTextSize(text, font, scale, thick) x = 5 y = frame.shape[0] - 2 * size[1] cv2.putText(frame, text, (x, y), font, scale, black, glow) cv2.putText(frame, text, (x, y), font, scale, yellow, thick) if source == 'video': timestamp = datetime.min + timedelta(seconds=(frameNum / fps)) elapsedTime = datetime.strftime(timestamp, '%H:%M:%S') timestamp = datetime.min + timedelta(seconds=(frameCount / fps)) totalTime = datetime.strftime(timestamp, '%H:%M:%S') text = 'Time: {}/{}'.format(elapsedTime, totalTime) size, _ = cv2.getTextSize(text, font, scale, thick) y = frame.shape[0] - 5 cv2.putText(frame, text, (x, y), font, scale, black, glow) cv2.putText(frame, text, (x, y), font, scale, yellow, thick) # Print the help message text = 'Press F1 for help' size, _ = cv2.getTextSize(text, font, scale, thick) x = frame.shape[1] - size[0] - 5 y = frame.shape[0] - size[1] + 5 cv2.putText(frame, text, (x, y), font, scale, black, glow) cv2.putText(frame, text, (x, y), font, scale, yellow, thick) #--------------------------------------------- def showHelp(windowTitle, shape): """ Displays an image with helping text. Parameters ---------- windowTitle: str Title of the window where to display the help shape: tuple Height and width of the window to create the help image. """ # Font settings font = cv2.FONT_HERSHEY_SIMPLEX scale = 1.0 thick = 1 # Color settings black = (0, 0, 0) red = (0, 0, 255) # Create the background image image = np.ones((shape[0], shape[1], 3)) * 255 # The help text is printed in one line per item in this list helpText = [ 'Controls:', '-----------------------------------------------', '[q] or [ESC]: quits from the application.', '[p]: toggles paused/playing the video/webcam input.', '[r]: restarts the video playback (video input only).', '[left/right arrow]: displays the previous/next frame (video input only).', '[page-up/down]: rewinds/fast forwards by 10 seconds (video input only).', ' ', ' ', 'Press any key to close this window...' ] # Print the controls help text xCenter = image.shape[1] // 2 yCenter = image.shape[0] // 2 margin = 20 # between-lines margin in pixels textWidth = 0 textHeight = margin * (len(helpText) - 1) lineHeight = 0 for line in helpText: size, _ = cv2.getTextSize(line, font, scale, thick) textHeight += size[1] textWidth = size[0] if size[0] > textWidth else textWidth lineHeight = size[1] if size[1] > lineHeight else lineHeight x = xCenter - textWidth // 2 y = yCenter - textHeight // 2 for line in helpText: cv2.putText(image, line, (x, y), font, scale, black, thick * 3) cv2.putText(image, line, (x, y), font, scale, red, thick) y += margin + lineHeight # Show the image and wait for a key press cv2.imshow(windowTitle, image) cv2.waitKey(0) #--------------------------------------------- def parseCommandLine(argv): """ Parse the command line of this utility application. This function uses the argparse package to handle the command line arguments. In case of command line errors, the application will be automatically terminated. Parameters ------ argv: list of str Arguments received from the command line. Returns ------ object Object with the parsed arguments as attributes (refer to the documentation of the argparse package for details) """ parser = argparse.ArgumentParser(description='Tests the face and emotion ' 'detector on a video file input.') parser.add_argument('source', nargs='?', const='Yes', choices=['video', 'cam'], default='cam', help='Indicate the source of the input images for ' 'the detectors: "video" for a video file or ' '"cam" for a webcam. The default is "cam".') parser.add_argument('-f', '--file', metavar='<name>', help='Name of the video file to use, if the source is ' '"video". The supported formats depend on the codecs ' 'installed in the operating system.') parser.add_argument('-i', '--id', metavar='<number>', default=0, type=int, help='Numerical id of the webcam to use, if the source ' 'is "cam". The default is 0.') args = parser.parse_args() if args.source == 'video' and args.file is None: parser.error('-f is required when source is "video"') return args #--------------------------------------------- # namespace verification for invoking main #--------------------------------------------- if __name__ == '__main__': main(sys.argv[1:])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 262, 2295, 36083, 1628, 13, 383, 1844, 2723, 2438, 318, 198, 2, 1695, 379, 3740, 1378, 12567, 13, 785, 14, 2290, 328, 452, 494, 8704, 14, 368, ...
2.48976
4,590
from . import Konform
[ 6738, 764, 1330, 17431, 687, 628 ]
3.833333
6
""" Holds global celery application state and startup / shutdown handlers. """ from celery import Celery from celery.app import app_or_default from celery.signals import ( beat_init, worker_process_init, worker_process_shutdown, setup_logging, ) from ichnaea.log import configure_logging from ichnaea.taskapp.config import ( configure_celery, init_beat, init_worker, shutdown_worker, ) celery_app = Celery("ichnaea.taskapp.app") configure_celery(celery_app)
[ 37811, 198, 39, 10119, 3298, 18725, 1924, 3586, 1181, 290, 13693, 1220, 18325, 32847, 13, 198, 37811, 198, 6738, 18725, 1924, 1330, 15248, 1924, 198, 6738, 18725, 1924, 13, 1324, 1330, 598, 62, 273, 62, 12286, 198, 6738, 18725, 1924, 13...
2.736264
182
import asyncio from typing import Tuple import heapq
[ 11748, 30351, 952, 198, 6738, 19720, 1330, 309, 29291, 198, 198, 11748, 24575, 80, 628, 198 ]
3.5
16
# Copyright 2017 Lajos Gerecs, Janos Czentye # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import importlib import logging import os import sys import threading from collections import Iterable import pexpect import yaml from yaml.error import YAMLError log = logging.getLogger() def kill_process (self): """ Kill the process and call the optional hook function. """ log.debug("Kill process...") self.stop() self.__killed = True if self.is_alive: self._process.terminate(force=True) def stop (self): """ Stop the process. :return: None """ log.debug("Terminate program under test: %s" % self) if self._process: self._process.sendcontrol('c') if self.is_alive: self._process.terminate() def get_process_output_stream (self): """ :return: Return with the process buffer. """ return self._process.before if self._process.before else "" class ESCAPECommandRunner(CommandRunner): """ Extended CommandRunner class for ESCAPE. Use threading.Event for signalling ESCAPE is up. """ ESC_PARAM_QUIT = "--quit" ESC_PARAM_SERVICE = "--service" def execute (self, wait_for_up=True): """ Create and start the process. Block until the process ends or timeout is exceeded. """ log.debug("\nStart program under test...") log.debug(self._command) try: self._process = pexpect.spawn(self._command[0], args=self._command[1:], timeout=self.kill_timeout, cwd=self._cwd, logfile=self.output_stream) if wait_for_up: self._process.expect(pattern="ESCAPEv2 is up") self.__ready.set() self._process.expect(pexpect.EOF) return self except pexpect.TIMEOUT: log.debug("Process running timeout(%ss) is exceeded!" % self.kill_timeout) self.kill_process() self.timeouted = True except pexpect.ExceptionPexpect as e: log.error("Got unexpected error:\n%s" % e.message) log.debug("\n\nError details:\n%s" % self._process.before) self.kill_process() def test (self, timeout=CommandRunner.KILL_TIMEOUT): """ Start a presumably simple process and test if the process is executed successfully within the timeout interval or been killed. :param timeout: use the given timeout instead of the default kill timeout :type timeout: int :return: the process is stopped successfully :rtype: bool """ try: proc = pexpect.spawn(self._command[0], args=self._command[1:], cwd=self._cwd, timeout=timeout) proc.expect(pexpect.EOF) return True except pexpect.ExceptionPexpect: return False class RunnableTestCaseInfo(object): """ Container class for storing the relevant information and config values of a test case. """ CONFIG_FILE_NAME = "test-config.yaml" CONFIG_CONTAINER_NAME = "test" RUNNER_SCRIPT_NAME = "run.sh" README_FILE_NAME = "README.txt" def readme (self): """ :return: load the README file :rtype: str """ with open(os.path.join(self.full_testcase_path, self.README_FILE_NAME)) as f: readme = f.read() return readme if readme else "" def load_test_case_class (self): """ :return: Return the TestCase class and it's parameters defined in the test case config file :rtype: tuple(object, dict) """ test_args = {} try: with open(self.config_file_name, 'r') as f: config = yaml.safe_load(f) except (IOError, YAMLError) as e: log.error("Failed to load configuration file: %s" % e) return None if self.CONFIG_CONTAINER_NAME in config: test_args = copy.copy(config[self.CONFIG_CONTAINER_NAME]) try: m = test_args.pop('module') c = test_args.pop('class') return getattr(importlib.import_module(m), c), test_args except (KeyError, ImportError): pass return None, test_args
[ 2, 15069, 2177, 406, 1228, 418, 402, 567, 6359, 11, 2365, 418, 327, 89, 3787, 68, 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, ...
2.503763
1,860
from microbit import * hands = Image.ALL_CLOCKS #A centre dot of brightness 2. ticker_image = Image("2\n").crop(-2,-2,5,5) #Adjust these to taste MINUTE_BRIGHT = 0.1111 HOUR_BRIGHT = 0.55555 #Generate hands for 5 minute intervals #Generate hands with ticker superimposed for 1 minute intervals. #Run a clock speeded up 60 times, so we can watch the animation. for tick in ticks(): display.show(tick) sleep(200)
[ 6738, 4580, 2545, 1330, 1635, 198, 198, 43365, 796, 7412, 13, 7036, 62, 5097, 11290, 50, 198, 198, 2, 32, 7372, 16605, 286, 22204, 362, 13, 198, 83, 15799, 62, 9060, 796, 7412, 7203, 17, 59, 77, 11074, 31476, 32590, 17, 12095, 17, ...
2.924138
145
#Variables #Working with build 2234 saberPort = "/dev/ttyUSB0" #Initializing Motorcontroller saber = Runtime.start("saber", "Sabertooth") saber.connect(saberPort) sleep(1) #Initializing Joystick joystick = Runtime.start("joystick","Joystick") print(joystick.getControllers()) python.subscribe("joystick","publishJoystickInput") joystick.setController(0) for x in range(0,100): print("power", x) saber.driveForwardMotor1(x) sleep(0.5) for x in range(100,-1,-1): print("power", x) saber.driveForwardMotor1(x) sleep(0.5)
[ 2, 23907, 2977, 198, 2, 28516, 351, 1382, 362, 24409, 198, 82, 27359, 13924, 796, 12813, 7959, 14, 42852, 27155, 15, 1, 198, 198, 2, 24243, 2890, 12533, 36500, 198, 82, 27359, 796, 43160, 13, 9688, 7203, 82, 27359, 1600, 366, 39646, ...
2.693878
196
# -*- coding: utf-8 -*- # This file is part of Weevely NG. # # Copyright(c) 2011-2012 Weevely Developers # http://code.google.com/p/weevely/ # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import base64, codecs from random import random, randrange, choice, shuffle from pollution import pollute_with_static_str from core.utils import randstr from core.moduleexception import ModuleException from string import Template, ascii_letters, digits PERMITTED_CHARS = ascii_letters + digits + '_.~' WARN_SHORT_PWD = 'Invalid password, use words longer than 3 characters' WARN_CHARS = 'Invalid password, password permitted chars are \'%s\'' % PERMITTED_CHARS
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 770, 2393, 318, 636, 286, 775, 44655, 306, 39058, 13, 198, 2, 198, 2, 15069, 7, 66, 8, 2813, 12, 6999, 775, 44655, 306, 34152, 198, 2, 2638, 1378, 8189, 13, 132...
3.362857
350
from musicscore.dtd.dtd import Sequence, GroupReference, Choice, Element from musicscore.musicxml.attributes.optional_unique_id import OptionalUniqueId from musicscore.musicxml.attributes.printobject import PrintObject from musicscore.musicxml.groups.common import Editorial from musicscore.musicxml.elements.xml_element import XMLElement from musicscore.musicxml.types.complextypes.arpeggiate import ComplexTypeArpeggiate from musicscore.musicxml.types.complextypes.articulations import ComplexTypeArticulations from musicscore.musicxml.types.complextypes.complextype import ComplexType from musicscore.musicxml.types.complextypes.dynamics import Dynamics from musicscore.musicxml.types.complextypes.fermata import ComplexTypeFermata from musicscore.musicxml.types.complextypes.ornaments import ComplexTypeOrnaments from musicscore.musicxml.types.complextypes.slide import ComplexTypeSlide from musicscore.musicxml.types.complextypes.slur import ComplexTypeSlur from musicscore.musicxml.types.complextypes.technical import ComplexTypeTechnical from musicscore.musicxml.types.complextypes.tied import ComplexTypeTied from musicscore.musicxml.types.complextypes.tuplet import ComplexTypeTuplet
[ 6738, 1928, 873, 7295, 13, 67, 8671, 13, 67, 8671, 1330, 45835, 11, 4912, 26687, 11, 18502, 11, 11703, 198, 6738, 1928, 873, 7295, 13, 28965, 19875, 13, 1078, 7657, 13, 25968, 62, 34642, 62, 312, 1330, 32233, 40257, 7390, 198, 6738, ...
3.362117
359
from types import SimpleNamespace from src.utils.keyboard import create_keyboard keys = SimpleNamespace( settings=':gear: Settings', cancel=':cross_mark: Cancel', back=':arrow_left: Back', next=':arrow_right: Next', add=':heavy_plus_sign: Add', edit=':pencil: Edit', save=':check_mark_button: Save', delete=':wastebasket: Delete', yes=':white_check_mark: Yes', no=':negetive_squared_cross_mark: No', ask_question=':red_question_mark: Ask a question', send_question=':envelope_with_arrow: Send question', ) keyboards = SimpleNamespace( main=create_keyboard(keys.ask_question, keys.settings), ask_question=create_keyboard(keys.cancel, keys.send_question), ) states = SimpleNamespace( main='MAIN', ask_question='ASK_QUESTION' )
[ 6738, 3858, 1330, 17427, 36690, 10223, 198, 198, 6738, 12351, 13, 26791, 13, 2539, 3526, 1330, 2251, 62, 2539, 3526, 628, 198, 13083, 796, 17427, 36690, 10223, 7, 198, 220, 220, 220, 6460, 28, 10354, 31763, 25, 16163, 3256, 198, 220, ...
2.646667
300
# Author: Guilherme Aldeia # Contact: guilherme.aldeia@ufabc.edu.br # Version: 1.0.0 # Last modified: 08-20-2021 by Guilherme Aldeia """ Simple exception that is raised by explainers when they don't support local or global explanations, or when they are not model agnostic. This should be catched and handled in the experiments. """
[ 2, 6434, 25, 220, 1962, 346, 372, 1326, 15586, 68, 544, 201, 198, 2, 14039, 25, 915, 346, 372, 1326, 13, 35885, 544, 31, 3046, 39305, 13, 15532, 13, 1671, 201, 198, 2, 10628, 25, 352, 13, 15, 13, 15, 201, 198, 2, 4586, 9518, 2...
3.044248
113
import click from covid_data_tracker.registry import PluginRegistry def plugin_selector(selected_country: str): """plugin selector uses COUNTRY_MAP to find the appropriate plugin for a given country. Parameters ---------- selected_country : str specify the country of interest. Returns ------- covid_data_tracker.plugins.BasePlugin More appropriately, returns an instance of a country-specific subclass of BasePlugin. """ if selected_country in PluginRegistry.keys(): klass = PluginRegistry[selected_country] instance = klass() else: raise AttributeError click.echo('No country plugin available') return instance def country_downloader(country: str): """Finds country plugin, fetches data, and downloads to csv with click alerts. Parameters ---------- country : str Name of country Returns ------- NoneType """ click.echo(f"selecting plugin for {country}") country_plugin = plugin_selector(country) click.echo(f"attempting to find available data for {country}") country_plugin.fetch() click.echo(f"downloading available data for {country}") country_plugin.check_instance_attributes() country_plugin.download()
[ 11748, 3904, 198, 6738, 39849, 312, 62, 7890, 62, 2213, 10735, 13, 2301, 4592, 1330, 42636, 8081, 4592, 628, 198, 4299, 13877, 62, 19738, 273, 7, 34213, 62, 19315, 25, 965, 2599, 198, 220, 220, 220, 37227, 33803, 31870, 3544, 31404, 4...
2.899777
449
import selenium from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException print("everything ok")
[ 11748, 384, 11925, 1505, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 220, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 1525, 1330, 2750, 220, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11284, 13, 9019, 1330,...
3.494118
85
from setuptools import setup setup(name='osmuf', version='0.1', install_requires=[ "seaborn", ], description='Urban Form analysis from OpenStreetMap', url='http://github.com/atelierlibre/osmuf', author='AtelierLibre', author_email='mail@atelierlibre.org', license='MIT', packages=['osmuf'], zip_safe=False)
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 3672, 11639, 418, 76, 3046, 3256, 198, 220, 220, 220, 220, 220, 2196, 11639, 15, 13, 16, 3256, 198, 220, 220, 220, 220, 220, 2721, 62, 47911, 41888, 198, 220, 220, 220, 220, ...
2.222222
171
# -*- coding: utf-8 -*- """ tests.test_model ~~~~~~~~~~~~~~~~ Tests the models provided by the updown rating app :copyright: 2016, weluse (https://weluse.de) :author: 2016, Daniel Banck <dbanck@weluse.de> :license: BSD, see LICENSE for more details. """ from __future__ import unicode_literals import random from django.test import TestCase from django.contrib.auth.models import User from updown.models import SCORE_TYPES from updown.exceptions import CannotChangeVote from tests.models import RatingTestModel
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41989, 13, 9288, 62, 19849, 198, 27156, 198, 198, 51, 3558, 262, 4981, 2810, 416, 262, 2325, 593, 7955, 598, 198, 198, 25, 22163, 4766, 25, 1584, 11, 5029,...
3.152439
164
import sys,os from typing import List from collections import defaultdict, Counter from itertools import groupby, chain, product import heapq from pprint import pprint import string
[ 11748, 25064, 11, 418, 198, 6738, 19720, 1330, 7343, 198, 6738, 17268, 1330, 4277, 11600, 11, 15034, 198, 6738, 340, 861, 10141, 1330, 1448, 1525, 11, 6333, 11, 1720, 198, 11748, 24575, 80, 198, 6738, 279, 4798, 1330, 279, 4798, 198, ...
2.890411
73
import numpy as np import openturns as ot def func_overflow(X, model=1, h_power=0.6): """Overflow model function. Parameters ---------- X : np.ndarray, shape : N x 8 Input variables - x1 : Flow, - x2 : Krisler Coefficient, - x3 : Zv, etc... model : bool, optional(default=1) If 1, the classical model. If 2, the economic model. Returns ------- Overflow S (if model=1) or Cost Cp (if model=2). """ X = np.asarray(X) if X.shape[0] == X.size: # It's a vector n = 1 dim = X.size ids = None else: n, dim = X.shape ids = range(n) assert dim == 8, "Incorect dimension : dim = %d != 8" % dim Q = X[ids, 0] Ks = X[ids, 1] Zv = X[ids, 2] Zm = X[ids, 3] Hd = X[ids, 4] Cb = X[ids, 5] L = X[ids, 6] B = X[ids, 7] H = (Q / (B * Ks * np.sqrt((Zm - Zv) / L)))**h_power S = Zv + H - Hd - Cb if model == 1: return S elif model == 2: Cp = (S > 0.) + (0.2 + 0.8 * (1. - np.exp(-1000. / (S**4)))) * (S <= 0.) + 1./20. * (Hd * (Hd > 8.) + 8*(Hd <= 8.)) return Cp else: raise AttributeError('Unknow model.') tmp = ot.Gumbel() tmp.setParameter(ot.GumbelMuSigma()([1013., 558.])) dist_Q = ot.TruncatedDistribution(tmp, 500., 3000.) dist_Ks = ot.TruncatedNormal(30., 8., 15., np.inf) dist_Zv = ot.Triangular(49., 50., 51.) dist_Zm = ot.Triangular(54., 55., 56.) dist_Hd = ot.Uniform(7., 9.) dist_Cb = ot.Triangular(55., 55.5, 56.) dist_L = ot.Triangular(4990., 5000., 5010.) dist_B = ot.Triangular(295., 300., 305.) margins_overflow = [dist_Q, dist_Ks, dist_Zv, dist_Zm, dist_Hd, dist_Cb, dist_L, dist_B] var_names_overflow = ["Q", "K_s", "Z_v", "Z_m", "H_d", "C_b", "L", "B"] def func_sum(x, a=None): """Additive weighted model function. Parameters ---------- x : np.ndarray The input values. a : np.ndarray The input coefficients. Returns ------- y : a.x^t """ if isinstance(x, list): x = np.asarray(x) n, dim = x.shape if a is None: a = np.ones((dim, 1)) if a.ndim == 1: a = a.reshape(-1, 1) assert a.shape[0] == dim, "Shape not good" elif a.ndim > 2: raise AttributeError('Dimension problem for constant a') y = np.dot(x, a) if y.size == 1: return y.item() elif y.size == y.shape[0]: return y.ravel() else: return y def func_prod(x, a=None): """Product weighted model function. Parameters ---------- x : np.ndarray The input values. a : np.ndarray The input coefficients. Returns ------- y : a.x^t """ if isinstance(x, list): x = np.asarray(x) n, dim = x.shape if a is None: a = np.ones((dim, 1)) if a.ndim == 1: a = a.reshape(-1, 1) assert a.shape[0] == dim, "Shape not good" elif a.ndim > 2: raise AttributeError('Dimension problem for constant a') y = np.sum(x, axis=1) if y.size == 1: return y.item() elif y.size == y.shape[0]: return y.ravel() else: return y def func_spec(x, a=[0.58, -1, -1.0, 0, 0., 0.]): """Product weighted model function. Parameters ---------- x : np.ndarray The input values. a : np.ndarray The input coefficients. Returns ------- y : a.x^t """ if isinstance(x, list): x = np.asarray(x) n, dim = x.shape y = a[0]*(x**2).prod(axis=1) + \ a[1]*x.prod(axis=1) + \ a[2]*(x**2).sum(axis=1) + \ a[3] * x.sum(axis=1) + \ a[4] * np.sin(x).sum(axis=1) + \ a[5] * np.cos(x).sum(axis=1) if y.size == 1: return y.item() elif y.size == y.shape[0]: return y.ravel() else: return y def func_cum_sum_weight(x, weights=None, use_sum=True, const=[0., 0., 0., 1., 0., 0.]): """Additive weighted model function. Parameters ---------- x : np.ndarray The input values. weights : np.ndarray The input coefficients. Returns ------- y : a.x^t """ if isinstance(x, list): x = np.asarray(x) n, dim = x.shape if weights is None: weights = np.zeros((dim, dim)) corr_dim = dim * (dim-1)/2 k = 1 for i in range(1, dim): for j in range(i): weights[i, j] = k k += 1 weights /= corr_dim if weights.ndim == 1: weights = weights.reshape(-1, 1) assert weights.shape[0] == dim, "Shape not good" elif weights.ndim > 2: raise AttributeError('Dimension problem for constant a') if use_sum: y = 1 for i in range(1, dim): for j in range(i): y *= (1. + weights[i, j] * func_spec(np.c_[x[:, i], x[:, j]], a=const)) else: y = 0 for i in range(1, dim): for j in range(i): y += weights[i, j] * func_spec(np.c_[x[:, i], x[:, j]], a=const) return y def multi_output_func_sum(x, output_dim=2): """Additive model function with multi output. Parameters ---------- x : np.ndarray The input values. output_dim : int The number of output dimension. Returns ------- y : [i * x] """ return np.asarray([x.sum(axis=1)*a for a in range(output_dim)]).T
[ 11748, 299, 32152, 355, 45941, 198, 11748, 1034, 298, 700, 82, 355, 30972, 198, 198, 4299, 25439, 62, 2502, 11125, 7, 55, 11, 2746, 28, 16, 11, 289, 62, 6477, 28, 15, 13, 21, 2599, 198, 220, 220, 220, 37227, 5886, 11125, 2746, 216...
1.921394
2,926
from flask_wtf import FlaskForm from wtforms import StringField,TextAreaField,SubmitField from wtforms.validators import Required # class LoginForm(FlaskForm): # email = StringField('Your Email Address',validators=[Required(),Email()]) # password = PasswordField('Password',validators =[Required()]) # remember = BooleanField('Remember me') # submit = SubmitField('Sign In')
[ 198, 6738, 42903, 62, 86, 27110, 1330, 46947, 8479, 198, 6738, 266, 83, 23914, 1330, 10903, 15878, 11, 8206, 30547, 15878, 11, 45135, 15878, 198, 6738, 266, 83, 23914, 13, 12102, 2024, 1330, 20906, 198, 2, 1398, 23093, 8479, 7, 7414, ...
3.37931
116
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette import status from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.requests import Request from starlette.responses import Response from starlette.types import ASGIApp from config import APISettings, CORSSettings, FastAPISettings, PayPalSettings, UvicornSettings, ShopSettings, NowPaymentsSettings import logging #### # Custom Middlewares # #### #### # # #### logging.basicConfig(filename="log.log", level=logging.INFO, format=f'%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s') logger = logging.getLogger(__name__) app = FastAPI(debug=FastAPISettings.DEBUG) app.add_middleware( CORSMiddleware, allow_origins=CORSSettings.ALLOW_ORIGINS, allow_methods=['*'], allow_headers=['*'] ) if UvicornSettings.MAX_CONTENT_SIZE: app.add_middleware( LimitPostContentSizeMiddleware, max_upload_size=UvicornSettings.MAX_CONTENT_SIZE ) if __name__== '__main__': import uvicorn uvicorn.run('main:app', reload=UvicornSettings.USE_RELOADER, log_level=UvicornSettings.LOG_LEVEL, port=UvicornSettings.PORT)
[ 6738, 3049, 15042, 1330, 12549, 17614, 198, 6738, 3049, 15042, 13, 27171, 1574, 13, 66, 669, 1330, 23929, 12310, 2509, 1574, 198, 198, 6738, 3491, 21348, 1330, 3722, 198, 6738, 3491, 21348, 13, 27171, 1574, 13, 8692, 1330, 7308, 6535, 5...
2.907268
399
"""Semi continuous unit operations. Unit operations that accept constant or box-shaped flow rate profile and provide periodic flow rate profile. """ __all__ = ['AlternatingChromatography', 'ACC', 'PCC', 'PCCWithWashDesorption'] __version__ = '0.7.1' __author__ = 'Jure Sencar' import typing as _typing import numpy as _np import scipy.interpolate as _interp from bio_rtd.chromatography import bt_load as _bt_load import bio_rtd.utils as _utils import bio_rtd.core as _core import bio_rtd.pdf as _pdf
[ 37811, 13900, 72, 12948, 4326, 4560, 13, 198, 198, 26453, 4560, 326, 2453, 6937, 393, 3091, 12, 16760, 5202, 2494, 7034, 198, 392, 2148, 27458, 5202, 2494, 7034, 13, 198, 198, 37811, 198, 834, 439, 834, 796, 37250, 23081, 803, 1925, 3...
3.02381
168
import matplotlib.pyplot as plt if __name__ == '__main__': main()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 1388, 3419, 198 ]
2.535714
28
#!/usr/bin/python3 import json from aioflureedb.signing import DbSigner privkey = "bf8a7281f43918a18a3feab41d17e84f93b064c441106cf248307d87f8a60453" address = "1AxKSFQ387AiQUX6CuF3JiBPGwYK5XzA1A" signer = DbSigner(privkey, address, "something/test") free_test(signer)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 11748, 33918, 198, 6738, 257, 952, 2704, 495, 276, 65, 13, 12683, 278, 1330, 360, 65, 11712, 263, 198, 198, 13776, 2539, 796, 366, 19881, 23, 64, 22, 30368, 69, 47106, 1507, 64, 1507, ...
2.045455
132
# Copyright 2016 Brocade Communications Systems, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from ne_base import NosDeviceAction from ne_base import log_exceptions import itertools
[ 2, 15069, 1584, 2806, 46395, 14620, 11998, 11, 3457, 13, 198, 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,...
3.905028
179
#!/usr/bin/env python3 ### # Based on signature.R ### import sys,os,logging import numpy as np import pandas as pd if __name__=="__main__": logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) if (len(sys.argv) < 3): logging.error("3 file args required, LINCS sig info for GSE70138 and GSE92742, and output file.") sys.exit(1) fn1 = sys.argv[1] #GSE70138_Broad_LINCS_sig_info_2017-03-06.txt.gz fn2 = sys.argv[2] #GSE92742_Broad_LINCS_sig_info.txt.gz ofile = sys.argv[3] #signature.tsv # part1 = pd.read_table(fn1, "\t", na_values=["-666", "-666.0"]) logging.info(f"columns: {part1.columns}") part1 = part1[["sig_id", "pert_id", "pert_iname", "pert_type", "cell_id", "pert_idose", "pert_itime"]] # part2 = pd.read_table(fn2, "\t", na_values=["-666", "-666.0"], dtype="str") part2.pert_time = part2.pert_time.astype(np.int32) logging.info(f"columns: {part2.columns}") part2 = part2[["sig_id", "pert_id", "pert_iname", "pert_type", "cell_id", "pert_idose", "pert_itime"]] # sign = pd.concat([part1, part2]) sign.drop_duplicates(subset=["sig_id"], keep="first", inplace=True) sign.to_csv(ofile, "\t", index=False)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 21017, 198, 2, 13403, 319, 9877, 13, 49, 198, 21017, 198, 198, 11748, 25064, 11, 418, 11, 6404, 2667, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 19...
2.260038
523
# ASSIGNMENT 3 """ During a programming contest, each contestant had to solve 3 problems (named P1, P2 and P3). Afterwards, an evaluation committee graded the solutions to each of the problems using integers between 0 and 10. The committee needs a program that will allow managing the list of scores and establishing the winners. Write a program that implements the functionalities exemplified below: (A) Add the result of a new participant (add, insert) (B) Modify scores (remove, remove between two postion, replace the score obtained by a certain participant at a certain problem with other score obtained by other participant) (C) Display participants whose score has different properties. """ def get(list, position): """ The function will extract a certain element from a list.""" return list[int(position)] def set(list, element, position): """ The functin will set a certain element from a list. :param list: [ ['2', '4', '8'], ['3', '5', '6'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'] ] :param element: ['5', '8', '9'] :param position: 1 :return: [ ['2', '4', '8'], ['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'] """ list.insert(int(position), element) list.remove(get(list, int(position) + 1)) def make_a_list(sentence): """ The function will make a list containing the given scores P1, P2 and P3 that are found in the command.""" list_one_score = [] for i in range(1, 4): list_one_score.append(sentence[i]) return list_one_score def add_scores(list, sentence): """ The function will add to the principal list (with all the scores of all the participants) a list with the scores of just one participant. """ list.append(make_a_list(sentence)) def insert_scores(list, sentence, position): """ The function will insert in a given position to the principal list (with all the scores of all the participants) a list with the scores of just one participant """ list.insert(int(position), make_a_list(sentence)) def remove_one_part(list, position): """ The function will set the scores of the participant at a given position to 0. So that, the participant <position> score P1=P2=P3= 0. """ nul_element = ['0', '0', '0'] set(list, nul_element, position) def remove_more_part(list, first_position, last_position): """ The function will set the scores of all the participants between the first position and last position to 0. For all the participants between <first_position> and <last_position>, P1=P1=P3= 0 """ nul_element = ['0', '0', '0'] for i in range(int(first_position), int(last_position) + 1): set(list, nul_element, i) def replace(list, problem, new_score): """ The function will replace a score obtained by a participant at a specific problem with a new score. List represents the list with the scores of a participant, where <problem> ( P1/P2/P3 ) will recive a new score """ set(list, new_score, int(problem[1]) - 1) def calc_average(list): """ The function will calculate the average of all the integers from a list ( it will calculate the sum of al the integers, and then it will divide the sum by the value of the len of tne list) :param list: [ '2', '4', '3' ] :return: 3 """ result = 0 for i in range(0, len(list)): result = result + int(get(list, i)) return result / len(list) def average_score_lesser(list, number): """ The function will display all the participants with an average score lesser than the given number. :param list: [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']] :param number: 7 :return:['10', '4', '6'], ['9', '3', '2'] """ l = [] # l is the required list for i in range(0, len(list)): if calc_average(get(list, i)) < number: l.append(get(list, i)) return l def average_score_equal(list, number): """ The function will display all the participants with an average score equal with the given number. :param list: [['5', '8', '9'], ['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']] :param number: 8 :return:['7', '8', '9'] """ l = [] # l is the required list for i in range(0, len(list)): if calc_average(get(list, i)) == number: l.append(get(list, i)) return l def average_score_greater(list, number): """ The function will return a list with all the participants with an average score greater than the given number. :param list: [['10', '4', '6'], ['9', '3', '2'], ['10', '10', '10'], ['7', '8', '9']] :param number: 7 :return: [['10', '10', '10'], ['7', '8', '9']] """ l = [] # l is the required list for i in range(0, len(list)): if calc_average(get(list, i)) > number: l.append(get(list, i)) return l def list_sorted(list): """ The function will return a list with participants sorted in decreasing order of average score :param list: [['5', '8', '9'], ['10', '4', '6'], ['10', '10', '10'], ['7', '8', '9'], ['10', '2', '9']] :return: [['10', '10', '10'], , ['7', '8', '9'], ['5', '8', '9'], ['10', '2', '9'], ['10', '4', '6']] """ l = [] for i in range(0, len(list)): get(list, i).insert(0, calc_average(get(list, i))) l.append(get(list, i)) l.sort(reverse=True) for i in range(0, len(l)): get(l, i) get(l, i).remove(get(get(l, i), 0)) return l if __name__ == '__main__': print_menu() run_menu()
[ 2, 24994, 16284, 10979, 513, 198, 37811, 198, 220, 220, 220, 5856, 257, 8300, 8414, 11, 1123, 44047, 550, 284, 8494, 513, 2761, 357, 13190, 350, 16, 11, 350, 17, 290, 350, 18, 737, 198, 220, 220, 220, 39063, 11, 281, 12660, 5583, ...
2.640111
2,159
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Examples for the NURBS-Python Package Released under MIT License Developed by Onur Rauf Bingol (c) 2016-2017 """ import os from geomdl import BSpline from geomdl import utilities from geomdl import exchange from geomdl import operations from geomdl.visualization import VisPlotly # Fix file path os.chdir(os.path.dirname(os.path.realpath(__file__))) # Create a BSpline surface instance surf = BSpline.Surface() # Set degrees surf.degree_u = 3 surf.degree_v = 3 # Set control points surf.set_ctrlpts(*exchange.import_txt("ex_surface02.cpt", two_dimensional=True)) # Set knot vectors surf.knotvector_u = utilities.generate_knot_vector(surf.degree_u, 6) surf.knotvector_v = utilities.generate_knot_vector(surf.degree_v, 6) # Set evaluation delta surf.delta = 0.025 # Evaluate surface surf.evaluate() # Plot the control point grid and the evaluated surface vis_comp = VisPlotly.VisSurface() surf.vis = vis_comp surf.render() # Evaluate surface tangent and normal at the given u and v uv = [0.2, 0.9] surf_tangent = operations.tangent(surf, uv) surf_normal = operations.normal(surf, uv) # Good to have something here to put a breakpoint pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 220, 220, 220, 21066, 329, 262, 399, 4261, 4462, 12, 37906, 15717, 198, 220, 220, 220, 28728, 739, 1...
2.773455
437
#=============================================================================== # Copyright 2020-2021 Intel Corporation # # 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. #=============================================================================== load("@onedal//dev/bazel:repos.bzl", "repos") micromkl_repo = repos.prebuilt_libs_repo_rule( includes = [ "include", "%{os}/include", ], libs = [ "%{os}/lib/intel64/libdaal_mkl_thread.a", "%{os}/lib/intel64/libdaal_mkl_sequential.a", "%{os}/lib/intel64/libdaal_vmlipp_core.a", ], build_template = "@onedal//dev/bazel/deps:micromkl.tpl.BUILD", ) micromkl_dpc_repo = repos.prebuilt_libs_repo_rule( includes = [ "include", ], libs = [ "lib/intel64/libdaal_sycl.a", ], build_template = "@onedal//dev/bazel/deps:micromkldpc.tpl.BUILD", )
[ 2, 23926, 25609, 18604, 198, 2, 15069, 12131, 12, 1238, 2481, 8180, 10501, 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,...
2.771084
498
## Generated by pyxsdgen from xml.etree import ElementTree as ET # types POINT2POINT_NS = 'http://schemas.ogf.org/nsi/2013/12/services/point2point' p2ps = ET.QName(POINT2POINT_NS, 'p2ps') capacity = ET.QName(POINT2POINT_NS, 'capacity') parameter = ET.QName(POINT2POINT_NS, 'parameter')
[ 2235, 2980, 515, 416, 12972, 87, 21282, 5235, 198, 198, 6738, 35555, 13, 316, 631, 1330, 11703, 27660, 355, 12152, 198, 198, 2, 3858, 628, 628, 198, 16402, 12394, 17, 16402, 12394, 62, 8035, 796, 705, 4023, 1378, 1416, 4411, 292, 13, ...
2.233577
137
import matplotlib.pyplot as plt import numpy as np x=20 y=1 plt.plot(x,y) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 198, 87, 28, 1238, 198, 88, 28, 16, 198, 198, 489, 83, 13, 29487, 7, 87, 11, 88, 8, 198, 489, 83, 13, 12860, 3419, 198 ]
2.023256
43
import os import sys import argparse import copy import numpy as np import scipy.special sys.path.append(os.getcwd()) def main(args): from nnest import NestedSampler g = GaussianMix() volume_switch = 1.0 / (5 * args.num_slow) sampler = NestedSampler(args.x_dim, loglike, transform=transform, log_dir=args.log_dir, num_live_points=args.num_live_points, hidden_dim=args.hidden_dim, num_layers=args.num_layers, num_blocks=args.num_blocks, num_slow=args.num_slow, use_gpu=args.use_gpu) sampler.run(train_iters=args.train_iters, mcmc_steps=args.mcmc_steps, volume_switch=volume_switch, noise=args.noise) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--x_dim', type=int, default=5, help="Dimensionality") parser.add_argument('--train_iters', type=int, default=2000, help="number of train iters") parser.add_argument("--mcmc_steps", type=int, default=0) parser.add_argument("--num_live_points", type=int, default=1000) parser.add_argument('--switch', type=float, default=-1) parser.add_argument('--hidden_dim', type=int, default=128) parser.add_argument('--num_layers', type=int, default=2) parser.add_argument('--batch_size', type=int, default=100) parser.add_argument('-use_gpu', action='store_true') parser.add_argument('--flow', type=str, default='nvp') parser.add_argument('--num_blocks', type=int, default=5) parser.add_argument('--noise', type=float, default=-1) parser.add_argument('--run_num', type=str, default='') parser.add_argument('--num_slow', type=int, default=2) parser.add_argument('--log_dir', type=str, default='logs/mog4_fast') args = parser.parse_args() main(args)
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 1822, 29572, 198, 11748, 4866, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 20887, 198, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 1136, 66, 16993, 28955, 628, 6...
2.394256
766
__all__ = ['Message'] import uuid from email.header import decode_header as _decode_header from email.message import Message as EmailMessage from email.utils import getaddresses from typing import Union, List, Dict, Any
[ 834, 439, 834, 796, 37250, 12837, 20520, 198, 198, 11748, 334, 27112, 198, 6738, 3053, 13, 25677, 1330, 36899, 62, 25677, 355, 4808, 12501, 1098, 62, 25677, 198, 6738, 3053, 13, 20500, 1330, 16000, 355, 9570, 12837, 198, 6738, 3053, 13,...
3.762712
59
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import unittest if __name__ == '__main__': unittest.main(warnings='ignore')
[ 6738, 384, 11925, 1505, 1330, 3992, 26230, 220, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 1525, 1330, 2750, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11284, 13, 9019, 1330, 5313, 32103, 21321, 198, 6738, 384...
3.197674
86
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Finetuning the library models for sequence classification on GLUE (Bert, XLM, XLNet, RoBERTa, Albert, XLM-RoBERTa).""" import dataclasses import logging import os, math import sys, copy from dataclasses import dataclass, field from typing import Callable, Dict, Optional import numpy as np import torch from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, EvalPrediction, GlueDataset from transformers import BertModel, BertConfig from transformers import GlueDataTrainingArguments as DataTrainingArguments from transformers import ( HfArgumentParser, TrainingArguments, glue_compute_metrics, glue_output_modes, glue_tasks_num_labels, set_seed, ) from my_robustness import MyRandomTokenNoise from my_trainer import MyTrainer from my_glue_dataset import MyGlueDataset from my_modeling_roberta import MyRobertaForSequenceClassification, MyRobertaForNCESequenceClassification from transformers.data.processors.utils import InputFeatures, InputExample #import matplotlib #matplotlib.use('Agg') #import matplotlib.pyplot as plt from my_utils import setLogger #import checklist_utils logger = logging.getLogger() def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments, CustomArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args, my_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args, my_args = parser.parse_args_into_dataclasses() all_args = (model_args, data_args, training_args, my_args) #training_args.learning_rate = my_args.my_learning_rate if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) log_fn = training_args.output_dir + '/log_' + ('train_' if training_args.do_train else '') + ('eval_' if training_args.do_eval else '') + ('evalcalibration_' if my_args.do_eval_calibration else '') + '.txt' print('logger file will be set to', log_fn) os.system('mkdir -p ' + training_args.output_dir) setLogger(logger, log_fn) my_args.log_fn = log_fn for kk in range(5): logger.info('==hostname %s', os.uname()[1]) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, ) logger.info("Training/evaluation parameters %s", training_args) # Set seed set_seed(training_args.seed) try: num_labels = glue_tasks_num_labels[data_args.task_name] output_mode = glue_output_modes[data_args.task_name] except KeyError: raise ValueError("Task not found: %s" % (data_args.task_name)) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) if my_args.train_mode == 'normal': assert('roberta' in model_args.model_name_or_path.lower()) #model = AutoModelForSequenceClassification.from_pretrained( model = MyRobertaForSequenceClassification.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, ) if my_args.train_mode == 'nce_noise': #nce_model = MyRobertaForSequenceClassification(config) assert('roberta' in model_args.model_name_or_path.lower()) model = MyRobertaForNCESequenceClassification.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, ) if my_args.train_from_scratch: print('=== training from scratch! reinitilize weights') embed_bak = copy.deepcopy(model.bert.embeddings) layer_bak = copy.deepcopy(model.bert.encoder.layer) model.init_weights() LL = my_args.layer_num print('=== applying layer_num', LL) # Initializing a BERT bert-base-uncased style configuration new_config = BertConfig(num_hidden_layers=LL) # Initializing a model from the bert-base-uncased style configuration new_bert = BertModel(new_config) print('=== using pretrained embedding') new_bert.embeddings = embed_bak """ for l in range(LL): print('copying encoder layer', l) new_bert.encoder.layer[l] = layer_bak[l] """ model.bert = new_bert model.config.num_hidden_layers = LL nce_noise_train_dataset, nce_noise_eval_dataset = None, None if my_args.train_mode == 'nce_noise' and training_args.do_train: # Get datasets nce_noise_train_dataset = (MyGlueDataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir, special_mode = 'nce_noise', nce_noise_file = my_args.nce_noise_file, mode = 'train', for_noiselm = False, my_args = my_args)) nce_noise_eval_dataset = (MyGlueDataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir, special_mode = 'nce_noise', nce_noise_file = my_args.nce_noise_eval_file, mode = 'dev', for_noiselm = False, my_args = my_args)) # Get datasets train_dataset = ( MyGlueDataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir, my_args = my_args) ) eval_dataset = (MyGlueDataset(data_args, tokenizer=tokenizer, mode="dev", cache_dir=model_args.cache_dir, my_args = my_args)) test_dataset = ( MyGlueDataset(data_args, tokenizer=tokenizer, mode="test", cache_dir=model_args.cache_dir, my_args = my_args) if training_args.do_predict else None ) logger.info('constructing datasets (splitting eval_dataset) for calibration...') dataset_cal_dev1 = copy.deepcopy(eval_dataset) dataset_cal_dev2 = copy.deepcopy(eval_dataset) dataset_cal_tr = copy.deepcopy(train_dataset) cal_num = int(len(eval_dataset) / 2) dataset_cal_dev1.features = dataset_cal_dev1.features[:cal_num] dataset_cal_dev2.features = dataset_cal_dev2.features[-cal_num:] #dataset_cal_tr.features = dataset_cal_tr.features[-cal_num:] logger.info('setting eval_dataset to dataset_cal_dev2...') eval_dataset = dataset_cal_dev2 # Initialize our Trainer trainer = MyTrainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset, compute_metrics=build_compute_metrics_fn(data_args.task_name), tokenizer = tokenizer, my_args = my_args, ) print('=== random_noise_rate:', my_args.my_random_noise_rate) my_noise = MyRandomTokenNoise(tokenizer, my_args.my_random_noise_rate) input_transform = None if my_args.my_random_noise_rate > 0: input_transform = my_noise.add_random_noise # Training final_evalres_savefn = None if training_args.do_train: #if my_args.train_mode == 'nce_noise': # trainer.nce_train(model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None, input_transform = input_transform) #else: set_seed(training_args.seed) #set seed again before constructing suite, so that it will be the same thing when do_eval suite = None #suite = checklist_utils.construct_checklist_suite(model, tokenizer, eval_dataset, all_args) return_d = {} trainer.train(model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None, input_transform = input_transform, train_mode = my_args.train_mode, nce_noise_dataset = nce_noise_train_dataset, nce_noise_ratio = my_args.nce_noise_ratio, nce_noise_bz = my_args.nce_noise_batch_size, nce_mode = my_args.nce_mode, nce_noise_eval_dataset = nce_noise_eval_dataset, return_d = return_d, checklist_suite = suite, all_args = all_args) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir) logger.info('===PRINTING EVAL_RES_LIS===') for eval_res in return_d['eval_res_lis']: logger.info(str(eval_res)) final_evalres_savefn = training_args.output_dir + '/eval_res_save/final_eval_res.save' torch.save(return_d['eval_res_lis'], final_evalres_savefn) logger.info('eval res saved to %s', final_evalres_savefn) final_eval_results, final_checklist_eval_results = {}, {} final_nce_eval_results, final_nce_train_results = {}, {} # evaluation eval_results = {} """ if data_args.task_name == "mnli": mnli_mm_data_args = dataclasses.replace(data_args, task_name="mnli-mm") logger.info('===SWITCHING to mnli-mm for test') eval_dataset = GlueDataset(mnli_mm_data_args, tokenizer=tokenizer, mode="dev", cache_dir=model_args.cache_dir) """ logger.info('seed: %d', training_args.seed) if training_args.do_eval: logger.info("*** evaluate ***") set_seed(training_args.seed) #set seed again before eval # loop to handle mnli double evaluation (matched, mis-matched) eval_datasets = [eval_dataset] #""" #we only look at the matched dev-set for mnli (mm is mismatched) assert(len(eval_datasets) == 1) for eval_dataset in eval_datasets: trainer.compute_metrics = build_compute_metrics_fn(eval_dataset.args.task_name) #prediction_output = trainer.predict(test_dataset=eval_dataset) eval_result = trainer.evaluate(eval_dataset=eval_dataset, input_transform = input_transform) if my_args.train_mode == 'nce_noise': eval_nce_result = trainer.nce_evaluate(nce_noise_eval_dataset) final_nce_eval_results.update(eval_nce_result) train_nce_result = trainer.nce_evaluate(nce_noise_train_dataset, max_step = 500) final_nce_train_results.update(train_nce_result) output_eval_file = os.path.join( training_args.output_dir, f"eval_results_{eval_dataset.args.task_name}.txt" ) if trainer.is_world_master(): with open(output_eval_file, "w") as writer: logger.info("***** eval results {} *****".format(eval_dataset.args.task_name)) for key, value in eval_result.items(): logger.info(" %s = %s", key, value) writer.write("%s = %s\n" % (key, value)) eval_results.update(eval_result) #final_eval_results['eval_acc'] = eval_result['eval_acc'] final_eval_results.update(eval_result) if my_args.do_eval_checklist: logger.info('*** eval checklist***') set_seed(training_args.seed) #set seed again before eval suite = checklist_utils.construct_checklist_suite(model, tokenizer, eval_dataset, all_args) cres = checklist_utils.run_checklist_suite(model, tokenizer, eval_dataset, all_args, given_suite = suite, verbose = True) final_checklist_eval_results.update(cres) """ if data_args.task_name.lower() == 'qqp': cres = checklist_utils.do_checklist_QQP(model, tokenizer, eval_dataset, all_args) final_checklist_eval_results.update(cres) if data_args.task_name.lower() == 'qnli': cres = checklist_utils.do_checklist_QNLI(model, tokenizer, eval_dataset, all_args) final_checklist_eval_results.update(cres) if data_args.task_name.lower() == 'sst-2': cres = checklist_utils.do_checklist_SST2(model, tokenizer, eval_dataset, all_args) final_checklist_eval_results.update(cres) """ """ for checklist_trans in ['typo', 'typo^2']: eval_checklist_dataset = MyGlueDataset(data_args, tokenizer=tokenizer, mode="dev", cache_dir=model_args.cache_dir, checklist_transform = checklist_trans, my_args = my_args) eval_result = trainer.evaluate(eval_dataset=eval_checklist_dataset, input_transform = None) for s in eval_result: final_checklist_eval_results['checklist_{}_{}'.format(checklist_trans, s)] = eval_result[s] """ if my_args.do_eval_noise_robustness: # loop to handle mnli double evaluation (matched, mis-matched) eval_datasets = [eval_dataset] set_seed(training_args.seed) #set seed again before eval """ if data_args.task_name == "mnli": mnli_mm_data_args = dataclasses.replace(data_args, task_name="mnli-mm") eval_datasets.append( GlueDataset(mnli_mm_data_args, tokenizer=tokenizer, mode="dev", cache_dir=model_args.cache_dir) ) """ #we only look at the matched dev-set for mnli (mm is mismatched) for noise_rate in [0.1, 0.2]: logger.info('*** eval_noise_robustness rate: %f ***', noise_rate) my_noise = MyRandomTokenNoise(tokenizer, noise_rate) input_transform = my_noise.add_random_noise assert(len(eval_datasets) == 1) for eval_dataset in eval_datasets: trainer.compute_metrics = build_compute_metrics_fn(eval_dataset.args.task_name) #prediction_output = trainer.predict(test_dataset=eval_dataset) eval_result = trainer.evaluate(eval_dataset=eval_dataset, input_transform = input_transform) output_eval_file = os.path.join( training_args.output_dir, f"eval_results_{eval_dataset.args.task_name}.txt" ) if trainer.is_world_master(): with open(output_eval_file, "w") as writer: logger.info("***** eval results {} *****".format(eval_dataset.args.task_name)) for key, value in eval_result.items(): logger.info(" %s = %s", key, value) writer.write("%s = %s\n" % (key, value)) if 'eval_mnli/acc' in eval_result: eval_result['eval_acc'] = eval_result['eval_mnli/acc'] final_eval_results['randomnoise{}_eval_acc'.format(noise_rate)] = eval_result['eval_acc'] import calibration as cal from my_calibration import TScalCalibrator if my_args.do_eval_calibration: logger.info("*** do calbiration ***") #if data_args.task_name.lower() == 'cola': #it's cola, let's do evaluate for mcc #res = trainer.evaluate(eval_dataset = dataset_cal_dev2) set_seed(training_args.seed) #set seed again before eval drawcal_res = trainer.eval_calibration(dataset_cal_dev2, verbose = True, fig_fn = training_args.output_dir + '/{}_calibration.pdf'.format(data_args.task_name)) save_fn = training_args.output_dir + '/drawcal.save' logger.info('saving drawcal_res to %s', save_fn) torch.save(drawcal_res, save_fn) cal_res = do_cal(trainer, dataset_cal_dev2, do_postcal = False, ss = 'cal_ori_') final_eval_results.update(cal_res) if my_args.do_eval_scaling_binning_calibration: logger.info('*** do scaling_binning calibration ***') set_seed(training_args.seed) cal_res = {} cal_res.update(do_cal(trainer, dataset_cal_dev2, do_postcal = True, do_plattbin = False, do_tscal = True, tr_d = dataset_cal_dev1, ss = 'cal_dev_')) cal_res.update(do_cal(trainer, dataset_cal_dev2, do_postcal = True, do_plattbin = False, do_tscal = True, tr_d = dataset_cal_tr, ss = 'cal_train_')) logger.info('===scaling_binning_calibration %s', str(cal_res)) final_eval_results.update(cal_res) if training_args.do_predict: logging.info("*** Test ***") test_datasets = [test_dataset] if data_args.task_name == "mnli": mnli_mm_data_args = dataclasses.replace(data_args, task_name="mnli-mm") test_datasets.append( GlueDataset(mnli_mm_data_args, tokenizer=tokenizer, mode="test", cache_dir=model_args.cache_dir) ) for test_dataset in test_datasets: predictions = trainer.predict(test_dataset=test_dataset).predictions if output_mode == "classification": predictions = np.argmax(predictions, axis=1) output_test_file = os.path.join( training_args.output_dir, f"test_results_{test_dataset.args.task_name}.txt" ) if trainer.is_world_master(): with open(output_test_file, "w") as writer: logger.info("***** Test results {} *****".format(test_dataset.args.task_name)) writer.write("index\tprediction\n") for index, item in enumerate(predictions): if output_mode == "regression": writer.write("%d\t%3.3f\n" % (index, item)) else: item = test_dataset.get_labels()[item] writer.write("%d\t%s\n" % (index, item)) if my_args.do_energy_analysis: logger.info('*** do_energy_analysis ***') eval_dataloader = trainer.get_eval_dataloader(dataset_cal_dev2) logger.info('loading baseline model...') if data_args.task_name.lower() == 'sst-2': base_model = MyRobertaForSequenceClassification.from_pretrained('./exps/glue_baseline_roberta-base/SST-2/LR2e-5BA32MAXSTEP5233WARMSTEP314/') if data_args.task_name.lower() == 'qnli': base_model = MyRobertaForSequenceClassification.from_pretrained('./exps/glue_baseline_roberta-base/QNLI/LR2e-5BA32MAXSTEP8278WARMSTEP496') if data_args.task_name.lower() == 'mrpc': base_model = MyRobertaForSequenceClassification.from_pretrained('./exps/glue_baseline_roberta-base/MRPC/LR1e-5BA16MAXSTEP2296WARMSTEP137') if data_args.task_name.lower() == 'mnli': base_model = MyRobertaForSequenceClassification.from_pretrained('./exps/glue_baseline_roberta-base/MNLI/LR2e-5BA32MAXSTEP30968WARMSTEP1858/') base_model = base_model.cuda() lis_energy, lis_logits, lis_logits_base = [], [], [] for step, inputs in enumerate(eval_dataloader): has_labels = any(inputs.get(k) is not None for k in ["labels", "lm_labels", "masked_lm_labels"]) for k, v in inputs.items(): inputs[k] = v.cuda() return_d = {} model.eval(); base_model.eval(); with torch.no_grad(): outputs = base_model(**inputs) lis_logits_base.append(outputs[1]) inputs['special_mode'] = 'nce_noise' inputs['nce_mode'] = my_args.nce_mode inputs['return_d'] = return_d inputs['nce_feed_type'] = 'data' inputs['nce_noise_ratio'] = my_args.nce_noise_ratio outputs = model(**inputs) lis_energy.append(return_d['nce_logits']) lis_logits.append(outputs[1]) all_energy = torch.cat(lis_energy, dim = 0).view(-1) all_probs = torch.softmax(torch.cat(lis_logits, dim = 0), dim = -1) all_probs_base = torch.softmax(torch.cat(lis_logits_base, dim = 0), dim = -1) sorted_idx = all_energy.sort(descending = False)[1] save_fn = training_args.output_dir + '/dev_energy.save' logger.info('saving all_energy to %s', save_fn) torch.save({'all_energy': all_energy.cpu(), 'all_probs': all_probs.cpu(), 'all_probs_base': all_probs_base.cpu()}, save_fn) print('low energy:') for idx in sorted_idx[:10].tolist(): print(idx, '\tenergy:', all_energy[idx].item(), 'prediction prob:', all_probs[idx].tolist(), 'prediction prob baseline:', all_probs_base[idx].tolist(), 'label:', dataset_cal_dev2[idx].label, 'text:', tokenizer.decode(dataset_cal_dev2[idx].input_ids[:100])) print('high energy:') for idx in sorted_idx[-10:].tolist(): if torch.argmax(all_probs_base[idx]).item() != dataset_cal_dev2[idx].label: print(idx, '\tenergy:', all_energy[idx].item(), 'prediction prob:', all_probs[idx].tolist(), 'prediction prob baseline:', all_probs_base[idx].tolist(), 'label:', dataset_cal_dev2[idx].label, 'text:', tokenizer.decode(dataset_cal_dev2[idx].input_ids[:70])) logger.info('output_dir: %s', training_args.output_dir) if my_args.train_mode == 'nce_noise': logger.info('===FINAL NCE_EVAL RESULT===') report_str = '[EVAL_DATA] ' for idx in final_nce_eval_results: report_str += idx + ':' + str(final_nce_eval_results[idx])[:5] + ', ' logger.info('%s', report_str) report_str = '[TRAIN_DATA] ' for idx in final_nce_train_results: report_str += idx + ':' + str(final_nce_train_results[idx])[:5] + ', ' logger.info('%s', report_str) """ logger.info('===FINAL CHECKLIST_EVAL RESULTS===') report_str, ll = '', [] for idx in final_checklist_eval_results: if idx != 'AVG': report_str += idx + ':' + str(final_checklist_eval_results[idx] * 100)[:5] + '%, ' #ll.append(final_checklist_eval_results[idx]) logger.info('%s AVG: %s', report_str, str(final_checklist_eval_results['AVG'] * 100)[:5] + '%') """ logger.info('===FINAL EVAL RESULTS===') report_str = '' for idx in final_eval_results: report_str += idx + ':' + str(final_eval_results[idx])[:5] + ', ' logger.info('%s', report_str) if final_evalres_savefn is not None: logger.info(final_evalres_savefn) return eval_results def _mp_fn(index): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 2864, 383, 3012, 9552, 15417, 4816, 46665, 290, 383, 12905, 2667, 32388, 3457, 13, 1074, 13, 198, 2, 15069, 357, 66, 8, 2864, 11, 15127, 23929, 44680, 6234, 13, 220, 1439, 2489, 10395, 13,...
2.250093
10,800
__all__ = [ "assistant", "event", "error" ]
[ 834, 439, 834, 796, 685, 366, 562, 10167, 1600, 366, 15596, 1600, 366, 18224, 1, 2361 ]
2.6875
16
guests=int(input()) reservations=set([]) while guests!=0: reservationCode=input() reservations.add(reservationCode) guests-=1 while True: r=input() if r!="END": reservations.discard(r) else: print(len(reservations)) VIPS=[]; Regulars=[] for e in reservations: if e[0].isnumeric(): VIPS.append(e) else: Regulars.append(e) VIPS.sort(); Regulars.sort() for k in VIPS: print(k) for k in Regulars: print(k) break
[ 5162, 3558, 28, 600, 7, 15414, 28955, 198, 411, 712, 602, 28, 2617, 26933, 12962, 198, 198, 4514, 10650, 0, 28, 15, 25, 198, 220, 220, 220, 24048, 10669, 28, 15414, 3419, 198, 220, 220, 220, 24722, 13, 2860, 7, 411, 13208, 10669, ...
1.867314
309
# Create a plotter and remove all lights after initialization. # Note how the mesh rendered is completely flat # import pyvista as pv plotter = pv.Plotter() plotter.remove_all_lights() plotter.renderer.lights # Expected: ## [] _ = plotter.add_mesh(pv.Sphere(), show_edges=True) plotter.show() # # Note how this differs from a plot with default lighting # pv.Sphere().plot(show_edges=True, lighting=True)
[ 2, 13610, 257, 7110, 353, 290, 4781, 477, 7588, 706, 37588, 13, 198, 2, 5740, 703, 262, 19609, 15111, 318, 3190, 6228, 198, 2, 198, 11748, 12972, 85, 12523, 355, 279, 85, 198, 29487, 353, 796, 279, 85, 13, 43328, 353, 3419, 198, 2...
3.037594
133
from typing import Dict, Tuple import numpy as np
[ 6738, 19720, 1330, 360, 713, 11, 309, 29291, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.4
15
import json import logging import os import pickle import sys import time import pyzmail # http://mypy.pythonblogs.com/12_mypy/archive/1253_workaround_for_python_bug_ascii_codec_cant_encode_character_uxa0_in_position_111_ordinal_not_in_range128.html reload(sys) sys.setdefaultencoding("utf8") logging.basicConfig(format='%(asctime)s : %(levelname)s :: %(message)s', level=logging.DEBUG) if __name__ == '__main__': run()
[ 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 25064, 198, 11748, 640, 198, 198, 11748, 12972, 89, 4529, 198, 198, 2, 2638, 1378, 1820, 9078, 13, 29412, 49096, 13, 785, 14, 1065, 62, 1820, 9078, ...
2.571429
168
# # ---------------------------------------------------------------------------------------------------- # # Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 only, as # published by the Free Software Foundation. # # This code is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # version 2 for more details (a copy is included in the LICENSE file that # accompanied this code). # # You should have received a copy of the GNU General Public License version # 2 along with this work; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. # # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA # or visit www.oracle.com if you need additional information or have any # questions. # # ---------------------------------------------------------------------------------------------------- import mx if mx.get_jdk(tag='default').javaCompliance < "1.9": mx.abort('JAVA_HOME is not a JDK9: ' + mx.get_jdk(tag='default').home) from mx_graal_9 import mx_post_parse_cmd_line, run_vm, get_vm, isJVMCIEnabled # pylint: disable=unused-import import mx_graal_bench # pylint: disable=unused-import
[ 2, 198, 2, 16529, 3880, 650, 198, 2, 198, 2, 15069, 357, 66, 8, 4343, 11, 1853, 11, 18650, 290, 14, 273, 663, 29116, 13, 1439, 2489, 10395, 13, 198, 2, 8410, 5626, 8355, 5781, 6375, 22657, 46, 6089, 27975, 38162, 9947, 5626, 34444...
3.709832
417
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import multivariate_normal
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 220, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 629, 541, 88, 13, 34242, 1330, 1963, 42524, 62, 11265, 628, 628, 628, 628 ]
3.075
40
from .lexer import SolidityLexer, YulLexer __all__ = ['SolidityLexer', 'YulLexer']
[ 6738, 764, 2588, 263, 1330, 15831, 414, 45117, 263, 11, 575, 377, 45117, 263, 198, 198, 834, 439, 834, 796, 37250, 46933, 414, 45117, 263, 3256, 705, 56, 377, 45117, 263, 20520, 198 ]
2.545455
33
#!/usr/bin/env python3 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Float, DateTime, Integer from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker Base = declarative_base() def get_session(engine): engine = create_engine(engine) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() return session
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 32446, 283, 876, 1330, 2377, 283, 876, 62, 8692, 198, 6738, 44161, 282, 26599, 1330, 29201, 11, 10903, 11, 48436, 11, 7536, 7575, 11, 34142, ...
3.176471
136
#!/usr/bin/env python ## Program: VMTK ## Module: $RCSfile: vmtkmeshboundaryinspector.py,v $ ## Language: Python ## Date: $Date: 2006/05/26 12:35:13 $ ## Version: $Revision: 1.3 $ ## Copyright (c) Luca Antiga, David Steinman. All rights reserved. ## See LICENSE file for details. ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ## PURPOSE. See the above copyright notices for more information. from __future__ import absolute_import #NEEDS TO STAY AS TOP LEVEL MODULE FOR Py2-3 COMPATIBILITY import vtk import sys from vmtk import vtkvmtk from vmtk import vmtkrenderer from vmtk import pypes if __name__=='__main__': main = pypes.pypeMain() main.Arguments = sys.argv main.Execute()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2235, 6118, 25, 220, 220, 569, 13752, 42, 198, 2235, 19937, 25, 220, 220, 220, 720, 7397, 50, 7753, 25, 410, 16762, 13276, 5069, 7784, 560, 1040, 806, 273, 13, 9078, 11, 85, 7...
2.762542
299