content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" create_ucs_sp_template.py Purpose: UCS Manager Create a UCS Service Profile Template Author: John McDonough (jomcdono@cisco.com) github: (@movinalot) Cisco Systems, Inc. """ from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.org.OrgOrg import OrgOrg HANDLE = UcsHandle( "sandbox-ucsm1.cisco.com", "admin", "password" ) HANDLE.login() ORG_ORG = OrgOrg( parent_mo_or_dn='org-root', name="devnet", ) HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit() SP_TEMPLATE = LsServer( parent_mo_or_dn='org-root/org-devnet', name="devcore_template", type="updating-template" ) HANDLE.add_mo(SP_TEMPLATE, modify_present=True) HANDLE.commit() HANDLE.logout()
[ 37811, 198, 17953, 62, 1229, 82, 62, 2777, 62, 28243, 13, 9078, 198, 198, 30026, 3455, 25, 198, 220, 220, 220, 49553, 9142, 13610, 257, 49553, 4809, 13118, 37350, 198, 13838, 25, 198, 220, 220, 220, 1757, 1982, 3987, 619, 357, 73, 2...
2.236842
342
# coding=utf-8 """ Handles EPAB's config file """ import logging import pathlib import elib_config CHANGELOG_DISABLE = elib_config.ConfigValueBool( 'changelog', 'disable', description='Disable changelog building', default=False ) CHANGELOG_FILE_PATH = elib_config.ConfigValuePath( 'changelog', 'file_path', description='Path to changelog file', default='CHANGELOG.md' ) CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS = elib_config.ConfigValueString( 'test', 'runner_options', description='Additional options for test run', default='' ) TEST_DURATION_COUNT = elib_config.ConfigValueInteger( 'test', 'duration_count', description='Amount of "slow" tests to show', default=10 ) TEST_DURATION_COUNT.set_limits(min_=0, max_=50) TEST_TARGET = elib_config.ConfigValueString( 'test', 'target', description='Target of pytest', default='test' ) TEST_COVERAGE_FAIL_UNDER = elib_config.ConfigValueInteger( 'test', 'coverage_fail_under', description='Minimal coverage to pass tests', default=20 ) TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100) TEST_PYTEST_TIMEOUT = elib_config.ConfigValueInteger( 'test', 'timeout', description='Timeout in seconds for pytest runner', default=300 ) TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600) LINT_LINE_LENGTH = elib_config.ConfigValueInteger( 'lint', 'line_length', description='Linter max line width', default=120 ) LINT_LINE_LENGTH.set_limits(min_=0, max_=500) PACKAGE_NAME = elib_config.ConfigValueString( 'package_name', description='Package name' ) FREEZE_ENTRY_POINT = elib_config.ConfigValueString( 'freeze', 'entry_point', description='Main entry point for pyinstaller', default='' ) FREEZE_DATA_FILES = elib_config.ConfigValueList( 'freeze', 'data_files', description='PyInstaller data-files list', element_type=str, default=[] ) DOC_REPO = elib_config.ConfigValueString( 'doc', 'repo', description='Documentation repository on Github', default='' ) DOC_FOLDER = elib_config.ConfigValuePath( 'doc', 'folder', description='Local documentation directory', default='./doc' ) DOC_FOLDER.must_be_dir() QUIET = elib_config.ConfigValueBool( 'quiet', description='Less console output', default=False ) VERBOSE = elib_config.ConfigValueBool( 'verbose', description='More console output', default=False ) TEST_AV_RUNNER_OPTIONS = elib_config.ConfigValueString( 'appveyor', 'test_runner_options', description='Additional command line options for tests run on AV', default='--long' ) ARTIFACTS = elib_config.ConfigValueList( 'appveyor', 'artifacts', description='List of artifacts for Appveyor', element_type=str, default=[] ) FLAKE8_EXCLUDE = elib_config.ConfigValueString( 'lint', 'flake8_exclude', description='List of comma separated files for flake8 to exclude', default='' ) MYPY_ARGS = elib_config.ConfigValueString( 'lint', 'mypy_args', description='Additional MyPy arguments', default='' ) QT_RES_SRC = elib_config.ConfigValueString( 'qt', 'res_src', description='Qt resource file (.qrc) location', default='' ) QT_RES_TGT = elib_config.ConfigValueString( 'qt', 'res_tgt', description='Compiled Qt resource file (.py) target location', default='' ) UPLOAD_TO_TWINE = elib_config.ConfigValueBool( 'twine', 'upload', description='Upload package to Twine after build', default=True, ) MAKE_GRAPH = elib_config.ConfigValueBool( 'graph', 'make', description='Generate graphs using PyReverse', default=True, ) def setup_config(epab_version: str): """ Set up elib_config package :param epab_version: installed version of EPAB as as string """ logger = logging.getLogger('EPAB') logger.debug('setting up config') elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml', config_sep_str='__', root_path=['tool', 'epab'] ) elib_config.write_example_config('pyproject.toml.example') if not pathlib.Path('pyproject.toml').exists(): raise FileNotFoundError('pyproject.toml') elib_config.validate_config()
[ 2, 19617, 28, 40477, 12, 23, 198, 37811, 198, 12885, 829, 10193, 33, 338, 4566, 2393, 198, 37811, 198, 198, 11748, 18931, 198, 11748, 3108, 8019, 198, 198, 11748, 1288, 571, 62, 11250, 198, 198, 3398, 15567, 3698, 7730, 62, 26288, 175...
2.742151
1,497
import os import argparse if __name__ == '__main__': create_flask_app()
[ 11748, 28686, 198, 11748, 1822, 29572, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 197, 17953, 62, 2704, 2093, 62, 1324, 3419, 198 ]
2.642857
28
import os import click from flask import Flask from flask.cli import with_appcontext from flask_sqlalchemy import SQLAlchemy __version__ = (1, 0, 0, "dev") db = SQLAlchemy() def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) # some deploy systems set the database url in the environ db_url = os.environ.get("DATABASE_URL") if db_url is None: # default to a sqlite database in the instance folder db_url = "sqlite:///" + os.path.join(app.instance_path, "flaskr.sqlite") # ensure the instance folder exists os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping( # default secret that should be overridden in environ or config SECRET_KEY=os.environ.get("SECRET_KEY", "dev"), SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False, ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) else: # load the test config if passed in app.config.update(test_config) # initialize Flask-SQLAlchemy and the init-db command db.init_app(app) app.cli.add_command(init_db_command) # apply the blueprints to the app from flaskr import auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make "index" point at "/", which is handled by "blog.index" app.add_url_rule("/", endpoint="index") return app
[ 11748, 28686, 198, 198, 11748, 3904, 198, 6738, 42903, 1330, 46947, 198, 6738, 42903, 13, 44506, 1330, 351, 62, 1324, 22866, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 198, 834, 9641, 834, 796, 357, 16, 11, ...
2.623568
611
import os, sys fn = sys.argv[1] if os.system('python compile.py %s __tmp.S' % fn) == 0: os.system('python asm.py __tmp.S %s' % fn[:-2])
[ 11748, 28686, 11, 25064, 198, 198, 22184, 796, 25064, 13, 853, 85, 58, 16, 60, 198, 198, 361, 28686, 13, 10057, 10786, 29412, 17632, 13, 9078, 4064, 82, 11593, 22065, 13, 50, 6, 4064, 24714, 8, 6624, 657, 25, 198, 220, 220, 220, 2...
2.151515
66
#!/usr/bin/env python # coding: UTF-8 # # @package Actor # @author Ariadne Pinheiro # @date 26/08/2020 # # Actor class, which is the base class for Disease objects. # ##
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 41002, 12, 23, 198, 2, 198, 2, 2488, 26495, 27274, 198, 2, 2488, 9800, 6069, 324, 710, 13727, 258, 7058, 198, 2, 2488, 4475, 2608, 14, 2919, 14, 42334, 198, 2, 198, ...
2.741935
62
"""Convert a Decimal Number to a Binary Number.""" def decimal_to_binary(num: int) -> str: """ Convert a Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>> # negatives work too >>> decimal_to_binary(-2) '-0b10' >>> # other floats will error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # strings will error as well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer """ if type(num) == float: raise TypeError("'float' object cannot be interpreted as an integer") if type(num) == str: raise TypeError("'str' object cannot be interpreted as an integer") if num == 0: return "0b0" negative = False if num < 0: negative = True num = -num binary = [] while num > 0: binary.insert(0, num % 2) num >>= 1 if negative: return "-0b" + "".join(str(e) for e in binary) return "0b" + "".join(str(e) for e in binary) if __name__ == "__main__": import doctest doctest.testmod()
[ 37811, 3103, 1851, 257, 4280, 4402, 7913, 284, 257, 45755, 7913, 526, 15931, 628, 198, 4299, 32465, 62, 1462, 62, 39491, 7, 22510, 25, 493, 8, 4613, 965, 25, 628, 220, 220, 220, 37227, 198, 220, 220, 220, 220, 220, 220, 220, 38240, ...
2.276276
666
#!/usr/bin/python3 #-*- coding: utf-8 -*- import urllib.parse import json import base64 import requests import logging
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 2956, 297, 571, 13, 29572, 198, 11748, 33918, 198, 11748, 2779, 2414, 198, 11748, 7007, 198, 11748, 18931, 198 ...
2.727273
44
import libcst as cst import libcst.matchers as m from fixit import CstLintRule from fixit import InvalidTestCase as Invalid from fixit import ValidTestCase as Valid
[ 11748, 9195, 66, 301, 355, 269, 301, 198, 11748, 9195, 66, 301, 13, 6759, 3533, 355, 285, 198, 6738, 4259, 270, 1330, 327, 301, 43, 600, 31929, 198, 6738, 4259, 270, 1330, 17665, 14402, 20448, 355, 17665, 198, 6738, 4259, 270, 1330, ...
3.458333
48
# AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/13_model_fn.ipynb (unless otherwise specified). __all__ = ['variable_summaries', 'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask'] # Cell from typing import Dict, Tuple from inspect import signature import tensorflow as tf import transformers from .modeling import MultiModalBertModel from .params import BaseParams from .top import (Classification, MultiLabelClassification, PreTrain, Seq2Seq, SequenceLabel, MaskLM) from .utils import get_embedding_table_from_model, get_transformer_main_model def variable_summaries(var, name): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" with tf.compat.v1.name_scope(name): mean = tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean', mean) with tf.compat.v1.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var - mean))) tf.compat.v1.summary.scalar('stddev', stddev) tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram', var) # Cell # Cell
[ 2, 47044, 7730, 1677, 1137, 11617, 0, 8410, 5626, 48483, 0, 9220, 284, 4370, 25, 2723, 62, 77, 1443, 14, 1485, 62, 19849, 62, 22184, 13, 541, 2047, 65, 357, 25252, 4306, 7368, 737, 198, 198, 834, 439, 834, 796, 37250, 45286, 62, 8...
2.437262
526
import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import math from datetime import datetime from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.collections import LineCollection from matplotlib import cm from SiMon.simulation import Simulation from SiMon.callback import Callback from matplotlib.ticker import MaxNLocator import time
[ 11748, 28686, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 46384, 11537, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 6738, 4818,...
3.565217
115
""" Particle Size Models: Pure Oil Jet =================================== Use the ``TAMOC`` `particle_size_models` module to simulate a laboratory scale pure oil jet into water. This script demonstrates the typical steps involved in using the `particle_size_models.PureJet` object, which requires specification of all of the fluid properties of the jet. """ # S. Socolofsky, March 2020, Texas A&M University <socolofs@tamu.edu>. from __future__ import (absolute_import, division, print_function) from tamoc import seawater, particle_size_models import numpy as np import warnings warnings.filterwarnings("ignore") if __name__ == '__main__': print('\n---------------------------------------------------------------') print('Demonstration using the PureJet class in the') print('particle_size_models module of TAMOC for the ') print('experiments in the paper by Brandvik et al. (2013).') print('\nComparisons are for the data reported in Table 3') print('of the paper') print('---------------------------------------------------------------') # Simulate an experiment from Brandvik et al. (2013). Their data uses # Oseberg oil, with the following reported properties rho_oil = 839.3 mu_oil = 5.e-3 sigma = 15.5e-3 # We will simulate data from Table 3 in the Brandvik et al. (2013) paper. # These experiments have a nozzle diameter of 1.5 mm d0 = 0.0015 # They also used seawater (assumed salinity of 34.5 psu) and released the # oil from a depth of about 6 m at a temperature of 13 deg C T = 273.15 + 13. S = 34.5 rho = seawater.density(T, S, 101325.) P = 101325. + rho * 9.81 * 6. rho = seawater.density(T, S, P) mu = seawater.mu(T, S, P) # With this information, we can initialize a # `particle_size_models.PureJet` object jet = particle_size_models.PureJet(rho_oil, mu_oil, sigma, rho, mu, fp_type = 1) # Brandvik et al. (2013) report the exit velocity at the nozzle. We # need to convert this to a mass flow rate. The mass flow rate should # always be reported within a numpy array, which allows for different # mass fluxes for different pseudocomponents of the oil. u_oil = 11.3 A_oil = np.pi * (d0 / 2.)**2 q_oil = u_oil * A_oil md_oil = np.array([rho_oil * q_oil]) # To simulate the no-dispersant case, all of the oil properties in the # jet object are currently correct. Hence, we may use: jet.simulate(d0, md_oil) # We compare the result to the measured data as follows: print('\nThe median droplet size for the no-disperant experiment is:') print(' Measured: %3.3d um' % 237) print(' Modeled : %3.3d um\n' % (jet.get_d50() * 1.e6)) # When dispersant is added in sufficient quantities, the interfacial # tension reduces and the droplet size gets smaller. At a dispersant # to oil ratio of 50, sigma is: sigma = 0.05e-3 # We can run this case by updating the properties of the jet object and # re-running the simualtion jet.update_properties(rho_oil, mu_oil, sigma, rho, mu, fp_type = 1) jet.simulate(d0, md_oil) # We compare the result to the measured data as follows: print('\nThe median droplet size for an experiments with a') print('dispersant to oil ratio of 50 is:') print(' Measured: %3.3d um' % 170) print(' Modeled : %3.3d um\n' % (jet.get_d50() * 1.e6)) # We can also plot the size distribution print('\nThe corresponding size distribution is plotted in Figure 1') jet.get_distributions(15) jet.plot_psd(1)
[ 37811, 198, 7841, 1548, 12849, 32329, 25, 220, 17129, 11474, 19013, 198, 10052, 18604, 198, 198, 11041, 262, 7559, 51, 2390, 4503, 15506, 4600, 3911, 1548, 62, 7857, 62, 27530, 63, 8265, 284, 29308, 257, 14010, 198, 9888, 5899, 3056, 12...
2.732644
1,354
import os.path import tron.Misc from tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.SocketActorNub import SocketActorNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'hal'
[ 11748, 28686, 13, 6978, 198, 198, 11748, 491, 261, 13, 44, 2304, 198, 6738, 491, 261, 1330, 308, 11, 12575, 198, 6738, 491, 261, 13, 16066, 13, 21575, 13, 4834, 19815, 364, 13, 1921, 25690, 2149, 9132, 27195, 12342, 1330, 25400, 40, ...
2.793814
97
from dataclasses import dataclass, field from decimal import Decimal from typing import Optional from xsdata.models.datatype import XmlDate
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 19720, 1330, 32233, 198, 6738, 2124, 82, 7890, 13, 27530, 13, 19608, 265, 2981, 1330, 1395, 4029, 10430, 628, 628 ]
3.763158
38
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Domain objects used within multiple extensions.""" from __future__ import absolute_import # pylint: disable=import-only-modules import python_utils
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 198, 2, 15069, 1946, 383, 9385, 544, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743...
3.771845
206
#!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for details. # GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_database_management_object_privilege_facts short_description: Fetches details about one or multiple ObjectPrivilege resources in Oracle Cloud Infrastructure description: - Fetches details about one or multiple ObjectPrivilege resources in Oracle Cloud Infrastructure - Gets the list of Object Privileges granted for the specified user. version_added: "2.9.0" author: Oracle (@oracle) options: managed_database_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database. type: str required: true user_name: description: - The name of the user whose details are to be viewed. type: str required: true name: description: - A filter to return only resources that match the entire name. type: str sort_by: description: - The field to sort information by. Only one sortOrder can be used. The default sort order for 'NAME' is ascending. The 'NAME' sort order is case-sensitive. type: str choices: - "NAME" sort_order: description: - The option to sort information in ascending ('ASC') or descending ('DESC') order. Ascending order is the default order. type: str choices: - "ASC" - "DESC" extends_documentation_fragment: [ oracle.oci.oracle ] """ EXAMPLES = """ - name: List object_privileges oci_database_management_object_privilege_facts: # required managed_database_id: "ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx" user_name: user_name_example # optional name: name_example sort_by: NAME sort_order: ASC """ RETURN = """ object_privileges: description: - List of ObjectPrivilege resources returned: on success type: complex contains: name: description: - The name of the privilege on the object. returned: on success type: str sample: name_example schema_type: description: - The type of the object. returned: on success type: str sample: schema_type_example owner: description: - The owner of the object. returned: on success type: str sample: owner_example grantor: description: - The name of the user who performed the grant returned: on success type: str sample: grantor_example hierarchy: description: - Indicates whether the privilege was granted with the HIERARCHY OPTION (YES) or not (NO) returned: on success type: str sample: YES object: description: - The name of the object. The object can be any object, including tables, packages, indexes, sequences, and so on. returned: on success type: str sample: object_example grant_option: description: - Indicates whether the privilege was granted with the GRANT OPTION (YES) or not (NO) returned: on success type: str sample: YES common: description: - "Indicates how the grant was made. Possible values: YES if the role was granted commonly (CONTAINER=ALL was used) NO if the role was granted locally (CONTAINER=ALL was not used)" returned: on success type: str sample: YES inherited: description: - Indicates whether the role grant was inherited from another container (YES) or not (NO) returned: on success type: str sample: YES sample: [{ "name": "name_example", "schema_type": "schema_type_example", "owner": "owner_example", "grantor": "grantor_example", "hierarchy": "YES", "object": "object_example", "grant_option": "YES", "common": "YES", "inherited": "YES" }] """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class, ) try: from oci.database_management import DbManagementClient HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False ObjectPrivilegeFactsHelperCustom = get_custom_class("ObjectPrivilegeFactsHelperCustom") if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 357, 66, 8, 12131, 11, 33160, 18650, 290, 14, 273, 663, 29116, 13, 198, 2, 770, 3788, 318, 925, 1695, 284, 345, 739, 262, 2846, 286, 262, 38644, 513, 13, 15, 5964, 393, 262, 2...
2.363518
2,308
"""https://en.cppreference.com/w/c/io """ from rbc import irutils from llvmlite import ir from rbc.targetinfo import TargetInfo from numba.core import cgutils, extending from numba.core import types as nb_types from rbc.errors import NumbaTypeError # some errors are available for Numba >= 0.55 int32_t = ir.IntType(32)
[ 37811, 5450, 1378, 268, 13, 20322, 35790, 13, 785, 14, 86, 14, 66, 14, 952, 198, 37811, 198, 198, 6738, 374, 15630, 1330, 4173, 26791, 198, 6738, 32660, 85, 4029, 578, 1330, 4173, 198, 6738, 374, 15630, 13, 16793, 10951, 1330, 12744, ...
2.963636
110
from setuptools import setup try: import pypandoc long_description = pypandoc.convert_file('README.md', 'rst', extra_args=()) except ImportError: import codecs long_description = codecs.open('README.md', encoding='utf-8').read() long_description = '\n'.join(long_description.splitlines()) setup( name='discoverhue', description='Auto discovery of Hue bridges', long_description=long_description, version='1.0.2', url='https://github.com/Overboard/discoverhue', author='Overboard', author_email='amwroute-git@yahoo.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='philips hue', packages=['discoverhue'], install_requires=['httpfind'], )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 28311, 25, 198, 220, 220, 220, 1330, 279, 4464, 392, 420, 198, 220, 220, 220, 890, 62, 11213, 796, 279, 4464, 392, 420, 13, 1102, 1851, 62, 7753, 10786, 15675, 11682, 13, 9132, 3256, 70...
2.663978
372
# The MIT License (MIT) # # Copyright (c) 2015 braindead # # 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. # # # This code was extracted from the logmmse package (https://pypi.org/project/logmmse/) and I # simply modified the interface to meet my needs. import numpy as np import math from scipy.special import expn from collections import namedtuple NoiseProfile = namedtuple("NoiseProfile", "sampling_rate window_size len1 len2 win n_fft noise_mu2") def profile_noise(noise, sampling_rate, window_size=0): """ Creates a profile of the noise in a given waveform. :param noise: a waveform containing noise ONLY, as a numpy array of floats or ints. :param sampling_rate: the sampling rate of the audio :param window_size: the size of the window the logmmse algorithm operates on. A default value will be picked if left as 0. :return: a NoiseProfile object """ noise, dtype = to_float(noise) noise += np.finfo(np.float64).eps if window_size == 0: window_size = int(math.floor(0.02 * sampling_rate)) if window_size % 2 == 1: window_size = window_size + 1 perc = 50 len1 = int(math.floor(window_size * perc / 100)) len2 = int(window_size - len1) win = np.hanning(window_size) win = win * len2 / np.sum(win) n_fft = 2 * window_size noise_mean = np.zeros(n_fft) n_frames = len(noise) // window_size for j in range(0, window_size * n_frames, window_size): noise_mean += np.absolute(np.fft.fft(win * noise[j:j + window_size], n_fft, axis=0)) noise_mu2 = (noise_mean / n_frames) ** 2 return NoiseProfile(sampling_rate, window_size, len1, len2, win, n_fft, noise_mu2) def denoise(wav, noise_profile: NoiseProfile, eta=0.15): """ Cleans the noise from a speech waveform given a noise profile. The waveform must have the same sampling rate as the one used to create the noise profile. :param wav: a speech waveform as a numpy array of floats or ints. :param noise_profile: a NoiseProfile object that was created from a similar (or a segment of the same) waveform. :param eta: voice threshold for noise update. While the voice activation detection value is below this threshold, the noise profile will be continuously updated throughout the audio. Set to 0 to disable updating the noise profile. :return: the clean wav as a numpy array of floats or ints of the same length. """ wav, dtype = to_float(wav) wav += np.finfo(np.float64).eps p = noise_profile nframes = int(math.floor(len(wav) / p.len2) - math.floor(p.window_size / p.len2)) x_final = np.zeros(nframes * p.len2) aa = 0.98 mu = 0.98 ksi_min = 10 ** (-25 / 10) x_old = np.zeros(p.len1) xk_prev = np.zeros(p.len1) noise_mu2 = p.noise_mu2 for k in range(0, nframes * p.len2, p.len2): insign = p.win * wav[k:k + p.window_size] spec = np.fft.fft(insign, p.n_fft, axis=0) sig = np.absolute(spec) sig2 = sig ** 2 gammak = np.minimum(sig2 / noise_mu2, 40) if xk_prev.all() == 0: ksi = aa + (1 - aa) * np.maximum(gammak - 1, 0) else: ksi = aa * xk_prev / noise_mu2 + (1 - aa) * np.maximum(gammak - 1, 0) ksi = np.maximum(ksi_min, ksi) log_sigma_k = gammak * ksi/(1 + ksi) - np.log(1 + ksi) vad_decision = np.sum(log_sigma_k) / p.window_size if vad_decision < eta: noise_mu2 = mu * noise_mu2 + (1 - mu) * sig2 a = ksi / (1 + ksi) vk = a * gammak ei_vk = 0.5 * expn(1, np.maximum(vk, 1e-8)) hw = a * np.exp(ei_vk) sig = sig * hw xk_prev = sig ** 2 xi_w = np.fft.ifft(hw * spec, p.n_fft, axis=0) xi_w = np.real(xi_w) x_final[k:k + p.len2] = x_old + xi_w[0:p.len1] x_old = xi_w[p.len1:p.window_size] output = from_float(x_final, dtype) output = np.pad(output, (0, len(wav) - len(output)), mode="constant") return output
[ 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 220, 198, 2, 15069, 357, 66, 8, 1853, 3632, 25124, 198, 2, 220, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788...
2.489897
2,029
# This file is part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import time import datetime from lib.common.out import * from lib.common.objects import File from lib.core.database import Database from lib.core.investigation import __project__ __sessions__ = Sessions()
[ 2, 770, 2393, 318, 636, 286, 34517, 532, 3740, 1378, 12567, 13, 785, 14, 8903, 525, 12, 30604, 14, 8903, 525, 198, 2, 4091, 262, 2393, 705, 43, 2149, 24290, 6, 329, 23345, 7170, 13, 198, 198, 11748, 640, 198, 11748, 4818, 8079, 19...
3.531915
94
#coding: utf-8 import xlrd from simple_report.core.document_wrap import BaseDocument, SpreadsheetDocument from simple_report.xls.workbook import Workbook from simple_report.xls.output_options import XSL_OUTPUT_SETTINGS
[ 2, 66, 7656, 25, 3384, 69, 12, 23, 201, 198, 201, 198, 11748, 2124, 75, 4372, 201, 198, 201, 198, 6738, 2829, 62, 13116, 13, 7295, 13, 22897, 62, 37150, 1330, 7308, 24941, 11, 31843, 21760, 24941, 201, 198, 6738, 2829, 62, 13116, ...
2.923077
78
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """ Function: Test error handler. Usage: pytest tests/ut/datavisual """ from unittest.mock import patch from werkzeug.exceptions import MethodNotAllowed, NotFound from ...backend.datavisual.conftest import TRAIN_ROUTES from ..mock import MockLogger from ....utils.tools import get_url from mindinsight.datavisual.processors import scalars_processor from mindinsight.datavisual.processors.scalars_processor import ScalarsProcessor
[ 2, 15069, 13130, 43208, 21852, 1766, 1539, 12052, 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, 198...
3.80756
291
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: cancel_build.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='cancel_build.proto', package='build', syntax='proto3', serialized_options=None, serialized_pb=_b('\n\x12\x63\x61ncel_build.proto\x12\x05\x62uild\x1a\x1bgoogle/protobuf/empty.proto\"!\n\rCancelRequest\x12\x10\n\x08\x62uild_id\x18\x01 \x01(\t\"o\n\x15\x43\x61ncelResponseWrapper\x12\x0c\n\x04\x63ode\x18\x01 \x01(\x05\x12\x13\n\x0b\x63odeExplain\x18\x02 \x01(\t\x12\r\n\x05\x65rror\x18\x03 \x01(\t\x12$\n\x04\x64\x61ta\x18\x04 \x01(\x0b\x32\x16.google.protobuf.Emptyb\x06proto3') , dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST = _descriptor.Descriptor( name='CancelRequest', full_name='build.CancelRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='build_id', full_name='build.CancelRequest.build_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=58, serialized_end=91, ) _CANCELRESPONSEWRAPPER = _descriptor.Descriptor( name='CancelResponseWrapper', full_name='build.CancelResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='build.CancelResponseWrapper.code', index=0, number=1, 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, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='build.CancelResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='build.CancelResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=93, serialized_end=204, ) _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type = google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest'] = _CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] = _CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), { 'DESCRIPTOR' : _CANCELREQUEST, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelRequest) }) _sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper = _reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _CANCELRESPONSEWRAPPER, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelResponseWrapper) }) _sym_db.RegisterMessage(CancelResponseWrapper) # @@protoc_insertion_point(module_scope)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 14241, 62, 11249, 13, 1676, 1462, 198, 198, 11748, 25064, 198, 62, 65, 2...
2.458227
1,951
''' This is a sample class for a model. You may choose to use it as-is or make any changes to it. This has been provided just to give you an idea of how to structure your model class. ''' from openvino.inference_engine import IENetwork, IECore import numpy as np import os import cv2 import sys
[ 7061, 6, 198, 1212, 318, 257, 6291, 1398, 329, 257, 2746, 13, 921, 743, 3853, 284, 779, 340, 355, 12, 271, 393, 787, 597, 2458, 284, 340, 13, 198, 1212, 468, 587, 2810, 655, 284, 1577, 345, 281, 2126, 286, 703, 284, 4645, 534, 2...
3.418605
86
NAMES_SAML2_PROTOCOL = "urn:oasis:names:tc:SAML:2.0:protocol" NAMES_SAML2_ASSERTION = "urn:oasis:names:tc:SAML:2.0:assertion" NAMEID_FORMAT_UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" BINDINGS_HTTP_POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" DATE_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" DATE_TIME_FORMAT_FRACTIONAL = "%Y-%m-%dT%H:%M:%S.%fZ"
[ 45, 29559, 62, 49302, 43, 17, 62, 4805, 2394, 4503, 3535, 796, 366, 700, 25, 78, 17765, 25, 14933, 25, 23047, 25, 49302, 43, 25, 17, 13, 15, 25, 11235, 4668, 1, 198, 45, 29559, 62, 49302, 43, 17, 62, 10705, 17395, 2849, 796, 366...
1.898477
197
import math for _ in range(int(input())): n=int(input()) flag=0 for i in range(2,n//2+1): if check(i)==True and check(n-i)==True: #print(i,n-i,square(i),square(n-i),"Yes") print("YES") flag=1 break if flag==0: #print(i,n-i,square(i),square(n-i),"No") print("NO")
[ 11748, 10688, 198, 1640, 4808, 287, 2837, 7, 600, 7, 15414, 28955, 2599, 198, 220, 220, 220, 299, 28, 600, 7, 15414, 28955, 198, 220, 220, 220, 6056, 28, 15, 198, 220, 220, 220, 329, 1312, 287, 2837, 7, 17, 11, 77, 1003, 17, 10,...
1.755
200
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='This repository hosts some work-in-progress experiments applying deep learning to predict age using tractometry data.', author='Joanna Qiao', license='BSD-3', )
[ 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 10677, 3256, 198, 220, 220, 220, 10392, 28, 19796, 62, 43789, 22784, 198, 220, 220, 220, 2196, 11639, 15, 13, 16, 13, 15,...
3.210526
95
#!/usr/bin/env python3 import argparse import os import random import requests import sys import tempfile import uuid from libs import colorprint from libs.cli import run_command SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) # assume well-known lvm volume group on host # ...later we'll figure out how to make this dynamic VG_NAME = "swift-runway-vg01" SWIFTSTACK_IMAGES_PREFIX = "ss-" SWIFTSTACK_IMAGES_BASE_URL = \ "https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images" IMAGE_MANIFEST_OBJECT_NAME = "manifest.json" UNIFIED_TARBALL_TYPE = "unified" SPLIT_TARBALL_TYPE = "split" TARBALL_TYPES = [UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE] def import_image(manifest, alias): ''' There are 2 possible image formats: unified and split. We support both. For unified format, the manifest will look like this: { "tarball_type": "unified", "fingerprint": "629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018", "tarball-object": "centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz" } For split format, the manifest will look like this: { "tarball_type": "split", "fingerprint": "22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de", "metadata-object": "centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz", "rootfs-object": "centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs" } ''' if manifest["tarball_type"] not in TARBALL_TYPES: raise Exception("Invalid tarball type: {}".format( manifest["tarball_type"])) elif manifest["tarball_type"] == UNIFIED_TARBALL_TYPE: import_unified_image(manifest, alias) elif manifest["tarball_type"] == SPLIT_TARBALL_TYPE: import_split_image(manifest, alias) else: raise Exception("Tarball type '{}' is valid, but a method to import " "it has not been implemented yet.") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('distro', type=str, help='Container distro') parser.add_argument('cname', metavar='containername', help='Container ' 'name') parser.add_argument('volsize', help='Volume size') parser.add_argument('volcount', type=int, help='Volume count') parser.add_argument('baseimage', nargs='?', help='Base image. Defaults: \'images:centos/7/amd64\' ' 'for RHEL distro, \'ubuntu:16.04\' otherwise') args = parser.parse_args() distro = args.distro container_name = args.cname base_image = args.baseimage volume_size = args.volsize volume_count = args.volcount if is_swiftstack_hosted_image(distro): import_image_if_needed(distro) default_image = distro else: default_image = get_default_image(distro) if base_image is None: base_image = default_image try: # make a container profile that maps 8 block devices to the guest rand_file_name = str(uuid.UUID(int=random.getrandbits(128))) run_command("./make_lxc_profile.py {} {} {} {} > " "/tmp/{}".format(container_name, VG_NAME, volume_size, volume_count, rand_file_name), cwd=SCRIPT_DIR, shell=True) run_command("lxc profile create {}-profile".format(container_name)) run_command("cat /tmp/{} | lxc profile edit {}-profile".format( rand_file_name, container_name), cwd=SCRIPT_DIR, shell=True) # launch the new container print("Trying to launch container from base image " "{}".format(base_image)) run_command("lxc launch {} {} -p {}-profile || " "lxc launch {} {} -p {}-profile".format(base_image, container_name, container_name, default_image, container_name, container_name), shell=True) except Exception as e: exit_with_error(str(e))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 7007, 198, 11748, 25064, 198, 11748, 20218, 7753, 198, 11748, 334, 27112, 198, 198, 6738, 9195, 82, 1330, 31...
2.068192
2,141
"""Criar uma funo que retorne min e max de uma sequncia numrica aleatria. S pode usar if, comparaes, recurso e funes que sejam de sua autoria. Se quiser usar laos tambm pode. Deve informar via docstring qual a complexidade de tempo e espao da sua soluo """ from math import inf def minimo_e_maximo(sequencia_numerica): ''' Retorna o minimo e o maximo de uma sequncia numrica aleatria. Complexidade: execuo: O(n) espao: O(3) ''' maximo = -inf # 1 minimo = +inf # 1 for elem in sequencia_numerica: # 1 if elem > maximo: # 2 maximo = elem # 1 if elem < minimo: # 2 minimo = elem # 2 return minimo, maximo # 1 # print(minimo_e_maximo([1, 2, 3, 4])) # print(minimo_e_maximo([1, 3, 10, 12, 44, 2, 24, 25])) # print(minimo_e_maximo([88, 66, 10, 2, 8])) print(recursivo_minmax([1, 2, 3, 4]))
[ 37811, 34, 380, 283, 334, 2611, 1257, 78, 8358, 1005, 8553, 949, 304, 3509, 390, 334, 2611, 33756, 19524, 544, 997, 30997, 198, 1000, 265, 7496, 13, 198, 198, 50, 279, 1098, 514, 283, 611, 11, 552, 3301, 274, 11, 664, 333, 568, 30...
2.111374
422
import dash_bootstrap_components as dbc import dash_html_components as html DBC_DOCS = ( "https://dash-bootstrap-components.opensource.faculty.ai/docs/components/" )
[ 11748, 14470, 62, 18769, 26418, 62, 5589, 3906, 355, 288, 15630, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 198, 35, 2749, 62, 38715, 50, 796, 357, 198, 220, 220, 220, 366, 5450, 1378, 42460, 12, 18769, 26418, 12, ...
2.819672
61
''' The visualization class provides an easy access to some of the visdom functionalities Accept as input a number that will be ploted over time or an image of type np.ndarray ''' from visdom import Visdom import numpy as np import numbers
[ 7061, 6, 198, 464, 32704, 1398, 3769, 281, 2562, 1895, 284, 617, 286, 262, 1490, 3438, 10345, 871, 198, 38855, 355, 5128, 257, 1271, 326, 481, 307, 458, 5191, 625, 640, 393, 281, 2939, 286, 2099, 45941, 13, 358, 18747, 198, 7061, 6,...
3.967213
61
"""Analyze condition number of the network.""" import numpy as np import matplotlib.pyplot as plt # import model def _get_sparse_mask(nx, ny, non, complex=False, nOR=50): """Generate a binary mask. The mask will be of size (nx, ny) For all the nx connections to each 1 of the ny units, only non connections are 1. Args: nx: int ny: int non: int, must not be larger than nx Return: mask: numpy array (nx, ny) """ mask = np.zeros((nx, ny)) if not complex: mask[:non] = 1 for i in range(ny): np.random.shuffle(mask[:, i]) # shuffling in-place return mask.astype(np.float32) n_kc_claws = np.arange(1, 50) conds = np.array([get_logcond(n_kc_claw=n) for n in n_kc_claws]) plt.figure() plt.plot(n_kc_claws, conds, 'o-') plt.xticks(n_kc_claws) plt.xlabel('N_KC_claw') plt.show()
[ 37811, 37702, 2736, 4006, 1271, 286, 262, 3127, 526, 15931, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 2, 1330, 2746, 198, 198, 4299, 4808, 1136, 62, 82, 29572, 62,...
2.109005
422
from rest_framework.authtoken.models import Token from rest_framework import serializers from applications.placement_cell.models import (Achievement, Course, Education, Experience, Has, Patent, Project, Publication, Skill, PlacementStatus, NotifyStudent)
[ 6738, 1334, 62, 30604, 13, 18439, 30001, 13, 27530, 1330, 29130, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 5479, 13, 489, 5592, 62, 3846, 13, 27530, 1330, 357, 32, 24957, 434, 11, 20537, 11, 7868, 11, 198, 220, ...
1.95122
205
import factory from concat_col_app.models import Color, Apple
[ 11748, 8860, 198, 198, 6738, 1673, 265, 62, 4033, 62, 1324, 13, 27530, 1330, 5315, 11, 4196, 628, 198 ]
3.421053
19
from pathlib import Path from typing import Dict from errors.common.exception import DppError
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713, 198, 198, 6738, 8563, 13, 11321, 13, 1069, 4516, 1330, 360, 381, 12331, 628, 628, 628, 628, 628 ]
3.586207
29
from .utility import * from .tricks import * from .tensorlog import * from .self_op import * from .resume import * from .optims import * from .metric import *
[ 198, 198, 6738, 764, 315, 879, 1330, 1635, 198, 6738, 764, 83, 23706, 1330, 1635, 198, 6738, 764, 83, 22854, 6404, 1330, 1635, 198, 6738, 764, 944, 62, 404, 1330, 1635, 198, 6738, 764, 411, 2454, 1330, 1635, 198, 6738, 764, 8738, 12...
3.037736
53
""" Copyright (C) 2018-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. """ import numpy as np from extensions.ops.range import Range from mo.front.extractor import FrontExtractorOp from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs from mo.graph.graph import Node
[ 37811, 198, 15069, 357, 34, 8, 2864, 12, 1238, 2481, 8180, 10501, 628, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 1...
3.849515
206
import cv2 from PIL import Image import argparse from pathlib import Path from multiprocessing import Process, Pipe,Value,Array import torch from config import get_config from mtcnn import MTCNN from Learner_trans_tf import face_learner from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score from sklearn.model_selection import KFold import os import glob import shutil import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors import datetime if __name__ == '__main__': parser = argparse.ArgumentParser(description='for face verification') parser.add_argument("-ds", "--dataset_dir", help="where to get data", default="noonan", type=str) parser.add_argument('-sd','--stored_result_dir',help='where to store data as np arrays', default="results/trans/", type=str) parser.add_argument("-k", "--kfold", help="returns the number of splitting iterations in the cross-validator.", default=10, type=int) parser.add_argument("-e", "--epochs", help="training epochs", default=20, type=int) parser.add_argument("-n", "--names_considered", help="names for different types considered, separated by commas", default="normal,noonan,others", type=str) parser.add_argument("-g", "--gpu_id", help="gpu id to use", default="", type=str) parser.add_argument("-s", "--use_shuffled_kfold", help="whether to use shuffled kfold.", action="store_true") parser.add_argument("-rs", "--random_seed", help="random seed used for k-fold split.", default=6, type=int) parser.add_argument("-tta", "--tta", help="whether test time augmentation",action="store_true") parser.add_argument("-a", "--additional_data_dir", help="where to get the additional data", default="", type=str) parser.add_argument("-ta", "--additional_test_or_train", help="use additional data in only train, or test, or both", default="", type=str) parser.add_argument("-as", "--stylegan_data_dir", help="where to get the additional data", default="", type=str) parser.add_argument("-ts", "--stylegan_test_or_train", help="use stylegan data in only train, or test, or both", default="", type=str) parser.add_argument("-tf", "--transfer", help="how many layer(s) used for transfer learning, " "but 0 means retraining the whole network.", default=0, type=int) parser.add_argument("-ac", "--arch", help="types of model used for encoder", default="mobile", type=str) args = parser.parse_args() for arg in vars(args): print(arg+':', getattr(args, arg)) emore_dir = 'faces_emore' conf = get_config(True, args) conf.emore_folder = conf.data_path/emore_dir mtcnn = MTCNN() print('mtcnn loaded') names_considered = args.names_considered.strip().split(',') exp_name = args.dataset_dir[:4] if args.additional_data_dir: if 'LAG' in args.additional_data_dir: exp_name += '_lag' elif 'literature' in args.additional_data_dir: exp_name += '_ltr' if args.kfold != 10: exp_name += ('_k' + str(args.kfold)) if args.epochs != 20: exp_name += ('_e' + str(args.epochs)) if args.transfer != 0 and args.transfer != 1: exp_name += ('_td' + str(args.transfer)) if args.use_shuffled_kfold: exp_name += ('_s' + str(args.random_seed)) print(exp_name) # prepare folders raw_dir = 'raw_112' verify_type = 'trans' if args.use_shuffled_kfold: verify_type += '_shuffled' # train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir = conf.emore_folder/'imgs' test_dir = conf.emore_folder/'test' conf.facebank_path = train_dir if os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir) for name in names_considered: os.makedirs(str(train_dir) + '/' + name, exist_ok=True) os.makedirs(str(test_dir) + '/' + name, exist_ok=True) if args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders = os.listdir(full_stylegan_dir) if args.additional_data_dir: full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir) # init kfold if args.use_shuffled_kfold: kf = KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed) else: kf = KFold(n_splits=args.kfold, shuffle=False, random_state=None) # collect and split raw data data_dict = {} idx_gen = {} for name in names_considered: tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/' + name + '*') if 'innm' in args.stylegan_data_dir: tmp_list = tmp_list + glob.glob(str(full_stylegan_dir) + '/' + name + '*') stylegan_folders = [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] = np.array(tmp_list) idx_gen[name] = kf.split(data_dict[name]) if 'literature' in args.additional_data_dir: data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir) + '/*')) idx_gen['ltr'] = kf.split(data_dict['ltr']) score_names = [] scores = [] wrong_names = [] args.stored_result_path = args.stored_result_dir + os.sep + str(datetime.datetime.now())[:19] if not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) # for fold_idx, (train_index, test_index) in enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx in range(args.kfold): train_set = {} test_set = {} for name in names_considered: (train_index, test_index) = next(idx_gen[name]) train_set[name], test_set[name] = data_dict[name][train_index], data_dict[name][test_index] if 'ltr' in data_dict.keys(): (train_index, test_index) = next(idx_gen['ltr']) train_set['ltr'], test_set['ltr'] = data_dict['ltr'][train_index], data_dict['ltr'][test_index] if 'train' in args.additional_test_or_train: train_set['noonan'] = np.concatenate((train_set['noonan'], train_set['ltr'])) if 'test' in args.additional_test_or_train: test_set['noonan'] = np.concatenate((test_set['noonan'], test_set['ltr'])) # remove previous data prev = glob.glob(str(train_dir) + '/*/*') for p in prev: os.remove(p) prev = glob.glob(str(test_dir) + '/*/*') for p in prev: os.remove(p) # save trains to conf.facebank_path/args.dataset_dir/'train' and # tests to conf.data_path/'facebank'/args.dataset_dir/'test' # count unbalanced data train_count = {} test_count = {} for name in names_considered: train_count[name] = 0 for i in range(len(train_set[name])): img_folder = str(train_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(train_dir), name, str(img))) train_count[name] += 1 # addition data from stylegan if 'interp' not in data_dict.keys(): folder = os.path.basename(train_set[name][i]) if args.stylegan_data_dir and ('train' in args.stylegan_test_or_train) and (folder in stylegan_folders): for img in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(train_dir), name, str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2]) + # '/' + verify_type + '/train/' + name + os.sep + img)) train_count[name] += 1 # test for i in range(len(test_set[name])): test_count[name] = 0 img_folder = str(test_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 # addition data from stylegan if 'interp' not in data_dict.keys(): folder = os.path.basename(test_set[name][i]) if args.stylegan_data_dir and ('test' in args.stylegan_test_or_train) and (folder in stylegan_folders): # and # (folder not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 print(train_count, test_count) # deal with unbalanced data """ if train_count['normal'] // train_count['noonan'] > 1: aug_num = train_count['normal'] // train_count['noonan'] - 1 for img in os.listdir(os.path.join(str(train_dir), 'noonan')): for aug_idx in range(aug_num): aug_img = img[:img.rfind('.')] + '_' + str(aug_idx) + img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan', img), os.path.join(str(train_dir), 'noonan', aug_img)) """ if 'fake' in args.additional_data_dir: fake_dict = {'noonan':'normal', 'normal':'noonan'} full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data = glob.glob(str(full_additional_dir) + os.sep + '*.png') print('additional:', args.additional_data_dir, len(add_data)) for name in names_considered: for img_f in add_data: if name in img_f.strip().split(os.sep)[-1]: # print('source:', img_f) # print('copy to:', img_f.replace(str(full_additional_dir), # str(train_dir) + os.sep + fake_dict[name])) # print('copy to:', img_f.replace(args.additional_data_dir, # verify_type + '/train/' + name)) shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f))) print(fold_idx) print('datasets ready') conf_train = get_config(True, args) conf_train.emore_folder = conf.data_path/emore_dir conf_train.stored_result_dir = args.stored_result_path learner = face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) # conf, inference=False, transfer=0 if args.transfer != 0: learner.load_state(conf.save_path, False, True) print('learner loaded') learner.train(conf_train, args.epochs) print('learner retrained.') learner.save_state() print('Model is saved') # prepare_facebank targets, names, names_idx = prepare_facebank(conf, learner.model, mtcnn, tta = args.tta) print('names_classes:', names) noonan_idx = names_idx['noonan'] print('facebank updated') for path in test_dir.iterdir(): if path.is_file(): continue # print(path) for fil in path.iterdir(): # print(fil) orig_name = ''.join([i for i in fil.name.strip().split('.')[0].split('_')[0] if not i.isdigit()]) for name in names_idx.keys(): if name in orig_name: score_names.append(names_idx[name]) """ if orig_name not in names_considered: print("Un-considered name:", fil.name) continue """ frame = cv2.imread(str(fil)) image = Image.fromarray(frame) faces = [image,] distance = learner.binfer(conf, faces, targets, args.tta) label = score_names[-1] score = np.exp(distance.dot(-1)) pred = np.argmax(score, 1) if pred != label: wrong_names.append(orig_name) scores.append(score) score_names = np.array(score_names) wrong_names = np.array(wrong_names) score_np = np.squeeze(np.array(scores)) n_classes = score_np.shape[1] score_names = label_binarize(score_names, classes=range(n_classes)) score_sum = np.zeros([score_np.shape[0], 1]) for i in range(n_classes): score_sum += score_np[:, i, None] # keep the dimension relative_scores = (score_np / score_sum) total_scores = relative_scores.ravel() total_names = score_names.ravel() name_path = os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path, wrong_names) label_path = os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path, score_names) score_path = os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path, relative_scores) print('saved!') # Compute ROC curve and ROC area for noonan fpr, tpr, _ = roc_curve(total_names, total_scores) #scores_np[:, noonan_idx] roc_auc = auc(fpr, tpr) # For PR curve precision, recall, _ = precision_recall_curve(total_names, total_scores) average_precision = average_precision_score(total_names, total_scores) # plots plt.figure() colors = list(mcolors.TABLEAU_COLORS) lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.4f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc="lower right") plt.savefig(args.stored_result_path + os.sep + '/fp_tp_{}.png'.format(exp_name)) plt.close() # plt.show() plt.figure() plt.step(recall, precision, where='post') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Average precision score ({}): AP={:0.4f}'.format(exp_name, average_precision)) plt.savefig(args.stored_result_path + os.sep + '/pr_{}.png'.format(exp_name)) plt.close()
[ 11748, 269, 85, 17, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 1822, 29572, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 18540, 305, 919, 278, 1330, 10854, 11, 36039, 11, 11395, 11, 19182, 198, 11748, 28034, 198, 6738, 4566, 1330, ...
2.057384
7,476
import time def event_call(other_arg, kwarg="-", result=None): """Call this metod, on returned result""" print(f"Bind Result, {result}\n"*10) print("other_arg", other_arg) print("kwarg", kwarg) if __name__ == "__main__": try: from dirio import Dirio except: from ..dirio import Dirio dr_cls = Dirio(target=TryClass, args=(888,), kwargs={}, worker=False) print("Starting values :", dr_cls.value, dr_cls) print("\n"*2) print("Wait 1 sec for your reply. metod 1 :", dr_cls.metod1(5, val2="1", dr_wait=1)) print("Wait until the reply comes. metod 1 :", dr_cls.metod1(5, val2="1", dr_wait=-1)) code0 = dr_cls.metod1(5, val2="1", dr_code=True) print("Metod 1, call, via bind to func", dr_cls.dr_bind(code0, event_call, args=("OtHeR aRg", ), kwargs={"kwarg": "KwArG"})) while True: # dr_cls.dr_binds_check() print("Run the method and give us the response reading code : dr_code=True") code1 = dr_cls.metod1(5, val2="1", dr_code=True) print("Is there data in the reading code? : dr_code=43534") while not dr_cls.metod1(dr_code=code1): print("We are waiting for the data with this code :", code1) time.sleep(.5) print("Returned metod 1 data :", dr_cls.metod1(dr_code=code1)) print("Methods called this way give the last return value : nothing or dr_code=False") code2 = dr_cls.metod2(10, val2="2", dr_code=True) print("Search by code only :", dr_cls.dr_code(code2, wait=1)) print("Trying metod 2, called and returned :", dr_cls.metod2(10, val2="2", dr_code=False)) print("Trying metod 3, called and returned :", dr_cls.metod3(15, val2="3")) print("\n"*2) time.sleep(3) dr_cls.dr_terminate()
[ 11748, 640, 628, 198, 198, 4299, 1785, 62, 13345, 7, 847, 62, 853, 11, 479, 86, 853, 2625, 12, 1600, 1255, 28, 14202, 2599, 198, 220, 220, 220, 37227, 14134, 428, 1138, 375, 11, 319, 4504, 1255, 37811, 198, 220, 220, 220, 3601, 7,...
2.188769
837
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """This module implements the abstract base class for backend modules. To create add-on backend modules subclass the Backend class in this module. Doing so requires that the required backend interface is implemented. """ from abc import ABC, abstractmethod from qiskit.version import __version__ from .models import BackendStatus def properties(self): """Return backend properties. Returns: BackendProperties: the configuration for the backend. If the backend does not support properties, it returns ``None``. """ return None def provider(self): """Return the backend Provider. Returns: BaseProvider: the Provider responsible for the backend. """ return self._provider def status(self): """Return backend status. Returns: BackendStatus: the status of the backend. """ return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0, status_msg='') def name(self): """Return backend name. Returns: str: the name of the backend. """ return self._configuration.backend_name def __repr__(self): """Official string representation of a Backend. Note that, by Qiskit convention, it is consciously *not* a fully valid Python expression. Subclasses should provide 'a string of the form <...some useful description...>'. [0] [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__ """ return "<{}('{}') from {}()>".format(self.__class__.__name__, self.name(), self._provider)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 2177, 11, 19764, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 1043, 287, 198, 2, 262, 38559, 24290...
2.367829
889
from typing import List import sys s = Solution() ans = s.jump([3,2,1,0,4]) print(ans)
[ 6738, 19720, 1330, 7343, 198, 11748, 25064, 198, 198, 82, 796, 28186, 3419, 198, 198, 504, 796, 264, 13, 43327, 26933, 18, 11, 17, 11, 16, 11, 15, 11, 19, 12962, 198, 4798, 7, 504, 8 ]
2.444444
36
import unittest from . import states
[ 11748, 555, 715, 395, 198, 198, 6738, 764, 1330, 2585, 628 ]
3.545455
11
from jinja2 import nodes from jinja2.ext import Extension
[ 6738, 474, 259, 6592, 17, 1330, 13760, 198, 6738, 474, 259, 6592, 17, 13, 2302, 1330, 27995, 628 ]
3.277778
18
import os def retrieve_molecule_number(pdb, resname): """ IDENTIFICATION OF MOLECULE NUMBER BASED ON THE TER'S """ count = 0 with open(pdb, 'r') as x: lines = x.readlines() for i in lines: if i.split()[0] == 'TER': count += 1 if i.split()[3] == resname: molecule_number = count + 1 break return molecule_number
[ 11748, 28686, 198, 198, 4299, 19818, 62, 76, 2305, 23172, 62, 17618, 7, 79, 9945, 11, 581, 3672, 2599, 628, 220, 220, 220, 37227, 198, 220, 220, 220, 220, 4522, 3525, 30643, 6234, 3963, 13070, 2538, 34, 24212, 36871, 13246, 29809, 196...
1.945205
219
# api.py # Part of PyBBIO # github.com/alexanderhiam/PyBBIO # MIT License # # Beaglebone platform API file. from bbio.platform.platform import detect_platform PLATFORM = detect_platform() if "3.8" in PLATFORM: from bone_3_8.adc import analog_init, analog_cleanup from bone_3_8.pwm import pwm_init, pwm_cleanup from serial_port import serial_cleanup elif "3.2" in PLATFORM: from bone_3_2.adc import analog_init, analog_cleanup from bone_3_2.pwm import pwm_init, pwm_cleanup from serial_port import serial_cleanup
[ 2, 40391, 13, 9078, 220, 198, 2, 2142, 286, 9485, 33, 3483, 46, 198, 2, 33084, 13, 785, 14, 1000, 87, 4066, 71, 1789, 14, 20519, 33, 3483, 46, 198, 2, 17168, 13789, 198, 2, 220, 198, 2, 1355, 19345, 15992, 3859, 7824, 2393, 13, ...
2.604878
205
import re import sys from urllib.parse import quote as _uriquote import requests from . import __version__, errors, utils from .converters import _county_types, _leaderboard_types, _vpn_types, _not_none from . import checks from .cog import request_cog GET='get' POST='post' def get_public_paths(self, **attrs): return self.request(RouteList.get_public_paths(), **attrs) def get_path_summary(self, **attrs): return self.request(RouteList.get_path_summary(), **attrs) # * modules # * games # * VPN # * VM def get_machine_running(self, **attrs): return self.request(RouteList.get_machine_running(), **attrs) # * user -badge def get_user_badges(self, username, **attrs): return self.request(RouteList.get_user_badges(username=username), **attrs) def get_all_badges(self, **attrs): return self.request(RouteList.get_all_badges(), **attrs) # * user -team # * user -notifications # * user -messages # * user -room def get_user_completed_rooms_count(self, username, **attrs): return self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs) def get_user_completed_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_completed_rooms(username=username, options={"limit": limit, "page": page}), **attrs) def get_user_created_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_created_rooms(username=username, options={"limit": limit, "page": page}), **attrs) # * user # * room def get_room_votes(self, room_code, **attrs): return self.request(RouteList.get_room_votes(room_code=room_code), **attrs) def get_room_details(self, room_code, loadWriteUps: bool=True, loadCreators: bool=True, loadUser: bool=True, **attrs): return self.request(RouteList.get_room_details(room_code=room_code, options={"loadWriteUps": loadWriteUps, "loadCreators": loadCreators, "loadUser": loadUser}), **attrs).get(room_code, {}) def get_room_tasks(self, room_code, **attrs): return self.request(RouteList.get_room_tasks(room_code=room_code), **attrs)
[ 11748, 302, 198, 11748, 25064, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 9577, 355, 4808, 333, 1557, 1258, 198, 198, 11748, 7007, 198, 198, 6738, 764, 1330, 11593, 9641, 834, 11, 8563, 11, 3384, 4487, 198, 6738, 764, 1102, 332, 1010...
2.522854
897
import os from argparse import ArgumentParser from pathlib import Path import gym import ray import ray.tune.result as ray_results import yaml from gym.spaces import Tuple from ray.cluster_utils import Cluster from ray.rllib.utils import try_import_tf, try_import_torch from ray.tune import run_experiments, register_env from ray.tune.logger import TBXLogger from ray.tune.resources import resources_to_json from ray.tune.tune import _make_scheduler from ray.tune.utils import merge_dicts from flatlander.envs import get_eval_config from flatlander.envs.flatland_sparse import FlatlandSparse from flatlander.envs.observations import make_obs from flatlander.envs.utils.global_gym_env import GlobalFlatlandGymEnv from flatlander.envs.utils.gym_env_fill_missing import FillingFlatlandGymEnv from flatlander.logging.custom_metrics import on_episode_end from flatlander.logging.wandb_logger import WandbLogger from flatlander.utils.loader import load_envs, load_models ray_results.DEFAULT_RESULTS_DIR = os.path.join(os.getcwd(), "..", "..", "..", "flatland-challenge-data/results")
[ 11748, 28686, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 11550, 198, 11748, 26842, 198, 11748, 26842, 13, 83, 1726, 13, 20274, 355, 26842, 62, 43420, 198, 11748, 331, 43695, 198, 6738,...
3.082621
351
#!/usr/bin/env python r""" This module contains keyword functions to supplement robot's built in functions and use in test where generic robot keywords don't support. """ import time from robot.libraries.BuiltIn import BuiltIn from robot.libraries import DateTime import re ############################################################################### def run_until_keyword_fails(retry, retry_interval, name, *args): r""" Execute a robot keyword repeatedly until it either fails or the timeout value is exceeded. Note: Opposite of robot keyword "Wait Until Keyword Succeeds". Description of argument(s): retry Max timeout time in hour(s). retry_interval Time interval in minute(s) for looping. name Robot keyword to execute. args Robot keyword arguments. """ # Convert the retry time in seconds retry_seconds = DateTime.convert_time(retry) timeout = time.time() + int(retry_seconds) # Convert the interval time in seconds interval_seconds = DateTime.convert_time(retry_interval) interval = int(interval_seconds) BuiltIn().log(timeout) BuiltIn().log(interval) while True: status = BuiltIn().run_keyword_and_return_status(name, *args) # Return if keywords returns as failure. if status is False: BuiltIn().log("Failed as expected") return False # Return if retry timeout as success. elif time.time() > timeout > 0: BuiltIn().log("Max retry timeout") return True time.sleep(interval) BuiltIn().log(time.time()) return True ############################################################################### ############################################################################### def htx_error_log_to_list(htx_error_log_output): r""" Parse htx error log output string and return list of strings in the form "<field name>:<field value>". The output of this function may be passed to the build_error_dict function. Description of argument(s): htx_error_log_output Error entry string containing the stdout generated by "htxcmdline -geterrlog". Example of htx_error_log_output contents: ######################## Result Starts Here ############################### Currently running ECG/MDT : /usr/lpp/htx/mdt/mdt.whit =========================== --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017 err=00000027 sev=1 Exerciser Name:hxenvidia Serial No:Not Available Part No:Not Available Location:Not Available FRU Number:Not Available Device:Not Available Error Text:cudaEventSynchronize for stopEvent returned err = 0039 from file , line 430. --------------------------------------------------------------------- --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017 err=00000027 sev=1 Exerciser Name:hxenvidia Serial No:Not Available Part No:Not Available Location:Not Available FRU Number:Not Available Device:Not Available Error Text:Hardware Exerciser stopped on error --------------------------------------------------------------------- ######################### Result Ends Here ################################ Example output: Returns the lists of error string per entry ['Device id:/dev/nvidia0', 'Timestamp:Mar 29 19:41:54 2017', 'err=00000027', 'sev=1', 'Exerciser Name:hxenvidia', 'Serial No:Not Available', 'Part No:Not Available', 'Location:Not Available', 'FRU Number:Not Available', 'Device:Not Available', 'Error Text:cudaEventSynchronize for stopEvent returned err = 0039 from file , line 430.'] """ # List which will hold all the list of entries. error_list = [] temp_error_list = [] parse_walk = False for line in htx_error_log_output.splitlines(): # Skip lines starting with "#" if line.startswith("#"): continue # Mark line starting with "-" and set parse flag. if line.startswith("-") and parse_walk is False: parse_walk = True continue # Mark line starting with "-" and reset parse flag. # Set temp error list to EMPTY. elif line.startswith("-"): error_list.append(temp_error_list) parse_walk = False temp_error_list = [] # Add entry to list if line is not emtpy elif parse_walk: temp_error_list.append(str(line)) return error_list ############################################################################### ############################################################################### def build_error_dict(htx_error_log_output): r""" Builds error list into a list of dictionary entries. Description of argument(s): error_list Error list entries. Example output dictionary: { 0: { 'sev': '1', 'err': '00000027', 'Timestamp': 'Mar 29 19:41:54 2017', 'Part No': 'Not Available', 'Serial No': 'Not Available', 'Device': 'Not Available', 'FRU Number': 'Not Available', 'Location': 'Not Available', 'Device id': '/dev/nvidia0', 'Error Text': 'cudaEventSynchronize for stopEvent returned err = 0039 from file , line 430.', 'Exerciser Name': 'hxenvidia' }, 1: { 'sev': '1', 'err': '00000027', 'Timestamp': 'Mar 29 19:41:54 2017', 'Part No': 'Not Available', 'Serial No': 'Not Available', 'Device': 'Not Available', 'FRU Number': 'Not Available', 'Location': 'Not Available', 'Device id': '/dev/nvidia0', 'Error Text': 'Hardware Exerciser stopped on error', 'Exerciser Name': 'hxenvidia' } }, """ # List which will hold all the list of entries. error_list = [] error_list = htx_error_log_to_list(htx_error_log_output) # dictionary which holds the error dictionry entry. error_dict = {} temp_error_dict = {} error_index = 0 # Loop through the error list. for entry_list in error_list: # Loop through the first error list entry. for entry in entry_list: # Split string into list for key value update. # Example: 'Device id:/dev/nvidia0' # Example: 'err=00000027' parm_split = re.split("[:=]", entry) # Populate temp dictionary with key value pair data. temp_error_dict[str(parm_split[0])] = parm_split[1] # Update the master dictionary per entry index. error_dict[error_index] = temp_error_dict # Reset temp dict to EMPTY and increment index count. temp_error_dict = {} error_index += 1 return error_dict ###############################################################################
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 81, 37811, 198, 1212, 8265, 4909, 21179, 5499, 284, 10327, 9379, 338, 3170, 287, 198, 12543, 2733, 290, 779, 287, 1332, 810, 14276, 9379, 26286, 836, 470, 1104, 13, 198, 198, 3781...
2.668991
2,725
# Copyright (c) OpenMMLab. All rights reserved. from .builder import NODES from .faceswap_nodes import FaceSwapNode from .frame_effect_nodes import (BackgroundNode, BugEyeNode, MoustacheNode, NoticeBoardNode, PoseVisualizerNode, SaiyanNode, SunglassesNode) from .helper_nodes import ModelResultBindingNode, MonitorNode, RecorderNode from .mmdet_nodes import DetectorNode from .mmpose_nodes import TopDownPoseEstimatorNode from .xdwendwen_nodes import XDwenDwenNode __all__ = [ 'NODES', 'PoseVisualizerNode', 'DetectorNode', 'TopDownPoseEstimatorNode', 'MonitorNode', 'BugEyeNode', 'SunglassesNode', 'ModelResultBindingNode', 'NoticeBoardNode', 'RecorderNode', 'FaceSwapNode', 'MoustacheNode', 'SaiyanNode', 'BackgroundNode', 'XDwenDwenNode' ]
[ 2, 15069, 357, 66, 8, 4946, 44, 5805, 397, 13, 1439, 2489, 10395, 13, 198, 6738, 764, 38272, 1330, 399, 3727, 1546, 198, 6738, 764, 32186, 86, 499, 62, 77, 4147, 1330, 15399, 10462, 499, 19667, 198, 6738, 764, 14535, 62, 10760, 62, ...
2.565217
322
#!/usr/bin/python3 import ibm_db import getopt import sys import os from toposort import toposort_flatten db = None host = "localhost" port = "50000" user = None pwd = None outfile = None targetdb = None try: opts, args = getopt.getopt(sys.argv[1:], "h:d:P:u:p:o:t:") except getopt.GetoptError: sys.exit(-1) for o, a in opts: if o == "-d": db = a if o == "-h": host = a if o == "-P": port = a if o == "-u": user = a if o == "-p": pwd = a if o == "-t": targetdb = a if db is None or user is None or pwd is None or targetdb is None: print("Usage: DBMove.py [-h <host> -P <port>] -d <db> -u <user> -p <pwd> -t <target>") sys.exit(1) db = db.upper() targetdb = targetdb.upper() cfg = (db, host, port, user, pwd) conn = ibm_db.connect("DATABASE=%s; HOSTNAME=%s; PORT=%s; PROTOCOL=TCPIP; UID=%s; PWD=%s" % cfg, "", "") get_db_type = "values nya.get_db_type()" find_edges = """ SELECT rtrim(t.tabschema) || '.' || rtrim(t.tabname) , coalesce(rtrim(r.reftabschema) || '.' || rtrim(r.reftabname), 'dummy') FROM syscat.tables t LEFT JOIN syscat.references r ON (t.tabschema, t.tabname) = (r.tabschema, r.tabname) WHERE t.tabschema not like 'SYS%' AND t.type = 'T' AND rtrim(t.tabschema) not like 'NYA_%' AND t.tabschema <> 'TMP' ORDER BY 1 """ identity_skip = """ select rtrim(tabschema) || '.' || rtrim(tabname) from syscat.columns where identity = 'Y' and generated = 'D' """ stmt = ibm_db.prepare(conn, get_db_type) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) db_type = tpl[0] edges = dict() stmt = ibm_db.prepare(conn, find_edges) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl: n1, n2 = tpl try: edges[n1].add(n2) except KeyError: edges[n1] = set() edges[n1].add(n2) tpl = ibm_db.fetch_tuple(stmt) sorted_nodes = list(toposort_flatten(edges)) # print(sorted_nodes) identity_skip_arr = [] edges = dict() stmt = ibm_db.prepare(conn, identity_skip) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl: identity_skip_arr.append(tpl[0]) tpl = ibm_db.fetch_tuple(stmt) # print(identity_skip) os.makedirs(db, exist_ok=True) export_file = open("%s/export.sql" % db, "w") load_file = open("%s/load.sql" % db, "w") export_file.write("connect to %s;\n" % db) load_file.write("connect to %s;\n" % targetdb) if db_type == "N": load_file.write("""set integrity for nya.person off;\n""") load_file.write("""alter table nya.person alter column EMAIL_UC drop generated alter column NORMALIZED_FIRSTNAME drop generated alter column NORMALIZED_LASTNAME drop generated;\n""") load_file.write("""set integrity for nya.person immediate checked;\n""") for t in sorted_nodes: if t == "dummy": continue export_file.write("export to %s.ixf of ixf lobs to . modified by codepage=819 messages export_%s.msg select * from %s;\n" % (t,t,t)) identityskip = "identityoverride" if t in identity_skip_arr: identityskip = " " load_file.write("load from %s.ixf of ixf lobs from . modified by generatedoverride %s messages load_%s.msg replace into %s;\n" % (t, identityskip, t, t)) if db_type == "N": load_file.write("""set integrity for nya.person off;\n""") load_file.write("""alter table nya.person alter column EMAIL_UC set generated always as ( upper(email)) alter column NORMALIZED_FIRSTNAME set generated always as ( NYA.REMOVE_DIACRITICS( FIRSTNAME ) ) alter column NORMALIZED_LASTNAME set generated always as ( NYA.REMOVE_DIACRITICS( LASTNAME ) );\n""") load_file.write("""set integrity for nya.person immediate checked force generated;\n""") load_file.write("""echo set integrity for all tables;\n""") export_file.write("connect reset;\n") load_file.write("connect reset;\n") export_file.close() load_file.close()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 24283, 76, 62, 9945, 198, 11748, 651, 8738, 198, 11748, 25064, 198, 11748, 28686, 198, 6738, 1353, 418, 419, 1330, 1353, 418, 419, 62, 2704, 41769, 198, 198, 9945, 796, 6045, ...
2.168365
1,865
import numpy as np DEFAULT_FILE_PATH = "utils/datasets/glove.6B.50d.txt" def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50): """Read pretrained GloVe vectors""" wordVectors = np.zeros((len(tokens), dimensions)) with open(filepath) as ifs: for line in ifs: line = line.strip() if not line: continue row = line.split() token = row[0] if token not in tokens: continue data = [float(x) for x in row[1:]] if len(data) != dimensions: raise RuntimeError("wrong number of dimensions") wordVectors[tokens[token]] = np.asarray(data) return wordVectors
[ 11748, 299, 32152, 355, 45941, 198, 198, 7206, 38865, 62, 25664, 62, 34219, 796, 366, 26791, 14, 19608, 292, 1039, 14, 4743, 659, 13, 21, 33, 13, 1120, 67, 13, 14116, 1, 198, 198, 4299, 3440, 26449, 53, 478, 669, 7, 83, 482, 641, ...
2.05042
357
# Copyright 2021 MosaicML. All Rights Reserved. """Performance profiling tools. The profiler gathers performance metrics during a training run that can be used to diagnose bottlenecks and facilitate model development. The metrics gathered include: * Duration of each :class:`.Event` during training * Time taken by the data loader to return a batch * Host metrics such as CPU, system memory, disk and network utilization over time * Execution order, latency and attributes of PyTorch operators and GPU kernels (see :doc:`profiler`) The following example demonstrates how to setup and perform profiling on a simple training run. .. literalinclude:: ../../../examples/profiler_demo.py :language: python :linenos: :emphasize-lines: 6, 27-49 It is required to specify an output ``profiler_trace_file`` during :class:`.Trainer` initialization to enable profiling. The ``profiler_trace_file`` will contain the profiling trace data once the profiling run completes. By default, the :class:`.Profiler`, :class:`.DataloaderProfiler` and :class:`.SystemProfiler` will be active. The :class:`.TorchProfiler` is **disabled** by default. To activate the :class:`.TorchProfiler`, the ``torch_profiler_trace_dir`` must be specified *in addition* to the ``profiler_trace_file`` argument. The ``torch_profiler_trace_dir`` will contain the Torch Profiler traces once the profiling run completes. The :class:`.Profiler` will automatically merge the Torch traces in the ``torch_profiler_trace_dir`` into the ``profiler_trace_file``, allowing users to view a unified trace. The complete traces can be viewed by in a Google Chrome browser navigating to ``chrome://tracing`` and loading the ``profiler_trace_file``. Here is an example trace file: .. image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt: Example Profiler Trace File :align: center Additonal details an be found in the Profiler Guide. """ from composer.profiler._event_handler import ProfilerEventHandler from composer.profiler._profiler import Marker, Profiler from composer.profiler._profiler_action import ProfilerAction # All needs to be defined properly for sphinx autosummary __all__ = [ "Marker", "Profiler", "ProfilerAction", "ProfilerEventHandler", ] Marker.__module__ = __name__ Profiler.__module__ = __name__ ProfilerAction.__module__ = __name__ ProfilerEventHandler.__module__ = __name__
[ 2, 15069, 33448, 5826, 18452, 5805, 13, 1439, 6923, 33876, 13, 198, 198, 37811, 32273, 31582, 4899, 13, 198, 198, 464, 1534, 5329, 43609, 2854, 20731, 1141, 257, 3047, 1057, 326, 460, 307, 973, 284, 37489, 3005, 11925, 721, 591, 290, ...
3.539797
691
''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import codecs import os import sys import time from setuptools import setup # Folder containing the setup.py root = os.path.dirname(os.path.abspath(__file__)) # Path to __version__ module version_file = os.path.join(root, 'gremlin_python', '__version__.py') # Check if this is a source distribution. # If not create the __version__ module containing the version if not os.path.exists(os.path.join(root, 'PKG-INFO')): timestamp = int(os.getenv('TIMESTAMP', time.time() * 1000)) / 1000 fd = codecs.open(version_file, 'w', 'utf-8') fd.write("'''") fd.write(__doc__) fd.write("'''\n") fd.write('version = %r\n' % os.getenv('VERSION', '?').replace('-SNAPSHOT', '.dev-%d' % timestamp)) fd.write('timestamp = %d\n' % timestamp) fd.close() # Load version from gremlin_python import __version__ version = __version__.version install_requires = [ 'aenum==1.4.5', 'tornado==4.4.1', 'six==1.10.0' ] if sys.version_info < (3,2): install_requires += ['futures==3.0.5'] setup( name='gremlinpython', version=version, packages=['gremlin_python', 'gremlin_python.driver', 'gremlin_python.driver.tornado', 'gremlin_python.process', 'gremlin_python.structure', 'gremlin_python.structure.io'], license='Apache 2', url='http://tinkerpop.apache.org', description='Gremlin-Python for Apache TinkerPop', long_description=codecs.open("README", "r", "UTF-8").read(), test_suite="tests", data_files=[("", ["LICENSE", "NOTICE"])], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', 'mock' ], install_requires=install_requires, classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Natural Language :: English", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ] )
[ 7061, 6, 198, 26656, 15385, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 273, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 17080, 6169, 351, 428, 670, 329, 3224, 1321, 198, 2301, 13493, 6634, 9238, ...
2.764056
996
from typing import Optional, Sequence import plotly.graph_objects as go def bar(x: Sequence, y: Sequence, text: Optional[Sequence] = None, width: Optional[int] = None, col: Optional[str] = None, opacity: float = 1, name: Optional[str] = None, show_legend: bool = False, show_init: bool = True) -> go.Bar: """Create a simple Trace object of a histogram. positional arguments: @ x : Coordinates of data on x-axis. @ y : Coordinates of data on y-axis. optional arguments: @ col : Color of bars. @ opacity : Opacity of bars. @ name : Display name of the trace in legend. @ show_legend : Show this trace in legend. @ show_init : Show this trace initially. """ return go.Bar(x=x, y=y, text=text, width=width, marker_color=col, opacity=opacity, name=name, showlegend=show_legend, visible=None if show_init else "legendonly")
[ 6738, 19720, 1330, 32233, 11, 45835, 198, 11748, 7110, 306, 13, 34960, 62, 48205, 355, 467, 198, 198, 4299, 2318, 7, 87, 25, 45835, 11, 198, 220, 220, 220, 220, 220, 220, 220, 331, 25, 45835, 11, 198, 220, 220, 220, 220, 220, 220,...
2.082397
534
# Copyright 2018-2021 Xanadu Quantum Technologies 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. r""" Contains the ArbitraryUnitary template. """ import pennylane as qml from pennylane.operation import Operation, AnyWires from pennylane.ops import PauliRot _PAULIS = ["I", "X", "Y", "Z"] def _tuple_to_word(index_tuple): """Convert an integer tuple to the corresponding Pauli word. The Pauli operators are converted as ``0 -> I``, ``1 -> X``, ``2 -> Y``, ``3 -> Z``. Args: index_tuple (Tuple[int]): An integer tuple describing the Pauli word Returns: str: The corresponding Pauli word """ return "".join([_PAULIS[i] for i in index_tuple])
[ 2, 15069, 2864, 12, 1238, 2481, 47482, 324, 84, 29082, 21852, 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, ...
3.172872
376
import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from pytorch_lightning.loggers import TensorBoardLogger from torch.utils.data import DataLoader from torchvision import transforms from torchvision.datasets import CelebA if __name__ == '__main__': # data transform = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.CenterCrop(148), transforms.Resize(128), transforms.ToTensor() ]) train_dataset = CelebA(root='data', split='train', transform=transform, download=False) val_dataset = CelebA(root='data', split='test', transform=transform, download=False) train_loader = DataLoader(train_dataset, batch_size=32, num_workers=8, shuffle=True, drop_last=True) val_loader = DataLoader(val_dataset, batch_size=32, num_workers=8, shuffle=False, drop_last=True) # model model = VanillaVAE() # training tb_logger = TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba', default_hp_metric=False) trainer = pl.Trainer(gpus=[0], max_epochs=200, logger=tb_logger) trainer.fit(model, train_loader, val_loader)
[ 11748, 12972, 13165, 354, 62, 2971, 768, 355, 458, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 6738, 12972, 13165, 354, ...
2.159332
659
# Import libraries import sys import pandas as pd from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): """ Load the data from the disaster response csvs Parameters: messages_filepath (str): Path to messages csv categories_filepath (str): Path to categories csv Returns: Dataframe: Merged data """ messages = pd.read_csv(messages_filepath) categories = pd.read_csv(categories_filepath) df = pd.merge(messages,categories,on='id') return df def clean_data(df): """ Cleans the categories Parameters: df (DataFrame): Messy DataFrame Returns: Dataframe: Cleaned dataframe """ categories = df['categories'].str.split( pat=';', expand=True) row = categories.iloc[[1]] category_colnames = row.apply(lambda x : x.values[0].split("-")[0]) categories.columns = category_colnames for column in categories: categories[column] = categories[column].astype(str).str[-1:] categories[column] = categories[column].astype(int) categories[column] = categories[column].map(lambda x: 1 if x > 1 else x) df.drop(['categories'], axis=1, inplace=True) df = df = pd.concat([df,categories], axis=1) df.drop_duplicates(inplace=True) return df def save_data(df, database_filename): """ Saves the DataFrame Parameters: df (DataFrame): Cleaned DataFrame database_filename (DataFrame): Path to the SQLite Database """ engine = create_engine('sqlite:///' + database_filename + '.db') df.to_sql(database_filename, engine, index=False, if_exists='replace') if __name__ == '__main__': main()
[ 2, 17267, 12782, 198, 11748, 25064, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 628, 198, 4299, 3440, 62, 7890, 7, 37348, 1095, 62, 7753, 6978, 11, 9376, 62, 7753, 6978, 2599, 198, 220, ...
2.647335
638
#!/usr/bin/env python3 import subprocess import sys import json SERVICES = { 'control': [ 'control', 'nodemgr', 'named', 'dns', ], 'config-database': [ 'nodemgr', 'zookeeper', 'rabbitmq', 'cassandra', ], 'webui': [ 'web', 'job', ], 'config': [ 'svc-monitor', 'nodemgr', 'device-manager', 'api', 'schema', ], } WARNING = 1 CRITICAL = 2 if __name__ == '__main__': cver = sys.argv[1] if '.' in str(cver): if cver == '5.0': version = 500 elif cver == '5.1': version = 510 else: print("CRITICAL: invalid version: {}".format(cver)) sys.exit(CRITICAL) elif not cver.isdigit(): print("CRITICAL: invalid version: {}".format(cver)) sys.exit(CRITICAL) else: version = int(cver) check_contrail_status(SERVICES, version=version)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 11748, 33918, 198, 198, 35009, 53, 34444, 796, 1391, 198, 220, 220, 220, 705, 13716, 10354, 685, 198, 220, 220, 220, 220, 220, 220, ...
1.830258
542
from flask import Flask, jsonify, request from flask_cors import CORS, cross_origin import simplejson as json from leaderboard.leaderboard import Leaderboard import uwsgidecorators import signalfx app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app) highscore_lb_starship = Leaderboard('highscores-starship',host='redis-instance') sfx = signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') if __name__ == '__main__': app.run(host='0.0.0.0', port=6001)
[ 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 2581, 198, 6738, 42903, 62, 66, 669, 1330, 327, 20673, 11, 3272, 62, 47103, 198, 198, 11748, 2829, 17752, 355, 33918, 198, 6738, 3554, 3526, 13, 27940, 3526, 1330, 10540, 3526, 198, 11748, ...
2.640777
206
import argparse import numpy as np from .._helpers import read, reader_map from ._helpers import _get_version_text
[ 11748, 1822, 29572, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 11485, 62, 16794, 364, 1330, 1100, 11, 9173, 62, 8899, 198, 6738, 47540, 16794, 364, 1330, 4808, 1136, 62, 9641, 62, 5239, 628, 198 ]
3.216216
37
import os, shutil from CCSLink import Spark_Session as SS def add_zipped_dependency(zip_from, zip_target): """ This method creates a zip of the code to be sent to the executors. It essentially zips the Python packages installed by PIP and submits them via addPyFile in the current PySpark context E.g. if we want to submit "metaphone" package so that we can do use `import metaphone` and use its methods inside UDF, we run this method with: - zip_from = /home/cdsw/.local/lib/python3.6/site-packages/ - zip_target = metaphone """ # change this to a path in your project zipped_fpath = f'/home/cdsw/zipped_packages/{zip_target}' if os.path.exists(zipped_fpath + '.zip'): os.remove(zipped_fpath + '.zip') shutil.make_archive( # path to the resulting zipped file (without the suffix) base_name=zipped_fpath, # resulting filename # specifies the format --> implies .zip suffix format='zip', # the root dir from where we want to zip root_dir=zip_from, # the dir (relative to root dir) which we want to zip # (all files in the final zip will have this prefix) base_dir=zip_target, ) # add the files to the executors SS.SPARK().sparkContext.addPyFile(f'{zipped_fpath}.zip')
[ 11748, 28686, 11, 4423, 346, 198, 6738, 327, 7902, 11280, 1330, 17732, 62, 36044, 355, 6723, 198, 198, 4299, 751, 62, 89, 3949, 62, 45841, 1387, 7, 13344, 62, 6738, 11, 19974, 62, 16793, 2599, 198, 220, 220, 220, 37227, 198, 220, 22...
2.674747
495
try: from .nbody_graph_search import Ugraph except (SystemError, ValueError): # not installed as a package from nbody_graph_search import Ugraph # This file defines how 3-body angle interactions are generated by moltemplate # by default. It can be overridden by supplying your own custom file. # To find 3-body "angle" interactions, we would use this subgraph: # # # *---*---* => 1st bond connects atoms 0 and 1 # 0 1 2 2nd bond connects atoms 1 and 2 # bond_pattern = Ugraph([(0, 1), (1, 2)]) # (Ugraph atom indices begin at 0, not 1) # The next function eliminates the redundancy between 0-1-2 and 2-1-0: def canonical_order(match): """ Before defining a new interaction, we must check to see if an interaction between these same 3 atoms has already been created (perhaps listed in a different, but equivalent order). If we don't check for this this, we will create many unnecessary redundant interactions (which can slow down he simulation). To avoid this, I define a "canonical_order" function which sorts the atoms and bonds in a way which is consistent with the symmetry of the interaction being generated... Later the re-ordered list of atom and bond ids will be tested against the list of atom/bond ids in the matches-found-so-far, before it is added to the list of interactions found so far. Note that the energy of an angle interaction is a function of the angle between. three consecutively bonded atoms (referred to here as: 0,1,2). This angle does not change when swapping the atoms at either end (0 and 2). So it does not make sense to define a separate 3-body angle interaction between atoms 0,1,2 AS WELL AS an interaction between 2,1,0. So we sort the atoms and bonds so that the first atom has a always has a lower atomID than the third atom. (Later we will check to see if we have already defined an interaction between these 3 atoms. If not then we create a new one.) """ # match[0][0:2] contains the ID numbers for the 3 atoms in the match atom0 = match[0][0] atom1 = match[0][1] atom2 = match[0][2] # match[1][0:1] contains the ID numbers for the 2 bonds bond0 = match[1][0] bond1 = match[1][1] if atom0 < atom2: # return ((atom0, atom1, atom2), (bond0, bond1)) same thing as: return match else: return ((atom2, atom1, atom0), (bond1, bond0))
[ 28311, 25, 198, 220, 220, 220, 422, 764, 77, 2618, 62, 34960, 62, 12947, 1330, 24384, 1470, 198, 16341, 357, 11964, 12331, 11, 11052, 12331, 2599, 198, 220, 220, 220, 1303, 407, 6589, 355, 257, 5301, 198, 220, 220, 220, 422, 299, 26...
3.010909
825
#!/pxrpythonsubst # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # ''' Creates a top-level, referenceable asset USD file from one or more 'variant' files, each of which can contain arbitrary scene description. When supplying multiple files, one must also provide the name for a variantSet that will be constructed to switch between the files. The asset file will place the variant files behind a "payload", which will enable consumers to defer loading and processing of the data when composed onto a UsdStage. The names of the created variations will be taken directly from the basename of their corresponding input file. ''' from __future__ import print_function from pxr import Tf, Kind, Sdf, Usd # ToDo: # - handle multiple variantSets # - layer multiple kinds of files (e.g. shading.usd over geom.usd) # - allow output filename to be independently specifiable? (Breaks with Pixar # convention) # - allow variant names to be specified independently of variant file names # - Compute and present (per-variant) UsdGeomModelAPI.extentsHint # - Compute and author UsdModelAPI::SetPayloadAssetDependencies() if __name__ == "__main__": import argparse, os, sys descr = __doc__.strip() parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr) parser.add_argument('assetName') parser.add_argument('variantFiles', nargs='+') parser.add_argument( '-k', '--kind', default='component', action='store', metavar='kind', help="Model kind, one of: component, group, or assembly") parser.add_argument( '-v', '--variantSet', default='', action='store', metavar='variantSet', help="Variantset to create to modulate variantFiles. Can be elided " "if only one file is supplied") parser.add_argument( '-i', '--identifier', default='', action='store', metavar='identifier', help="The identifier you would expect your Ar asset-resolver plugin " "to resolve to the (installed) assetName.usd file this script creates. " " If unspecified, defaults to assetName.usd") parser.add_argument( '-d', '--defaultVariantSelection', default='', action='store', metavar='defaultVariantSelection', help="This variant will be selected by default when the asset is " "added to a composition. If unspecified, will be the variant for " "'variantFile1'") args = parser.parse_args() if not args.assetName or args.assetName == '': parser.error("No assetName specified") stage = CreateModelStage(args.assetName, assetIdentifier=args.identifier, kind=args.kind, filesToReference=args.variantFiles, variantSetName=args.variantSet, defaultVariantSelection=args.defaultVariantSelection) if stage: stage.GetRootLayer().Save() exit(0) else: exit(1)
[ 2, 48443, 8416, 81, 79, 5272, 684, 549, 301, 198, 2, 198, 2, 15069, 1584, 46706, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 25189, 4891, 13789, 4943, 198, 2, 351, 262, 1708, 17613, 26, ...
2.848084
1,435
import sys import os sys.path.append('./code/') from skeleton import Skeleton from read_data import * from calibration import Calibration from ukf_filter import ukf_Filter_Controler from canvas import Canvas from regression import * import time from functools import wraps import os def make_folder(folder_name): if not os.path.isdir(folder_name): os.mkdir(folder_name) return folder_name def get_save_skeleton_data_folder_name(person_name, pos_mode, model): folder_name = make_folder('result') folder_name = make_folder(folder_name + '/' + person_name) folder_name = make_folder(folder_name + '/' + pos_mode) folder_name = make_folder(folder_name + '/' + model) return folder_name + '/' def save_sk_data_to_csv(folder_name, filename, data): filename = folder_name + filename f = open(filename, "w", encoding="UTF-8") for i in range(len(data)): for j in range(len(data[i])): for k in range(3): f.write(str(data[i][j][k])) if j == (len(data[i])-1) and k == 2: f.write('\n') else: f.write(',')
[ 11748, 25064, 198, 11748, 28686, 198, 17597, 13, 6978, 13, 33295, 7, 4458, 14, 8189, 14, 11537, 198, 198, 6738, 18328, 1330, 19460, 10565, 198, 6738, 1100, 62, 7890, 1330, 1635, 198, 6738, 36537, 1330, 2199, 571, 1358, 198, 6738, 334, ...
2.63198
394
from __future__ import print_function import json import os from django.conf import settings from django.contrib.auth.hashers import make_password from django.contrib.auth.models import User from wagtail.wagtailcore.models import Page, Site from v1.models import HomePage, BrowseFilterablePage
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 33918, 198, 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 10134, 7084, 1330, 787, 62, 28712, 198...
3.505882
85
# Simple python3 script to compare output with a reference output. # Usage: python3 compareOutputs.py testOutput.h5 testRefOutput.h5 import sys import h5py import numpy as np if len(sys.argv) != 3: print("Expected two arguments. Output and reference output file.") sys.exit(1) filename = sys.argv[1] ref_filename = sys.argv[2] f = h5py.File(filename, 'r') ref_f = h5py.File(ref_filename, 'r') out = np.array(f['output_data']) out_ref = np.array(ref_f['output_data']) if out.shape != out_ref.shape: print("The files do not contain the same number of outputs.") print("The output size: {0}.".format(out.shape[0])) print("The reference size: {0}.".format(out_ref.shape[0])) sys.exit(1) ref_value = np.copy(out_ref) ref_value[ref_value == 0.0] = 1.0 error = (out_ref - out) / ref_value maximal_error = np.amax(error) print("Maximal error between the output and the reference is {0}.".format(maximal_error)) if maximal_error < 10**(-6): print("OK:Output seems to match the reference.") sys.exit(0) print("Failure:Output does not match the reference.") maximal_error = np.amax(error, axis=1) print(maximal_error.shape) for i in range(0, 5): print("Image", i) print("Expected:", end="") for j in range(0, 10): print(out_ref[i, j], end = " ") print("\nGot:", end="") for j in range(0, 10): print(out[i, j], end=" ") print("\nMaximal error:", maximal_error[i], "\n") sys.exit(1)
[ 2, 17427, 21015, 18, 4226, 284, 8996, 5072, 351, 257, 4941, 5072, 13, 198, 2, 29566, 25, 21015, 18, 8996, 26410, 82, 13, 9078, 1332, 26410, 13, 71, 20, 1332, 8134, 26410, 13, 71, 20, 198, 198, 11748, 25064, 198, 11748, 289, 20, 90...
2.51468
579
# -*- coding: utf-8 -*- from rest_framework import serializers from .models import Tag
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 764, 27530, 1330, 17467, 628 ]
3
30
from amqpstorm.management import ApiConnectionError from amqpstorm.management import ApiError from amqpstorm.management import ManagementApi if __name__ == '__main__': API = ManagementApi('http://127.0.0.1:15672', 'guest', 'guest') try: result = API.aliveness_test('/') if result['status'] == 'ok': print("RabbitMQ is alive!") else: print("RabbitMQ is not alive! :(") except ApiConnectionError as why: print('Connection Error: %s' % why) except ApiError as why: print('ApiError: %s' % why)
[ 6738, 716, 80, 79, 12135, 13, 27604, 1330, 5949, 72, 32048, 12331, 198, 6738, 716, 80, 79, 12135, 13, 27604, 1330, 5949, 72, 12331, 198, 6738, 716, 80, 79, 12135, 13, 27604, 1330, 8549, 32, 14415, 198, 198, 361, 11593, 3672, 834, 66...
2.39916
238
# -*- coding: utf-8 -*- from zvt.contract.api import df_to_db from zvt.contract.recorder import Recorder from zvt.domain.meta.stockhk_meta import Stockhk from zvt.recorders.em import em_api if __name__ == "__main__": recorder = EMStockhkRecorder() recorder.run() # the __all__ is generated __all__ = ["EMStockhkRecorder"]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 1976, 36540, 13, 28484, 13, 15042, 1330, 47764, 62, 1462, 62, 9945, 198, 6738, 1976, 36540, 13, 28484, 13, 8344, 2875, 1330, 3311, 2875, 198, 6738, 1976, 3654...
2.629921
127
from util.io import read_setting_json, read_0h_data, read_24h_data, draw_single_curve from util.convert import split_array_into_samples, calculate_avg_of_sample, convert_to_percentage from util.calculus import calculate_summary_of_sample, fit_sigmoid_curve import matplotlib.pyplot as plt import numpy as np import csv setting = read_setting_json() setting = setting["rule"] # load experiment parameter # experiment parameter is stored in file of ./data/setting.json initial_filename = setting["0h_datafile"] final_filename = setting["24h_datafile"] # sample width and height are the size of each sample area sample_width = setting["sample_width"] sample_height = setting["sample_height"] dilution_protocol = setting["dilution_protocol"] # width of each dilution basic_width = setting["basic_width"] # number of each control group control_number_list = setting["control_number"] # output directory output_directory = setting["output_directory"] # import initial concentration and calculate x_data initial_concentration = setting["initial_concentration"] repeat_times = int(sample_width / basic_width) x_data = [] current_concentration = initial_concentration for i in range(repeat_times): x_data.append(current_concentration) current_concentration /= dilution_protocol # load raw data initial_sd_data = read_0h_data() final_sd_data = read_24h_data() # reshape data into the size of board rebuild_0h_data = initial_sd_data.reshape((32, -1)) rebuild_24h_data = final_sd_data.reshape((32, -1)) # reshape data into a 2-dimensional array contains each group data sample_divided_list_0h = split_array_into_samples(rebuild_0h_data, sample_width, sample_height) sample_divided_list_24h = split_array_into_samples(rebuild_24h_data, sample_width, sample_height) # handle data of control groups control_0h_summary = 0 for number in control_number_list: number = number - 1 sample = sample_divided_list_0h[number] control_0h_summary = control_0h_summary + calculate_summary_of_sample(sample) control_0h_average = control_0h_summary / (sample_width * sample_height * len(control_number_list)) control_24h_summary = 0 for number in control_number_list: number = number - 1 sample = sample_divided_list_24h[number] control_24h_summary = control_24h_summary + calculate_summary_of_sample(sample) control_24h_average = control_24h_summary / (sample_width * sample_height * len(control_number_list)) # calculate standard deviation of each grid sd_matrix = [] for line in rebuild_24h_data: new_line = [] for element in line: sd_data = (float(element) - control_0h_average.item()) \ / (control_24h_average.item() - control_0h_average.item()) new_line.append(sd_data) sd_matrix.append(new_line) sd_matrix = np.array(sd_matrix) # split array into different samples sd_groups = split_array_into_samples(sd_matrix, sample_width, sample_height) sd_groups = np.array(sd_groups, dtype=float) RESULT_LIST = [] for sample in sd_groups: result = calculate_avg_of_sample(sample, sample_width, basic_width) RESULT_LIST.append(result) RESULT_LIST = np.array(RESULT_LIST) FULL_RESULT_LIST = [] for group in sd_groups: x_index = 0 y_index = 0 sample_buffer = [] data_buffer = [] while y_index < sample_height: while x_index < basic_width: x = x_index while x < sample_width: data_buffer.append(group[y_index][x]) x += basic_width sample_buffer.append(data_buffer) data_buffer = [] x_index += 1 y_index += 1 x_index = 0 FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST = np.array(FULL_RESULT_LIST, dtype=float) optional_color = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'] EC50_LIST = [] EC50_AVG_LIST = [] sample_num = 0 for SAMPLE in FULL_RESULT_LIST: sample_num += 1 fig, ax = plt.subplots() index = 0 ax.set_title('Sample '+str(sample_num)) x_buffer = [] x_sampling_buffer = [] y_sampling_buffer = [] for repeat in SAMPLE: x, y, x_sampling, y_sampling = fit_sigmoid_curve(x_data, repeat) x_buffer.append(x) x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling) draw_single_curve(ax, x, y, x_sampling, y_sampling, optional_color[index]) index += 1 EC50_LIST.append(x_buffer) # draw the average result avg = np.mean(x_buffer) EC50_AVG_LIST.append(avg) # draw the average curve x_sampling_buffer = np.array(x_sampling_buffer).T y_sampling_buffer = np.array(y_sampling_buffer).T x_sampling_avg = [] y_sampling_avg = [] for line in x_sampling_buffer: x_sampling_avg.append(np.mean(line)) for line in y_sampling_buffer: y_sampling_avg.append(np.mean(line)) ax.plot(avg, 0.5, 'o', color='black') ax.plot(x_sampling_avg, y_sampling_avg, color='black') plt.savefig("./output/" + output_directory + "/figs" + "/Sample " + str(sample_num)) plt.cla() plt.close(fig) # output grouped result output_f_grouped = open("./output/" + output_directory + "/result_grouped.csv", "w") csv_writer_grouped = csv.writer(output_f_grouped) csv_writer_grouped.writerow(["initial concentration: " + str(initial_concentration), "dilution protocol: " + str(dilution_protocol)]) csv_writer_grouped.writerow("") sample_num = 0 for SAMPLE in FULL_RESULT_LIST: SAMPLE = SAMPLE.T sample_num += 1 csv_writer_grouped.writerow(["Sample " + str(sample_num)]) for repeat in SAMPLE: csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow("") ec50_result_list = [] for ec50_index in EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list) average_ec50 = np.power(10, EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([]) csv_writer_grouped.writerow(["Average EC50", "Std"]) csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)]) csv_writer_grouped.writerow("") output_f_grouped.close() output_f_full = open("./output/" + output_directory + "/result_full.csv", "w") csv_writer_full = csv.writer(output_f_full) for line in sd_matrix: csv_writer_full.writerow(line) output_f_full.close() print("Finished")
[ 6738, 7736, 13, 952, 1330, 1100, 62, 33990, 62, 17752, 11, 1100, 62, 15, 71, 62, 7890, 11, 1100, 62, 1731, 71, 62, 7890, 11, 3197, 62, 29762, 62, 22019, 303, 198, 6738, 7736, 13, 1102, 1851, 1330, 6626, 62, 18747, 62, 20424, 62, ...
2.536683
2,508
# -*- test-case-name: twisted.names.test.test_rootresolve -*- # Copyright (c) 2001-2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Resolver implementation for querying successive authoritative servers to lookup a record, starting from the root nameservers. @author: Jp Calderone todo:: robustify it break discoverAuthority into several smaller functions documentation """ from twisted.internet import defer from twisted.names import dns from twisted.names import common def lookupNameservers(host, atServer, p=None): # print 'Nameserver lookup for', host, 'at', atServer, 'with', p if p is None: p = dns.DNSDatagramProtocol(_DummyController()) p.noisy = False return retry( (1, 3, 11, 45), # Timeouts p, # Protocol instance (atServer, dns.PORT), # Server to query [dns.Query(host, dns.NS, dns.IN)] # Question to ask ) def lookupAddress(host, atServer, p=None): # print 'Address lookup for', host, 'at', atServer, 'with', p if p is None: p = dns.DNSDatagramProtocol(_DummyController()) p.noisy = False return retry( (1, 3, 11, 45), # Timeouts p, # Protocol instance (atServer, dns.PORT), # Server to query [dns.Query(host, dns.A, dns.IN)] # Question to ask ) def extractAuthority(msg, cache): records = msg.answers + msg.authority + msg.additional nameservers = [r for r in records if r.type == dns.NS] # print 'Records for', soFar, ':', records # print 'NS for', soFar, ':', nameservers if not nameservers: return None, nameservers if not records: raise IOError("No records") for r in records: if r.type == dns.A: cache[str(r.name)] = r.payload.dottedQuad() for r in records: if r.type == dns.NS: if str(r.payload.name) in cache: return cache[str(r.payload.name)], nameservers for addr in records: if addr.type == dns.A and addr.name == r.name: return addr.payload.dottedQuad(), nameservers return None, nameservers def discoverAuthority(host, roots, cache=None, p=None): if cache is None: cache = {} rootAuths = list(roots) parts = host.rstrip('.').split('.') parts.reverse() authority = rootAuths.pop() soFar = '' for part in parts: soFar = part + '.' + soFar # print '///////', soFar, authority, p msg = defer.waitForDeferred(lookupNameservers(soFar, authority, p)) yield msg msg = msg.getResult() newAuth, nameservers = extractAuthority(msg, cache) if newAuth is not None: # print "newAuth is not None" authority = newAuth else: if nameservers: r = str(nameservers[0].payload.name) # print 'Recursively discovering authority for', r authority = defer.waitForDeferred(discoverAuthority(r, roots, cache, p)) yield authority authority = authority.getResult() # print 'Discovered to be', authority, 'for', r ## else: ## # print 'Doing address lookup for', soFar, 'at', authority ## msg = defer.waitForDeferred(lookupAddress(soFar, authority, p)) ## yield msg ## msg = msg.getResult() ## records = msg.answers + msg.authority + msg.additional ## addresses = [r for r in records if r.type == dns.A] ## if addresses: ## authority = addresses[0].payload.dottedQuad() ## else: ## raise IOError("Resolution error") # print "Yielding authority", authority yield authority discoverAuthority = defer.deferredGenerator(discoverAuthority) def bootstrap(resolver): """Lookup the root nameserver addresses using the given resolver Return a Resolver which will eventually become a C{root.Resolver} instance that has references to all the root servers that we were able to look up. """ domains = [chr(ord('a') + i) for i in range(13)] # f = lambda r: (log.msg('Root server address: ' + str(r)), r)[1] f = lambda r: r L = [resolver.getHostByName('%s.root-servers.net' % d).addCallback(f) for d in domains] d = defer.DeferredList(L) d.addCallback(lambda r: Resolver([e[1] for e in r if e[0]])) return DeferredResolver(d)
[ 2, 532, 9, 12, 1332, 12, 7442, 12, 3672, 25, 19074, 13, 14933, 13, 9288, 13, 9288, 62, 15763, 411, 6442, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 5878, 12, 10531, 40006, 24936, 46779, 13, 198, 2, 4091, 38559, 24290, 329, 3307, 13,...
2.267093
2,033
# ================================================================ # MIT License # Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang) # ================================================================ import os, sys rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) sys.path.insert(1, rootpath) import tensorflow as tf import numpy as np from PIL import Image from absl import app from absl import flags from common_flags import FLAGS from ids.voc2012 import get_colormap as get_voc2012_colormap from ids.cityscapes_fine import get_colormap as get_cityscapes_colormap flags.DEFINE_string("input_dir", None, "input dir path") flags.DEFINE_string("output_dir", None, "output dir path") flags.DEFINE_string("colormap", "voc2012", "colormap name") flags.DEFINE_integer("ignore_label", 255, "ignore label") if __name__ == "__main__": app.run(main)
[ 2, 46111, 4770, 25609, 18604, 198, 2, 17168, 13789, 198, 2, 15069, 357, 66, 8, 33448, 1225, 904, 5948, 13415, 648, 357, 5450, 1378, 12567, 13, 785, 14, 276, 904, 5948, 13415, 648, 8, 198, 2, 46111, 4770, 25609, 18604, 198, 198, 1174...
3.111864
295
from inspect import signature import json import time import os import glob import logging from pathlib import Path from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver from watchdog.events import PatternMatchingEventHandler from EDScoutCore.FileSystemUpdatePrompter import FileSystemUpdatePrompter default_journal_path = os.path.join(str(Path.home()), "Saved Games\\Frontier Developments\\Elite Dangerous") journal_file_pattern = "journal.*.log" logger = logging.getLogger('JournalInterface') if __name__ == '__main__': journalWatcher = JournalWatcher() journalWatcher.set_callback(ReportJournalChange) print('running') try: while True: time.sleep(1) except KeyboardInterrupt: print('done') journalWatcher.stop()
[ 6738, 10104, 1330, 9877, 201, 198, 11748, 33918, 201, 198, 11748, 640, 201, 198, 11748, 28686, 201, 198, 11748, 15095, 201, 198, 11748, 18931, 201, 198, 201, 198, 6738, 3108, 8019, 1330, 10644, 201, 198, 6738, 26856, 13, 672, 2655, 690,...
2.865772
298
import sqlite3 conn = sqlite3.connect('example.db') c = conn.cursor() import os import hashlib import time get_dir_data('./') # Save (commit) the changes conn.commit() conn.close()
[ 11748, 44161, 578, 18, 198, 37043, 796, 44161, 578, 18, 13, 8443, 10786, 20688, 13, 9945, 11537, 198, 198, 66, 796, 48260, 13, 66, 21471, 3419, 628, 198, 11748, 28686, 198, 11748, 12234, 8019, 198, 11748, 640, 628, 198, 198, 1136, 62,...
2.724638
69
""" Migration script to add 'ldda_parent_id' column to the implicitly_converted_dataset_association table. """ from sqlalchemy import * from sqlalchemy.orm import * from migrate import * from migrate.changeset import * import logging log = logging.getLogger( __name__ ) metadata = MetaData()
[ 37811, 198, 44, 4254, 4226, 284, 751, 705, 335, 6814, 62, 8000, 62, 312, 6, 5721, 284, 262, 31821, 62, 1102, 13658, 62, 19608, 292, 316, 62, 562, 41003, 3084, 13, 198, 37811, 198, 198, 6738, 44161, 282, 26599, 1330, 1635, 198, 6738,...
3.352273
88
import pandas as pd import numpy as np import matplotlib.pyplot as plt import prince from sklearn import utils from sklearn.cluster import DBSCAN import itertools from cmca import CMCA from ccmca import CCMCA from matplotlib import rc plt.style.use('ggplot') df = pd.read_csv("./uk2018.csv") df["prtclcgb"].replace({5: 8, 9: 8, 10:8, 11:8, 12:8, 13:8, 15:8, 19:8}, inplace=True) df["prtclcgb"].replace({6: 5}, inplace=True) df["prtclcgb"].replace({7: 6}, inplace=True) df["prtclcgb"].replace({8: 7}, inplace=True) alpha = r'$ \alpha $' tableau10 = { 'teal': '#78B7B2', 'blue': '#507AA6', 'orange': '#F08E39', 'red': '#DF585C', 'green': '#5BA053', 'purple': '#AF7BA1', 'yellow': '#ECC854', 'brown': '#9A7460', 'pink': '#FD9EA9', 'gray': '#BAB0AC', 7: '#9A7460', 1: '#507AA6', 2: '#F08E39', 3: '#DF585C', 4: '#5BA053', 0: '#78B7B2', 6: '#ECC854', 5: '#AF7BA1', 8: '#FD9EA9', 9: '#BAB0AC', -1: '#BAB0AC', 99: '#BAB0AC', 'LDP': '#507AA6', 'DPJ': '#F08E39' } X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth = df_to_mat(df) X = pd.concat([X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth]) print(X_con.shape, X_lab.shape, X_ldp.shape, X_snp.shape, X_gre.shape, X_uip.shape, X_oth.shape, X.shape) ##Disctionay for Level and Party party = {1:"Con", 2:"Lab", 3:"LD", 4:"SNP", 5:"Green", 6:"UKIP", 7:"Other"} ##Fitting cMCA and export plots cmca = CMCA(n_components=2, copy=True, check_input=True) cmca = cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5) Y_fg = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg = np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col')) prefix_to_info = cmca.gen_prefix_to_info() f_6 = plt.figure() plt.xlim([-2.5, 2.5]) plt.ylim([-2.5, 2.5]) plt.scatter(Y_fg[:, 0], Y_fg[:, 1], c=tableau10[X_lab["prtclcgb"].iloc[0]], label=party[X_lab["prtclcgb"].iloc[0]], alpha=0.3, linewidths=0) plt.scatter(Y_bg[:, 0], Y_bg[:, 1], c=tableau10[X_con["prtclcgb"].iloc[0]], label=party[X_con["prtclcgb"].iloc[0]], alpha=0.3, linewidths=0) handles, labels = plt.gca().get_legend_handles_labels() handles = [handles[1],handles[0]] labels = ["Con","Lab"] plt.legend(handles, labels, loc="lower right", shadow=False, scatterpoints=1, fontsize=8) plt.xlabel('cPC1') plt.ylabel('cPC2') plt.title("cMCA (tg: LAB, bg: CON, " + str(alpha) + ": 1.5)") plt.show() f_6.savefig("cMCA_ESS2018_labcon_org.pdf", bbox_inches='tight')
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 19716, 198, 6738, 1341, 35720, 1330, 3384, 4487, 198, 6738, 1341, 35720, 13, 565, 5819, 1330,...
1.934537
1,329
""" Problem: Given a list of possibly overlapping intervals, return a new list of intervals where all overlapping intervals have been merged. The input list is not necessarily ordered in any way. For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should return [(1, 3), (4, 10), (20, 25)]. """ from typing import List, Tuple if __name__ == "__main__": print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25)])) print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25), (6, 12)])) """ SPECS: TIME COMPLEXITY: O(n) SPACE COMPLEXITY: O(n) """
[ 37811, 198, 40781, 25, 198, 198, 15056, 257, 1351, 286, 5457, 32997, 20016, 11, 1441, 257, 649, 1351, 286, 20016, 810, 198, 439, 32997, 20016, 423, 587, 23791, 13, 198, 198, 464, 5128, 1351, 318, 407, 6646, 6149, 287, 597, 835, 13, ...
2.62963
216
import time import emoji # Put your commands here COMMAND1 = "testing testing" COMMAND2 = "roger roger" BLUEON = str("blue on") BLUEOFF = str("blue off") REDON = str("red on") REDOFF = str("red off") GREENON = str("green on") GREENOFF = str("green off") YELLOWON = str("yellow on") YELLOWOFF = str("yellow off") CLOCK = str("update clock") SCRAMBLE = str('scramble the 7') HACKER = str('hack the 7') SINGLEREADING = str('light') setup = False # Your handling code goes in this function def handle_command(command): """ Determine if the command is valid. If so, take action and return a response, if necessary. """ if not setup: setup_gpio() setup = True response = "" if command.find(COMMAND1) >= 0: response = str("Surprise!") elif command.find(COMMAND2) >= 0: response = (emoji.emojize('Python\n is\n :thumbs_up: :thumbs_up: :thumbs_up:')) # Blue LED Commands elif command.find(BLUEON) >= 0: GPIO.output(17, True) response = emoji.emojize("" + "Turning :radio_button: ON...") elif command.find(BLUEOFF) >= 0: GPIO.output(17, False) response = emoji.emojize("" + "Turning :radio_button: OFF...") # Red LED Commands elif command.find(REDON) >= 0: GPIO.output(27, True) response = emoji.emojize("" + "Turning :red_circle: ON...") elif command.find(REDOFF) >= 0: GPIO.output(27, False) response = emoji.emojize("" + "Turning :red_circle: OFF...") # Green LED Commands elif command.find(GREENON) >= 0: GPIO.output(5, True) response = emoji.emojize("" + "Turning :green_apple: ON...") elif command.find(GREENOFF) >= 0: GPIO.output(5, False) response = emoji.emojize("" + "Turning :green_apple: OFF...") # Yellow LED Commands elif command.find(YELLOWON) >= 0: GPIO.output(22, True) response = emoji.emojize("" + "Turning :sunny: ON...") elif command.find(YELLOWOFF) >= 0: GPIO.output(22, False) response = emoji.emojize("" + "Turning :sunny: OFF...") # 7 Segment Commands elif command.find(CLOCK) >= 0: print('Updating the clock!') response = segment.updateClock() elif command.find(SCRAMBLE) >= 0: print(emoji.emojize(":egg: There is nothing better than scrambled eggs! :egg:")) response = segment.scramble() elif command.find(HACKER) >= 0: print('Message') response = segment.hacker() elif command.find(SINGLEREADING) >= 0: a = lite.printReading() a = int(a) time.sleep(1) print(a) response = ('Here is what the LDR Sensor said to me: ' + str(a)) return response
[ 11748, 640, 198, 11748, 44805, 198, 198, 2, 5930, 534, 9729, 994, 198, 9858, 44, 6981, 16, 796, 366, 33407, 4856, 1, 198, 9858, 44, 6981, 17, 796, 366, 305, 1362, 686, 1362, 1, 198, 198, 9148, 8924, 1340, 796, 965, 7203, 17585, 31...
2.330221
1,178
# coding=utf-8 """RSES :)"""
[ 2, 19617, 28, 40477, 12, 23, 198, 37811, 6998, 1546, 14373, 37811, 198 ]
2.230769
13
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 35937, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 19...
3.806452
341
"""Support for MQTT discovery.""" import asyncio import logging from hatasmota.discovery import ( TasmotaDiscovery, get_device_config as tasmota_get_device_config, get_entities_for_platform as tasmota_get_entities_for_platform, get_entity as tasmota_get_entity, has_entities_with_platform as tasmota_has_entities_with_platform, unique_id_from_hash, ) from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.typing import HomeAssistantType from .const import DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_PLATFORMS = [ "switch", ] ALREADY_DISCOVERED = "tasmota_discovered_components" CONFIG_ENTRY_IS_SETUP = "tasmota_config_entry_is_setup" DATA_CONFIG_ENTRY_LOCK = "tasmota_config_entry_lock" TASMOTA_DISCOVERY_DEVICE = "tasmota_discovery_device" TASMOTA_DISCOVERY_ENTITY_NEW = "tasmota_discovery_entity_new_{}" TASMOTA_DISCOVERY_ENTITY_UPDATED = "tasmota_discovery_entity_updated_{}_{}_{}_{}" def clear_discovery_hash(hass, discovery_hash): """Clear entry in ALREADY_DISCOVERED list.""" del hass.data[ALREADY_DISCOVERED][discovery_hash] def set_discovery_hash(hass, discovery_hash): """Set entry in ALREADY_DISCOVERED list.""" hass.data[ALREADY_DISCOVERED][discovery_hash] = {}
[ 37811, 15514, 329, 337, 48, 15751, 9412, 526, 15931, 198, 11748, 30351, 952, 198, 11748, 18931, 198, 198, 6738, 6877, 8597, 4265, 13, 67, 40821, 1330, 357, 198, 220, 220, 220, 309, 8597, 4265, 35, 40821, 11, 198, 220, 220, 220, 651, ...
2.56
500
# Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """TFX InfraValidator executor definition.""" import contextlib import functools import os import signal import threading import time from typing import Any, Dict, List, Optional from absl import logging from tfx import types from tfx.components.infra_validator import error_types from tfx.components.infra_validator import request_builder from tfx.components.infra_validator import serving_bins from tfx.components.infra_validator import types as iv_types from tfx.components.infra_validator.model_server_runners import kubernetes_runner from tfx.components.infra_validator.model_server_runners import local_docker_runner from tfx.dsl.components.base import base_executor from tfx.proto import infra_validator_pb2 from tfx.types import artifact_utils from tfx.types.standard_component_specs import BLESSING_KEY from tfx.types.standard_component_specs import EXAMPLES_KEY from tfx.types.standard_component_specs import MODEL_KEY from tfx.types.standard_component_specs import REQUEST_SPEC_KEY from tfx.types.standard_component_specs import SERVING_SPEC_KEY from tfx.types.standard_component_specs import VALIDATION_SPEC_KEY from tfx.utils import io_utils from tfx.utils import path_utils from tfx.utils import proto_utils from tfx.utils.model_paths import tf_serving_flavor from tensorflow_serving.apis import classification_pb2 from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_log_pb2 from tensorflow_serving.apis import regression_pb2 _DEFAULT_NUM_TRIES = 5 _DEFAULT_POLLING_INTERVAL_SEC = 1 _DEFAULT_MAX_LOADING_TIME_SEC = 300 _DEFAULT_MODEL_NAME = 'infra-validation-model' # Proto message keys for oneof block. _TENSORFLOW_SERVING = 'tensorflow_serving' _LOCAL_DOCKER = 'local_docker' _KUBERNETES = 'kubernetes' # Artifact property keys _BLESSED_KEY = 'blessed' _MODEL_FLAG_KEY = 'has_model' # Filename of infra blessing artifact on succeed. _BLESSED_FILENAME = 'INFRA_BLESSED' # Filename of infra blessing artifact on fail. _NOT_BLESSED_FILENAME = 'INFRA_NOT_BLESSED' def _create_model_server_runner( model_path: str, serving_binary: serving_bins.ServingBinary, serving_spec: infra_validator_pb2.ServingSpec): """Create a ModelServerRunner from a model, a ServingBinary and a ServingSpec. Args: model_path: An IV-flavored model path. (See model_path_utils.py) serving_binary: One of ServingBinary instances parsed from the `serving_spec`. serving_spec: A ServingSpec instance of this infra validation. Returns: A ModelServerRunner. """ platform = serving_spec.WhichOneof('serving_platform') if platform == 'local_docker': return local_docker_runner.LocalDockerRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) elif platform == 'kubernetes': return kubernetes_runner.KubernetesRunner( model_path=model_path, serving_binary=serving_binary, serving_spec=serving_spec ) else: raise NotImplementedError('Invalid serving_platform {}'.format(platform)) def _convert_to_prediction_log(request: iv_types.Request): """Try convert infra validation request to TF-Serving PredictionLog.""" if isinstance(request, classification_pb2.ClassificationRequest): return prediction_log_pb2.PredictionLog( classify_log=prediction_log_pb2.ClassifyLog(request=request)) elif isinstance(request, regression_pb2.RegressionRequest): return prediction_log_pb2.PredictionLog( regress_log=prediction_log_pb2.RegressLog(request=request)) elif isinstance(request, predict_pb2.PredictRequest): return prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) else: raise NotImplementedError( f'Cannot convert {type(request)} to PredictionLog')
[ 2, 15069, 13130, 3012, 11419, 13, 1439, 6923, 33876, 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, ...
3.018405
1,467
def read() -> str: """Returns a string""" return "org.allnix"
[ 198, 198, 4299, 1100, 3419, 4613, 965, 25, 198, 220, 220, 220, 37227, 35561, 257, 4731, 37811, 198, 220, 220, 220, 1441, 366, 2398, 13, 439, 77, 844, 1, 198 ]
2.4
30
# from folder workMETRLA # MODEL CODE # -*- coding: utf-8 -*- """ Created on Mon Sep 28 10:28:06 2020 @author: wb """ import torch import torch.nn as nn import math # from GCN_models import GCN # from One_hot_encoder import One_hot_encoder import torch.nn.functional as F import numpy as np from scipy.sparse.linalg import eigs from Param import * from torchsummary import summary DEVICE = 'cuda:1' ''' Attention ScaledDotProductAttention dk B,N,T,CattentionC=1 C ---> embedded size 32 or 64 dk = 32 328head832*8=256NIPS17 tranformerdk=64head = 8 all embeded size = 512 ''' ''' S spatial MultiHeadAttention ''' ''' T Temporal MultiHeadAttention ''' ### STBlock ### Encoder ### ST Transformer: Total Model def print_params(model_name, model): param_count = 0 for name, param in model.named_parameters(): if param.requires_grad: param_count += param.numel() print(f'{model_name}, {param_count} trainable parameters in total.') return import sys import pandas as pd if __name__ == '__main__': main() ''' 1. only Spatial Transformer PEMSBAY 12 in 12 out 2. only Temporal Transformer PEMSBAY 12 in 12 out 3. Temporal-Spatial Transformer PEMSBAY 12 in 12 out 4. C 12C B N T C=1 B,N,T,C=2 123 12 in 12 out PEMSBAY '''
[ 2, 422, 9483, 670, 47123, 7836, 32, 201, 198, 201, 198, 2, 19164, 3698, 42714, 201, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 2892, 8621, 2579, 838, 25, 2078, 25, 3312, ...
2.20743
646
# animation for medium article from termcolor import colored import time import imageio import pyautogui pyautogui.FAILSAFE = True matrix = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 2, 2, 2, 0, 0, 0], [0, 0, 0, 0, 0, 2, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 1, 1, 1, 1, 1, 1, 0], [1, 0, 1, 0, 0, 0, 0, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 0, 1, 0, 1, 0, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] lst = set() for i in range(21): for z in range(10): for row in range(len(matrix)): if 0 not in matrix[row]: lst.add(row) if (i == 20 or i > row) and row in lst: print(colored("1 " * 10, "green")) else: for element in range(len(matrix[row])): if i == row and z == element: print(colored(matrix[row][element], "green"), end=" ", flush=False) elif matrix[row][element] == 1: print(colored(matrix[row][element], "red"), end=" ", flush=False) elif matrix[row][element] == 2: print(colored(matrix[row][element], "blue"), end=" ", flush=False) else: print(matrix[row][element], end=" ", flush=False) print("") print("") # takes a screenshot pyautogui.moveTo(338, 580, duration = 0) pyautogui.hotkey('command', 'shift', '4') pyautogui.dragTo(547, 1000, duration = 0, button = 'left')
[ 2, 11034, 329, 7090, 2708, 198, 198, 6738, 3381, 8043, 1330, 16396, 198, 11748, 640, 198, 11748, 2939, 952, 198, 11748, 12972, 2306, 519, 9019, 198, 198, 9078, 2306, 519, 9019, 13, 7708, 4146, 4090, 15112, 796, 6407, 198, 198, 6759, 8...
1.6632
1,250
from django.db import models from products.models import Product from utils.models import Utility
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 6738, 3186, 13, 27530, 1330, 8721, 198, 6738, 3384, 4487, 13, 27530, 1330, 34030, 628, 628, 628, 198 ]
3.888889
27
from django.shortcuts import render from hierarchical_app.models import Folder # Create your views here.
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 38958, 62, 1324, 13, 27530, 1330, 48107, 198, 2, 13610, 534, 5009, 994, 13, 628, 198 ]
4.115385
26
import sys import os import argparse import logging import json import time import subprocess from shutil import copyfile import numpy as np from sklearn import metrics from easydict import EasyDict as edict import torch from torch.utils.data import DataLoader import torch.nn.functional as F from torch.nn import DataParallel from vit_pytorch import ViT from tensorboardX import SummaryWriter sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../') torch.manual_seed(0) torch.cuda.manual_seed_all(0) from data.dataset import ImageDataset # noqa from model.classifier import Classifier # noqa from utils.misc import lr_schedule # noqa from model.utils import get_optimizer # noqa parser = argparse.ArgumentParser(description='Train model') parser.add_argument('cfg_path', default=None, metavar='CFG_PATH', type=str, help="Path to the config file in yaml format") parser.add_argument('save_path', default=None, metavar='SAVE_PATH', type=str, help="Path to the saved models") parser.add_argument('--num_workers', default=8, type=int, help="Number of " "workers for each data loader") parser.add_argument('--device_ids', default='0,1,2,3', type=str, help="GPU indices ""comma separated, e.g. '0,1' ") parser.add_argument('--pre_train', default=None, type=str, help="If get" "parameters from pretrained model") parser.add_argument('--resume', default=0, type=int, help="If resume from " "previous run") parser.add_argument('--logtofile', default=False, type=bool, help="Save log " "in save_path/log.txt if set True") parser.add_argument('--verbose', default=False, type=bool, help="Detail info") if __name__ == '__main__': main()
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 33918, 198, 11748, 640, 198, 11748, 850, 14681, 198, 6738, 4423, 346, 1330, 4866, 7753, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 357...
2.645588
680
groupSize = input() groups = list(map(int,input().split(' '))) tmpArray1 = set() tmpArray2 = set() for i in groups: if i in tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i) tmpArray2.add(i) for i in tmpArray2: print(i)
[ 8094, 10699, 796, 5128, 3419, 198, 24432, 796, 1351, 7, 8899, 7, 600, 11, 15414, 22446, 35312, 10786, 705, 22305, 198, 22065, 19182, 16, 796, 900, 3419, 198, 22065, 19182, 17, 796, 900, 3419, 198, 1640, 1312, 287, 2628, 25, 198, 220, ...
2.112903
124
import unittest from hf_src.main import soma
[ 11748, 555, 715, 395, 198, 6738, 289, 69, 62, 10677, 13, 12417, 1330, 3870, 64, 628 ]
2.875
16
import copy import json from oic.utils.authn.client import CLIENT_AUTHN_METHOD from oic.utils.keyio import KeyJar from oic.utils.keyio import KeyBundle __author__ = 'roland' import logging logger = logging.getLogger(__name__) def request_and_return(conv, url, response=None, method="GET", body=None, body_type="json", state="", http_args=None, **kwargs): """ :param url: The URL to which the request should be sent :param response: Response type :param method: Which HTTP method to use :param body: A message body if any :param body_type: The format of the body of the return message :param http_args: Arguments for the HTTP _client :return: A cls or ErrorResponse instance or the HTTP response instance if no response body was expected. """ if http_args is None: http_args = {} _cli = conv._client try: _resp = _cli.http_request(url, method, data=body, **http_args) except Exception: raise conv.position = url conv.last_response = _resp conv.last_content = _resp.content if not "keyjar" in kwargs: kwargs["keyjar"] = conv.keyjar _response = _cli.parse_request_response(_resp, response, body_type, state, **kwargs) conv.protocol_response.append((_response, _resp.content)) return _response
[ 11748, 4866, 198, 11748, 33918, 198, 198, 6738, 267, 291, 13, 26791, 13, 18439, 77, 13, 16366, 1330, 45148, 62, 32, 24318, 45, 62, 49273, 198, 6738, 267, 291, 13, 26791, 13, 2539, 952, 1330, 7383, 47511, 198, 6738, 267, 291, 13, 267...
2.510638
564
import FWCore.ParameterSet.Config as cms hltPFPuppiNoLep = cms.EDProducer("PuppiProducer", DeltaZCut = cms.double(0.1), DeltaZCutForChargedFromPUVtxs = cms.double(0.2), EtaMaxCharged = cms.double(99999.0), EtaMaxPhotons = cms.double(2.5), EtaMinUseDeltaZ = cms.double(-1.0), MinPuppiWeight = cms.double(0.01), NumOfPUVtxsForCharged = cms.uint32(0), PUProxyValue = cms.InputTag("hltPixelClustersMultiplicity"), PtMaxCharged = cms.double(-1.0), PtMaxNeutrals = cms.double(200.0), PtMaxNeutralsStartSlope = cms.double(0.0), PtMaxPhotons = cms.double(20.0), UseDeltaZCut = cms.bool(True), UseFromPVLooseTight = cms.bool(False), algos = cms.VPSet( cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(1.0, 1.0), MinNeutralPt = cms.vdouble(0.5105, 0.821), MinNeutralPtSlope = cms.vdouble(9.51e-06, 1.902e-05), RMSEtaSF = cms.vdouble(1.0, 1.0), etaMax = cms.vdouble(2.5, 3.5), etaMin = cms.vdouble(0.0, 2.5), ptMin = cms.vdouble(0.0, 0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr = cms.bool(True), combOpt = cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.1), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(True) )) ), cms.PSet( EtaMaxExtrap = cms.double(2.0), MedEtaSF = cms.vdouble(0.75), MinNeutralPt = cms.vdouble(3.656), MinNeutralPtSlope = cms.vdouble(5.072e-05), RMSEtaSF = cms.vdouble(1.0), etaMax = cms.vdouble(10.0), etaMin = cms.vdouble(3.5), ptMin = cms.vdouble(0.0), puppiAlgos = cms.VPSet(cms.PSet( algoId = cms.int32(5), applyLowPUCorr = cms.bool(True), combOpt = cms.int32(0), cone = cms.double(0.4), rmsPtMin = cms.double(0.5), rmsScaleFactor = cms.double(1.0), useCharged = cms.bool(False) )) ) ), applyCHS = cms.bool(True), candName = cms.InputTag("particleFlowTmp"), clonePackedCands = cms.bool(False), invertPuppi = cms.bool(False), puppiDiagnostics = cms.bool(False), puppiNoLep = cms.bool(True), useExistingWeights = cms.bool(False), useExp = cms.bool(False), usePUProxyValue = cms.bool(True), vertexName = cms.InputTag("goodOfflinePrimaryVertices"), vtxNdofCut = cms.int32(4), vtxZCut = cms.double(24) )
[ 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 198, 71, 2528, 47, 5837, 7211, 72, 2949, 43, 538, 796, 269, 907, 13, 1961, 11547, 2189, 7203, 47, 7211, 72, 11547, 2189, 1600, 198, 220, 220, 220, 16978, 57, 26254...
1.747246
1,543
# -*- coding: utf-8 -*- ## \package wizbin.build # MIT licensing # See: docs/LICENSE.txt import commands, os, shutil, subprocess, traceback, wx from dbr.functions import FileUnstripped from dbr.language import GT from dbr.log import DebugEnabled from dbr.log import Logger from dbr.md5 import WriteMD5 from fileio.fileio import ReadFile from fileio.fileio import WriteFile from globals.bitmaps import ICON_EXCLAMATION from globals.bitmaps import ICON_INFORMATION from globals.errorcodes import dbrerrno from globals.execute import ExecuteCommand from globals.execute import GetExecutable from globals.execute import GetSystemInstaller from globals.ident import btnid from globals.ident import chkid from globals.ident import inputid from globals.ident import pgid from globals.paths import ConcatPaths from globals.paths import PATH_app from globals.strings import GS from globals.strings import RemoveEmptyLines from globals.strings import TextIsEmpty from globals.system import PY_VER_MAJ from globals.tooltips import SetPageToolTips from input.toggle import CheckBox from input.toggle import CheckBoxESS from startup.tests import UsingTest from ui.button import CreateButton from ui.checklist import CheckListDialog from ui.dialog import DetailedMessageDialog from ui.dialog import ShowErrorDialog from ui.layout import BoxSizer from ui.output import OutputLog from ui.panel import BorderedPanel from ui.progress import PD_DEFAULT_STYLE from ui.progress import ProgressDialog from ui.progress import TimedProgressDialog from ui.style import layout as lyt from wiz.helper import FieldEnabled from wiz.helper import GetField from wiz.helper import GetMainWindow from wiz.helper import GetPage from wiz.wizard import WizardPage ## Build page
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2235, 3467, 26495, 266, 528, 8800, 13, 11249, 198, 198, 2, 17168, 15665, 198, 2, 4091, 25, 34165, 14, 43, 2149, 24290, 13, 14116, 628, 198, 11748, 9729, 11, 28686...
2.975166
604
from YoshiViz import Gui if __name__ == '__main__': #file director gui = Gui.Gui() """ report_generator.\ generate_pdf_report(fileDirectory, repositoryName, tempCommunityType) """ print('the type of', repositoryName, 'is', tempCommunityType, '\n"check .\YoshiViz\output"')
[ 6738, 38936, 53, 528, 1330, 1962, 72, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1303, 7753, 3437, 198, 220, 220, 220, 11774, 796, 1962, 72, 13, 8205, 72, 3419, 198, 220, 220, 220, 37227,...
2.54918
122
''' Wrap an __init__ function so that I don't have to assign all the parameters to a self. variable. ''' # https://stackoverflow.com/questions/5048329/python-decorator-for-automatic-binding-init-arguments import inspect from functools import wraps def lazy_init(init): ''' Create an annotation to assign all the parameters to a self. variable. ''' arg_names = inspect.getfullargspec(init)[0] # pylint: disable=E1101 return new_init
[ 7061, 6, 41028, 281, 11593, 15003, 834, 2163, 523, 326, 314, 836, 470, 423, 284, 8333, 477, 262, 198, 17143, 7307, 284, 257, 2116, 13, 7885, 13, 705, 7061, 198, 2, 3740, 1378, 25558, 2502, 11125, 13, 785, 14, 6138, 507, 14, 1120, ...
3.02649
151
# def register_feed(): import os import cv2 path = '/UserImage' cam = cv2.VideoCapture(0) name=input("Name: ") cv2.namedWindow("test") img_counter = 0 while True: ret, frame = cam.read() if not ret: print("failed to grab frame") break else: cv2.imshow("test", frame) k = cv2.waitKey(1) if k%256 == 27: # ESC pressed print("Escape hit, closing...") break elif k%256 == 32: # SPACE pressed # img_name = "opencv_frame_{}.png".format(img_counter) cv2.imwrite(name + ".jpg", frame) # print("{} written!".format(img_name)) print("Image Captured! Proceed...") img_counter += 1 cam.release() cv2.destroyAllWindows()
[ 2, 825, 7881, 62, 12363, 33529, 198, 11748, 28686, 198, 11748, 269, 85, 17, 198, 6978, 796, 31051, 12982, 5159, 6, 198, 20991, 796, 269, 85, 17, 13, 10798, 49630, 7, 15, 8, 198, 3672, 28, 15414, 7203, 5376, 25, 366, 8, 198, 198, ...
2.039164
383
# -*- encoding: utf-8 -*- ''' @Author : lance @Email : wangyl306@163.com ''' import time from model_cx.inceptionresnet import inceptionresnet from model_cx.vgg19two import vgg19_all_lr from model_cx.inceptionv3 import inceptionv3 from model_cx.densenet import densenet from model_cx.nasnet import nasnet from model_cx.merge import merge from model_cx.bcnn import bilinearnet from model_cx.resnet import ResNet50 from model_cx.mobilenetv2 import mobilenetv2 from model_cx.senet import senet if __name__=="__main__": classes = 1 epochs = 100 steps_per_epoch = 113 validation_steps = 48 shape=(224,224) print("...") start = time.time() # # try: # print("densenet") # densenet(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e: # print(e) # try: # print("bcnn") # bilinearnet(classes, epochs, steps_per_epoch, validation_steps, shape) # # except Exception as e: # print(e) # try: # print("resnet") # ResNet50(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e: # print(e) try: print("merge") merge(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as e: print(e) # try: # print("ince_res") # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) # # inceptionresnet(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e: # print(e) # try: # print("mobilenetv2") # mobilenetv2(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e: # print(e) # try: # print("inceptionv3") # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, (299, 299)) # # inceptionv3(classes, epochs, steps_per_epoch, validation_steps, shape) # except Exception as e: # print(e) try: print("nasnet") nasnet(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as e: print(e) try: print("vgg19two") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, shape) except Exception as e: print(e) try: print("senet") vgg19_all_lr(classes, epochs, steps_per_epoch, validation_steps, (100,100)) except Exception as e: print(e) end = time.time() print("ETA:", (end - start) / 3600)
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 7061, 6, 201, 198, 31, 13838, 1058, 220, 220, 220, 220, 220, 300, 590, 220, 220, 201, 198, 31, 15333, 1058, 220, 220, 266, 648, 2645, 20548, 31, 24136, 13, 785,...
2.168447
1,217
"""Coordinate changes in state space models.""" import abc try: # cached_property is only available in Python >=3.8 from functools import cached_property except ImportError: from cached_property import cached_property import numpy as np import scipy.special # for vectorised factorial from probnum import config, linops, randvars
[ 37811, 7222, 45480, 2458, 287, 1181, 2272, 4981, 526, 15931, 198, 198, 11748, 450, 66, 198, 198, 28311, 25, 198, 220, 220, 220, 1303, 39986, 62, 26745, 318, 691, 1695, 287, 11361, 18189, 18, 13, 23, 198, 220, 220, 220, 422, 1257, 31...
3.431373
102
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth.provider import OAuthProvider from allauth.socialaccount import app_settings providers.registry.register(LinkedInProvider)
[ 6738, 477, 18439, 13, 14557, 23317, 1330, 9549, 198, 6738, 477, 18439, 13, 14557, 23317, 13, 15234, 4157, 13, 8692, 1330, 32549, 30116, 198, 6738, 477, 18439, 13, 14557, 23317, 13, 15234, 4157, 13, 12162, 1071, 13, 15234, 1304, 1330, 44...
4
70
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets from torch.autograd import Variable from sklearn.model_selection import train_test_split import time import pandas as pd import numpy as np import csv batch_size = 128 NUM_EPOCHS = 30 LR = 0.001 TIME_STEP = 4 #----------------------------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A = csv_data.shape[0] board_data = csv_data[:,0:16] # X = np.log2(X) X = torch.FloatTensor(board_data) X = np.int64(board_data) # X = np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) #------------------------------------------------------- X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2,shuffle=False) X_train = torch.FloatTensor(X_train) X_test = torch.FloatTensor(X_test) Y_train = torch.LongTensor(Y_train) Y_test = torch.LongTensor(Y_test) train_dataset = torch.utils.data.TensorDataset(X_train,Y_train) # test_dataset = torch.utils.data.TensorDataset(X_test,Y_test) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True ) # test_loader = torch.utils.data.DataLoader(dataset=test_dataset, # batch_size=batch_size, # shuffle=False # ) batch_size = 128 NUM_EPOCHS = 30 LR = 0.001 TIME_STEP = 4 #----------------------------------------------- csv_data = pd.read_csv('./drive/My Drive/DATA.csv') csv_data = csv_data.values A = csv_data.shape[0] board_data = csv_data[:,0:16] # X = np.log2(X) X = torch.FloatTensor(board_data) X = np.int64(board_data) # X = np.reshape(X, (-1,4,4)) XT = X.transpose(0,2,1) X = np.concatenate((X,XT),axis=1) print(X.shape) direction_data = csv_data[:,16] Y = np.int64(direction_data) model = CCRNN() model = model.cuda() optimizer = optim.Adam(model.parameters(), lr = 0.001) if __name__ == '__main__': for epoch in range(0, NUM_EPOCHS): train(epoch)
[ 11748, 28034, 201, 198, 11748, 28034, 13, 20471, 355, 299, 77, 201, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 201, 198, 11748, 28034, 13, 40085, 355, 6436, 201, 198, 6738, 28034, 10178, 1330, 40522, 201, 198, 6738, 28034, 13, ...
2.198242
1,024