text
stringlengths
1
927k
#!/usr/bin/env python # Copyright (c) 2019 Brad Atkinson <brad.scripting@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ri...
""" K-prototypes clustering for mixed categorical and numerical data """ # pylint: disable=super-on-old-class,unused-argument,attribute-defined-outside-init from collections import defaultdict import numpy as np from scipy import sparse from sklearn.externals.joblib import Parallel, delayed from sklearn.utils import...
import numpy as np from collections import Counter class Vocab(object): def __init__(self, config): self.config = config self.load_vocab() def load_vocab(self): special_tokens = [self.config.unk, self.config.pad, self.config.end] self.tok_to_id = load_tok_to_id(self.config.p...
""" Copyright (c) 2015-2020 Raj Patel(raj454raj@gmail.com), StopStalk 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 ...
""" Ory APIs Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501 The version of the OpenAPI document: v0.0.1-alpha.3 Contact: support@ory.sh Generated by: http...
import numpy as np import matplotlib.pyplot as plt from magpylib.source.magnet import Box,Cylinder from magpylib import Collection, displaySystem, Sensor from scipy.optimize import fsolve, least_squares import matplotlib.animation as manimation import random import MDAnalysis import MDAnalysis.visualization.streamlines...
# coding: utf-8 from sqlalchemy.testing import eq_, is_ from sqlalchemy import exc from sqlalchemy.sql import table from sqlalchemy.testing import fixtures, AssertsCompiledSQL from sqlalchemy import testing from sqlalchemy import Integer, Text, LargeBinary, Unicode, UniqueConstraint,\ Index, MetaData, select, ins...
import konfi @konfi.template() class UserInfo: name: str country: str @konfi.template() class AppConfig: name: str = "konfi" user: UserInfo if __name__ == "__main__": konfi.set_sources( konfi.YAML("config.yml"), konfi.Env(prefix="app_"), ) # the return type is usually ...
''' @Author: ZM @Date and Time: 2019/10/8 6:28 @File: Dataset.py ''' class Dataset: def __init__(self, x, y=None, transform=None, y_transform=None): self.x = x self.y = y self.transform = transform self.y_transform = y_transform def __len__(self): return...
import os.path import time import numpy as np from DataStructure.PatientPhenotype import PatientPhenotype from DataStructure.Snp import Snp class Output: def __init__(self,path,numberOfChromosomes): self.__path = path self.__numberOfChromosomes = numberOfChromosomes def w...
from torch import nn from torch.optim import Adam from mask_generators import ImageMaskGenerator, DropoutMaskGenerator from nn_utils import ResBlock, MemoryLayer, SkipConnection from prob_utils import normal_parse_params, GaussianLoss # sampler from the model generative distribution # here we return mean of the Gaus...
# Copyright (c) 2017, Intel Research and Development Ireland Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from typing import Optional from fairseq.modules import ( LayerNorm, MultiheadAttention, ESPNETMultiHeadedAttention,...
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'includes': [ '../build/win_precompile.gypi', 'base.gypi', ], 'targets': [ { 'tar...
from collections import deque from dataclasses import dataclass, field from typing import Iterator, Tuple from algorithm.graph.node import Graph, Node @dataclass class BFS: graph: Graph = field(default_factory=Graph) visited: Tuple[int, ...] = field(default_factory=tuple) queue: deque = field(default_fac...
import json import traceback from collections import defaultdict, namedtuple from copy import deepcopy from functools import partial from time import sleep from couchdbkit import ResourceNotFound, BulkSaveError, Document from django.conf import settings from django.http import Http404 from jsonobject.exceptions import...
""" Test cast_class in tagulous.models.tagged """ import inspect import pickle from pytest import fixture from tagulous.models.cast import cast_instance, get_cast_class from tests.tagulous_tests_app.cast import NewBase, OldBase, Target EXPECTED_CAST_NAME = "TagulousCastTaggedTarget" @fixture def Cast(): # Cr...
from django.urls import include, path from django.contrib import admin from django.views.generic import RedirectView from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('form/', include('form.urls...
from models.google_cloud import GoogleLanguageTranslationModel, HuggingFaceLanguageTranslationModel from models.en2spa_transformer import En2SpaSeq2SeqTransformer def test_google_translation(): model = GoogleLanguageTranslationModel() assert model.predict(text='Hello', target='de') == 'Hallo' def test_hugging...
#!/usr/local/homebrew/bin/python import usb.core import usb.util import sys import getopt import time # find our device dev = usb.core.find(idVendor=0x04d8, idProduct=0xf372) # was it found? if dev is None: raise ValueError('Device not found') # Linux kernel sets up a device driver for USB device, which you hav...
def btSync(display, utime, ujson, bluetooth, startNewThread, playBuzzer, loadJSON, saveJSON, showControls, update, clear): run = True toDo = loadJSON("to-do.json") toDoList = list(toDo.keys()) toDoDone = False shoppingItems = loadJSON("boodschappen.json") shoppingItemsList = list(shoppingItems....
""" banderplug.py Author: Jacob Ruzi This script is intended to be run with an ini formatted configuration file that defines a 'Choose Your Own Adventure' game. See example_game.ini and README.md for guidelines on how to format your game. See BanderPlug.log in the current directory for error details. """ import config...
# Copyright 2019 NeuroData (http://neurodata.io) # # 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 ag...
#!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_server.settings.local') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import ...
# Copyright 2021 Jeremy Schulman # # 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 ...
from typing import List, Callable, Dict, Tuple, Union import math import matplotlib.pyplot as plt class ApproxMultiplicationTable: """ Multiplication done using a lookup table instead of a math unit """ table_entries: Dict[Tuple[int, int], int] num_significant_bits: int def __init__(self, nu...
# -*- coding: utf-8 -*- """ rst2txt.__main__ ~~~~~~~~~~~~~~~~ A minimal front end to the Docutils Publisher, producing plain text. :copyright: Copyright 2018, Stephen Finucane <stephen@that.guru>. :license: BSD, see LICENSE for details. """ import locale locale.setlocale(locale.LC_ALL, '') # noqa...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 12, transform = "Difference", sigma = 0.0, exog_count = 20, ar_order = 12);
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Johns Hopkins University (Shinji Watanabe) # Northwestern Polytechnical University (Pengcheng Guo) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ConvolutionModule definition.""" from torch import nn class ConvolutionMod...
""" Examples for Data Bootcamp course (data input and graphics) **Warning** Web data access will change in the near future, when Pandas spins off the web access tools into a new package. http://pandas.pydata.org/pandas-docs/stable/remote_data.html Repository of materials (including this file): * https://github.com/NY...
# -*- coding: utf-8 -*- import os import sys root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, root_dir) import unittest class TestMain(unittest.TestCase): def test_main(self): # NOTE the blank index of result is a minor different to the requirement. # If...
# coding: utf-8 """ Waitlisted API Waitlisted API OpenAPI spec version: 2.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obt...
from fastapi import FastAPI from starlette.responses import PlainTextResponse from starlette.staticfiles import StaticFiles from typing import Dict, Optional as Opt from pydantic import BaseModel from starlette.requests import Request """ * Have programme create the srimdata and pickle/sqlite it * create api points wi...
#hardware platform:FireBeetle-ESP32 import SD import os sd = SD.sdcard() #create sdcard object os.mount(sd,"/sd") #mount sdcard with specified dir print(os.listdir("/sd")) #print the filename in '/sd' dir f=open("sd/HelloWord.txt","w") #open file 'HelloWord.txt' in ...
'''台本の行の種類の定義 ''' from enum import Enum class PscClass(Enum): '''台本の行の種類 ''' TITLE = 0 # 題名 AUTHOR = 1 # 著者名 CHARSHEADLINE = 2 # 登場人物見出し CHARACTER = 3 # 登場人物 H1 = 4 # 柱 (レベル1) H2 = 5 ...
from collections import defaultdict import re """ Parser of the gRPC message dump for human reading as produced by scalapb and printed by the Scala CasperLabs client. """ class MaybeList(list): def __getattr__(self, name): if len(self) != 1: raise Exception( f"Attempt to acces...
# Copyright 2020-2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
"""Integrate accuracy report with auto annotation Revision ID: 5181f24c23aa Revises: 810f7e51911d Create Date: 2021-07-22 19:38:41.741133 """ """ OpenVINO DL Workbench Migration: Integrate accuracy report with auto annotation Copyright (c) 2021 Intel Corporation Licensed under the Apache License, Version 2.0 (...
class Position: def __init__(self, line, column): self._line = line self._column = column @property def line(self): return self._line @line.setter def line(self, line): self._line = line @property def column(self): return self._column @column.s...
"""Demo of Zinnia with MarkItUp"""
import re from sys import getsizeof import requests # RE_XLS_FILE = re.compile(r'<a.+</a>') # RE_XLS_FILE = re.compile(r'href=".+"') # RE_XLS_FILE = re.compile(r'href="[^"]+\.xls"') RE_XLS_FILE = re.compile(r'href="([^"]+\.xls)"') request_url = 'https://kpk.kss45.ru/%D1%83%D1%87%D0%B5%D0%B1%D0%BD%D0%B0%D1%8F-%D1%80%...
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter(name='hoursmins') def hoursmins(value): if value == None or value == "": return "" s = int(value) * 60 hours, remainder = divmod(s, 3600) minutes, seconds = di...
from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request from product_spiders.items import ProductLoader, Product import re class refithomeSpider(BaseSpider): name = "refitmyhome.com" allowed_domains = ["refitmyhome.com"] start_urls = ['http://re...
import unittest import os import sys from fortranformat._input import input as _input from fortranformat._lexer import lexer as _lexer from fortranformat._parser import parser as _parser from fortranformat._exceptions import InvalidFormat import fortranformat.config as config class HEditDescriptorTests(unittest.TestC...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
""" Filename globbing utility. Mostly a copy of `glob` from Python 3.5. Changes include: * `yield from` and PEP3102 `*` removed. * Hidden files are not ignored. """ import os import re import fnmatch __all__ = ["glob", "iglob", "escape"] def glob(pathname, recursive=False): """Return a list of paths matching...
""" Implemenation of uncertainty-aware option selection """ from abc import ABC, abstractmethod from typing import Tuple import torch from torch import BoolTensor, LongTensor, Tensor from torch.distributions import Categorical from rainy.net.policy import BernoulliPolicy def _debug_minmax(name: str, t: Tensor) -...
from flask import request from injector import inject from controllers.common.models.CommonModels import CommonModels from controllers.test.models.TestModels import TestModels from infrastructor.IocManager import IocManager from infrastructor.api.ResourceBase import ResourceBase @TestModels.ns.route('/path/<int:value...
from typing import Optional from pyspark.sql import DataFrame, SparkSession from pyspark.sql.functions import lit, col, expr, unhex from pyspark.sql.types import StructType from spark3.ethereum.condition import Conditions from spark3.ethereum.contract import Contract from spark3.providers import IContractABIProvider,...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.9.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re ...
import numpy as np import matplotlib.pyplot as plt import random import sys class KBanditProblem: def __init__(self, k, stationary=True): self.k = k self.stationary = stationary self.values = np.random.normal(loc=0.0, scale=1, size=k) self.optimal = self.values.argmax() # this ...
r"""File-like objects that read from or write to a string buffer. This implements (nearly) all stdio methods. f = StringIO() # ready for writing f = StringIO(buf) # ready for reading f.close() # explicitly release resources held flag = f.isatty() # always false pos = f.tell() # get current pos...
# Copyright (c) 2019 Graphcore Ltd. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
"""Tests Home Assistant color util methods.""" import unittest import homeassistant.util.color as color_util class TestColorUtil(unittest.TestCase): """Test color util methods.""" # pylint: disable=invalid-name def test_color_RGB_to_xy(self): """Test color_RGB_to_xy.""" self.assertEqual((...
#!/usr/bin/env python3 """ Twitter's rate limits allow App Auth contexts to search at 450 requests every 15 minutes, and User Auth contexts at 180 requests per 15 minutes. This script exercises both contexts and counts how tweets it is able to receive. We should see a significant number more tweets coming back for A...
# matplotlib backtest for missing $DISPLAY import matplotlib matplotlib.use('Agg') # scientific computing library import numpy as np # visualization tools import matplotlib.pyplot as plt import seaborn as sns # prettify plots plt.rcParams['figure.figsize'] = [8.0, 6.0] sns.set_palette(sns.color_palette("muted")) sns...
from sqlalchemy import Column, Integer, String, Enum as PgEnum, Float from enum import Enum from sqlalchemy.orm import relationship from api.utils.db_init import Base class Influence(Enum): bad = "bad" neutral = "neutral" good = "good" class Nutrition(Base): __tablename__ = 'nutrition' id = Co...
from pymongo import MongoClient import random from datetime import datetime random.seed(datetime.now()) class VkBot(): def __init__(self, user_id): print("Создан объект бота!") self.user_id = user_id self.send = {'lang': '', 'level': '', 'format': '', 'discus': ''} self.steps = {1...
# -*- coding: utf-8 -*- """ This is a program reading a raster dataset of the heights of a hilly area. It then calculates the maximum slope in all the raster cells using the "D8" algorithm and displays the heights as well as the maximum gradients as images. It finally creates an output txt file containing the calculat...
n = int(input()) en = set(map(int, input().split())) b = int(input()) fr = set(map(int, input().split())) print(len(en.symmetric_difference(fr)))
from .paths import get_backup_path, get_resources_path from .logging import initialize_logging
# Taken from https://raw.githubusercontent.com/tensorflow/text/v2.5.0/tensorflow_text/tools/wordpiece_vocab/wordpiece_tokenizer_learner_lib.py # # coding=utf-8 # Copyright 2021 TF.Text Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the ...
#!C:\Users\Public\todoapp\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip' __requires__ = 'pip==10.0.1' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit...
import pygame from pygame.locals import * from .const import * from . import widget from . import table from . import basic from . import pguglobals _SLIDER_HORIZONTAL = 0 _SLIDER_VERTICAL = 1 class _slider(widget.Widget): _value = None def __init__(self,value,orient,min,max,size,step=1,**params): p...
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..utils import TCat def test_TCat_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(deprecated='1.0.0', nohash=True, ...
# -*- coding: utf-8 -*- # Copyright 2015 www.suishouguan.com # # Licensed under the Private License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless required b...
import inspect class Registry(object): def __init__(self, name): self._name = name self._module_dict = dict() def __repr__(self): format_str = self.__class__.__name__ + '(name={}, items={})'.format( self._name, list(self._module_dict.keys())) return format_str ...
import time, os, sys, logging from subprocess import Popen, PIPE, STDOUT TRACK_PROCESS_SPAWNS = True if (os.getenv('EM_BUILD_VERBOSE') and int(os.getenv('EM_BUILD_VERBOSE')) >= 3) else False def timeout_run(proc, timeout=None, note='unnamed process', full_output=False): start = time.time() if timeout is not None:...
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='open-mmlab://resnet50_v1c', backbone=dict( type='ResNetV1c', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), dilations=(1, 1, 2, 4), strides=...
""" A module containing a class that exports a PySB model to a single Python source file that, when imported, will recreate the same model. This is intended for saving a dynamically generated model so that it can be reused without re-running the dynamic generation process. Note that any macro calls and other program st...
def maximum_consecutive(lst, n): count = 0 result = 0 for i in range(0, n): if (lst[i] == 0): count = 0 else: count+= 1 result = max(result, count) return result lst=[0,0,0,1,1,1,0,0,0,1,1,0,1,1,1,1,0,0,1,1] n=len(lst) print(maxim...
from django.contrib import admin from .models import Order, OrderItem class OrderItemInline(admin.TabularInline): model = OrderItem raw_id_fields = ['product'] class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name', 'email', 'address', 'postal_code', 'city', 'paid', 'created', '...
import os import yaml default_config_yaml = """ # Metadata use_exif_size: yes default_focal_prior: 0.85 # Params for features feature_type: HAHOG # Feature type (AKAZE, SURF, SIFT, HAHOG, ORB) feature_root: 1 # If 1, apply square root mapping to features feature_min_frames...
import lazypredict import sys import numpy as np np.set_printoptions(threshold=sys.maxsize) #Read data file import pandas as pd filepath = "dataset/trial_1200/balanced_dataset2.csv" df = pd.read_csv(filepath) features = df # Labels are the values we want to predict labels = np.array(df['protection_level']) # Remov...
# Copyright (C) 2003 Python Software Foundation import unittest import warnings warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__) import macfs import os import sys import tempfile from test import test_support class TestMacfs(unittest.TestCase): def setUp(self): fp = open(test_su...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Examples for Python-nvd3 is a Python wrapper for NVD3 graph library. NVD3 is an attempt to build re-usable charts and chart components for d3.js without taking away the power that d3.js gives you. Project location : https://github.com/areski/python-nvd3 """ from nvd3 imp...
# MQTT Logger for MicroPython by Thorsten von Eicken (c) 2020 # # Requires mqtt_async for asyncio-based MQTT. #!!!!!!!!!! This code was pulled out of mqrepl and is not finished. It's probably better to #!!!!!!!!!! hook Logging and make sure all errors and exceptions result in calls to Logging. #!!!!!!!!!! This way ver...
import os import copy import collections import warnings import logging import inspect from collections import OrderedDict import configparser import numpy as np import tensorflow as tf class _SettingsContextManager(object): def __init__(self, manager, tmp_settings): self._manager = manager sel...
import os import time import Queue import random import shutil import logging import datetime import tempfile import requests import threading import subprocess import pkg_resources from jenkinsapi.jenkins import Jenkins from jenkinsapi.custom_exceptions import JenkinsAPIException log = logging.getLogger(__name__) ...
from model.group import Group, clean import random def test_delete_some_group(app, db, check_ui): if len(db.get_group_list()) == 0: test_group = Group() test_group.dummy() app.group.create(test_group) old_groups = db.get_group_list() group = random.choice(old_groups) app.group...
#!/usr/bin/env python import os import numpy as np import tensorflow as tf from tensorflow.keras.models import Model from scipy.misc import imread from sklearn.cluster import KMeans from sklearn.decomposition.pca import PCA from tqdm import tqdm from utils import (kernel_classifier_distance_and_std_from_activations,...
import json import logging import requests import urllib3 from enum import Enum from kube_hunter.core.types import Discovery, Kubelet from kube_hunter.core.events import handler from kube_hunter.core.events.types import OpenPortEvent, Vulnerability, Event, Service urllib3.disable_warnings(urllib3.exceptions.Insecure...
import argparse import itertools import logging import os import wikipediaapi from descriptions.descriptions_downloader import check_and_get_checker from descriptions.descriptions_downloader import download_from_wikidata_tags from descriptions.descriptions_downloader import download_from_wikipedia_tags from descripti...
""" Base class for objects that are backed by database documents. | Copyright 2017-2020, Voxel51, Inc. | `voxel51.com <https://voxel51.com/>`_ | """ from copy import deepcopy import eta.core.serial as etas class Document(object): """Base class for objects that are associated with :class:`fiftyone.core.datas...
""" Script for training model on PyTorch. """ import os import time import logging import argparse import random import numpy as np import torch.nn as nn import torch.backends.cudnn as cudnn import torch.utils.data from common.logger_utils import initialize_logging from common.train_log_param_saver import TrainL...
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the COPYING file. """ List the contents of a package """ import zipfile import os import tabulate from qisys import ui import qisys.parsers def configure_parser(parse...
from lxml.html import parse def main(): baseurl = 'http://www.schoolcolleges.com/school.select.php?offset=%s&val=city=%270%27&select=%s' states = [ 'Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'BIHAR', 'Chhattisgarh', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jammu & Kashmir', 'Jharkhand', 'Ka...
import numpy as np import nose import cudamat as cm def setup(): cm.cublas_init() def teardown(): cm.cublas_shutdown() def test_reshape(): m = 256 n = 1 cm1 = np.array(np.random.rand(n, m)*10, dtype=np.float32, order='F') cm2 = np.array(np.random.rand(m, n)*10, dtype=np.float32, order='F') ...
import pickle import tqdm from collections import Counter class TorchVocab(object): """Defines a vocabulary object that will be used to numericalize a field. Attributes: freqs: A collections.Counter object holding the frequencies of tokens in the data used to build the Vocab. stoi:...
from __future__ import absolute_import, division, print_function from cctbx.array_family import flex import os import mmtbx.model import libtbx.load_env from six.moves import cStringIO as StringIO from libtbx.utils import format_cpu_times, null_out from libtbx.test_utils import approx_equal, show_diff import iotbx.pdb ...
import errno from http import client as httplib import logging import multiprocessing import os import signal import socket import string import subprocess import sys import time import unittest from waitress import server from waitress.compat import WIN from waitress.utilities import cleanup_unix_socket dn = os.path...
""" fuzza.transformer ----------------- The transformer module for data transformation. """ from .transformer import init
#!/usr/bin/ctx python # -*- coding: UTF-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import pytest import time import redis from pprint import pprint as pp from sensor.constants import (TEST_CAHNNEL_ID, CONFIG) class PublishMock(object): de...
#!/usr/bin/env python3 """This module provides the PID and the log file name of the running DQM applications (consumers), thus completing the information generated by ExtractAppInfoFromXML. When used as a script the following options are accepted: -f Show all columns -h show headers """ from __future__ import prin...
""" Data Storage System ******************* """ import errno import functools import json from collections import defaultdict, namedtuple import concurrent.futures from datetime import datetime from fnmatch import fnmatchcase import hashlib import os import re import tempfile import time import uuid from io import open...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'phil.zhang' from abc import ABCMeta, abstractmethod, abstractproperty import six from algotrade.event_engine import EventEngineMixin # class BaseBroker(six.with_metaclass(ABCMeta), EventEngineMixin): # def __init__(self): # self.event_engine ...
# -*- encoding:utf-8 -*- from collections import namedtuple from copy import deepcopy import re import textwrap import warnings import jinja2 from numpydoc.numpydoc import update_config from numpydoc.xref import DEFAULT_LINKS from numpydoc.docscrape import ( NumpyDocString, FunctionDoc, ClassDoc, Pars...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
import pytest import irl def test_equality_on_normalize(): url1 = irl.URL.parse("http://ヒ.example.com/abc%af?ヒq%CC#%dE") url2 = irl.URL.parse("HTTP://xn--pdk.eXaMpLe.CoM/abc%AF?%E3%83%92q%cc#%De") assert url1 == url2 @pytest.mark.parametrize( ["url", "addr"], [ ("http://example.com", ("...