content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" backend/events/tests/test_views.py Tests for the events page views. We use the test client. Read more at https://docs.djangoproject.com/en/2.1/topics/testing/tools/ """ import json from django.test import TestCase
[ 37811, 198, 1891, 437, 14, 31534, 14, 41989, 14, 9288, 62, 33571, 13, 9078, 198, 198, 51, 3558, 329, 262, 2995, 2443, 5009, 13, 775, 779, 262, 1332, 5456, 13, 4149, 517, 379, 198, 220, 220, 220, 3740, 1378, 31628, 13, 28241, 648, ...
2.896104
77
import os import os.path os.mkdir('example') os.mkdir('example/one') f = open('example/one/file.txt', 'wt') f.write('contents') f.close() f = open('example/two.txt', 'wt') f.write('contents') f.close() os.path.walk('example', visit, '(User data)')
[ 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 198, 418, 13, 28015, 15908, 10786, 20688, 11537, 198, 418, 13, 28015, 15908, 10786, 20688, 14, 505, 11537, 198, 69, 796, 1280, 10786, 20688, 14, 505, 14, 7753, 13, 14116, 3256, 705, 46569,...
2.530612
98
#!/usr/bin/env python # Part of tikplay # Yes, this is a bit of a non-test. from nose.tools import * from tikplay.provider.retriever import Retriever
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 2142, 286, 256, 1134, 1759, 198, 2, 3363, 11, 428, 318, 257, 1643, 286, 257, 1729, 12, 9288, 13, 198, 198, 6738, 9686, 13, 31391, 1330, 1635, 198, 6738, 256, 1134, 1759, 13, 152...
2.830189
53
import csv import io from datetime import datetime import peewee as pw from flask import Blueprint from flask import g from flask import make_response from flask import redirect from flask import render_template from flask import request from flask import url_for from wtforms import Form from wtforms import IntegerField from wtforms import validators as vals from myfunds.core.constants import CryptoDirection from myfunds.core.models import CryptoActionLog from myfunds.core.models import CryptoBalance from myfunds.core.models import CryptoCurrency from myfunds.core.models import CryptoTransaction from myfunds.core.models import db_proxy from myfunds.modules import cmc from myfunds.web import ajax from myfunds.web import auth from myfunds.web import notify from myfunds.web import utils from myfunds.web.constants import DATETIME_FORMAT from myfunds.web.forms import AddCryptoBalanceForm from myfunds.web.forms import AddCyptoTransactionForm from myfunds.web.forms import DeleteCryptoBalanceForm from myfunds.web.forms import UpdateCryptoBalanceQuantityForm USD_CODE = "USD" USD_PRECISION = 2 CRYPTO_PRECISION = 8 bp = Blueprint("crypto", __name__, template_folder="templates") class ActionsFilterForm(Form): offset = IntegerField(validators=[vals.Optional()]) limit = IntegerField(validators=[vals.Optional()])
[ 11748, 269, 21370, 198, 11748, 33245, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 613, 413, 1453, 355, 279, 86, 198, 6738, 42903, 1330, 39932, 198, 6738, 42903, 1330, 308, 198, 6738, 42903, 1330, 787, 62, 26209, 198, 6738,...
3.422392
393
""" Wrap commonly-used torch builtins in nn.Module subclass for easier automatic construction of script """ import torch import torch.nn as nn import torch.nn.functional as F # TODO: Many more to be implemented __all__ = [ "argmax", "argmin", "matmul", "add", "sin", "cos", "abs", "flatten", "clip", "shape", "det", "And", "Or", "Xor", "concat", "ceil", "floor", "bitshift", "conv", "elu", "hardsigmoid", "hardswish", "compress", ]
[ 37811, 198, 54, 2416, 8811, 12, 1484, 28034, 3170, 1040, 287, 299, 77, 13, 26796, 47611, 198, 1640, 4577, 11353, 5103, 286, 4226, 198, 37811, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, ...
2.15625
256
# Copyright (c) 2011 - 2017, 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. """``snmphelpers.py`` `SNMP specific helpers functions` """ import sys import os import shutil import tarfile from subprocess import Popen, PIPE import pytest import paramiko as paramiko from . import helpers from . import loggers # create logger for module def is_mibs_folder_empty(path): """Checks is MIBs folder empty of not. Args: path(str): path to MIBs folder Returns: bool: True if empty and False if not Examples:: is_mibs_folder_empty() """ empty = True if os.path.exists(path): for file_n in os.listdir(path): if 'ONS' in file_n or "ons" in file_n: empty = False return empty def clear_mibs_folder(path): """Removes all ONS mibs from MIBS folder. Args: path(str): path to MIBs folder Examples:: clear_mibs_folder() """ if os.path.exists(path): shutil.rmtree(path) def get_remote_file(hostname, port, username, password, remotepath, localpath): """Get remote file to local machine. Args: hostname(str): Remote IP-address port(int): Remote SSH port username(str): Remote host username for authentication password(str): Remote host password for authentication remotepath(str): Remote file to download location path localpath(str): Local path to save remote file Examples:: get_remote_file(host, port, username, password, tar_remotepath, tar_localpath) """ transport = paramiko.Transport((hostname, port)) transport.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(transport) try: sftp.get(remotepath=remotepath, localpath=localpath) finally: sftp.close() transport.close() def untar_file(tar_path, untar_path): """Unpack tar file. Args: tar_path(str): Path to tar file untar_path(str): Path where to unpack Examples:: untar_file(tar_localpath, mib_path_txt) """ old_folder = os.path.join(untar_path, 'mibs') if os.path.isfile(old_folder): os.remove(old_folder) tar = tarfile.open(tar_path) tar.extractall(untar_path) tar.close() os.remove(tar_path) def file_convert(mib_txt_path, mib_py_path): """Convert .txt MIB to .py. Args: mib_txt_path(str): Full path to .txt MIB. mib_py_path(str): Full path to .py MIB Examples:: file_convert(mib_txt_path, mib_py_path) """ mod_logger_snmp = loggers.module_logger(name=__name__) # translate .txt mib into python format using 3rd party tools 'smidump' smidump = Popen(['smidump', '-k', '-f', 'python', mib_txt_path], stdout=PIPE) list_stdout = smidump.communicate()[0] if len(list_stdout) == 0: return "Fail" # create tmp directory for filling MIBs dictionary mib_path_tmp = os.path.join(mib_py_path, 'tmp') if not os.path.exists(mib_path_tmp): os.makedirs(mib_path_tmp) # added tmp path into sys.path for imports converted MIB's sys.path.append(mib_path_tmp) # get file without extension file_name = os.path.splitext(os.path.basename(mib_txt_path))[0] # create .py name temp_file_name = "{0}.py".format(file_name) # create .tmp file path for imports temp_file_path = os.path.join(mib_path_tmp, temp_file_name) # save and import converted MIB's with open(temp_file_path, "ab") as a: a.write(list_stdout) temp_module = __import__(os.path.splitext(os.path.basename(mib_txt_path))[0]) # update helpers.MIBS_DICT with MIB data if "moduleName" in list(temp_module.MIB.keys()) and "nodes" in list(temp_module.MIB.keys()): helpers.MIBS_DICT.update({temp_module.MIB["moduleName"]: list(temp_module.MIB["nodes"].keys())}) # clear tmp file path sys.path.remove(mib_path_tmp) os.remove(temp_file_path) # translate MIB from .py into pysnmp format using 3rd party tools 'libsmi2pysnmp' pipe = Popen(['libsmi2pysnmp', '--no-text'], stdout=PIPE, stdin=PIPE) stdout = pipe.communicate(input=list_stdout) # get MIB name from itself, add .py and save it. mib_name = "{0}.py".format(temp_module.MIB["moduleName"]) mib_py_path = os.path.join(mib_py_path, mib_name) mod_logger_snmp.debug("Convert %s to %s" % (file_name, temp_file_name)) with open(mib_py_path, 'a') as py_file: for string in stdout: if string is not None: str_dict = string.decode('utf-8').split('\n') for each_str in str_dict: if "ModuleCompliance" in each_str: if "ObjectGroup" in each_str: py_file.write(each_str + '\n') elif "Compliance)" in each_str: pass else: py_file.write(each_str + '\n') return mib_name def convert_to_py(txt_dir_path, py_dir_path): """Converts .txt MIB's to .py. Args: txt_dir_path(str): Path to dir with .txt MIB's. py_dir_path(str): Path to dir with .py MIB's Examples:: convert_to_py(mib_path_tmp, mib_path) """ mod_logger_snmp = loggers.module_logger(name=__name__) txt_dir_path = os.path.join(txt_dir_path, "MIB") mod_logger_snmp.debug("Converts .txt MIB's to .py") os.environ['SMIPATH'] = txt_dir_path for mib in os.listdir(txt_dir_path): mib_txt_path = os.path.join(txt_dir_path, mib) retry_count = 3 retry = 1 while retry <= retry_count: mib_py = file_convert(mib_txt_path, py_dir_path) if mib_py not in os.listdir(py_dir_path): mod_logger_snmp.debug("Converted MIB %s is not present at %s" % (mib, py_dir_path)) retry += 1 if retry > retry_count: mod_logger_snmp.debug("Can not convert %s" % (mib, )) else: mod_logger_snmp.debug("Converted MIB %s is present at %s" % (mib, py_dir_path)) retry = retry_count + 1 shutil.rmtree(txt_dir_path) shutil.rmtree(os.path.join(py_dir_path, "tmp")) def create_mib_folder(config, path, env): """Creates MIB folder. Args: config(dict): Configuration dictionary. path(str): Path to MIB folder. env(Environment): Environment object. Examples:: create_mib_folder() """ if config is None: pytest.fail("UI settings not fount in environment configuration.") host = config['host'] port = int(config['port']) username = config['username'] password = config['password'] tar_folder = config['tar_remotepath'] tar_file = os.path.split(tar_folder)[1] branch = env.env_prop['switchppVersion'] platform = getattr(getattr(env.switch[1], 'hw', None), 'snmp_path', None) tar_remotepath = tar_folder.format(**locals()) if not os.path.exists(path): os.makedirs(path) tar_localpath = os.path.join(path, tar_file) mib_path_tmp = os.path.join(path, 'tmp') if not os.path.exists(mib_path_tmp): os.makedirs(mib_path_tmp) mib_path_txt = os.path.join(path, 'txt') if not os.path.exists(mib_path_txt): os.makedirs(mib_path_txt) get_remote_file(host, port, username, password, tar_remotepath, tar_localpath) untar_file(tar_localpath, mib_path_txt) convert_to_py(mib_path_txt, path)
[ 2, 15069, 357, 66, 8, 2813, 532, 2177, 11, 8180, 10501, 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, ...
2.26502
3,562
import json import logging from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound from django.core.exceptions import ObjectDoesNotExist from django.views.decorators.csrf import csrf_exempt # See note below on saveplaylist import models # Set up logging logger = logging.getLogger("apps") # View function decorators ########################## def log_request(f): """Records request info to the log file""" wrapper.__doc__ = f.__doc__ return wrapper def handle_not_found(f): """ For views that request a specific object (e.g. a playlist), return a 404 page and log an error if the object was not found. Assumes the object being looked for is passed as a kwarg named 'item_id'. If this view does not fit this pattern, you will not be able to handle 404 errors for it with this decorator. """ wrapper.__doc__ = f.__doc__ return wrapper # View functions ################ #TODO: check for external errors like database access problems def playlists(request): """ Generic view for /data/playlists/, choosing a view function for the request type. Saves a playlist or returns a list of them, depending on request type. A GET request will return a list of available playlists in JSON format; a POST request saves a new playlist to the server, using the POST data (also in JSON format). Does not actually do anything itself, but rather calls the correct function for the task. """ # If POST, we're saving a playlist if request.method == "POST": return saveplaylist(request) # Otherwise, default behavior is to return a list of playlists else: return playlistlist(request) # Utility methods ################# def json_response(output): """Returns an HTTP Response with the data in output as the content in JSON format""" return HttpResponse(json.dumps(output), mimetype="application/json")
[ 11748, 33918, 198, 11748, 18931, 198, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 11, 367, 29281, 31077, 22069, 18453, 11, 367, 29281, 31077, 3673, 21077, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 139...
3.309244
595
import os from pathlib import Path import pandas as pd from collections import defaultdict from typing import Dict, List from .config import REQUIRED_D, API_KEY_FILENAME import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) def get_required_parameters(service_code: str) -> List[str]: """Get list of required parameters for service.""" return REQUIRED_D[service_code] def _get_path_to_module() -> Path: """Get path to this module.""" return Path(os.path.realpath(__file__)).parent def get_api_key_path(filename=API_KEY_FILENAME) -> Path: """Load api key.""" path_to_dir = _get_path_to_module() return path_to_dir / filename def extract_df(r_dict: dict) -> pd.DataFrame: """Extract DataFrame from dictionary. Parameters ---------- r_dict Obtained from response through xmltodict. """ r_body = r_dict['responseBody'] r_items_list = r_body['responseList']['item'] try: df_items = pd.DataFrame(r_items_list) except Exception as e: logger.warning(f"Failed to create DataFrame.", exc_info=True) try: df_items = pd.DataFrame(r_items_list, index=[0]) except Exception as e: logger.error("Failed to create DataFrame.") raise e return df_items def split_list_of_dicts(dict_list: List[dict], key: str) -> Dict[str,List[dict]]: """Split list of dictionaries into multiples lists based on a specific key. Output lists are stored in a dicionary with the value used as key. Example: >>> dict_list = [ { "recordType": "a", "foo": 1, "bar": 1, }, { "recordType": "b", "foo": 2, "bar": 2, }, { "recordType": "b", "foo": 3, "bar": 3, } ] >>> split_list_of_dicts(dict_list, 'recordType') { "a": [ { "recordType": "a", "foo": 1, "bar": 1, }, ], "b": [ { "recordType": "b", "foo": 2, "bar": 2, }, { "recordType": "b", "foo": 3, "bar": 3, } ] } ] """ result = defaultdict(list) for d in dict_list: result[d[key]].append(d) return result
[ 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 198, 198, 6738, 764, 11250, 1330, 4526, 10917, 37819, 62, 35, 11, ...
1.949657
1,311
# -*- coding: utf-8 -*- import networkx as nx import pandas as pd #Other nodes connected by one node r=open('input_data/BC-related_RRI_network.txt') ll=r.readlines() r.close() rna_pairs=[] node_to_nodes={} for l in ll: ws=l.strip().split('\t') qx=sorted(ws[0:2]) rna_pairs.append((qx[0],qx[1])) for i in [0,1]: if i==0: j=1 else: j=0 if qx[i] not in node_to_nodes: node_to_nodes[qx[i]]=[qx[j]] else: node_to_nodes[qx[i]].append(qx[j]) #Dictionary of Node No. r=open('input_data/RRI_node.csv') r.readline() no2node={} for l in r: ws=l.strip().split(',') no2node[ws[0]]='~'.join(ws[1:7]) r.close() #Sort nodes by node degree node_degree={} for k in node_to_nodes: node_degree[k]=len(node_to_nodes[k]) df=pd.DataFrame(node_degree,index=['Degree']) df=df.sort_values(by='Degree',axis=1,ascending=False) nodes=df.columns.values #Compute the relative conectivity of subgraphs G=nx.Graph() node_G=[] w=open('RC_in_BC-related_RRI_network.csv','w') w.write('Node,No.,Relative connectivity\n') k=0 lim=len(nodes) while k<lim: node_key=nodes[k] node_G.append(node_key) G.add_node(node_key)#Add the node in subgraphs for node in node_G: if node in set(node_to_nodes[node_key]): G.add_edge(node_key,node)#Add the edge in subgraphs largest_components=max(nx.connected_components(G),key=len) k+=1 w.write(no2node[node_key]+','+str(k)+','+str(len(largest_components)/float(len(node_G)))+'\n') w.close()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 11748, 3127, 87, 355, 299, 87, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 201, 198, 2, 6395, 13760, 5884, 416, 530, 10139, 201, 198, 81, 28,...
1.918854
838
# -*- coding: utf-8 -*- import abc from macdaily.cls.command import Command from macdaily.util.tools.print import print_info
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 450, 66, 198, 198, 6738, 8352, 29468, 13, 565, 82, 13, 21812, 1330, 9455, 198, 6738, 8352, 29468, 13, 22602, 13, 31391, 13, 4798, 1330, 3601, 62, 10951, 62...
2.844444
45
""" FS commandline module. Allows to: - list host filesystems - remove a specific host filesystem - add a specific host filesystem """ from os.path import basename from piotr.cmdline import CmdlineModule, module, command from piotr.user import UserDirectory as ud from piotr.util import confirm
[ 37811, 198, 10652, 3141, 1370, 8265, 13, 198, 198, 34934, 284, 25, 198, 198, 12, 1351, 2583, 29905, 82, 198, 12, 4781, 257, 2176, 2583, 29905, 198, 12, 751, 257, 2176, 2583, 29905, 198, 37811, 198, 198, 6738, 28686, 13, 6978, 1330, ...
3.547619
84
import tracking_pts_logger_master import tracking_pts_logger
[ 11748, 9646, 62, 457, 82, 62, 6404, 1362, 62, 9866, 198, 11748, 9646, 62, 457, 82, 62, 6404, 1362, 198 ]
3.05
20
from singlecellmultiomics.modularDemultiplexer.baseDemultiplexMethods import UmiBarcodeDemuxMethod, NonMultiplexable # ScarTrace
[ 6738, 2060, 3846, 16680, 29005, 873, 13, 4666, 934, 11522, 586, 2480, 87, 263, 13, 8692, 11522, 586, 2480, 87, 46202, 1330, 471, 11632, 33, 5605, 1098, 11522, 2821, 17410, 11, 8504, 31217, 87, 540, 201, 198, 201, 198, 2, 12089, 2898, ...
2.54386
57
from datetime import date, time from django.contrib.postgres.fields import ArrayField from django.db import models from django.utils import timezone from django_fsm import FSMField, transition from rest_framework.reverse import reverse from simple_history.models import HistoricalRecords from bridger.buttons import ActionButton from bridger.display import FieldSet, InstanceDisplay, Section from bridger.enums import RequestType from bridger.search import register as search_register from bridger.tags import TagModelMixin
[ 6738, 4818, 8079, 1330, 3128, 11, 640, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 7353, 34239, 13, 25747, 1330, 15690, 15878, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198...
3.940299
134
#automated error checking for RNAstructure python interface from __future__ import print_function import inspect from functools import wraps from collections import defaultdict debug = False lookup_exceptions = defaultdict(lambda:RuntimeError, { 1:IOError, 2:IOError, 3:IndexError, 4:IndexError, 5:EnvironmentError, 6:StructureError, 7:StructureError, 8:StructureError, 9:StructureError, 10:ValueError, 11:ValueError, 12:ValueError, 13:IOError, 14:RNAstructureInternalError, 15:ValueError, 16:ValueError, 17:ValueError, 18:ValueError, 19:ValueError, 20:ValueError, 21:RNAstructureInternalError, 22:RNAstructureInternalError, 23:ValueError, 24:ValueError, 25:ValueError, 26:ValueError })
[ 2, 2306, 296, 515, 4049, 10627, 329, 25897, 301, 5620, 21015, 7071, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 10104, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 6738, 17268, 1330, 4277, 11600, 198, 24442, 796, 1...
1.929254
523
from collections import defaultdict, Counter from itertools import product, permutations from glob import glob import json import os from pathlib import Path import pickle import sqlite3 import string import sys import time import matplotlib as mpl from matplotlib import colors from matplotlib import pyplot as plt from matplotlib.gridspec import GridSpec from matplotlib.lines import Line2D import matplotlib.patches as mpatches from multiprocessing import Pool import numpy as np import pandas as pd from palettable.colorbrewer.qualitative import Paired_12 from palettable.colorbrewer.diverging import PuOr_5, RdYlGn_6, PuOr_10, RdBu_10 from palettable.scientific.diverging import Cork_10 from scipy.spatial import distance_matrix, ConvexHull, convex_hull_plot_2d from scipy.stats import linregress, pearsonr, lognorm import seaborn as sns import svgutils.compose as sc import asym_io from asym_io import PATH_BASE, PATH_ASYM, PATH_ASYM_DATA import asym_utils as utils import folding_rate import paper_figs import structure PATH_FIG = PATH_ASYM.joinpath("Figures") PATH_FIG_DATA = PATH_FIG.joinpath("Data") custom_cmap = sns.diverging_palette(230, 22, s=100, l=47, n=13) c_helix = custom_cmap[2] c_sheet = custom_cmap[10] col = [c_helix, c_sheet, "#CB7CE6", "#79C726"] #################################################################### ### SI Figures #################################################################### ### FIG 1 #################################################################### ### FIG 2 #################################################################### ### FIG 3 #################################################################### ### FIG 4 #################################################################### ### FIG 5 #################################################################### ### FIG 6 #################################################################### ### FIG 7 #################################################################### ### FIG 8 #################################################################### ### FIG 9 #################################################################### ### FIG 10 #################################################################### ### FIG 11 # To create this figure, you need to download the complete # Human and E. coli proteomes at: # https://alphafold.ebi.ac.uk/download # and then change the code so that "base" points to the # folder that contains the downloaded ".pdb" files
[ 6738, 17268, 1330, 4277, 11600, 11, 15034, 198, 6738, 340, 861, 10141, 1330, 1720, 11, 9943, 32855, 198, 6738, 15095, 1330, 15095, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 2298, 293, 198, 11748...
3.957813
640
from btw_mcp import * package_release("vanilla", "main", directory="ce_release")
[ 6738, 275, 4246, 62, 76, 13155, 1330, 1635, 198, 198, 26495, 62, 20979, 7203, 10438, 5049, 1600, 366, 12417, 1600, 8619, 2625, 344, 62, 20979, 4943 ]
3.115385
26
#!/usr/bin/env python # (c) 2020 Sylvain Le Groux <slegroux@ccrma.stanford.edu> import pytest from pytest import approx import numpy as np import torch from IPython import embed from beam_search import Tokenizer, Score, BeamSearch
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 357, 66, 8, 12131, 24286, 391, 1004, 402, 472, 87, 1279, 82, 1455, 472, 87, 31, 535, 81, 2611, 13, 14192, 3841, 13, 15532, 29, 198, 198, 11748, 12972, 9288, 198, 6738, 12972, 92...
3.093333
75
__author__ = 'annyz' from pprint import pprint, pformat # NOQA import logging import os import sys from datetime import datetime from hydra.lib import util from hydra.kafkatest.runtest import RunTestKAFKA from hydra.lib.boundary import Scanner from optparse import OptionParser l = util.createlogger('runSuitMaxRate', logging.INFO)
[ 834, 9800, 834, 796, 705, 7737, 89, 6, 198, 198, 6738, 279, 4798, 1330, 279, 4798, 11, 279, 18982, 220, 1303, 8005, 48, 32, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, ...
3.209524
105
from rest_framework import serializers from series.models import Series from villains.models import Villain
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 2168, 13, 27530, 1330, 7171, 198, 6738, 25239, 13, 27530, 1330, 9757, 391, 628, 628 ]
4.48
25
#!/usr/bin/env python """ Writes out map popularity of last two pools.""" from datetime import datetime, timedelta from utils.map_pools import map_type_filter, pools from utils.tools import execute_sql, last_time_breakpoint, map_name_lookup SQL = """SELECT map_type, COUNT(*) as cnt FROM matches WHERE started BETWEEN {:0.0f} AND {:0.0f} {} AND team_size = {} GROUP BY map_type ORDER BY cnt DESC""" def run(): """ Run the report.""" map_names = map_name_lookup() weeks = pools()[-2:] for size in (1, 2): print("TEAM" if size > 1 else "1v1") week_infos = [] for idx, week in enumerate(weeks): week_info = [] year = int(week[:4]) month = int(week[4:6]) day = int(week[6:]) start = last_time_breakpoint(datetime(year, month, day)) end = start + timedelta(days=14) sql = SQL.format( start.timestamp(), end.timestamp(), map_type_filter(week, size), size ) total = 0 for map_type, count in execute_sql(sql): week_info.append((map_names[map_type], count,)) total += count hold = [] for name, count in week_info: hold.append("{:17}: {:4.1f}%".format(name, 100.0 * count / total)) week_infos.append(hold) print("{:^24} {:^24}".format(*weeks)) for idx in range(len(week_infos[0])): print("{} {}".format(week_infos[0][idx], week_infos[1][idx])) if __name__ == "__main__": run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 12257, 274, 503, 3975, 11533, 286, 938, 734, 20354, 526, 15931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 6738, 3384, 4487, 13, 8899, 62, 7742, 82, 13...
2.065617
762
# -*- coding: utf-8 -*- # Example for using WebDriver object: driver = get_driver() e.g driver.current_url from webframework import TESTDATA from variables import strings from selenium.webdriver.common.by import By from webframework.extension.util.common_utils import * from webframework.extension.util.webtimings import get_measurements from webframework.extension.parsers.parameter_parser import get_parameter from time import sleep
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 17934, 329, 1262, 5313, 32103, 2134, 25, 4639, 796, 651, 62, 26230, 3419, 304, 13, 70, 4639, 13, 14421, 62, 6371, 198, 6738, 3992, 30604, 1330, 43001, 26947, 198, 6...
3.536585
123
import getpass import os import platform import psycopg2 import sys import tempfile from glob import glob from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT, quote_ident from subprocess import check_output, PIPE, Popen from time import sleep from ._compat import ustr from .utils import is_executable, Uri, Version __all__ = [ "PostgresFactory", "PostgresCluster", ]
[ 11748, 651, 6603, 198, 11748, 28686, 198, 11748, 3859, 198, 11748, 17331, 22163, 70, 17, 198, 11748, 25064, 198, 11748, 20218, 7753, 198, 198, 6738, 15095, 1330, 15095, 198, 6738, 17331, 22163, 70, 17, 13, 2302, 5736, 1330, 3180, 3535, ...
3.112
125
# -*- coding: utf-8 -*- import pandas as pd
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 19798, 292, 355, 279, 67, 628 ]
2.142857
21
from rest_framework import serializers from bluebottle.utils.model_dispatcher import get_donation_model from bluebottle.bb_projects.serializers import ProjectPreviewSerializer as BaseProjectPreviewSerializer from bluebottle.bb_accounts.serializers import UserPreviewSerializer DONATION_MODEL = get_donation_model()
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 4171, 10985, 293, 13, 26791, 13, 19849, 62, 6381, 8071, 2044, 1330, 651, 62, 9099, 341, 62, 19849, 198, 6738, 4171, 10985, 293, 13, 11848, 62, 42068, 13, 46911, 11341, 1330, 4...
3.709302
86
# WORKS BUT ISN'T FAST ENOUGH first_run = True while(True): inp = input().split() if len(inp) == 1: break if first_run: first_run = False else: print() nPlayers, nGames = [int(x) for x in inp] resultsW = [0] * nPlayers resultsL = [0] * nPlayers for i in range( int( ((nGames*nPlayers)*(nPlayers - 1)) / 2 ) ): p1, p1move, p2, p2move = [int(x) if x.isdigit() else x for x in input().split()] if p1move == p2move: continue if (p1move == "scissors" and p2move == "paper") or (p1move == "paper" and p2move == "rock") or (p1move == "rock" and p2move == "scissors"): resultsW[p1-1] += 1 resultsL[p2-1] += 1 else: resultsW[p2-1] += 1 resultsL[p1-1] += 1 for i in range(nPlayers): w_plus_l = resultsL[i] + resultsW[i] if w_plus_l == 0: print("-") else: print("%.3f" % (resultsL[i] / w_plus_l)) print("\n\n\n\n\n\n\n") print(resultsW)
[ 2, 30936, 50, 21728, 3180, 45, 6, 51, 376, 11262, 12964, 32632, 198, 11085, 62, 5143, 796, 6407, 198, 4514, 7, 17821, 2599, 198, 220, 220, 220, 287, 79, 796, 5128, 22446, 35312, 3419, 198, 220, 220, 220, 611, 18896, 7, 259, 79, 8,...
1.895604
546
############################################################################### # Copyright 2019 Alex M. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ############################################################################### from . import vcp import sys from typing import Type, List, Union, Iterable def get_vcps() -> List[Type[vcp.VCP]]: """ Discovers virtual control panels. This function should not be used directly in most cases, use :py:meth:`get_monitors()` or :py:meth:`iterate_monitors()` to get monitors with VCPs. Returns: List of VCPs in a closed state. Raises: NotImplementedError: not implemented for your operating system VCPError: failed to list VCPs """ if sys.platform == "win32" or sys.platform.startswith("linux"): return vcp.get_vcps() else: raise NotImplementedError(f"not implemented for {sys.platform}") def get_monitors() -> List[Monitor]: """ Creates a list of all monitors. Returns: List of monitors in a closed state. Raises: NotImplementedError: not implemented for your operating system VCPError: failed to list VCPs Example: Setting the power mode of all monitors to standby:: for monitor in get_monitors(): try: monitor.open() # put monitor in standby mode monitor.power_mode = "standby" except VCPError: print("uh-oh") raise finally: monitor.close() Setting all monitors to the maximum brightness using the context manager:: for monitor in get_monitors(): with monitor as m: # set back-light luminance to 100% m.luminance = 100 """ return [Monitor(v) for v in get_vcps()]
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 15069, 13130, 4422, 337, 13, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169...
2.785985
1,056
import numpy as np import torch from torch.optim import Adam from torch.utils.data import DataLoader from tqdm import tqdm
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 13, 40085, 1330, 7244, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 628 ]
3.542857
35
import simpy as sp import numpy as np import seaborn as sns import matplotlib.pyplot as plt from scipy import stats, integrate lamda = 75 alpha = 0.333 mu1 = 370 mu2 = 370*(0.666) num_bins = 50 runtime = 1000 # tic = [] # toc = [] # env = sp.Environment() q = sp.Store(env) env.process(client(env, lamda, q, tic)) env.process(server(env, alpha, mu1, mu2, q, toc)) env.run(until=runtime) l = len(tic) a = toc b = toc #b = toc[0:l:40] histdata = [b[i] - b[i-1] for i in range(1, len(b))] sns.distplot(histdata, kde=False, fit=stats.expon) plt.xlabel("inter departure time (s)") plt.xlim(0,0.15) #plt.ylim(0,100) plt.savefig('dist1.png') plt.show() #plt.hist(histdata, num_bins) #plt.show()
[ 11748, 985, 9078, 355, 599, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 629, 541, 88, 1330, 9756, 11, 19386, 198, 198, 2543, ...
2.181818
319
word_list = ['pseudolamellibranchiate', 'microcolorimetrically', 'pancreaticoduodenostomy', 'theologicoastronomical', 'pancreatoduodenectomy', 'tetraiodophenolphthalein', 'choledocholithotripsy', 'hematospectrophotometer', 'deintellectualization', 'pharyngoepiglottidean', 'psychophysiologically', 'pathologicopsychological', 'pseudomonocotyledonous', 'philosophicohistorical', 'Pseudolamellibranchia', 'chlamydobacteriaceous', 'cholecystoduodenostomy', 'anemometrographically', 'duodenopancreatectomy', 'dacryocystoblennorrhea', 'thymolsulphonephthalein', 'aminoacetophenetidine', 'ureterocystanastomosis', 'undistinguishableness', 'disestablishmentarian', 'cryptocrystallization', 'scientificogeographical', 'chemicopharmaceutical', 'overindustrialization', 'counterinterpretation', 'superincomprehensible', 'dacryocystorhinostomy', 'choledochoduodenostomy', 'cholecystogastrostomy', 'photochronographically', 'philosophicoreligious', 'scleroticochoroiditis', 'pyopneumocholecystitis', 'crystalloluminescence', 'phoneticohieroglyphic', 'historicogeographical', 'counterreconnaissance', 'pathologicoanatomical', 'omnirepresentativeness', 'establishmentarianism', 'glossolabiopharyngeal', 'pseudohermaphroditism', 'anthropoclimatologist', 'cholecystojejunostomy', 'epididymodeferentectomy', 'pericardiomediastinitis', 'cholecystolithotripsy', 'tessarescaedecahedron', 'electrotelethermometer', 'pharmacoendocrinology', 'poliencephalomyelitis', 'duodenocholedochotomy', 'cholecystonephrostomy', 'formaldehydesulphoxylate', 'dacryocystosyringotomy', 'counterpronunciamento', 'cholecystenterorrhaphy', 'deanthropomorphization', 'microseismometrograph', 'pseudoparthenogenesis', 'Pseudolamellibranchiata', 'ureteropyelonephritis', 'electroencephalography', 'anticonstitutionalist', 'electroencephalograph', 'hypsidolichocephalism', 'mandibulosuspensorial', 'acetylphenylhydrazine', 'hexanitrodiphenylamine', 'historicocabbalistical', 'hexachlorocyclohexane', 'anatomicophysiological', 'pseudoanthropological', 'microcryptocrystalline', 'lymphangioendothelioma', 'nonrepresentationalism', 'blepharoconjunctivitis', 'hydropneumopericardium', 'stereoroentgenography', 'otorhinolaryngologist', 'scientificohistorical', 'phenolsulphonephthalein', 'mechanicointellectual', 'counterexcommunication', 'duodenocholecystostomy', 'noninterchangeability', 'thermophosphorescence', 'naphthylaminesulphonic', 'polioencephalomyelitis', 'stereophotomicrograph', 'philosophicotheological', 'theologicometaphysical', 'benzalphenylhydrazone', 'scleroticochorioiditis', 'anthropomorphologically', 'thyroparathyroidectomize', 'disproportionableness', 'heterotransplantation', 'membranocartilaginous', 'scientificophilosophical', 'thyroparathyroidectomy', 'enterocholecystostomy', 'Prorhipidoglossomorpha', 'constitutionalization', 'poluphloisboiotatotic', 'anatomicopathological', 'zoologicoarchaeologist', 'protransubstantiation', 'labioglossopharyngeal', 'pneumohydropericardium', 'choledochoenterostomy', 'zygomaticoauricularis', 'anthropomorphological', 'stereophotomicrography', 'aquopentamminecobaltic', 'hexamethylenetetramine', 'macracanthrorhynchiasis', 'palaeodendrologically', 'intertransformability', 'hyperconscientiousness', 'laparocolpohysterotomy', 'indistinguishableness', 'formaldehydesulphoxylic', 'blepharosphincterectomy', 'transubstantiationalist', 'transubstantiationite', 'prostatovesiculectomy', 'pathologicohistological', 'platydolichocephalous', 'pneumoventriculography', 'photochromolithograph', 'gastroenteroanastomosis', 'chromophotolithograph', 'pentamethylenediamine', 'historicophilosophica', 'intellectualistically', 'gastroenterocolostomy', 'pancreaticogastrostomy', 'appendorontgenography', 'photospectroheliograph'] stages = [''' +---+ | | O | /|\ | / \ | | ========= ''', ''' +---+ | | O | /|\ | / | | ========= ''', ''' +---+ | | O | /|\ | | | ========= ''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | | | | | ========= ''', ''' +---+ | | O | | | | ========= ''', ''' +---+ | | | | | | ========= '''] logo = ''' _ | | | |__ __ _ _ __ __ _ _ __ ___ __ _ _ __ | '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ | | | | (_| | | | | (_| | | | | | | (_| | | | | |_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_| __/ | |___/ '''
[ 4775, 62, 4868, 796, 37250, 7752, 463, 349, 480, 297, 571, 25642, 9386, 3256, 198, 705, 24055, 8043, 320, 21879, 1146, 3256, 198, 705, 79, 1192, 630, 291, 375, 84, 375, 268, 455, 9145, 3256, 198, 705, 1169, 928, 3713, 459, 1313, 225...
2.38038
1,998
# import all relevant contents from the associated module. from vandal.objects.montecarlo import ( MonteCarlo, MCapp, ) from vandal.objects.eoq import( EOQ, EOQapp, ) from vandal.objects.dijkstra import Dijkstra # all relevant contents. __all__ = [ 'MonteCarlo', 'EOQ', 'Dijkstra', 'MCapp', 'EOQapp', ]
[ 2, 1330, 477, 5981, 10154, 422, 262, 3917, 8265, 13, 201, 198, 6738, 26271, 13, 48205, 13, 2144, 660, 7718, 5439, 1330, 357, 201, 198, 220, 220, 220, 22489, 9914, 5439, 11, 201, 198, 220, 220, 220, 13122, 1324, 11, 201, 198, 8, 20...
2.2
165
# Django from django.contrib import admin # local Django from authentication.models import User admin.site.register(User)
[ 2, 37770, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 2, 1957, 37770, 198, 6738, 18239, 13, 27530, 1330, 11787, 628, 198, 28482, 13, 15654, 13, 30238, 7, 12982, 8, 198 ]
3.757576
33
from .__version__ import __version__ from .core import create, remove, launch_shell
[ 6738, 764, 834, 9641, 834, 1330, 11593, 9641, 834, 198, 6738, 764, 7295, 1330, 2251, 11, 4781, 11, 4219, 62, 29149, 198 ]
3.818182
22
import os from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.flatpages.models import FlatPage from django.test import TestCase from django.test.utils import override_settings if __name__ == '__main__': unittest.main()
[ 11748, 28686, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 41989, 13, 26791, 1330, 14267, 1532, 15022, ...
3.3
100
from flask_restx.fields import String, Boolean, Raw, List, Float, Nested
[ 6738, 42903, 62, 2118, 87, 13, 25747, 1330, 10903, 11, 41146, 11, 16089, 11, 7343, 11, 48436, 11, 399, 7287, 628 ]
3.52381
21
from gnews import GNews
[ 6738, 308, 10827, 1330, 402, 9980 ]
3.833333
6
#!/usr/bin/python3 ''' * Copyright (C) 2021 Ral Osuna Snchez-Infante * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE.txt file for details. ''' ################## #Needed libraries# ################## import matplotlib as mpl mpl.use('TkAgg') import matplotlib.pyplot as plt import qiskit as q import sys from qiskit.visualization import plot_histogram from qiskit.providers.ibmq import least_busy from random import getrandbits ''' Grover's algorithim. Intro ''' ####################### #Functions definitions# ####################### ''' Usage function calling the program with "-h" or "--help" will display the help without returning an error (help was intended) calling the progam with no options or wrong ones, will display the same help but returning an error Please bear in mind that some combination of options are simply ignored, see the text of this function itself ''' ''' Check whether parameter is an integer ''' ''' Initialization: Simply apply an H gate to every qubit ''' ''' Implement multi controlled Z-gate, easy to reutilize ''' ''' Oracle metaimplementation This function will simply call one of the possibles oracles functions ''' ''' Oracle implementation for 2 qubits. Simply a controlled-Z gate (cz in qiskit). For qubits different to 1, an x-gate is needed before and after the cz-gate ''' ''' Oracle implementation for 3 qubits and single solution. Reference for oracles: https://www.nature.com/articles/s41467-017-01904-7 (table 1) ''' ''' Oracle implementation for 3 qubits and two possible solutions. Reference for oracles: https://www.nature.com/articles/s41467-017-01904-7 (table 2) ''' ''' Diffusion operator: Flip sign and amplify For 2 qubits, simply apply H and Z to each qubit, then cz, and then apply H again to each qubit: ''' ''' Add measurements and plot the quantum circuit: ''' ''' Generate results from quantum simulator (no plotting) ''' ''' Generate results from real quantum hardware (no plotting) ''' def results_qhw(qc): ''' #Only needed if credentials are not stored (e.g., deleted and regeneration is needed token='XXXXXXXX' #Use token from ibm quantum portal if needed to enable again, should be stored under ~/.qiskit directory q.IBMQ.save_account(token) ''' provider = q.IBMQ.load_account() provider = q.IBMQ.get_provider() device = q.providers.ibmq.least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) transpiled_grover_circuit = q.transpile(qc, device, optimization_level=3) qobj = q.assemble(transpiled_grover_circuit) job = device.run(qobj) q.tools.monitor.job_monitor(job, interval=2) return job ''' Plot results ''' ############################## #End of functions definitions# ############################## ################################ #Program actually starts here!!# ################################ #Initialization grover_circuit = initialize() #Generate the oracle randomly according to the command line arguments oracle(grover_circuit) #Diffusion if (not(int(sys.argv[1]) == 3 and int(sys.argv[2]) == 1)): diffusion(grover_circuit) #Add measurements measure(grover_circuit) #Generate results in simulator job_sim = results_qsim(grover_circuit) #Plot these results draw_job(job_sim, "Quantum simulator output") #Generate results in quantum hw if requested if int(sys.argv[4]) == 1: plt.show(block=False) plt.draw() #Next line needed for keeping computations in background while still seeing the previous plots plt.pause(0.001) #Generate results in real quantum hardware job_qhw = results_qhw(grover_circuit) #Plot these results as well draw_job(job_qhw, "Quantum hardware output") #Keep plots active when done till they're closed, used for explanations during presentations plt.show()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 7061, 6, 198, 1635, 15069, 357, 34, 8, 33448, 371, 282, 8834, 9613, 5489, 2395, 89, 12, 18943, 12427, 198, 1635, 198, 1635, 770, 3788, 743, 307, 9518, 290, 9387, 739, 262, 2846, ...
3.170213
1,269
# -*- coding: utf-8 -*- import json from typing import List from TM1py.Objects.Git import Git from TM1py.Objects.GitCommit import GitCommit from TM1py.Objects.GitPlan import GitPushPlan, GitPullPlan, GitPlan from TM1py.Services.ObjectService import ObjectService from TM1py.Services.RestService import RestService, Response from TM1py.Utils.Utils import format_url
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 33918, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 21232, 16, 9078, 13, 10267, 82, 13, 38, 270, 1330, 15151, 198, 6738, 21232, 16, 9078, 13, 10267, 82, 13, 38...
3.084034
119
from hypothesis import strategies from hypothesis_geometry import planar from tests.bind_tests.hints import (BoundCell, BoundDiagram, BoundEdge, BoundVertex) from tests.bind_tests.utils import (bound_source_categories, to_bound_multipoint, to_bound_multisegment) from tests.strategies import (doubles, integers_32, sizes) from tests.utils import to_maybe booleans = strategies.booleans() coordinates = doubles empty_diagrams = strategies.builds(BoundDiagram) source_categories = strategies.sampled_from(bound_source_categories) cells = strategies.builds(BoundCell, sizes, source_categories) vertices = strategies.builds(BoundVertex, coordinates, coordinates) edges = strategies.builds(BoundEdge, to_maybe(vertices), cells, booleans, booleans) cells_lists = strategies.lists(cells) edges_lists = strategies.lists(edges) vertices_lists = strategies.lists(vertices) diagrams = strategies.builds(BoundDiagram, cells_lists, edges_lists, vertices_lists) multipoints = planar.multipoints(integers_32).map(to_bound_multipoint) multisegments = planar.multisegments(integers_32).map(to_bound_multisegment)
[ 6738, 14078, 1330, 10064, 198, 6738, 14078, 62, 469, 15748, 1330, 1410, 283, 198, 198, 6738, 5254, 13, 21653, 62, 41989, 13, 71, 29503, 1330, 357, 49646, 28780, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 22...
2.146747
661
""" @Author: YangCheng @contact: 1248644045@qq.com @Software: Y.C @Time: 2020/7/21 15:22 """ from typing import List from pydantic import BaseModel, Field from tortoise import Tortoise from tortoise.contrib.pydantic import pydantic_model_creator, pydantic_queryset_creator from lib.tortoise.pydantic import json_encoders from .models import Tag, Category, Article Tortoise.init_models(["apps.blog.models"], "models") # -*- tag -*- # Tag create/update TagCreateRequest = pydantic_model_creator( Tag, name="TagCreateRequest", exclude_readonly=True ) TagCreateResponse = pydantic_model_creator( Category, name="TagCreateResponse", exclude=["articles"] ) TagCreateResponse.Config.json_encoders = json_encoders # Tag List TagListSerializer = pydantic_queryset_creator( Tag, name="TagListSerializer", exclude=["articles"] ) # -*- Category -*- # Category create/update CategoryCreateRequest = pydantic_model_creator( Category, name="CategoryCreateRequest", exclude_readonly=True ) CategoryCreateResponse = pydantic_model_creator( Category, name="CategoryCreateResponse", exclude=("articles",) ) CategoryCreateResponse.Config.json_encoders = json_encoders # Category List CategoryListSerializer = pydantic_queryset_creator( Category, name="CategoryListSerializer", exclude=("articles",) ) # -*- Article -*- # Article create/update ArticleCreateResponse = pydantic_model_creator( Article, name="ArticleCreateResponse" ) ArticleCreateResponse.Config.json_encoders = json_encoders ArticleListSerializer = pydantic_queryset_creator( Article, name="ArticleListSerializer" ) # Article List
[ 37811, 198, 31, 13838, 25, 220, 220, 10998, 7376, 782, 198, 31, 32057, 25, 220, 1105, 2780, 2414, 1821, 2231, 31, 38227, 13, 785, 198, 31, 25423, 25, 575, 13, 34, 198, 31, 7575, 25, 220, 220, 220, 220, 12131, 14, 22, 14, 2481, 1...
3.057944
535
from skimage import img_as_bool, io, color, morphology import matplotlib.pyplot as plt import numpy as np import pandas as pd # Testing process # Import images one = img_as_bool(color.rgb2gray(io.imread('1.jpg'))) cross = img_as_bool(color.rgb2gray(io.imread('cross.jpg'))) grid = img_as_bool(color.rgb2gray(io.imread('grid.jpg'))) # Get skeleton one_skel = morphology.skeletonize(one) cross_skel = morphology.skeletonize(cross) grid_skel = morphology.skeletonize(grid) # Get medial axis one_med, one_med_distance = morphology.medial_axis(one, return_distance=True) cross_med, cross_med_distance = morphology.medial_axis(cross, return_distance=True) grid_med, grid_med_distance = morphology.medial_axis(grid, return_distance=True) # Get skeleton distance one_skel_distance = one_med_distance*one_skel # Data processing for "1.jpg" one_skel_nonzero = one_skel_distance.nonzero() trans = np.transpose(one_skel_nonzero) df_coords = pd.DataFrame(data = trans, columns = ["y", "x"]) df_dist = pd.DataFrame(data = one_skel_distance[one_skel_nonzero]) combined = pd.concat([df_coords, df_dist], axis=1)
[ 6738, 1341, 9060, 1330, 33705, 62, 292, 62, 30388, 11, 33245, 11, 3124, 11, 46320, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 2, ...
2.720988
405
# global_data.py import os from dotenv import load_dotenv # Read the bot token from the .env file load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DEBUG_MODE = os.getenv('DEBUG_MODE') BOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DB_FILE = os.path.join(BOT_DIR, 'database/room_wizard_db.db') LOG_FILE = os.path.join(BOT_DIR, 'logs/discord.log') DEV_GUILDS = [730115558766411857] # Embed color EMBED_COLOR = 0x6C48A7 DEFAULT_FOOTER = 'Just pinning things.'
[ 2, 3298, 62, 7890, 13, 9078, 198, 198, 11748, 28686, 198, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 198, 2, 4149, 262, 10214, 11241, 422, 262, 764, 24330, 2393, 198, 2220, 62, 26518, 24330, 3419, 198, 10468, 43959, 7...
2.354369
206
""" Model Definition """ from tensorflow import keras from tensorflow.keras.applications import ResNet101V2 from tensorflow.keras.layers import ( BatchNormalization, Conv2D, Dense, Dropout, Flatten, LSTM, MaxPool2D, TimeDistributed, Lambda ) import tensorflow as tf from .spatial_transformer.bilinear_sampler import BilinearSampler
[ 37811, 198, 17633, 30396, 198, 37811, 198, 198, 6738, 11192, 273, 11125, 1330, 41927, 292, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 1324, 677, 602, 1330, 1874, 7934, 8784, 53, 17, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 1...
2.87395
119
#!/usr/bin/env python3 """Generate fake serialized NNs to test the lightweight classes""" import argparse import json import h5py import numpy as np if __name__ == "__main__": _run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 8645, 378, 8390, 11389, 1143, 399, 47503, 284, 1332, 262, 18700, 6097, 37811, 198, 198, 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 289, 20, 9078, 198, 11748, 299,...
2.96875
64
''' Collection of Windows-specific I/O functions ''' import msvcrt import time import ctypes from platforms import winconstants, winclipboard EnumWindows = ctypes.windll.user32.EnumWindows EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) GetWindowText = ctypes.windll.user32.GetWindowTextW GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW IsWindowVisible = ctypes.windll.user32.IsWindowVisible
[ 7061, 6, 198, 36307, 286, 3964, 12, 11423, 314, 14, 46, 5499, 198, 7061, 6, 198, 198, 11748, 13845, 85, 6098, 83, 198, 11748, 640, 198, 11748, 269, 19199, 198, 6738, 9554, 1330, 1592, 9979, 1187, 11, 1592, 15036, 3526, 198, 198, 483...
2.884146
164
# messenger.py - contains functions to create different kinds of messages like info or error # color the text, usage: print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC BCOLORS = { 'HEADER': '\033[95m', 'OKBLUE': '\033[94m', 'OKGREEN': '\033[92m', 'WARNING': '\033[93m', 'FAIL': '\033[91m', 'ENDC': '\033[0m', 'BOLD': '\033[1m', 'UNDERLINE': '\033[4m' } # Information message # Action message # Error message
[ 2, 31228, 13, 9078, 532, 4909, 5499, 284, 2251, 1180, 6982, 286, 6218, 588, 7508, 393, 4049, 628, 198, 2, 3124, 262, 2420, 11, 8748, 25, 3601, 275, 4033, 669, 13, 31502, 1343, 366, 20361, 25, 1400, 4075, 422, 76, 1039, 3520, 13, 1...
2.461929
197
import json import RPi.GPIO as GPIO from modules.sensor import getTempC, getHumidity currentPins = loadConfig().values() def bootActuators(): '''Assumes that pi is booting and set off all the relays''' GPIO.setmode(GPIO.BOARD) for i, p in enumerate(currentPins): GPIO.setup(p, GPIO.OUT) GPIO.output(p, GPIO.HIGH) print(p, GPIO.input(p)) print('Actuators turned off') bootActuators()
[ 11748, 33918, 198, 11748, 25812, 72, 13, 16960, 9399, 355, 50143, 198, 6738, 13103, 13, 82, 22854, 1330, 651, 30782, 34, 11, 651, 32661, 17995, 628, 198, 14421, 47, 1040, 796, 3440, 16934, 22446, 27160, 3419, 198, 198, 4299, 6297, 6398,...
2.497076
171
import json import habu if __name__ == "__main__": main()
[ 11748, 33918, 198, 198, 11748, 387, 11110, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.5
26
import json import os import requests from dotenv import load_dotenv # You have to configure in this file to notify other services load_dotenv(override=True)
[ 11748, 33918, 198, 11748, 28686, 198, 198, 11748, 7007, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 198, 2, 921, 423, 284, 17425, 287, 428, 2393, 284, 19361, 584, 2594, 628, 628, 198, 2220, 62, 26518, 24330, 7, 2502, 1...
3.565217
46
import random import string
[ 11748, 4738, 198, 11748, 4731 ]
5.4
5
import signal import sys import time import pyupm_grove as grove import pyupm_i2clcd as lcd if __name__=='__main__': signal.signal(signal.SIGINT, interruptHandler) myLcd = lcd.Jhd1313m1(0, 0x3E,0x62) sensorluz=grove.GroveLight(0) coloR=255 colorG=200 colorB=100 myLcd.setColor(coloR,colorG,colorB) #read the input and print, waiting 1/2 seconds between reading while True: valorSensor=sensorluz.value() myLcd.setCursor(0,0) myLcd.write('%6d'% valorSensor) time.sleep(0.5) del sensorluz
[ 11748, 6737, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 12972, 929, 76, 62, 27333, 303, 355, 7128, 303, 198, 11748, 12972, 929, 76, 62, 72, 17, 565, 10210, 355, 300, 10210, 198, 361, 11593, 3672, 834, 855, 6, 834, 12417, 834, 1...
2.202586
232
from setuptools import setup, find_packages setup( name='FSM', version='0.1', author='Ben Coughlan', author_email='ben@cgsy.com.au', packages=find_packages(), license_file='LICENSE', )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 10652, 44, 3256, 198, 220, 220, 220, 2196, 11639, 15, 13, 16, 3256, 198, 220, 220, 220, 1772, 11639, 11696, 327, 619, 962...
2.413793
87
import random from typing import Tuple, Dict, Any import scipy import itertools import graphviz import numpy as np import pandas as pd from clustviz.pam import plot_pam from pyclustering.utils import euclidean_distance_square from pyclustering.cluster.clarans import clarans as clarans_pyclustering def compute_cost_clarans(data: pd.DataFrame, _cur_choice: list) -> Tuple[float, Dict[Any, list]]: """ A function to compute the configuration cost. (modified from that of CLARA) :param data: The input dataframe. :param _cur_choice: The current set of medoid choices. :return: The total configuration cost, the medoids. """ total_cost = 0.0 medoids = {} for idx in _cur_choice: medoids[idx] = [] for i in list(data.index): choice = -1 min_cost = np.inf for m in medoids: # fast_euclidean from CLARA tmp = np.linalg.norm(data.loc[m] - data.loc[i]) if tmp < min_cost: choice = m min_cost = tmp medoids[choice].append(i) total_cost += min_cost # print("total_cost: ", total_cost) return total_cost, medoids def plot_tree_clarans(data: pd.DataFrame, k: int) -> None: """ plot G_{k,n} as in the paper of CLARANS; only to use with small input data. :param data: input DataFrame. :param k: number of points in each combination (possible set of medoids). """ n = len(data) num_points = int(scipy.special.binom(n, k)) num_neigh = k * (n - k) if (num_points > 50) or (num_neigh > 10): print( "Either graph nodes are more than 50 or neighbors are more than 10, the graph would be too big" ) return # all possibile combinations of k elements from input data name_nodes = list(itertools.combinations(list(data.index), k)) dot = graphviz.Digraph(comment="Clustering") # draw nodes, also adding the configuration cost for i in range(num_points): tot_cost, meds = compute_cost_clarans(data, list(name_nodes[i])) tc = round(tot_cost, 3) dot.node(str(name_nodes[i]), str(name_nodes[i]) + ": " + str(tc)) # only connect nodes if they have k-1 common elements for i in range(num_points): for j in range(num_points): if i != j: if ( len(set(list(name_nodes[i])) & set(list(name_nodes[j]))) == k - 1 ): dot.edge(str(name_nodes[i]), str(name_nodes[j])) graph = graphviz.Source(dot) # .view() display(graph)
[ 11748, 4738, 198, 6738, 19720, 1330, 309, 29291, 11, 360, 713, 11, 4377, 198, 198, 11748, 629, 541, 88, 198, 11748, 340, 861, 10141, 198, 11748, 4823, 85, 528, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, ...
2.273675
1,151
from __future__ import absolute_import, print_function, unicode_literals import os import requests from metapub.findit import FindIt from metapub.exceptions import * from requests.packages import urllib3 urllib3.disable_warnings() OUTPUT_DIR = 'findit' CURL_TIMEOUT = 4000 if __name__=='__main__': import sys try: start_pmid = int(sys.argv[1]) except (IndexError, TypeError) as err: print("Supply a pubmed ID as the starting point for this script.") sys.exit() for pmid in range(start_pmid, start_pmid+1000): try_backup_url(pmid)
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 28686, 198, 11748, 7007, 198, 198, 6738, 1138, 499, 549, 13, 19796, 270, 1330, 9938, 1026, 198, 6738, 1138, 499, 549...
2.570175
228
import tensorflow as tf from kgcnn.layers.base import GraphBaseLayer from kgcnn.layers.gather import GatherNodesOutgoing, GatherNodesIngoing from kgcnn.layers.pooling import PoolingLocalEdges from kgcnn.layers.modules import LazySubtract
[ 11748, 11192, 273, 11125, 355, 48700, 198, 198, 6738, 14211, 66, 20471, 13, 75, 6962, 13, 8692, 1330, 29681, 14881, 49925, 198, 6738, 14211, 66, 20471, 13, 75, 6962, 13, 70, 1032, 1330, 402, 1032, 45, 4147, 7975, 5146, 11, 402, 1032, ...
2.975309
81
from typing import Callable, Tuple, Union StrOrBytes = Union[str, bytes] StrOrBytesPair = Tuple[StrOrBytes, StrOrBytes] KeysStore = Callable[[], Union[StrOrBytes, StrOrBytesPair]]
[ 6738, 19720, 1330, 4889, 540, 11, 309, 29291, 11, 4479, 198, 198, 13290, 5574, 45992, 796, 4479, 58, 2536, 11, 9881, 60, 198, 13290, 5574, 45992, 47, 958, 796, 309, 29291, 58, 13290, 5574, 45992, 11, 4285, 5574, 45992, 60, 198, 40729,...
2.967213
61
from django.contrib import admin from api.models import Device admin.site.register(Device, DeviceAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 40391, 13, 27530, 1330, 16232, 628, 198, 198, 28482, 13, 15654, 13, 30238, 7, 24728, 11, 16232, 46787, 8, 198 ]
3.483871
31
# from django.contrib import admin # from django.urls import path from django.conf.urls import url from help import views urlpatterns = [ url(r'^$', views.index) ]
[ 2, 422, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 2, 422, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 1037, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, ...
2.816667
60
# coding=utf-8 import random from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ from notifications.models import EventType from social_graph import EdgeType try: from hashlib import sha1 as sha_constructor, md5 as md5_constructor except ImportError: pass #---------------------NOTIFICATIONS--------------------------------- #---------------------EDGES----------------------------------------- #---------------------GENERAL----------------------------------------- def generate_sha1(string, salt=None): """ Generates a sha1 hash for supplied string. Doesn't need to be very secure because it's not used for password checking. We got Django for that. :param string: The string that needs to be encrypted. :param salt: Optionally define your own salt. If none is supplied, will use a random string of 5 characters. :return: Tuple containing the salt and hash. """ if not isinstance(string, (str, unicode)): string = str(string) if isinstance(string, unicode): string = string.encode("utf-8") if not salt: salt = sha_constructor(str(random.random())).hexdigest()[:5] hash = sha_constructor(salt+string).hexdigest() return (salt, hash) # A tuple of standard large number to their converters intword_converters = ( (3, lambda number: _('%(value)dK')), (6, lambda number: _('%(value)dM')), (9, lambda number: _('%(value)dG')), ) def intmin(value): """ """ try: value = int(value) except (TypeError, ValueError): return value if value < 1000: return value for exponent, converter in intword_converters: large_number = 10 ** exponent if value < large_number * 1000: new_value = value / large_number tpl = "+%s" if value > large_number else "%s" return tpl % converter(new_value) % {'value': new_value} return value
[ 2, 19617, 28, 40477, 12, 23, 198, 11748, 4738, 198, 6738, 42625, 14208, 13, 7295, 13, 23870, 1330, 12940, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 42625, 14208, 13, 26791, 13, ...
2.845188
717
from django.urls import path from . import views urlpatterns = [ path('', views.get_percentage, name='get_percentage'), path('get_percentage_value', views.get_percentage_value, name='get_percentage_value'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009, 13, 1136, 62, 25067, 496, 11, 1438, 11639, 1136, 62, 25067, 496, 33809, ...
2.881579
76
# Generated by Django 3.2.8 on 2021-10-12 15:54 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 23, 319, 33448, 12, 940, 12, 1065, 1315, 25, 4051, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
"""Schedule multiple flows of a type.""" from .base import BaseHandler
[ 37811, 27054, 5950, 3294, 15623, 286, 257, 2099, 526, 15931, 198, 198, 6738, 764, 8692, 1330, 7308, 25060, 628 ]
3.842105
19
import logging logger = logging.getLogger(__name__)
[ 11748, 18931, 628, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628 ]
3.055556
18
from app.helpers.sqlalchemy import db
[ 6738, 598, 13, 16794, 364, 13, 25410, 282, 26599, 1330, 20613 ]
3.363636
11
# # PySNMP MIB module HUAWEI-CDP-COMPLIANCE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-CDP-COMPLIANCE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:31:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint") hwDatacomm, = mibBuilder.importSymbols("HUAWEI-MIB", "hwDatacomm") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus") ZeroBasedCounter32, TimeFilter = mibBuilder.importSymbols("RMON2-MIB", "ZeroBasedCounter32", "TimeFilter") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Unsigned32, TimeTicks, Counter32, IpAddress, iso, NotificationType, ObjectIdentity, ModuleIdentity, Counter64, Bits, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "TimeTicks", "Counter32", "IpAddress", "iso", "NotificationType", "ObjectIdentity", "ModuleIdentity", "Counter64", "Bits", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Integer32") TextualConvention, TruthValue, TimeStamp, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "TruthValue", "TimeStamp", "DisplayString") hwCdpComplianceMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198)) if mibBuilder.loadTexts: hwCdpComplianceMIB.setLastUpdated('200905050000Z') if mibBuilder.loadTexts: hwCdpComplianceMIB.setOrganization('Huawei Technologies co.,Ltd.') hwCdpComplianceObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1)) hwCdpComplianceNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 2)) hwCdpComplianceConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 3)) hwCdpComplianceConfiguration = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1)) hwCdpComplianceStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 2)) hwCdpComplianceRemoteSystemsData = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 3)) hwCdpComplianceEnable = MibScalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1, 1), EnabledStatus().clone()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwCdpComplianceEnable.setStatus('current') hwCdpComplianceNotificationInterval = MibScalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(5)).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: hwCdpComplianceNotificationInterval.setStatus('current') hwCdpCompliancePortConfigTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1, 3), ) if mibBuilder.loadTexts: hwCdpCompliancePortConfigTable.setStatus('current') hwCdpCompliancePortConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1, 3, 1), ).setIndexNames((0, "HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpCompliancePortConfigIfIndex")) if mibBuilder.loadTexts: hwCdpCompliancePortConfigEntry.setStatus('current') hwCdpCompliancePortConfigIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1, 3, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwCdpCompliancePortConfigIfIndex.setStatus('current') hwCdpCompliancePortConfigAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("rxOnly", 2))).clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwCdpCompliancePortConfigAdminStatus.setStatus('current') hwCdpCompliancePortConfigHoldTime = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 254)).clone(180)).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: hwCdpCompliancePortConfigHoldTime.setStatus('current') hwCdpCompliancePortConfigNotificationEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1, 3, 1, 4), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwCdpCompliancePortConfigNotificationEnable.setStatus('current') hwCdpCompliancePortStatsReset = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 1, 3, 1, 5), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwCdpCompliancePortStatsReset.setStatus('current') hwCdpComplianceStatsRemTablesLastChangeTime = MibScalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 2, 1), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwCdpComplianceStatsRemTablesLastChangeTime.setStatus('current') hwCdpComplianceStatsRemTablesAgeouts = MibScalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 2, 2), ZeroBasedCounter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwCdpComplianceStatsRemTablesAgeouts.setStatus('current') hwCdpComplianceStatsRxPortTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 2, 3), ) if mibBuilder.loadTexts: hwCdpComplianceStatsRxPortTable.setStatus('current') hwCdpComplianceStatsRxPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 2, 3, 1), ).setIndexNames((0, "HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceStatsRxPortIfIndex")) if mibBuilder.loadTexts: hwCdpComplianceStatsRxPortEntry.setStatus('current') hwCdpComplianceStatsRxPortIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 2, 3, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwCdpComplianceStatsRxPortIfIndex.setStatus('current') hwCdpComplianceStatsRxPortFramesTotal = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 2, 3, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwCdpComplianceStatsRxPortFramesTotal.setStatus('current') hwCdpComplianceStatsRxPortAgeoutsTotal = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 2, 3, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwCdpComplianceStatsRxPortAgeoutsTotal.setStatus('current') hwCdpComplianceRemoteTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 3, 1), ) if mibBuilder.loadTexts: hwCdpComplianceRemoteTable.setStatus('current') hwCdpComplianceRemoteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 3, 1, 1), ).setIndexNames((0, "HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceRemLocalPortIfIndex")) if mibBuilder.loadTexts: hwCdpComplianceRemoteEntry.setStatus('current') hwCdpComplianceRemLocalPortIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 3, 1, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: hwCdpComplianceRemLocalPortIfIndex.setStatus('current') hwCdpComplianceRemTimeMark = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 3, 1, 1, 2), TimeFilter()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwCdpComplianceRemTimeMark.setStatus('current') hwCdpComplianceRemoteInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 1, 3, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 1600))).setMaxAccess("readonly") if mibBuilder.loadTexts: hwCdpComplianceRemoteInfo.setStatus('current') hwCdpComplianceNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 2, 1)) hwCdpComplianceRemTablesChange = NotificationType((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 2, 1, 1)).setObjects(("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceStatsRemTablesLastChangeTime"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceStatsRemTablesAgeouts")) if mibBuilder.loadTexts: hwCdpComplianceRemTablesChange.setStatus('current') hwCdpComplianceCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 3, 1)) hwCdpComplianceGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 3, 2)) hwCdpComplianceCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 3, 1, 1)).setObjects(("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceConfigGroup"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceStatsGroup"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceRemSysGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hwCdpComplianceCompliance = hwCdpComplianceCompliance.setStatus('current') hwCdpComplianceConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 3, 2, 1)).setObjects(("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceEnable"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceNotificationInterval"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpCompliancePortConfigAdminStatus"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpCompliancePortConfigHoldTime"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpCompliancePortConfigNotificationEnable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hwCdpComplianceConfigGroup = hwCdpComplianceConfigGroup.setStatus('current') hwCdpComplianceStatsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 3, 2, 2)).setObjects(("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceStatsRxPortFramesTotal"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpCompliancePortStatsReset"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceStatsRemTablesLastChangeTime"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceStatsRemTablesAgeouts"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceStatsRxPortAgeoutsTotal")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hwCdpComplianceStatsGroup = hwCdpComplianceStatsGroup.setStatus('current') hwCdpComplianceRemSysGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 3, 2, 3)).setObjects(("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceRemoteInfo"), ("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceRemTimeMark")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hwCdpComplianceRemSysGroup = hwCdpComplianceRemSysGroup.setStatus('current') hwCdpComplianceTrapGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 198, 3, 2, 4)).setObjects(("HUAWEI-CDP-COMPLIANCE-MIB", "hwCdpComplianceRemTablesChange")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hwCdpComplianceTrapGroup = hwCdpComplianceTrapGroup.setStatus('current') mibBuilder.exportSymbols("HUAWEI-CDP-COMPLIANCE-MIB", hwCdpComplianceRemoteTable=hwCdpComplianceRemoteTable, hwCdpCompliancePortConfigAdminStatus=hwCdpCompliancePortConfigAdminStatus, hwCdpComplianceRemoteInfo=hwCdpComplianceRemoteInfo, hwCdpComplianceGroups=hwCdpComplianceGroups, hwCdpComplianceRemoteEntry=hwCdpComplianceRemoteEntry, hwCdpCompliancePortConfigIfIndex=hwCdpCompliancePortConfigIfIndex, hwCdpComplianceEnable=hwCdpComplianceEnable, hwCdpComplianceNotifications=hwCdpComplianceNotifications, hwCdpComplianceCompliance=hwCdpComplianceCompliance, hwCdpCompliancePortConfigTable=hwCdpCompliancePortConfigTable, hwCdpComplianceNotificationPrefix=hwCdpComplianceNotificationPrefix, hwCdpComplianceStatsGroup=hwCdpComplianceStatsGroup, hwCdpComplianceStatsRemTablesAgeouts=hwCdpComplianceStatsRemTablesAgeouts, hwCdpComplianceStatsRemTablesLastChangeTime=hwCdpComplianceStatsRemTablesLastChangeTime, hwCdpComplianceStatsRxPortIfIndex=hwCdpComplianceStatsRxPortIfIndex, hwCdpComplianceRemTimeMark=hwCdpComplianceRemTimeMark, hwCdpComplianceRemoteSystemsData=hwCdpComplianceRemoteSystemsData, hwCdpComplianceStatsRxPortAgeoutsTotal=hwCdpComplianceStatsRxPortAgeoutsTotal, hwCdpCompliancePortStatsReset=hwCdpCompliancePortStatsReset, hwCdpComplianceRemTablesChange=hwCdpComplianceRemTablesChange, hwCdpComplianceConfiguration=hwCdpComplianceConfiguration, hwCdpComplianceTrapGroup=hwCdpComplianceTrapGroup, hwCdpComplianceMIB=hwCdpComplianceMIB, hwCdpComplianceRemLocalPortIfIndex=hwCdpComplianceRemLocalPortIfIndex, hwCdpComplianceObjects=hwCdpComplianceObjects, hwCdpComplianceNotificationInterval=hwCdpComplianceNotificationInterval, hwCdpComplianceStatsRxPortEntry=hwCdpComplianceStatsRxPortEntry, hwCdpCompliancePortConfigEntry=hwCdpCompliancePortConfigEntry, PYSNMP_MODULE_ID=hwCdpComplianceMIB, hwCdpComplianceCompliances=hwCdpComplianceCompliances, hwCdpComplianceRemSysGroup=hwCdpComplianceRemSysGroup, hwCdpCompliancePortConfigHoldTime=hwCdpCompliancePortConfigHoldTime, hwCdpComplianceStatsRxPortTable=hwCdpComplianceStatsRxPortTable, hwCdpComplianceConformance=hwCdpComplianceConformance, hwCdpComplianceConfigGroup=hwCdpComplianceConfigGroup, hwCdpComplianceStatistics=hwCdpComplianceStatistics, hwCdpCompliancePortConfigNotificationEnable=hwCdpCompliancePortConfigNotificationEnable, hwCdpComplianceStatsRxPortFramesTotal=hwCdpComplianceStatsRxPortFramesTotal)
[ 2, 198, 2, 9485, 15571, 7378, 337, 9865, 8265, 367, 34970, 8845, 40, 12, 34, 6322, 12, 9858, 6489, 16868, 5222, 12, 8895, 33, 357, 4023, 1378, 16184, 76, 489, 8937, 13, 785, 14, 79, 893, 11632, 8, 198, 2, 7054, 45, 13, 16, 2723,...
2.657889
4,823
import re from pybb.processors import BaseProcessor from pybb.compat import get_user_model from . import settings
[ 11748, 302, 198, 198, 6738, 12972, 11848, 13, 14681, 669, 1330, 7308, 18709, 273, 198, 6738, 12972, 11848, 13, 5589, 265, 1330, 651, 62, 7220, 62, 19849, 198, 198, 6738, 764, 1330, 6460, 628 ]
3.441176
34
import unittest from selenium import webdriver from PageObjectModel.Pages.addAndEditionDataPage import AddAndEditionData_Page from time import sleep url = 'https://buggy-testingcup.pgs-soft.com/'
[ 11748, 555, 715, 395, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 7873, 10267, 17633, 13, 47798, 13, 2860, 1870, 7407, 653, 6601, 9876, 1330, 3060, 1870, 7407, 653, 6601, 62, 9876, 198, 6738, 640, 1330, 3993, 628, 198, ...
3.222222
63
from q2_api_client.clients.base_q2_client import BaseQ2Client from q2_api_client.endpoints.mobile_ws_endpoints import CalendarEndpoint
[ 6738, 10662, 17, 62, 15042, 62, 16366, 13, 565, 2334, 13, 8692, 62, 80, 17, 62, 16366, 1330, 7308, 48, 17, 11792, 198, 6738, 10662, 17, 62, 15042, 62, 16366, 13, 437, 13033, 13, 24896, 62, 18504, 62, 437, 13033, 1330, 26506, 12915, ...
3.022222
45
#!/usr/bin/env python """ Set of utilities to issue/verify/revoke a CG token with REST calls Requires valid username and password either in bash environment or given at the command line. Issue Token: Token can be easily created (and stored to env) with the folloing: # create token using CG_USERNAME, CG_PASSWORD, and CG_API env variables ./cg_token.py # create token specifying all the parameters on command line ./cg_token.py --username <login> --password <password> --endpoint <url> # create token using CG_USERNAME, CG_API, but prompt for password ./cg_token.py --password - # add token to environmental variables export CG_TOKEN=`./cg_token.py` # add token to environmental variable, specify extra parameters export CG_TOKEN=`./cg_token.py --username <login> --endpoint <newurl>` Verify or Revoke Token: Verifying or Revoking requires the positional 'verify' or 'revoke' command line argument. User can still override env variables with command-line arguments. Uses CG_API, and CG_TOKEN env variables for both. Verify uses CG_CLIENT_ID and CG_CLIENT_IP for consumer ID & user client IP, Revoke uses CG_USERNAME and CG_PASSWORD for security purposes : # Verify token, overriding CG_CLIENT_ID and CG_CLIENT_IP with command # line (Upon success, it will print the remaining lifetime of the token # in seconds) ./cg_token.py verify --clientid <ID> --clientip <IP> # Revoke token, overriding CG_TOKEN with command line ./cg_token.py revoke --token <token> Print debug info to stderr: Append the flag "--debug" or "-d" : ./cg_token.py --debug """ import sys, os, getpass import json import logging import requests import argparse from requests import exceptions as rex # This is used sed to disable InsecureRequestWarning. requests.packages.urllib3.disable_warnings() logger = logging.getLogger(__name__) def logger_initialize(debug) : """Initializes the format and level for the logger""" _format = ("%(levelname)s - %(asctime)s\n%(message)s\n") if debug : logging.basicConfig(format=_format, level=logging.DEBUG) else : logging.basicConfig(format=_format, level=logging.WARNING) def log_response(method, url, response, request) : """Logs request and response when in debug mode""" if request.get('password', '') : request['password'] = '*******' logger.debug("URL: " + url) logger.debug("Request: " + method) logger.debug("Request Data (in JSON format)" ": " + json.dumps(request,indent=4,separators=(',',': '))) logger.debug("Response (in JSON format)" ": " + json.dumps(response,indent=4,separators=(',',': '))) def parse_args() : """Defines command line positional and optional arguments and checks for valid action input if present. Additionally prompts with getpass if user specifies "--password -" to override CG_PASSWORD Args: none Returns: A (tuple) containing the following: args (namespace) : used to overwrite env variables when necessary action (string) : for main to use as a switch for calls to perform """ parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action="store_true", help='Allow debug info to be written to stderr') parser.add_argument("-e", "--endpoint", default=os.getenv('CG_API',''), help="Set API url") parser.add_argument("-p", "--password", default=os.getenv('CG_PASSWORD',''), help="Set password. '-' for secure prompting") parser.add_argument("-u", "--username", default=os.getenv('CG_USERNAME',''), help="Set Username") parser.add_argument("-t", "--token", default=os.getenv('CG_TOKEN',''), help="Set Token for Verify/Revoke") parser.add_argument("-l", "--lifetime", type=long, default=43200, help="Set Lifetime for Token Issue in seconds" ". minimum=3600 (1hr), maximum=12*3600 (12hr)") parser.add_argument("-b", "--binding", type=int, default=1, help="1: Bind with IP Address, 0: Don't Bind") parser.add_argument("-c", "--clientid", default=os.getenv('CG_CLIENT_ID',''), help="Set Client ID for Verify") parser.add_argument("-i", "--clientip", default=os.getenv('CG_CLIENT_IP',''), help="Set Client IP for Verify") parser.add_argument("action", nargs='?', type=str, default='issue', help='issue/verify/revoke') args = parser.parse_args() logger_initialize(args.debug) if args.password and args.password == '-' : args.password = getpass.getpass("Enter desired CG Password: ") if not args.endpoint : logger.error('CG_API (API url for REST calls) ' 'not specified\n') sys.exit(1) if args.action.lower() not in ['issue','verify','revoke'] : logger.error('Invalid Action') sys.exit(1) return (args,args.action.lower()) def cg_rest(method, endpoint, headers={}, **kwargs) : """Calls the CG REST endpoint passing keyword arguments given. 'cg_rest' provides a basic wrapper around the HTTP request to the rest endpoint, and attempts to provide informative error messages when errors occur. Exceptions are passed to the calling function for final resolution. cg_rest('POST', <url>, headers=<HTTP headers dict>, username=<username>, password=<password>, ...) or with a previously constructed data/params dict cg_rest('POST', <url>, headers=headers, **data/params) or with no header necessary cg_rest('POST', <url>, **data/params) Args: method (str): the HTTP method that will be called endpoint (str, URL): the REST endpoint headers (dict, optional): HTTP headers kwargs (optional): common keywords include username, password, etc. Returns: (dict): decodes the response and returns it as a dictionary Raises: Raises CGException when the gateway server return an error status. Other exceptions may be raised based errors with the HTTP request and response. See documentation of Python's request module for a complete list. """ try : if method.upper() == 'POST' or method.upper() == 'PUT' : r = requests.request(method.upper(), endpoint, timeout=50, verify=False, headers=headers, data=kwargs) else : # Must be 'GET' or 'DELETE' r = requests.request(method.upper(), endpoint, timeout=50, verify=False, headers=headers, params=kwargs) r.raise_for_status() except (rex.ConnectionError, rex.HTTPError, rex.MissingSchema) as e : logger.debug("Problem with API endpoint '%s', " "is it entered correctly?" %endpoint) raise except (rex.Timeout) as e : logger.debug('Request timed out, the service may be ' 'temporarily unavailable') raise response = r.json() log_response(method, endpoint, response, kwargs) # If status is not provided, default to error. if response.get('status','') and response.get('status','') == 'error' : logger.debug("Call fails with '%s'" %response['result']['message']) raise CGException(response['result']) return response def issue_token(endpoint, username, password, lifetime, binding) : """Calls the Gateway issueToken function and returns token. Args: endpoint (string, URL): the REST endpoint username (string): the user's login password (string): the user's password lifetime (int): the lifetime of a token in seconds (3600 <= lifetime <= 12*3600) binding (int): 1 if user wants token to be bound to user IP 0 else Returns: (string): Open Service API token Raises: Passes any exceptions raised in cg_rest. """ data = { 'username' : username, 'password' : password, 'lifetime' : lifetime, 'binding' : binding } url = endpoint.rstrip('/') + '/token' logger.debug('Issuing token from %s' %url) response = cg_rest('POST', url, **data) return response['result']['token'] def verify_token(endpoint, username, token, client_id, client_ip) : """Calls the Gateway verifyToken function, returns remaining token lifetime. Args: endpoint(string, URL): the REST endpoint username (string): token (string): Token to verify client_id (string): Consumer ID client_ip (string): User Client's IP Address Returns: (int): Remaining lifetime of token (in seconds) Raises: Passes any exceptions raised in cg_rest. """ data = { 'token' : token, 'consumer' : client_id, 'remote_addr' : client_ip, 'username' : username } url = endpoint.rstrip('/') + '/token' logger.debug("Verifying token '%s' from '%s'" %(token,url)) data_length = str(len(json.dumps(data))) headers = {'Content-Length' : data_length} response = cg_rest('PUT', url, headers=headers, **data) return response['result']['lifetime'] def revoke_token(endpoint, username, password, token) : """Calls the Gateway revokeToken function Args: endpoint (string, URL): the REST endpoint username (string): the user's login password (string): the user's password token (string): The token to be revoked Returns: void Raises: Passes any exceptions raised in cg_rest. """ params = { 'token' : token, 'username' : username, 'password' : password, } url = endpoint.rstrip('/') + "/token" logger.debug("Revoking token '%s' from '%s'" %(token,url)) response = cg_rest('DELETE', url, **params) if __name__ == '__main__' : main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 7248, 286, 20081, 284, 2071, 14, 332, 1958, 14, 18218, 2088, 257, 29925, 11241, 351, 30617, 3848, 198, 39618, 4938, 20579, 290, 9206, 2035, 287, 27334, 2858, 393, 198, ...
2.571069
3,975
from .Generic import GenericHandler
[ 6738, 764, 46189, 1330, 42044, 25060, 628 ]
5.285714
7
from audioop import add from erd import * from table import * # This function converts an ERD object into a Database object # The Database object should correspond to a fully correct implementation # of the ERD, including both data structure and constraints, such that the # CREATE TABLE statements generated by the Database object will populate an # empty MySQL database to exactly implement the conceptual design communicated # by the ERD. # # @TODO: Implement me!
[ 6738, 6597, 404, 1330, 751, 198, 6738, 1931, 67, 1330, 1635, 198, 6738, 3084, 1330, 1635, 198, 198, 2, 770, 2163, 26161, 281, 13793, 35, 2134, 656, 257, 24047, 2134, 198, 2, 383, 24047, 2134, 815, 6053, 284, 257, 3938, 3376, 7822, 1...
4.33945
109
# Program to self calibrate OTF data import Obit, OTF, Image, OSystem, OErr, OTFGetSoln, InfoList, Table # Init Obit err=OErr.OErr() ObitSys=OSystem.OSystem ("Python", 1, 103, 1, ["None"], 1, ["./"], 1, 0, err) OErr.printErrMsg(err, "Error with Obit startup") # Files disk = 1 # Dirty inFullFile = "OTFDirtyFull.fits" # input Full OTF data inSubFile = "OTFDirtySub.fits" # input Full OTF data #Clean #inFullFile = "OTFCleanFull.fits" # input Full OTF data #inSubFile = "OTFCleanSub.fits" # input Full OTF data # Set data fullData = OTF.newPOTF("Input data", inFullFile, disk, 1, err) subData = OTF.newPOTF("Input data", inSubFile, disk, 1, err) OErr.printErrMsg(err, "Error creating input data object") # Calibration parameters calType = "Filter" solint = 5.0 / 86400.0 minRMS = 0.0 minEl = 0.0 calJy = [1.0,1.0] dim = OTF.dim dim[0] = 1 inInfo = OTF.POTFGetList(subData) InfoList.PInfoListAlwaysPutFloat(inInfo, "SOLINT", dim, [solint]) InfoList.PInfoListAlwaysPutFloat(inInfo, "MINRMS", dim, [minRMS]) InfoList.PInfoListAlwaysPutFloat(inInfo, "MINEL", dim, [minEl]) dim[0] = len(calJy) InfoList.PInfoListAlwaysPutFloat(inInfo, "CALJY", dim, calJy) dim[0] = len(calType) InfoList.PInfoListAlwaysPutString(inInfo, "calType", dim, [calType]) dim[0] = 1 solnTable = OTFGetSoln.POTFGetSolnFilter (subData, fullData, err) soln = Table.PTableGetVer(solnTable) # Update Cal table # Soln2Cal parameters (most defaulted) OTF.Soln2CalInput["InData"] = fullData OTF.Soln2CalInput["soln"] = soln # Use highest extant Cal table as input oldCal = Obit.OTFGetHighVer(fullData.me, "OTFCal") if oldCal == 0: # Must not be one oldCal = -1 OTF.Soln2CalInput["oldCal"] = oldCal OTF.Soln2CalInput["newCal"] = 0 OTF.Soln2Cal(err,OTF.Soln2CalInput) # Shutdown OErr.printErr(err) print 'Done, calibrated',inFullFile
[ 2, 6118, 284, 2116, 33801, 378, 440, 10234, 1366, 198, 11748, 1835, 270, 11, 440, 10234, 11, 7412, 11, 7294, 6781, 11, 440, 9139, 81, 11, 440, 10234, 3855, 50, 10875, 11, 14151, 8053, 11, 8655, 198, 198, 2, 44707, 1835, 270, 198, ...
2.369231
780
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup r = requests.get("https://twitter.com/ThePSF", headers={"User-Agent": ""}) if r.status_code == 200: s = BeautifulSoup(r.content, "html.parser") # extract tweets l_tw = [] for p in s.find_all("p", attrs={"class": "tweet-text"}): l_tw.append(p.text.strip()) print(l_tw)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 198, 81, 796, 7007, 13, 1136, 7203, 5450, ...
2.339286
168
#!/usr/bin/python # -*- coding: utf-8 -*- import decimal import multiprocessing import random def roundDecimal(v): ''' Sembra che l'arrotondamento di un decimal sia pi complicato del previsto ''' return v.quantize(decimal.Decimal('0.01'), rounding=decimal.ROUND_HALF_UP) def maybeStart(startCb, debug): ''' Ogni tanto esegue questa callback... Ad ogni restart di un worker in maniera casuale esegue la callback ''' if debug: return workers = multiprocessing.cpu_count() * 2 + 1 if random.randrange(workers) == 0: startCb()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 32465, 198, 11748, 18540, 305, 919, 278, 198, 11748, 4738, 628, 198, 4299, 2835, 10707, 4402, 7, 85, 2599, 198, ...
2.443983
241
# Generated by Django 3.2.4 on 2021-09-24 15:29 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 19, 319, 33448, 12, 2931, 12, 1731, 1315, 25, 1959, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
from django.shortcuts import render
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198 ]
4
9
# -*- coding: utf-8 -*- """ Created on Mon Feb 11 09:18:37 2019 @author: if715029 """ import pandas as pd import numpy as np import sklearn.metrics as skm import scipy.spatial.distance as sc #%% Leer datos data = pd.read_excel('../data/Test de pelculas(1-16).xlsx', encoding='latin_1') #%% Seleccionar datos (a mi estilo) pel = pd.DataFrame() for i in range((len(data.T)-5)//3): pel = pel.append(data.iloc[:,6+i*3]) pel = pel.T print(pel) #%% Seleccionar datos (estilo Riemann) csel = np.arange(6,243,3) cnames = list(data.columns.values[csel]) datan = data[cnames] #%% Promedios movie_prom = datan.mean(axis=0) user_prom = datan.mean(axis=1) #%% Calificaciones a binarios (>= 3) datan = datan.copy() datan[datan<3] = 0 datan[datan>=3] = 1 #%% Calcular distancias de indices de similitud #D1 = sc.pdist(datan,'hamming') # hamming == matching D1 = sc.pdist(datan,'jaccard') D1 = sc.squareform(D1) #D2 = sc.pdist(data_b,'jaccard') # hamming == matching #D2 = sc.squareform(D2) Isim1 = 1-D1 #%% Seleccionar usuario y determinar sus parecidos user = 1 Isim_user = Isim1[user] Isim_user_sort = np.sort(Isim_user) indx_user = np.argsort(Isim_user) #%% Recomendacin de pelculas p1. USER = datan.loc[user] USER_sim = datan.loc[indx_user[-2]] indx_recomend1 = (USER_sim==1)&(USER==0) recomend1 = list(USER.index[indx_recomend1]) #%% Recomendacin peliculas p2. USER = datan.loc[user] USER_sim = np.mean(datan.loc[indx_user[-6:-1]],axis = 0) USER_sim[USER_sim<=.5]=0 USER_sim[USER_sim>.5]=1 indx_recomend2 = (USER_sim==1)&(USER==0) recomend2 = list(USER.index[indx_recomend2])
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 3158, 1367, 7769, 25, 1507, 25, 2718, 13130, 198, 198, 31, 9800, 25, 611, 4869, 1120, 1959, 198, 37811, 198, 198, 11748, 19798, 292, 355, ...
2.180822
730
import logging
[ 11748, 18931 ]
7
2
import numpy import rasterio import gdal print('all modules imported') # path to the folder with the ndvi rasters base_path = "/Users/hk/Downloads/gaga/" # shapefile with forest mask forest_mask = base_path + "waldmaske_wgs84.shp" # initialize the necessary rasters for the ndvi calculation. ndvi_2017 = rasterio.open(base_path + "ndvi_17.tiff", driver="GTiff") ndvi_2018 = rasterio.open(base_path + "ndvi_18.tiff", driver="GTiff") # print out metadata about the ndvi's print(ndvi_2018.count) # number of raster bands print(ndvi_2017.count) # number of raster bands print(ndvi_2018.height) # column count print(ndvi_2018.dtypes) # data type of the raster e.g. ('float64',) print(ndvi_2018.crs) # projection of the raster e.g. EPSG:32632 print("calculate ndvi difference") # this is will give us an array of values, not an actual raster image. ndvi_diff_array = numpy.subtract(ndvi_2018.read(1), ndvi_2017.read(1)) print("reclassify") # reclassify ndvi_diff_reclass_array = numpy.where( ndvi_diff_array <= -0.05, 1, 9999.0 ) # create a new (empty) raster for the "original" diff ndvi_diff_image = rasterio.open(base_path + "ndvi_diff.tif", "w", driver="Gtiff", width=ndvi_2018.width, height=ndvi_2018.height, count=1, crs=ndvi_2018.crs, transform=ndvi_2018.transform, dtype='float64') # create a new (empty) raster for the reclassified diff ndvi_diff_reclass_image = rasterio.open(base_path + "ndvi_reclass_diff.tif", "w", driver="Gtiff", width=ndvi_2018.width, height=ndvi_2018.height, count=1, crs=ndvi_2018.crs, transform=ndvi_2018.transform, dtype='float64') # write the ndvi's to raster ndvi_diff_image.write(ndvi_diff_array.astype("float64"), 1) ndvi_diff_reclass_image.write(ndvi_diff_reclass_array.astype("float64"), 1) ndvi_diff_image.close() ndvi_diff_reclass_image.close() # extract forest areas # Make sure to add correct Nodata and Alpha values. They have to match the reclassified values. warp_options = gdal.WarpOptions(cutlineDSName=forest_mask, cropToCutline=True, dstNodata=9999, dstAlpha=9999) gdal.Warp(base_path + "change_masked.tif", base_path + "ndvi_reclass_diff.tif", options=warp_options) print("finished")
[ 11748, 299, 32152, 198, 11748, 374, 1603, 952, 198, 11748, 308, 31748, 198, 4798, 10786, 439, 13103, 17392, 11537, 198, 198, 2, 3108, 284, 262, 9483, 351, 262, 299, 67, 8903, 374, 7060, 198, 8692, 62, 6978, 796, 12813, 14490, 14, 71, ...
2.427061
946
def product_from_branch(branch): """ Return a product name from this branch name. :param branch: eg. "ceph-3.0-rhel-7" :returns: eg. "ceph" """ if branch.startswith('private-'): # Let's just return the thing after "private-" and hope there's a # product string match somewhere in there. return branch[8:] # probably not gonna work for "stream" branches :( parts = branch.split('-', 1) return parts[0]
[ 4299, 1720, 62, 6738, 62, 1671, 3702, 7, 1671, 3702, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 8229, 257, 1720, 1438, 422, 428, 8478, 1438, 13, 628, 220, 220, 220, 1058, 17143, 8478, 25, 29206, 13, 366, 344, 746, 12, 18...
2.610169
177
import requests url = 'https://notify-api.line.me/api/notify'#LINE NotifyAPIURL token = '2RNdAKwlaj69HK0KlEdMX1y575gDWNKrPpggFcLnh82' # ms = ""# while True: now=dt.('cpu_temps') dt = getCpuTempFromFile(data_file) #CPU print(cpu_temps) if print(cpu_temp) == "print >= 80":#CPU80 line(postdate=message, date=postdate, palams=postdate)#line break time.sleep(1)
[ 11748, 7007, 198, 198, 6371, 796, 705, 5450, 1378, 1662, 1958, 12, 15042, 13, 1370, 13, 1326, 14, 15042, 14, 1662, 1958, 6, 2, 24027, 1892, 1958, 17614, 21886, 198, 30001, 796, 705, 17, 42336, 67, 10206, 40989, 1228, 3388, 38730, 15, ...
2.106383
188
"""titiler.application""" __version__ = "0.6.0"
[ 37811, 83, 270, 5329, 13, 31438, 37811, 198, 198, 834, 9641, 834, 796, 366, 15, 13, 21, 13, 15, 1, 198 ]
2.333333
21
#!/usr/bin/env python import os from collections import defaultdict hosts = {'mill001', 'mill004', 'mill005'} user = 'a7109534' file_location = '/work/a7109534/' #file_location = '/home/ryan/workspace/JGroups' #file_location = '/home/pg/p11/a7109534/' file_wildcard = '*' extension = ".csv" get_file = file_location + file_wildcard + extension destination = '.' number_of_rounds = 18 os.system("rm *" + extension) for hostname in hosts: cmd = "scp " + user + "@" + hostname + ":" + get_file + " " + destination print cmd os.system(cmd)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 28686, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 4774, 82, 796, 1391, 6, 17805, 8298, 3256, 705, 17805, 22914, 3256, 705, 17805, 22544, 6, 92, 198, 7220, 796, 705, 64, 4314...
2.631579
209
"""Data providers.""" import os try: # try-except statement needed because # pip module is not available in google app engine import pip except ImportError: pip = None import yaml import six from .artifact_store import get_artifact_store from .http_provider import HTTPProvider from .firebase_provider import FirebaseProvider from .s3_provider import S3Provider from .gs_provider import GSProvider from . import logs
[ 37811, 6601, 9549, 526, 15931, 198, 11748, 28686, 198, 198, 28311, 25, 198, 220, 220, 220, 1303, 1949, 12, 16341, 2643, 2622, 780, 198, 220, 220, 220, 1303, 7347, 8265, 318, 407, 1695, 287, 23645, 598, 3113, 198, 220, 220, 220, 1330, ...
3.403101
129
import numpy as np import pandas as pd from server.model_inference.config import labels from server.model_inference.core_model import get_model_prediction from server.util.prediction_to_json import pandas_to_json
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 4382, 13, 19849, 62, 259, 4288, 13, 11250, 1330, 14722, 198, 6738, 4382, 13, 19849, 62, 259, 4288, 13, 7295, 62, 19849, 1330, 651, 62, 19849, 62, 2...
3.359375
64
import asyncio import json import socket import time from botsdk.util.BotPlugin import BotPlugin from botsdk.util.Error import printTraceBack
[ 11748, 30351, 952, 198, 11748, 33918, 198, 11748, 17802, 198, 11748, 640, 198, 198, 6738, 29641, 34388, 13, 22602, 13, 20630, 37233, 1330, 18579, 37233, 198, 6738, 29641, 34388, 13, 22602, 13, 12331, 1330, 3601, 2898, 558, 7282, 628, 628,...
3.585366
41
from schedule.scheduler4_0 import schedule from schedule.ra_sched import Schedule, RA from unittest.mock import MagicMock, patch from datetime import date import unittest import random if __name__ == "__main__": unittest.main()
[ 6738, 7269, 13, 1416, 704, 18173, 19, 62, 15, 1330, 7269, 198, 6738, 7269, 13, 430, 62, 1416, 704, 1330, 19281, 11, 17926, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 6139, 44, 735, 11, 8529, 198, 6738, 4818, 8079, 1330, 3128, 19...
3.133333
75
""" Main Module """ import logging from ulauncher.api.client.Extension import Extension from ulauncher.api.client.EventListener import EventListener from ulauncher.api.shared.event import KeywordQueryEvent from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem from ulauncher.api.shared.action.RenderResultListAction import RenderResultListAction from ulauncher.api.shared.action.DoNothingAction import DoNothingAction from ulauncher.api.shared.action.HideWindowAction import HideWindowAction from ulauncher.api.shared.action.OpenUrlAction import OpenUrlAction from dockerhub.client import Client logger = logging.getLogger(__name__) if __name__ == '__main__': DockerHubExtension().run()
[ 37811, 8774, 19937, 37227, 198, 198, 11748, 18931, 198, 198, 6738, 14856, 1942, 2044, 13, 15042, 13, 16366, 13, 11627, 3004, 1330, 27995, 198, 6738, 14856, 1942, 2044, 13, 15042, 13, 16366, 13, 9237, 33252, 1330, 8558, 33252, 198, 6738, ...
3.597015
201
# -*- coding: utf-8 -*- from geeklist.api import BaseGeeklistApi, GeekListOauthApi, GeekListUserApi from access import consumer_info #please access.py which contains consumer_info = { 'key': YOUR_KEY, 'secret': secret} BaseGeeklistApi.BASE_URL ='http://sandbox-api.geekli.st/v1' oauth_api = GeekListOauthApi(consumer_info=consumer_info) request_token = oauth_api.request_token(type='oob') import webbrowser webbrowser.open('http://sandbox.geekli.st/oauth/authorize?oauth_token=%s' % request_token['oauth_token']) #read verifier verifier = raw_input('Please enter verifier code>') oauth_access_token = oauth_api.access_token(request_token=request_token, verifier=verifier) access_token = { 'key':oauth_access_token['oauth_token'], 'secret':oauth_access_token['oauth_token_secret'] } user_api = GeekListUserApi(consumer_info, access_token) print user_api.user_info() user_api.create_card(headline='First card created with the python wrapper API')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 27314, 4868, 13, 15042, 1330, 7308, 10082, 988, 4868, 32, 14415, 11, 33639, 8053, 46, 18439, 32, 14415, 11, 33639, 8053, 12982, 32, 14415, 198, 198, 6738, 1895, 13...
2.798246
342
""" Template for Characters Copy this module up one level and name it as you like, then use it as a template to create your own Character class. To make new logins default to creating characters of your new type, change settings.BASE_CHARACTER_TYPECLASS to point to your new class, e.g. settings.BASE_CHARACTER_TYPECLASS = "game.gamesrc.objects.mychar.MyChar" Note that objects already created in the database will not notice this change, you have to convert them manually e.g. with the @typeclass command. """ from ev import Character as DefaultCharacter from ev import Script import random
[ 37811, 198, 198, 30800, 329, 26813, 198, 198, 29881, 428, 8265, 510, 530, 1241, 290, 1438, 340, 355, 345, 588, 11, 788, 198, 1904, 340, 355, 257, 11055, 284, 2251, 534, 898, 15684, 1398, 13, 198, 198, 2514, 787, 649, 2604, 1040, 427...
3.640244
164
""" ( ) : One 1 Two 2 Three 3 Four 4 , . . . """ if __name__ == "__main__": # main() short_variant()
[ 37811, 198, 357, 1267, 220, 220, 220, 220, 1058, 198, 3198, 220, 352, 198, 7571, 220, 362, 198, 12510, 220, 513, 198, 15137, 220, 604, 198, 220, 837, 220, 220, 220, 220, 220, 220, 220, 764, 198, 220, 220, 220, 220, 220, 220, 764, ...
1.715909
88
from w_i_stage import IStage from direct.interval.IntervalGlobal import Sequence, Func, Wait
[ 6738, 266, 62, 72, 62, 14247, 1330, 314, 29391, 198, 6738, 1277, 13, 3849, 2100, 13, 9492, 2100, 22289, 1330, 45835, 11, 11138, 66, 11, 16314, 628 ]
3.481481
27
# -*- coding: utf-8 -*- """ """ from . import convertor from . import model_loader from . import storage from . import parallel from . import logging
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 198, 37811, 198, 6738, 764, 1330, 10385, 273, 198, 6738, 764, 1330, 2746, 62, 29356, 198, 6738, 764, 1330, 6143, 198, 6738, 764, 1330, 10730, 198, 6738, 764,...
3.212766
47
"""NeuronUnit model class for reduced neuron models""" import numpy as np from neo.core import AnalogSignal import quantities as pq import neuronunit.capabilities as cap import neuronunit.models as mod import neuronunit.capabilities.spike_functions as sf from neuronunit.models import backends from generic_network import net_sim_runner, get_dummy_synapses
[ 37811, 8199, 44372, 26453, 2746, 1398, 329, 5322, 43164, 4981, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 19102, 13, 7295, 1330, 50088, 11712, 282, 198, 11748, 17794, 355, 279, 80, 198, 198, 11748, 43164, 20850, 13, 11128,...
3.75
96
#!/usr/bin/env python3 import argparse import csv import datetime import json import logging import os import sys import warnings from collections import defaultdict from copy import copy from dataclasses import dataclass from itertools import islice, cycle, chain from random import randint, shuffle, choice, sample from textwrap import shorten, wrap from typing import List, Any, Dict, Tuple from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen import canvas script_name = os.path.basename(sys.argv[0]) description = """ Generate characters for the Delta Green pen-and-paper roleplaying game from Arc Dream Publishing. """ __version__ = "1.4" logger = logging.getLogger(script_name) TEXT_COLOR = (0, 0.1, 0.5) DEFAULT_FONT = "Special Elite" MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC") SUGGESTED_BONUS_CHANCE = 75 def generate_label(profession): return ", ".join( e for e in [ profession.get("label", ""), profession.get("employer", ""), profession.get("division", ""), ] if e ) def get_options(): """Get options and arguments from argv string.""" parser = argparse.ArgumentParser(description=description) parser.add_argument( "-v", "--verbosity", action="count", default=0, help="specify up to three times to increase verbosity, " "i.e. -v to see warnings, -vv for information messages, or -vvv for debug messages.", ) parser.add_argument("-V", "--version", action="version", version=__version__) parser.add_argument( "-o", "--output", action="store", default=f"DeltaGreenPregen-{datetime.datetime.now() :%Y-%m-%d-%H-%M}.pdf", help="Output PDF file. Defaults to %(default)s.", ) parser.add_argument( "-t", "--type", action="store", help=f"Select single profession to generate." ) parser.add_argument("-l", "--label", action="store", help="Override profession label.") parser.add_argument( "-c", "--count", type=int, action="store", help="Generate this many characters of each profession.", ) parser.add_argument( "-e", "--employer", action="store", help="Set employer for all generated characters." ) parser.add_argument( "-u", "--unequipped", action="store_false", dest="equip", help="Don't generate equipment.", default=True, ) data = parser.add_argument_group(title="Data", description="Data file locations") data.add_argument( "--professions", action="store", default="data/professions.json", help="Data file for professions - defaults to %(default)s", ) return parser.parse_args() def init_logger(verbosity, stream=sys.stdout): """Initialize logger and warnings according to verbosity argument. Verbosity levels of 0-3 supported.""" is_not_debug = verbosity <= 2 level = ( [logging.ERROR, logging.WARNING, logging.INFO][verbosity] if is_not_debug else logging.DEBUG ) log_format = ( "%(message)s" if is_not_debug else "%(asctime)s %(levelname)-8s %(name)s %(module)s.py:%(funcName)s():%(lineno)d %(message)s" ) logging.basicConfig(level=level, format=log_format, stream=stream) if is_not_debug: warnings.filterwarnings("ignore") if __name__ == "__main__": sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 1822, 29572, 198, 11748, 269, 21370, 198, 11748, 4818, 8079, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 14601, 198, 6738, 17268, 133...
2.513037
1,419
from typing import Union from unittest.mock import Mock, create_autospec import pytest from pytest import MonkeyPatch from philipstv import PhilipsTVAPI, PhilipsTVPairer, PhilipsTVRemote, PhilipsTVRemoteError from philipstv.model import ( AllChannels, AmbilightColor, AmbilightColors, AmbilightLayer, AmbilightPower, AmbilightPowerValue, AmbilightTopology, Application, ApplicationComponent, ApplicationIntent, Applications, Channel, ChannelID, ChannelList, ChannelShort, CurrentChannel, CurrentVolume, DeviceInfo, InputKey, InputKeyValue, PowerState, PowerStateValue, SetChannel, Volume, ) CHANNELS = AllChannels( version=1, id="all", list_type="MixedSources", medium="mixed", operator="OPER", install_country="Poland", channel=[ Channel( ccid=35, preset="1", name="Polsat HD", onid=1537, tsid=24, sid=2403, service_type="audio_video", type="DVB_C", logo_version=33, ), Channel( ccid=40, preset="3", name="TVN HD", onid=666, tsid=24, sid=2403, service_type="audio_video", type="DVB_C", logo_version=33, ), ], ) APPLICATION_SPOTIFY = Application( intent=ApplicationIntent( component=ApplicationComponent( package_name="com.spotify.tv.android", class_name="com.spotify.tv.android.SpotifyTVActivity", ), action="android.intent.action.MAIN", ), label="Spotify", order=0, id="com.spotify.tv.android.SpotifyTVActivity-com.spotify.tv.android", type="app", ) APPLICATION_NETFLIX = Application( intent=ApplicationIntent( component=ApplicationComponent( package_name="com.netflix.ninja", class_name="com.netflix.ninja.MainActivity", ), action="android.intent.action.MAIN", ), label="Netflix", order=0, id="com.netflix.ninja.MainActivity-com.netflix.ninja", type="app", ) APPLICATIONS = Applications( version=0, applications=[APPLICATION_SPOTIFY, APPLICATION_NETFLIX], )
[ 6738, 19720, 1330, 4479, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 11, 2251, 62, 2306, 418, 43106, 198, 198, 11748, 12972, 9288, 198, 6738, 12972, 9288, 1330, 26997, 33952, 198, 198, 6738, 5206, 541, 301, 85, 1330, 46905, 68...
2.146568
1,078
"""Implementation of benchmarks. Copyright (c) 2019 Red Hat Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import sys from random import randint from fastlog import log from time import time from queue import Queue from threading import Thread from report_generator import generate_csv_report from component_generator import ComponentGenerator from setup import parse_tags # directory containing test results RESULT_DIRECTORY = "test_results" def check_number_of_results(queue_size, component_analysis_count, stack_analysis_count): """Check if we really got the same number of results as expected. When the server respond by any HTTP error code (4xx, 5xx), the results are NOT stored in the queue. This means that number of results stored in the queue might be less than number of threads set up by user via CLI parameters in certain situations. This function check this situation. """ log.info("queue size: {size}".format(size=queue_size)) expected = component_analysis_count + 2 * stack_analysis_count if queue_size != expected: log.warning("Warning: {expected} results expected, but only {got} is presented".format( expected=expected, got=queue_size)) log.warning("This means that {n} analysis ends with error or exception".format( n=expected - queue_size)) def prepare_component_generators(python_payload, maven_payload, npm_payload): """Prepare all required component generators for selected payload types.""" component_generator = ComponentGenerator() g_python = component_generator.generator_for_ecosystem("pypi") g_maven = component_generator.generator_for_ecosystem("maven") g_npm = component_generator.generator_for_ecosystem("npm") generators = [] if python_payload: generators.append(g_python) if maven_payload: generators.append(g_maven) if npm_payload: generators.append(g_npm) return generators def initialize_generators(generators): """Initialize the generators randomly so we don't start from the 1st item.""" for i in range(randint(10, 100)): for g in generators: next(g) def component_analysis_benchmark(queue, threads, component_analysis, thread_count, python_payload, maven_payload, npm_payload): """Component analysis benchmark.""" generators = prepare_component_generators(python_payload, maven_payload, npm_payload) initialize_generators(generators) for t in range(thread_count): g = generators[randint(0, len(generators) - 1)] ecosystem, component, version = next(g) with log.indent(): log.info("Component analysis for E/P/V {} {} {}".format(ecosystem, component, version)) t = Thread(target=component_analysis.start, args=(t, ecosystem, component, version, queue)) t.start() threads.append(t) # skip some items for i in range(randint(5, 25)): next(g) def stack_analysis_benchmark(queue, threads, stack_analysis, thread_count, python_payload, maven_payload, npm_payload): """Stack analysis benchmark.""" # TODO: read automagically from the filelist manifests = ( ("maven", "clojure_1_6_0.xml"), ("maven", "clojure_1_7_0.xml"), ("maven", "clojure_1_8_0.xml"), ("maven", "clojure_junit.xml"), ("pypi", "click_6_star.txt"), ("pypi", "array_split.txt"), ("pypi", "fastlog_urllib_requests.txt"), ("pypi", "requests_latest.txt"), ("pypi", "numpy_latest.txt"), ("pypi", "flask_latest.txt"), ("pypi", "scipy_latest.txt"), ("pypi", "pygame_latest.txt"), ("pypi", "pyglet_latest.txt"), ("pypi", "dash_latest.txt"), ("pypi", "pudb_latest.txt"), ("pypi", "pytest_latest.txt"), ("pypi", "numpy_1_11_0.txt"), ("pypi", "numpy_1_12_0.txt"), ("pypi", "numpy_1_16_2.txt"), ("pypi", "numpy_1_16_3.txt"), ("pypi", "numpy_scipy.txt"), ("pypi", "pytest_2_0_0.txt"), ("pypi", "pytest_2_0_1.txt"), ("pypi", "pytest_3_2_2.txt"), ("pypi", "requests_2_20_0.txt"), ("pypi", "requests_2_20_1.txt"), ("pypi", "requests_2_21_0.txt"), ("pypi", "scipy_1_1_0.txt"), ("pypi", "scipy_1_2_0.txt"), ("pypi", "scipy_1_2_1.txt"), ("npm", "array.json"), ("npm", "dependency_array.json"), ("npm", "dependency_emitter_component.json"), ("npm", "dependency_jquery.json"), ("npm", "dependency_jquery_react.json"), ("npm", "dependency_lodash.json"), ("npm", "dependency_lodash_react_jquery.json"), ("npm", "dependency_react.json"), ("npm", "dependency_to_function.json"), ("npm", "dependency_to_function_vue_array.json"), ("npm", "dependency_underscore.json"), ("npm", "dependency_underscore_react_jquery.json"), ("npm", "dependency_vue.json"), ("npm", "dependency_vue_to_function.json"), ("npm", "empty.json"), ("npm", "jquery.json"), ("npm", "lodash.json"), ("npm", "mocha.json"), ("npm", "no_requirements.json"), ("npm", "underscore.json"), ("npm", "wisp.json"), ) for t in range(thread_count): manifest_idx = randint(0, len(manifests) - 1) manifest = manifests[manifest_idx] with log.indent(): log.info("Stack analysis") ecosystem = manifest[0] manifest_file = manifest[1] t = Thread(target=stack_analysis.start, args=(t, ecosystem, manifest_file, queue)) t.start() threads.append(t) def wait_for_all_threads(threads): """Wait for all threads to finish.""" log.info("Waiting for all threads to finish") for t in threads: t.join() log.success("Done") def run_test(cfg, test, i, component_analysis, stack_analysis): """Run one selected test.""" test_name = test["Name"] log.info("Starting test #{n} with name '{desc}'".format(n=i, desc=test_name)) with log.indent(): start = time() threads = [] queue = Queue() with log.indent(): component_analysis_count = int(test["Component analysis"]) stack_analysis_count = int(test["Stack analysis"]) python_payload = test["Python payload"] in ("Yes", "yes") maven_payload = test["Maven payload"] in ("Yes", "yes") npm_payload = test["NPM payload"] in ("Yes", "yes") component_analysis_benchmark(queue, threads, component_analysis, component_analysis_count, python_payload, maven_payload, npm_payload) stack_analysis_benchmark(queue, threads, stack_analysis, stack_analysis_count, python_payload, maven_payload, npm_payload) wait_for_all_threads(threads) queue_size = queue.qsize() check_number_of_results(queue_size, component_analysis_count, stack_analysis_count) end = time() # TODO: use better approach to join paths filename = RESULT_DIRECTORY + "/" + test_name.replace(" ", "_") + ".csv" log.info("Generating test report into file '{filename}'".format(filename=filename)) generate_csv_report(queue, test, start, end, end - start, filename) def run_all_loaded_tests(cfg, tests, component_analysis, stack_analysis): """Run all tests read from CSV file.""" i = 1 for test in tests: run_test(cfg, test, i, component_analysis, stack_analysis) i += 1 def run_tests_with_tags(cfg, tests, tags, component_analysis, stack_analysis): """Run tests read from CSV file that are marged by any of tags provided in tags parameter.""" i = 1 for test in tests: test_tags = parse_tags(test["Tags"]) test_name = test["Name"] if tags <= test_tags: run_test(cfg, test, i, component_analysis, stack_analysis) i += 1 else: log.info("Skipping test #{n} with name '{desc}'".format(n=i, desc=test_name)) def no_tests(tests): """Predicate for number of tests.""" return not tests or len(tests) == 0 def start_tests(cfg, tests, tags, component_analysis, stack_analysis): """Start all tests using the already loaded configuration.""" log.info("Run tests") with log.indent(): if no_tests(tests): log.error("No tests loaded!") sys.exit(-1) if len(tests) == 1: log.success("Loaded 1 test") else: log.success("Loaded {n} tests".format(n=len(tests))) if not tags: run_all_loaded_tests(cfg, tests, component_analysis, stack_analysis) else: run_tests_with_tags(cfg, tests, tags, component_analysis, stack_analysis)
[ 37811, 3546, 32851, 286, 31747, 13, 198, 198, 15269, 357, 66, 8, 13130, 2297, 10983, 3457, 13, 198, 198, 1212, 1430, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096, 198, 270, 739, 262, 2846, 286, 262, 22961, 36...
2.36574
4,063
# Core Django imports from django.contrib import admin # Imports from my apps from bus_system.apps.bus.models import BusModel admin.site.register(BusModel)
[ 2, 7231, 37770, 220, 17944, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 2, 1846, 3742, 422, 616, 6725, 198, 6738, 1323, 62, 10057, 13, 18211, 13, 10885, 13, 27530, 1330, 5869, 17633, 198, 198, 28482, 13, 15654, 13, ...
3.3125
48
'''Various astro calcs mainly based on Meuss. ''' import numpy as np import math import time from datetime import datetime
[ 7061, 6, 40009, 6468, 305, 2386, 6359, 8384, 1912, 319, 2185, 1046, 13, 220, 198, 7061, 6, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 640, 198, 6738, 4818, 8079, 1330, 4818, 8079, 628, 198 ]
3.25641
39
import win32com.client import time if __name__ == '__main__': cc = CalcClient() cc.calc('ADD', 123, 567) cc.calc('SUB', 123, 567) cc.calc('MUL', 123, 567) cc.calc('DIV', 123, 567)
[ 11748, 1592, 2624, 785, 13, 16366, 201, 198, 11748, 640, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 36624, 796, 2199, 66, 11792, 3419, 201, 198, 220, 220, 220, 36...
1.962617
107