code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import logging
logging.basicConfig(level=logging.DEBUG)
import pytest
from hpolib.benchmarks.nas.nasbench_201 import ImageNetNasBench201Benchmark, Cifar100NasBench201Benchmark, \
Cifar10ValidNasBench201Benchmark, Cifar10NasBench201Benchmark as Cifar10NasBench201BenchmarkContainer
from hpolib.benchmarks.nas.nasbe... | tests/test_nasbench_201.py | import logging
logging.basicConfig(level=logging.DEBUG)
import pytest
from hpolib.benchmarks.nas.nasbench_201 import ImageNetNasBench201Benchmark, Cifar100NasBench201Benchmark, \
Cifar10ValidNasBench201Benchmark, Cifar10NasBench201Benchmark as Cifar10NasBench201BenchmarkContainer
from hpolib.benchmarks.nas.nasbe... | 0.498535 | 0.54819 |
import numpy as np
from .pyramid import Pyramid
from .filters import parse_filter
from .c.wrapper import corrDn, upConv
class WaveletPyramid(Pyramid):
"""Multiscale wavelet pyramid
Parameters
----------
image : `array_like`
1d or 2d image upon which to construct to the pyramid.
height : '... | pyrtools/pyramids/WaveletPyramid.py | import numpy as np
from .pyramid import Pyramid
from .filters import parse_filter
from .c.wrapper import corrDn, upConv
class WaveletPyramid(Pyramid):
"""Multiscale wavelet pyramid
Parameters
----------
image : `array_like`
1d or 2d image upon which to construct to the pyramid.
height : '... | 0.919728 | 0.746786 |
from datetime import datetime
from newsapi import NewsApiClient
from unittest.mock import patch
from os.path import join, dirname, realpath
from sentinel_connectors.historical import GoogleNewsHistoricalConnector
from sentinel_connectors.stream import GoogleNewsStreamConnector
from sentinel_connectors.gn_common import ... | sentinel_connectors/tests/test-connectors/test_gn.py | from datetime import datetime
from newsapi import NewsApiClient
from unittest.mock import patch
from os.path import join, dirname, realpath
from sentinel_connectors.historical import GoogleNewsHistoricalConnector
from sentinel_connectors.stream import GoogleNewsStreamConnector
from sentinel_connectors.gn_common import ... | 0.545044 | 0.310054 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['ObjectStorageBucket']
class ObjectStorageBucket(pulumi.CustomResource):
def __init__(__self__,
... | sdk/python/pulumi_linode/object_storage_bucket.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['ObjectStorageBucket']
class ObjectStorageBucket(pulumi.CustomResource):
def __init__(__self__,
... | 0.805135 | 0.193642 |
import sys
import argparse as ap
import numpy as np
from astropy.time import Time
from astropy.coordinates import (
SkyCoord,
EarthLocation
)
import astropy.units as u
# pylint: disable=invalid-name
# pylint: disable=redefined-outer-name
# pylint: disable=no-member
def argParse():
"""
Parse the co... | convert_times.py | import sys
import argparse as ap
import numpy as np
from astropy.time import Time
from astropy.coordinates import (
SkyCoord,
EarthLocation
)
import astropy.units as u
# pylint: disable=invalid-name
# pylint: disable=redefined-outer-name
# pylint: disable=no-member
def argParse():
"""
Parse the co... | 0.638272 | 0.362377 |
import logging as log
import boto3
try:
# These are installed only for the case of a dev instance
from moto import mock_ec2
from moto import mock_s3
import responses
except ImportError:
log.debug("Development library moto is not installed.")
from cloudbridge.cloud.base import BaseCloudProvider
f... | cloudbridge/cloud/providers/aws/provider.py | import logging as log
import boto3
try:
# These are installed only for the case of a dev instance
from moto import mock_ec2
from moto import mock_s3
import responses
except ImportError:
log.debug("Development library moto is not installed.")
from cloudbridge.cloud.base import BaseCloudProvider
f... | 0.608245 | 0.125923 |
import npc
from npc.commands import util
from npc.character import Character
import pytest
from tests.util import fixture_dir
def test_find_empty_dirs(tmp_path):
tmp_path.joinpath('empty1').mkdir()
tmp_path.joinpath('empty2').mkdir()
tmp_path.joinpath('not_empty').mkdir()
tmp_path.joinpath('not_empty'... | tests/commands/test_cmd_util.py | import npc
from npc.commands import util
from npc.character import Character
import pytest
from tests.util import fixture_dir
def test_find_empty_dirs(tmp_path):
tmp_path.joinpath('empty1').mkdir()
tmp_path.joinpath('empty2').mkdir()
tmp_path.joinpath('not_empty').mkdir()
tmp_path.joinpath('not_empty'... | 0.336222 | 0.316211 |
import vtk
import h5py
import numpy as np
from vtk.util.vtkAlgorithm import VTKPythonAlgorithmBase
import otter.plugins.common as common
from otter.plugins.common.Reader import Reader
from otter.plugins.common.Reader import BlockInformation, VariableInformation
class PetscHDF5DataSetReader(VTKPythonAlgorithmBase):
... | otter/plugins/common/PetscHDF5Reader.py | import vtk
import h5py
import numpy as np
from vtk.util.vtkAlgorithm import VTKPythonAlgorithmBase
import otter.plugins.common as common
from otter.plugins.common.Reader import Reader
from otter.plugins.common.Reader import BlockInformation, VariableInformation
class PetscHDF5DataSetReader(VTKPythonAlgorithmBase):
... | 0.338733 | 0.209288 |
from datetime import datetime
from .common import ScraperTest
class RacesTest(ScraperTest):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.meet = {
'date': datetime(2016, 2, 1),
'track': 'Kilmore',
'url': '/racing-results/victoria/Kilmore/2016-02-01/'
}
cls.expected_races = [
{
... | pypunters/test/races.py | from datetime import datetime
from .common import ScraperTest
class RacesTest(ScraperTest):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.meet = {
'date': datetime(2016, 2, 1),
'track': 'Kilmore',
'url': '/racing-results/victoria/Kilmore/2016-02-01/'
}
cls.expected_races = [
{
... | 0.421552 | 0.158597 |
# Rest server
from MiniREST.RESTServer import RESTServer, responseCodes, responseTypes
class RCubicServer(RESTServer):
"""RCubicServer - creates a new RCubicServer instance.
Extends RESTServer with custom functions.
"""
def __init__(self, *args, **kwargs):
"""Create a RCubicServer. Call 's... | RCubic/RCubicServer.py |
# Rest server
from MiniREST.RESTServer import RESTServer, responseCodes, responseTypes
class RCubicServer(RESTServer):
"""RCubicServer - creates a new RCubicServer instance.
Extends RESTServer with custom functions.
"""
def __init__(self, *args, **kwargs):
"""Create a RCubicServer. Call 's... | 0.636918 | 0.339636 |
import os
from pathlib import Path
import cv2
import numpy as np
INPUT_IMAGES_DIR = 'LR6_data/train/images'
INPUT_MASKS_DIR = 'LR6_data/train/masks'
OUTPUT_IMAGES_DIR = 'LR6_data/train/train_images2'
OUTPUT_MASKS_DIR = 'LR6_data/train/train_masks2'
BACKGROUDS_DIR = 'LR6_data/train2/backgrounds'
MASK_EXTENSIO... | LR6/LR6_data_collector.py | import os
from pathlib import Path
import cv2
import numpy as np
INPUT_IMAGES_DIR = 'LR6_data/train/images'
INPUT_MASKS_DIR = 'LR6_data/train/masks'
OUTPUT_IMAGES_DIR = 'LR6_data/train/train_images2'
OUTPUT_MASKS_DIR = 'LR6_data/train/train_masks2'
BACKGROUDS_DIR = 'LR6_data/train2/backgrounds'
MASK_EXTENSIO... | 0.165323 | 0.117851 |
from django.db import migrations, models
import django.db.models.deletion
from utils.migrate_base_product import update_id_on_models
def link_retreat_to_base_product(apps, schema_editor):
retreat_model = apps.get_model('retirement',
'retreat')
base_product_model = apps.g... | retirement/migrations/0016_auto_20190815_0328.py |
from django.db import migrations, models
import django.db.models.deletion
from utils.migrate_base_product import update_id_on_models
def link_retreat_to_base_product(apps, schema_editor):
retreat_model = apps.get_model('retirement',
'retreat')
base_product_model = apps.g... | 0.333829 | 0.067424 |
import tvm
import json
from functools import reduce
from .. import _ffi_api
from ..target import TENET
class TenetContext(object):
def __init__(self, level):
self.level = level
self.space_time_loops = [[[], []] for i in range(level)] # outer --> inner
self.memory_scopes = [None for i in r... | python/tvm/auto_tensorize/backend/tenet_integrate.py | import tvm
import json
from functools import reduce
from .. import _ffi_api
from ..target import TENET
class TenetContext(object):
def __init__(self, level):
self.level = level
self.space_time_loops = [[[], []] for i in range(level)] # outer --> inner
self.memory_scopes = [None for i in r... | 0.399812 | 0.345547 |
import os
import tempfile
import zipfile
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template, send_file, after_this_request, send_from_directory
from PIL import Image
import pillow_heif
pillow_heif.register_heif_opener() # Give PIL access to HEIF
ALLOWED_EXTENSIONS = set(['heic', '... | heicconverter.py | import os
import tempfile
import zipfile
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template, send_file, after_this_request, send_from_directory
from PIL import Image
import pillow_heif
pillow_heif.register_heif_opener() # Give PIL access to HEIF
ALLOWED_EXTENSIONS = set(['heic', '... | 0.363421 | 0.090534 |
import os
import random
import argparse
import numpy as np
import cv2
import torch
import torch.nn as nn
import decord
from decord import VideoReader
from model import *
from data.data_utils import *
from data.test_video_clip_dataset import BasicTransform
def detect_initial_slide_transition_candidates_resnet2d(n... | test_slide_detection_2d.py | import os
import random
import argparse
import numpy as np
import cv2
import torch
import torch.nn as nn
import decord
from decord import VideoReader
from model import *
from data.data_utils import *
from data.test_video_clip_dataset import BasicTransform
def detect_initial_slide_transition_candidates_resnet2d(n... | 0.224906 | 0.179531 |
# Standard imports
from datetime import datetime, timedelta
class TimeActivity(object):
"""Class that will handle the logic of the processes."""
def __init__(self):
"""Constructor. (place holder for now)."""
self.__todayDate = datetime.today()
def getCurrentTimePerProcess(self, session):... | Modules/Chronos/TimeActivity.py | # Standard imports
from datetime import datetime, timedelta
class TimeActivity(object):
"""Class that will handle the logic of the processes."""
def __init__(self):
"""Constructor. (place holder for now)."""
self.__todayDate = datetime.today()
def getCurrentTimePerProcess(self, session):... | 0.736021 | 0.294862 |
import tensorflow as tf
from mamltf2.model import Model
class Reptile(Model):
def __init__(self, *args, nInnerSteps = 5, **kwargs):
super().__init__(*args, **kwargs)
self.nInnerSteps = nInnerSteps
self.interpolationRateInitial = self.outerLearningRate
self.sgd = tf.keras.optimizers.... | mamltf2/methods/reptile.py | import tensorflow as tf
from mamltf2.model import Model
class Reptile(Model):
def __init__(self, *args, nInnerSteps = 5, **kwargs):
super().__init__(*args, **kwargs)
self.nInnerSteps = nInnerSteps
self.interpolationRateInitial = self.outerLearningRate
self.sgd = tf.keras.optimizers.... | 0.806853 | 0.331945 |
from __future__ import absolute_import
from dohq_teamcity.custom.base_model import TeamCityObject
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from dohq_teamcity.models.group import Group # noqa: F401,E501
from dohq_teamcity.models.groups import Groups # noqa: F401,E501
from doh... | dohq_teamcity/api/group_api.py | from __future__ import absolute_import
from dohq_teamcity.custom.base_model import TeamCityObject
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from dohq_teamcity.models.group import Group # noqa: F401,E501
from dohq_teamcity.models.groups import Groups # noqa: F401,E501
from doh... | 0.764012 | 0.058885 |
import argparse
import fileinput
from fairseq.models.transformer import TransformerModel
from tqdm import tqdm
import numpy as np
def main():
parser = argparse.ArgumentParser(
description=(
"Extract back-translations from the stdout of _fairseq-generate. "
"If there are mu... | examples/backtranslation/gen_mono_lprob.py | import argparse
import fileinput
from fairseq.models.transformer import TransformerModel
from tqdm import tqdm
import numpy as np
def main():
parser = argparse.ArgumentParser(
description=(
"Extract back-translations from the stdout of _fairseq-generate. "
"If there are mu... | 0.432782 | 0.089893 |
import os
from landolfio.settings.base import * # noqa
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["landolfio.vofdoesburg.nl"]
SESSION_COOKIE_SE... | website/landolfio/settings/production.py | import os
from landolfio.settings.base import * # noqa
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["landolfio.vofdoesburg.nl"]
SESSION_COOKIE_SE... | 0.136263 | 0.090133 |
try:
import unittest2 as unittest
except ImportError:
import unittest
from mock import patch
import app_config
app_config.DATABASE_NAME = 'carebot_test.db'
from plugins.npr.start_tracking import NPRStartTracking
from util.models import Story
from tests.test_util.db import clear_stories
class TestSpreadshee... | tests/test_plugin_track.py |
try:
import unittest2 as unittest
except ImportError:
import unittest
from mock import patch
import app_config
app_config.DATABASE_NAME = 'carebot_test.db'
from plugins.npr.start_tracking import NPRStartTracking
from util.models import Story
from tests.test_util.db import clear_stories
class TestSpreadshee... | 0.605799 | 0.270468 |
import math
import torch
import torch.nn as nn
from torch.nn import init
BATCHNORM_TRACK_RUNNING_STATS = False
BATCHNORM_MOVING_AVERAGE_DECAY = 0.9997
class BNorm_init(nn.BatchNorm2d):
def reset_parameters(self):
init.uniform_(self.weight, 0, 1)
init.zeros_(self.bias)
class Conv2d_init(nn.Conv2... | models.py | import math
import torch
import torch.nn as nn
from torch.nn import init
BATCHNORM_TRACK_RUNNING_STATS = False
BATCHNORM_MOVING_AVERAGE_DECAY = 0.9997
class BNorm_init(nn.BatchNorm2d):
def reset_parameters(self):
init.uniform_(self.weight, 0, 1)
init.zeros_(self.bias)
class Conv2d_init(nn.Conv2... | 0.925281 | 0.355971 |
import tkinter as tk
import requests
import json
import os
from collections import OrderedDict
from tkinter import messagebox
from tkinter import ttk
from bs4 import BeautifulSoup, SoupStrainer
# Combobox widget
global oro_ddl
oro_ddl = None
stFont = ("calibri",12)
# Token is given to each unique IEX AP... | stocku.py | import tkinter as tk
import requests
import json
import os
from collections import OrderedDict
from tkinter import messagebox
from tkinter import ttk
from bs4 import BeautifulSoup, SoupStrainer
# Combobox widget
global oro_ddl
oro_ddl = None
stFont = ("calibri",12)
# Token is given to each unique IEX AP... | 0.143397 | 0.093099 |
import os
import time
import requests
import json
import base64
from datetime import datetime
from distutils.util import strtobool
from dotenv import load_dotenv
from flask import Flask, request, redirect
from flasgger import Swagger, swag_from
from pixoo.pixoo import Channel, Pixoo
from PIL import Image
from swag im... | app.py | import os
import time
import requests
import json
import base64
from datetime import datetime
from distutils.util import strtobool
from dotenv import load_dotenv
from flask import Flask, request, redirect
from flasgger import Swagger, swag_from
from pixoo.pixoo import Channel, Pixoo
from PIL import Image
from swag im... | 0.39946 | 0.061678 |
basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
if basedir == '': basedir = '.'
sys.path.append(basedir+'/miasmX')
from miasmX.arch.ppc_arch import ppc_mn
from miasmX.arch.ia32_arch import x86_afs
import logging
console_handler = logging.StreamHandler()
console_handler.setFormatt... | plasmasm/arch/PPC_MIASM.py | basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
if basedir == '': basedir = '.'
sys.path.append(basedir+'/miasmX')
from miasmX.arch.ppc_arch import ppc_mn
from miasmX.arch.ia32_arch import x86_afs
import logging
console_handler = logging.StreamHandler()
console_handler.setFormatt... | 0.196788 | 0.185855 |
from vumi.config import (
ConfigText, ConfigInt, ConfigBool, ConfigClientEndpoint, ConfigDict,
ConfigFloat, ConfigClassName, ClientEndpointFallback)
from vumi.transports.smpp.iprocessors import (
IDeliveryReportProcessor, IDeliverShortMessageProcessor,
ISubmitShortMessageProcessor)
from vumi.codecs.ivum... | vumi/transports/smpp/config.py | from vumi.config import (
ConfigText, ConfigInt, ConfigBool, ConfigClientEndpoint, ConfigDict,
ConfigFloat, ConfigClassName, ClientEndpointFallback)
from vumi.transports.smpp.iprocessors import (
IDeliveryReportProcessor, IDeliverShortMessageProcessor,
ISubmitShortMessageProcessor)
from vumi.codecs.ivum... | 0.578448 | 0.165661 |
from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore import permissions
from Products.CMFCore.utils import getToolByName
from bika.lims.permissions import AddAttachment
def upgrade(tool):
# Hack prevent out-of-date upgrading
# Related: PR #1484
# https://github.com/bika... | bika/lims/upgrade/to3002.py | from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore import permissions
from Products.CMFCore.utils import getToolByName
from bika.lims.permissions import AddAttachment
def upgrade(tool):
# Hack prevent out-of-date upgrading
# Related: PR #1484
# https://github.com/bika... | 0.619701 | 0.150091 |
import requests
from datetime import date
class Stoncks:
base_url = "https://www.alphavantage.co/query?"
api_key = "API_KEY"
def __init__(self, function, crypto, base_currency, analysis):
self.function = function
self.crypto = crypto
self.base_currency = base_currency
self... | forevis/crypto/Classes/Stoncks.py | import requests
from datetime import date
class Stoncks:
base_url = "https://www.alphavantage.co/query?"
api_key = "API_KEY"
def __init__(self, function, crypto, base_currency, analysis):
self.function = function
self.crypto = crypto
self.base_currency = base_currency
self... | 0.61451 | 0.213224 |
from __future__ import print_function
import sys
import numpy as np
#This code calculates the aproximate memory footprint of PMPIC (total and per process)
#It can thus be used to choose a value of maxparcels to maximise memory usage
#number of grid/parcel variables
n_grids=32
n_parcels=38
#number of bytes in a varia... | planner.py | from __future__ import print_function
import sys
import numpy as np
#This code calculates the aproximate memory footprint of PMPIC (total and per process)
#It can thus be used to choose a value of maxparcels to maximise memory usage
#number of grid/parcel variables
n_grids=32
n_parcels=38
#number of bytes in a varia... | 0.181662 | 0.245362 |
from graphgen import _helpers
from graphgen.analysis import edge_num_distr
import networkx as nx
import random
import numpy as np
import math
UNIFORM = -1
NORMAL = -2
def naive_random_graph(num_vertices, num_edges=UNIFORM, seed=None):
"""
Generate a random undirected graph in a naive way.
First, a random number o... | graphgen/graph_generators.py | from graphgen import _helpers
from graphgen.analysis import edge_num_distr
import networkx as nx
import random
import numpy as np
import math
UNIFORM = -1
NORMAL = -2
def naive_random_graph(num_vertices, num_edges=UNIFORM, seed=None):
"""
Generate a random undirected graph in a naive way.
First, a random number o... | 0.754192 | 0.627666 |
import os
import sys
import signal
import argparse
import subprocess
import json
parser = argparse.ArgumentParser(description = 'Create a dataproc cluster')
parser.add_argument('script')
parser.add_argument('-n','--cluster-name', type=str, required=False) #name of the cluster so you can create multiple
parser.add_argu... | powerwatch/analysis/execute.py | import os
import sys
import signal
import argparse
import subprocess
import json
parser = argparse.ArgumentParser(description = 'Create a dataproc cluster')
parser.add_argument('script')
parser.add_argument('-n','--cluster-name', type=str, required=False) #name of the cluster so you can create multiple
parser.add_argu... | 0.124226 | 0.079282 |
import torch
import math
import random
import numbers
import numpy as np
from . import functional as F
from torch.nn.modules.utils import _ntuple
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, x):
for t in self.transforms:
x = t(x)
return x
class Cen... | utils/mytransform.py | import torch
import math
import random
import numbers
import numpy as np
from . import functional as F
from torch.nn.modules.utils import _ntuple
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, x):
for t in self.transforms:
x = t(x)
return x
class Cen... | 0.737631 | 0.352313 |
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _snap.SWIG_PyInstanceMethod_New(func)
else:
from new import instancemethod as new_instancemethod
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import i... | setup/snap.py |
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _snap.SWIG_PyInstanceMethod_New(func)
else:
from new import instancemethod as new_instancemethod
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import i... | 0.404037 | 0.111338 |
import socket
from uasync import Promise
class AsyncSocket:
def __init__(self, sock):
self.sock = sock
self.current_task = None
self.ready = False
self.sock.setblocking(False)
def ready_callback(sock):
self.ready = True
if self.current_task:
... | server/asocket.py | import socket
from uasync import Promise
class AsyncSocket:
def __init__(self, sock):
self.sock = sock
self.current_task = None
self.ready = False
self.sock.setblocking(False)
def ready_callback(sock):
self.ready = True
if self.current_task:
... | 0.391871 | 0.070208 |
import asyncio
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
from typing import List, Set
import arrow
import asyncpg
import psutil
from bot import run_cluster
from classyjson import ClassyDict
from util.code import execute_code, format_exception
from util.cooldowns import Cool... | villager-bot/karen.py | import asyncio
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
from typing import List, Set
import arrow
import asyncpg
import psutil
from bot import run_cluster
from classyjson import ClassyDict
from util.code import execute_code, format_exception
from util.cooldowns import Cool... | 0.565539 | 0.12424 |
import csv
import sys
import datetime
import sqlite3
import os
from typing import List, Any, Union, NamedTuple, Tuple
from .env import TWDFT_DATA_DIR, INSPECTORS
def conv_site_name_to_id(site: str) -> str:
db_filename = "twdft.db"
db_path = os.path.join(TWDFT_DATA_DIR, db_filename)
with sqlite3.connect(... | twdft/database.py | import csv
import sys
import datetime
import sqlite3
import os
from typing import List, Any, Union, NamedTuple, Tuple
from .env import TWDFT_DATA_DIR, INSPECTORS
def conv_site_name_to_id(site: str) -> str:
db_filename = "twdft.db"
db_path = os.path.join(TWDFT_DATA_DIR, db_filename)
with sqlite3.connect(... | 0.484868 | 0.191876 |
import os
import logging
import random
from flask import Flask, request
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
logger = logging.getLogger(__name__)
app = Flask(__name__)
moves = ['F', 'T', 'L', 'R']
def my_data(all_data):
my_name = all_data['_links']['self']['href']
my_coord = all_dat... | samples/python/main.py | import os
import logging
import random
from flask import Flask, request
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
logger = logging.getLogger(__name__)
app = Flask(__name__)
moves = ['F', 'T', 'L', 'R']
def my_data(all_data):
my_name = all_data['_links']['self']['href']
my_coord = all_dat... | 0.308919 | 0.193642 |
from __future__ import annotations
import asyncio
from datetime import datetime
from typing import Any, Dict
import aiohttp
from .client import GitHubClient
from .const import (
BASE_GITHUB_URL,
OAUTH_ACCESS_TOKEN_PATH,
OAUTH_DEVICE_LOGIN_PATH,
DeviceFlowError,
GitHubClientKwarg,
GitHubReques... | aiogithubapi/device.py | from __future__ import annotations
import asyncio
from datetime import datetime
from typing import Any, Dict
import aiohttp
from .client import GitHubClient
from .const import (
BASE_GITHUB_URL,
OAUTH_ACCESS_TOKEN_PATH,
OAUTH_DEVICE_LOGIN_PATH,
DeviceFlowError,
GitHubClientKwarg,
GitHubReques... | 0.682256 | 0.08152 |
from __future__ import print_function
import imp
import fnmatch
import os
import shutil
import subprocess
import sys
import time
from collections import OrderedDict
try:
import configparser
except ImportError:
import ConfigParser as configparser
from . import toml
if 'FileNotFoundError' not in globals():
... | game/blenderpanda/pman/__init__.py | from __future__ import print_function
import imp
import fnmatch
import os
import shutil
import subprocess
import sys
import time
from collections import OrderedDict
try:
import configparser
except ImportError:
import ConfigParser as configparser
from . import toml
if 'FileNotFoundError' not in globals():
... | 0.205057 | 0.066509 |
from treebank_toolkit.sentence import ConllSent
from treebank_toolkit.parser_state import State
class TransitionSystemBase(object):
_actions_list = None
@classmethod
def _valid_transitions(cls, parserstate):
""" Prepares the set of gold transitions given a parser state """
raise NotImplem... | treebank_toolkit/transition_system.py | from treebank_toolkit.sentence import ConllSent
from treebank_toolkit.parser_state import State
class TransitionSystemBase(object):
_actions_list = None
@classmethod
def _valid_transitions(cls, parserstate):
""" Prepares the set of gold transitions given a parser state """
raise NotImplem... | 0.684159 | 0.483405 |
import numpy
import pytest
import skimage.data
import skimage.color
import skimage.filters
import skimage.measure
import cellprofiler.__main__
import cellprofiler_core.image
import cellprofiler_core.measurement
import cellprofiler_core.object
import cellprofiler_core.pipeline
import cellprofiler_core.preferences
impo... | CellProfiler/tests/conftest.py | import numpy
import pytest
import skimage.data
import skimage.color
import skimage.filters
import skimage.measure
import cellprofiler.__main__
import cellprofiler_core.image
import cellprofiler_core.measurement
import cellprofiler_core.object
import cellprofiler_core.pipeline
import cellprofiler_core.preferences
impo... | 0.451568 | 0.302275 |
import argparse
import itertools as it
import json
import math
import matplotlib.pyplot as plt
import os
import pathlib
_here = pathlib.Path(__file__).resolve().parent
def main(dataset, models, forward, accepts, rejects):
assert not (accepts and rejects)
if forward:
if accepts:
string = ... | histogram.py | import argparse
import itertools as it
import json
import math
import matplotlib.pyplot as plt
import os
import pathlib
_here = pathlib.Path(__file__).resolve().parent
def main(dataset, models, forward, accepts, rejects):
assert not (accepts and rejects)
if forward:
if accepts:
string = ... | 0.270866 | 0.208018 |
import unittest
from dcpquery import config
from dcpquery.db.models import File, BundleFileLink
from dcpquery.exceptions import DCPFileNotFoundError
from tests import vx_bf_links
class TestFiles(unittest.TestCase):
project_file = next(l.file for l in vx_bf_links if l.name == 'project_0.json')
process_file = ... | tests/unit/test_orm/test_files.py | import unittest
from dcpquery import config
from dcpquery.db.models import File, BundleFileLink
from dcpquery.exceptions import DCPFileNotFoundError
from tests import vx_bf_links
class TestFiles(unittest.TestCase):
project_file = next(l.file for l in vx_bf_links if l.name == 'project_0.json')
process_file = ... | 0.416797 | 0.269344 |
"""Tests for LlvmEnv.fork()."""
from time import time
from compiler_gym.envs import LlvmEnv
from compiler_gym.util.runfiles_path import runfiles_path
from tests.test_main import main
pytest_plugins = ["tests.envs.llvm.fixtures"]
EXAMPLE_BITCODE_FILE = runfiles_path(
"CompilerGym/compiler_gym/third_party/cBench/c... | tests/envs/llvm/fork_env_test.py | """Tests for LlvmEnv.fork()."""
from time import time
from compiler_gym.envs import LlvmEnv
from compiler_gym.util.runfiles_path import runfiles_path
from tests.test_main import main
pytest_plugins = ["tests.envs.llvm.fixtures"]
EXAMPLE_BITCODE_FILE = runfiles_path(
"CompilerGym/compiler_gym/third_party/cBench/c... | 0.598195 | 0.507263 |
import argparse
import re
import os
import ray
from ray.tune import run_experiments
from ray.tune.registry import register_trainable, register_env, get_trainable_cls
import ray.rllib.contrib.maddpg.maddpg as maddpg
from rllib_multiagent_particle_env import env_creator
from util import parse_args
def setup_ray():
... | how-to-use-azureml/reinforcement-learning/multiagent-particle-envs/files/particle_train.py | import argparse
import re
import os
import ray
from ray.tune import run_experiments
from ray.tune.registry import register_trainable, register_env, get_trainable_cls
import ray.rllib.contrib.maddpg.maddpg as maddpg
from rllib_multiagent_particle_env import env_creator
from util import parse_args
def setup_ray():
... | 0.505859 | 0.145996 |
from Stack import Stack
from Brackets import Brackets
def brackets_validator(str):
print(str)
flag = True
opening_bracket_stack = Stack()
position = 0
for ch in str:
position += 1
if (ch == '(' or ch == '[' or ch == '{'):
temp = Brackets(ch, position)
openin... | Brackets_Validator.py | from Stack import Stack
from Brackets import Brackets
def brackets_validator(str):
print(str)
flag = True
opening_bracket_stack = Stack()
position = 0
for ch in str:
position += 1
if (ch == '(' or ch == '[' or ch == '{'):
temp = Brackets(ch, position)
openin... | 0.099099 | 0.277914 |
import os
import time
import json
import urllib
import subprocess
TRACE_PATH = '../cooked_traces/'
with open('./chrome_retry_log', 'wb') as f:
f.write('chrome retry log\n')
os.system('sudo sysctl -w net.ipv4.ip_forward=1')
ip_data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
ip = str(ip_data['... | run_exp/run_all_traces.py | import os
import time
import json
import urllib
import subprocess
TRACE_PATH = '../cooked_traces/'
with open('./chrome_retry_log', 'wb') as f:
f.write('chrome retry log\n')
os.system('sudo sysctl -w net.ipv4.ip_forward=1')
ip_data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
ip = str(ip_data['... | 0.062238 | 0.046055 |
import pytest
from valida.conditions import (
KeyDataType,
KeyLength,
ValueDataType,
ValueLength,
KeyLike,
Value,
Key,
Index,
NullCondition,
ConditionAnd,
ConditionOr,
ConditionXor,
ConditionLike,
)
from valida.datapath import DataPath, ListValue, MapValue
from valid... | tests/test_conditions.py | import pytest
from valida.conditions import (
KeyDataType,
KeyLength,
ValueDataType,
ValueLength,
KeyLike,
Value,
Key,
Index,
NullCondition,
ConditionAnd,
ConditionOr,
ConditionXor,
ConditionLike,
)
from valida.datapath import DataPath, ListValue, MapValue
from valid... | 0.671363 | 0.75638 |
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# TODO: Ask the user how much assignments they want through loop through
untilLooped = input("Enter the amount of assignments you want to loop through: ")
startingNum = 1
# Line Spacer
print("If the website tells you 'wrong us... | zybrowser.py | import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# TODO: Ask the user how much assignments they want through loop through
untilLooped = input("Enter the amount of assignments you want to loop through: ")
startingNum = 1
# Line Spacer
print("If the website tells you 'wrong us... | 0.064407 | 0.169991 |
import os
import logging
import json
import random
from pathlib import Path
import spacy
from spacy.util import minibatch, compounding
from collections import defaultdict
log = logging.getLogger('CVE_Analyzer')
# ------------------------ PERFORMANCES ------------------------
def _compute_performances(performaces, ... | cve_analyzer/analyzer.py |
import os
import logging
import json
import random
from pathlib import Path
import spacy
from spacy.util import minibatch, compounding
from collections import defaultdict
log = logging.getLogger('CVE_Analyzer')
# ------------------------ PERFORMANCES ------------------------
def _compute_performances(performaces, ... | 0.555435 | 0.250322 |
from datetime import datetime
from django.http import HttpResponseNotFound, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import requests
from urllib.parse import urlencode
from uuid import uuid4
from fedireads import models
from fedireads.remote_user import get_or_create_remote_user
from fedireads... | fedireads/outgoing.py | from datetime import datetime
from django.http import HttpResponseNotFound, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import requests
from urllib.parse import urlencode
from uuid import uuid4
from fedireads import models
from fedireads.remote_user import get_or_create_remote_user
from fedireads... | 0.376852 | 0.084644 |
import sys
from enum import Enum
class EnumIOType(Enum):
NONE = "IOType.NONE"
OUTPUT = "IOType.OUTPUT"
INPUT = "IOType.INPUT"
from django.db import models
class ConnectedSystem(models.Model):
name = models.CharField(max_length=255,verbose_name="Name of Connection")
lastIP = models.GenericIPAdd... | pylightcommon/models.py | import sys
from enum import Enum
class EnumIOType(Enum):
NONE = "IOType.NONE"
OUTPUT = "IOType.OUTPUT"
INPUT = "IOType.INPUT"
from django.db import models
class ConnectedSystem(models.Model):
name = models.CharField(max_length=255,verbose_name="Name of Connection")
lastIP = models.GenericIPAdd... | 0.330255 | 0.129926 |
import os, sys, bisect
import numarray as num
import hippoplotter as plot
import irf_loader
from Interpolator import Interpolator
from ks import ks1, ks2
irf_loader.Loader_go()
SkyDir = irf_loader.SkyDir
class Psf(object):
_factory = irf_loader.IrfsFactory_instance()
def __init__(self, irfsName, energy=100.,... | irfLoader/python/psf_tests.py | import os, sys, bisect
import numarray as num
import hippoplotter as plot
import irf_loader
from Interpolator import Interpolator
from ks import ks1, ks2
irf_loader.Loader_go()
SkyDir = irf_loader.SkyDir
class Psf(object):
_factory = irf_loader.IrfsFactory_instance()
def __init__(self, irfsName, energy=100.,... | 0.378459 | 0.229935 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from celery.schedules import crontab
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/c... | analyzer/analyzer/settings.py | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from celery.schedules import crontab
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/c... | 0.351422 | 0.070304 |
import numpy as np
import torch
import numba as nb
import open3d as o3d
import frnn
import dgl
from numba import types, deferred_type
from numba.typed import Dict, List
import pickle
from Constants import *
from Operator import *
from cuHelper import *
import time
I = 16 # 2^I is for hashing function
Large = 2**I
@... | Particles.py | import numpy as np
import torch
import numba as nb
import open3d as o3d
import frnn
import dgl
from numba import types, deferred_type
from numba.typed import Dict, List
import pickle
from Constants import *
from Operator import *
from cuHelper import *
import time
I = 16 # 2^I is for hashing function
Large = 2**I
@... | 0.345768 | 0.463566 |
import os
from collections import defaultdict
from ctypes import c_float
from itertools import chain
from typing import List, Tuple
import pyglet
from pyglet.gl import *
from pyglet.graphics.vertexdomain import create_domain, create_attribute_usage
from .wavefront_parsers import ObjectParser, WavefrontObjectFactory
f... | engine/views/opengl_mesh.py | import os
from collections import defaultdict
from ctypes import c_float
from itertools import chain
from typing import List, Tuple
import pyglet
from pyglet.gl import *
from pyglet.graphics.vertexdomain import create_domain, create_attribute_usage
from .wavefront_parsers import ObjectParser, WavefrontObjectFactory
f... | 0.731634 | 0.211641 |
import re
import requests
from bs4 import BeautifulSoup
#re = \(?0?([1-9]{2})[ \-\.\)]{0,2}(9[ \-\.]?\d{4})[ \-\.]?(\d{4})
#soup.prettify() faz o parsing do html
dominio = 'https://django-anuncios.solyd.com.br'
url = 'https://django-anuncios.solyd.com.br/automoveis/'
def GET(url):
try:
resposta = requ... | random designs-python/crawler/crawler.py | import re
import requests
from bs4 import BeautifulSoup
#re = \(?0?([1-9]{2})[ \-\.\)]{0,2}(9[ \-\.]?\d{4})[ \-\.]?(\d{4})
#soup.prettify() faz o parsing do html
dominio = 'https://django-anuncios.solyd.com.br'
url = 'https://django-anuncios.solyd.com.br/automoveis/'
def GET(url):
try:
resposta = requ... | 0.181916 | 0.140543 |
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import resource_helper
from neutron.common import exceptions as n_exc
from oslo_log import log
from neutron_dynamic_routing._i18n import _
from neutron_dynamic_routing.extensions import bgp as bgp_ext
LOG = log.getL... | neutron_dynamic_routing/extensions/vrf.py |
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import resource_helper
from neutron.common import exceptions as n_exc
from oslo_log import log
from neutron_dynamic_routing._i18n import _
from neutron_dynamic_routing.extensions import bgp as bgp_ext
LOG = log.getL... | 0.636466 | 0.09611 |
from functools import wraps
import os.path
import click
import ndef
version_message = '%%(prog)s %%(version)s (ndeflib %s)' % ndef.__version__
command_plugins = os.path.join(os.path.dirname(__file__), 'commands')
def echo(*args, **kwargs):
click.echo(*args, **kwargs)
def info(*args):
if click.get_current_... | src/ndeftool/cli.py |
from functools import wraps
import os.path
import click
import ndef
version_message = '%%(prog)s %%(version)s (ndeflib %s)' % ndef.__version__
command_plugins = os.path.join(os.path.dirname(__file__), 'commands')
def echo(*args, **kwargs):
click.echo(*args, **kwargs)
def info(*args):
if click.get_current_... | 0.474144 | 0.098382 |
import time, urllib, urllib2
from Adafruit_MCP230xx import *
import RPi.GPIO as GPIO
# Raspberry Pi Pin Usage
APPLIANCE0_RPI_PIN = 18
# MCP23017 I2C Port Expander Pin Usage
APPLIANCE0_LED_PIN = 10
APPLIANCE1_LED_PIN = 11
APPLIANCE2_LED_PIN = 12
APPLIANCE3_LED_PIN = 13
APPLIANCE4_LED_PIN = 14
APPLIANCE0_BUTTON_PIN =... | power_manager.py | import time, urllib, urllib2
from Adafruit_MCP230xx import *
import RPi.GPIO as GPIO
# Raspberry Pi Pin Usage
APPLIANCE0_RPI_PIN = 18
# MCP23017 I2C Port Expander Pin Usage
APPLIANCE0_LED_PIN = 10
APPLIANCE1_LED_PIN = 11
APPLIANCE2_LED_PIN = 12
APPLIANCE3_LED_PIN = 13
APPLIANCE4_LED_PIN = 14
APPLIANCE0_BUTTON_PIN =... | 0.258045 | 0.10697 |
import datetime as dt
import rasterio
import geopandas as gpd
from det_tool import functions as fun
from det_tool import classes as cls
from pre_processor import functions as pfun
from config import cityModel_path, foot_height_shp, roof_raster, facade_solar_energy, updated_JSON, report_path
def process(model_path, sh... | det_tool/process.py | import datetime as dt
import rasterio
import geopandas as gpd
from det_tool import functions as fun
from det_tool import classes as cls
from pre_processor import functions as pfun
from config import cityModel_path, foot_height_shp, roof_raster, facade_solar_energy, updated_JSON, report_path
def process(model_path, sh... | 0.31363 | 0.260766 |
import csv
import os
import shutil
from glob import glob
import pytest
import xlsxwriter
from cliboa.conf import env
from cliboa.scenario.transform.file import CsvHeaderConvert, CsvMerge, ExcelConvert, FileConvert
from cliboa.util.exception import InvalidCount, InvalidFormat
from cliboa.util.helper import Helper
from... | tests/scenario/transform/test_file.py | import csv
import os
import shutil
from glob import glob
import pytest
import xlsxwriter
from cliboa.conf import env
from cliboa.scenario.transform.file import CsvHeaderConvert, CsvMerge, ExcelConvert, FileConvert
from cliboa.util.exception import InvalidCount, InvalidFormat
from cliboa.util.helper import Helper
from... | 0.299822 | 0.256523 |
from neuralnetwork.FeedForward import FeedForward
from neuralnetwork.Sigmoid import Sigmoid
from neuralnetwork.Backpropagation import Backpropagation
from utils import preprocess, feature_engineer
import pandas as pd
import numpy as np
from numpy import argmax
from sklearn.model_selection import train_test_split
fr... | predicting-taxi-fares/train.py | from neuralnetwork.FeedForward import FeedForward
from neuralnetwork.Sigmoid import Sigmoid
from neuralnetwork.Backpropagation import Backpropagation
from utils import preprocess, feature_engineer
import pandas as pd
import numpy as np
from numpy import argmax
from sklearn.model_selection import train_test_split
fr... | 0.49292 | 0.324169 |
import hashlib
import hmac
import time
import uuid
import requests
from celery import states
from celery.task import Task
from celery.exceptions import Ignore
from vigil.celery import app
class OverwatchTask(Task):
"""
Report the given error to overwatch
"""
expected_data = {
'bot_name': '',... | vigil/tasks/logic/overwatch.py | import hashlib
import hmac
import time
import uuid
import requests
from celery import states
from celery.task import Task
from celery.exceptions import Ignore
from vigil.celery import app
class OverwatchTask(Task):
"""
Report the given error to overwatch
"""
expected_data = {
'bot_name': '',... | 0.477311 | 0.163312 |
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
county_name = "Alameda County"
df_population = pd.read_csv("population_all.csv")
df_population = df_population[["Year", county_name]]
X = df_population
df_demand ... | modules/module8/extra/predict_3d_demand.py | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
county_name = "Alameda County"
df_population = pd.read_csv("population_all.csv")
df_population = df_population[["Year", county_name]]
X = df_population
df_demand ... | 0.663124 | 0.664064 |
from flask import Flask, jsonify, redirect, render_template, session, url_for, request
from flaskext.mysql import MySQL
app = Flask(__name__, static_url_path = "")
from myprojectprototype.script import dataAnalytic
import functools
from sqlalchemy import create_engine
import pandas as pd
import simplejson as json
def ... | src/myprojectprototype/app/views.py | from flask import Flask, jsonify, redirect, render_template, session, url_for, request
from flaskext.mysql import MySQL
app = Flask(__name__, static_url_path = "")
from myprojectprototype.script import dataAnalytic
import functools
from sqlalchemy import create_engine
import pandas as pd
import simplejson as json
def ... | 0.415254 | 0.069038 |
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from pretix.api.serializers.i18n import I18nAwareModelSerializer
from pretix.base.models import Seat, Voucher
class VoucherListSerializer(serializers.ListSerializer):
def create(self, validated_data):
codes = set... | src/pretix/api/serializers/voucher.py | from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from pretix.api.serializers.i18n import I18nAwareModelSerializer
from pretix.base.models import Seat, Voucher
class VoucherListSerializer(serializers.ListSerializer):
def create(self, validated_data):
codes = set... | 0.447702 | 0.105902 |
import pytest
import numpy as np
from mikeio import Dfs0
from datetime import datetime
import fmskill
from fmskill.observation import PointObservation
@pytest.fixture
def fn_mod():
return "tests/testdata/SW/ts_storm_4.dfs0"
@pytest.fixture
def fn_obs():
return "tests/testdata/SW/eur_Hm0.dfs0"
def test_com... | tests/test_simple_compare.py | import pytest
import numpy as np
from mikeio import Dfs0
from datetime import datetime
import fmskill
from fmskill.observation import PointObservation
@pytest.fixture
def fn_mod():
return "tests/testdata/SW/ts_storm_4.dfs0"
@pytest.fixture
def fn_obs():
return "tests/testdata/SW/eur_Hm0.dfs0"
def test_com... | 0.472927 | 0.572603 |
from django.http import HttpResponse
import cv2
import numpy as np
import requests
import datetime
import hashlib
import base64
import hmac
import json
import os
import glob
def uploadImg(request):
'''
上传图片并保存到当前目录下,便于后续处理;同时返回该图片数据,便于在页面上显示已经上传的图片
'''
if request.method == 'POST':
file_list = ... | backend/views.py | from django.http import HttpResponse
import cv2
import numpy as np
import requests
import datetime
import hashlib
import base64
import hmac
import json
import os
import glob
def uploadImg(request):
'''
上传图片并保存到当前目录下,便于后续处理;同时返回该图片数据,便于在页面上显示已经上传的图片
'''
if request.method == 'POST':
file_list = ... | 0.318909 | 0.160595 |
import re
class Token:
def __init__(self, t, v):
self.type = t
self.value = v
def __str__(self):
return 'Token = `{}\' : `{}\''.format(self.type, self.value)
class Lexer:
_keyword = ['let', 'def', 'if', 'elsif', 'else', 'end']
_literal = ['nil', 'true', 'false']
def __init_... | lexer.py | import re
class Token:
def __init__(self, t, v):
self.type = t
self.value = v
def __str__(self):
return 'Token = `{}\' : `{}\''.format(self.type, self.value)
class Lexer:
_keyword = ['let', 'def', 'if', 'elsif', 'else', 'end']
_literal = ['nil', 'true', 'false']
def __init_... | 0.359701 | 0.158793 |
import random
import math
import time
import threading
from PyQt5.QtChart import (QAreaSeries, QBarSet, QChart, QChartView,
QLineSeries, QPieSeries, QScatterSeries, QSplineSeries,
QStackedBarSeries, QValueAxis)
from PyQt5.QtCore import (
pyqtSlot, QPoint, QPoi... | no_use_files/test.py |
import random
import math
import time
import threading
from PyQt5.QtChart import (QAreaSeries, QBarSet, QChart, QChartView,
QLineSeries, QPieSeries, QScatterSeries, QSplineSeries,
QStackedBarSeries, QValueAxis)
from PyQt5.QtCore import (
pyqtSlot, QPoint, QPoi... | 0.325199 | 0.273526 |
import numpy as np
from ..cy.lib import maxDist,minDist
from copy import deepcopy
class molecule(object):
'''
Base molecule class. All molecules should inherit from this class
and call the stron
'''
def __init__(self):
self.placed=False
self.natoms=0
self.positions=[]
self.names=[]
self.t... | molecules/molecule.py | import numpy as np
from ..cy.lib import maxDist,minDist
from copy import deepcopy
class molecule(object):
'''
Base molecule class. All molecules should inherit from this class
and call the stron
'''
def __init__(self):
self.placed=False
self.natoms=0
self.positions=[]
self.names=[]
self.t... | 0.417628 | 0.179261 |
import json
from http import HTTPStatus
import tornado.gen as gen
from jupyterlab_pullrequests.manager import PullRequestsManager
from notebook.utils import url_path_join
from tornado.httpclient import AsyncHTTPClient, HTTPClientError, HTTPRequest
from tornado.httputil import url_concat
from tornado.web import HTTPErr... | jupyterlab_pullrequests/github_manager.py | import json
from http import HTTPStatus
import tornado.gen as gen
from jupyterlab_pullrequests.manager import PullRequestsManager
from notebook.utils import url_path_join
from tornado.httpclient import AsyncHTTPClient, HTTPClientError, HTTPRequest
from tornado.httputil import url_concat
from tornado.web import HTTPErr... | 0.344554 | 0.076857 |
import os
import sys
import time
import codecs
from logging import FileHandler
import logging.config
basedir = os.path.abspath(os.path.dirname(__file__))
logdir = os.path.join(basedir, 'logs')
logini_path = os.path.join(basedir, 'log.ini')
if not os.path.exists(logdir):
os.mkdir(logdir)
class SafeFileHandler(F... | wait/autotest.2020.03.16/log.py |
import os
import sys
import time
import codecs
from logging import FileHandler
import logging.config
basedir = os.path.abspath(os.path.dirname(__file__))
logdir = os.path.join(basedir, 'logs')
logini_path = os.path.join(basedir, 'log.ini')
if not os.path.exists(logdir):
os.mkdir(logdir)
class SafeFileHandler(F... | 0.342242 | 0.051106 |
from bs4 import BeautifulSoup
import logging
import time
import tweepy
import requests
from conf import settings
from services.twitter import config
log = logging.getLogger()
def send_tweets(tweets, delay):
"""
:param tweets:
:param delay:
:return:
"""
twitter_api = config.create_api()
... | services/twitter/utils.py |
from bs4 import BeautifulSoup
import logging
import time
import tweepy
import requests
from conf import settings
from services.twitter import config
log = logging.getLogger()
def send_tweets(tweets, delay):
"""
:param tweets:
:param delay:
:return:
"""
twitter_api = config.create_api()
... | 0.380183 | 0.081337 |
from django.conf import settings
from django.contrib import admin
from django.db.models import JSONField
from django import forms
from django.utils.html import mark_safe
from django_json_widget.widgets import JSONEditorWidget
from worlds.models import Pipeline, Job, StreamLog, CompletedLog, Cluster, NodePool
class ... | worlds/admin.py | from django.conf import settings
from django.contrib import admin
from django.db.models import JSONField
from django import forms
from django.utils.html import mark_safe
from django_json_widget.widgets import JSONEditorWidget
from worlds.models import Pipeline, Job, StreamLog, CompletedLog, Cluster, NodePool
class ... | 0.361277 | 0.075142 |
import os
from keystoneauth1.identity import v2
from keystoneauth1.identity import v3
from keystoneauth1 import session
# Assumes openrc file is sourced.
class Credentials(object):
def __init__(self):
self.password = None
self.username = None
self.tenant_name = None
self.auth_url... | openstack_client/cloud_orchestrator/credentials.py |
import os
from keystoneauth1.identity import v2
from keystoneauth1.identity import v3
from keystoneauth1 import session
# Assumes openrc file is sourced.
class Credentials(object):
def __init__(self):
self.password = None
self.username = None
self.tenant_name = None
self.auth_url... | 0.247351 | 0.048677 |
from spectre.readers import get_chromophore_peex_data
def test_m0_reader():
filename = "test/m0"
erg1, trd1, trm1, mo = get_chromophore_peex_data(filename, False)
assert type(erg1) == list
assert len(erg1) == 4
assert len(erg1) == len(trd1)
assert type(trm1) == dict
assert mo == -1 # no m... | test/test_readers.py | from spectre.readers import get_chromophore_peex_data
def test_m0_reader():
filename = "test/m0"
erg1, trd1, trm1, mo = get_chromophore_peex_data(filename, False)
assert type(erg1) == list
assert len(erg1) == 4
assert len(erg1) == len(trd1)
assert type(trm1) == dict
assert mo == -1 # no m... | 0.545044 | 0.803135 |
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import matplotlib
class ParameterScan (object):
def __init__(self, rr):
self.startTime = 0
sel... | tellurium/ParameterScan/ParameterScan.py | import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import matplotlib
class ParameterScan (object):
def __init__(self, rr):
self.startTime = 0
sel... | 0.688678 | 0.413803 |
import pytest
from mergify_engine import context
from mergify_engine import github_types
from mergify_engine import subscription
from mergify_engine import utils
from mergify_engine.clients import github
@pytest.mark.asyncio
async def test_user_permission_cache(redis_cache: utils.RedisCache) -> None:
class FakeC... | mergify_engine/tests/unit/test_context.py | import pytest
from mergify_engine import context
from mergify_engine import github_types
from mergify_engine import subscription
from mergify_engine import utils
from mergify_engine.clients import github
@pytest.mark.asyncio
async def test_user_permission_cache(redis_cache: utils.RedisCache) -> None:
class FakeC... | 0.456652 | 0.295916 |
import logging
from pymultimatic.model import (
Device,
Error,
OperatingModes,
QuickModes,
Room,
SettingModes,
SystemInfo,
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_LOCK,
DEVICE_CLASS_POWER,
DEV... | homeassistant/components/vaillant/binary_sensor.py |
import logging
from pymultimatic.model import (
Device,
Error,
OperatingModes,
QuickModes,
Room,
SettingModes,
SystemInfo,
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_LOCK,
DEVICE_CLASS_POWER,
DEV... | 0.799599 | 0.126947 |
"""Align trajectories to their average structure."""
import logging.config
import time
from pathlib import Path
from typing import Any
from typing import List
import click
import mdtraj as md
import numpy as np
from mdtraj.utils import in_units_of
from nptyping import Float
from nptyping import NDArray
from .. import... | src/qaa/commands/cmd_align.py | """Align trajectories to their average structure."""
import logging.config
import time
from pathlib import Path
from typing import Any
from typing import List
import click
import mdtraj as md
import numpy as np
from mdtraj.utils import in_units_of
from nptyping import Float
from nptyping import NDArray
from .. import... | 0.878301 | 0.334997 |
import sys
import Queue
from threading import Thread
__all__ = ['TasksRunner']
DEFAULT_WORKERS_NUMBER = 20
QUEUE_GET_TIMEOUT = 3
class TasksRunner(object):
def __init__(self, task_executor=None, max_workers=None, verbose=None,
daemonic_workers=True):
self._executor = task_executor
... | client/src/main/python/slipstream/utils/tasksrunner.py | import sys
import Queue
from threading import Thread
__all__ = ['TasksRunner']
DEFAULT_WORKERS_NUMBER = 20
QUEUE_GET_TIMEOUT = 3
class TasksRunner(object):
def __init__(self, task_executor=None, max_workers=None, verbose=None,
daemonic_workers=True):
self._executor = task_executor
... | 0.233881 | 0.098036 |
from __future__ import print_function
import numpy as np
def gen_noise(shape, prob=0.1, seed_layers=0):
"""Generate uniform noise data of requested shape"""
noise = (np.random.random_sample(shape) < prob).astype(np.int8)
noise[:,:seed_layers,:,:] = 0
return noise
def sample_track_params(n, num_det_la... | src/data_processing/toy3d.py | from __future__ import print_function
import numpy as np
def gen_noise(shape, prob=0.1, seed_layers=0):
"""Generate uniform noise data of requested shape"""
noise = (np.random.random_sample(shape) < prob).astype(np.int8)
noise[:,:seed_layers,:,:] = 0
return noise
def sample_track_params(n, num_det_la... | 0.754373 | 0.61173 |
from operator import mul
from functools import reduce
import sys
class BitStream:
def __init__(self, string, string_is_hex=True):
if string_is_hex:
nbits = 4 * len(string)
bigint = int(string,base=16)
string = f'{bigint:0{nbits}b}'
self.string = string
se... | 16/star.py | from operator import mul
from functools import reduce
import sys
class BitStream:
def __init__(self, string, string_is_hex=True):
if string_is_hex:
nbits = 4 * len(string)
bigint = int(string,base=16)
string = f'{bigint:0{nbits}b}'
self.string = string
se... | 0.290981 | 0.295933 |
import numpy
import cv2
from . import structure_block
import os
import csv
import kdtree
import time
import multiprocessing
import datetime
from math import ceil
def video_to_structure(path_to_video: str, destination_folder: str, name_prefix: str, path_to_palette: str = None, ticks_per_frame:int = 2, starting_frame: ... | minecraft_movie_player/image_converter.py | import numpy
import cv2
from . import structure_block
import os
import csv
import kdtree
import time
import multiprocessing
import datetime
from math import ceil
def video_to_structure(path_to_video: str, destination_folder: str, name_prefix: str, path_to_palette: str = None, ticks_per_frame:int = 2, starting_frame: ... | 0.38943 | 0.205057 |
import numpy as np
def compute_mean_terr(res, N, d, Σ, g, ε0):
"""Compute mean tracking error from a set of quantum measurements.
Parameters
----------
res: dict
Measurements from a quantum circuit in Qiskit format.
N: int
Number of available stocks.
d: int
Numb... | index_tracking/compute_tracking_error.py |
import numpy as np
def compute_mean_terr(res, N, d, Σ, g, ε0):
"""Compute mean tracking error from a set of quantum measurements.
Parameters
----------
res: dict
Measurements from a quantum circuit in Qiskit format.
N: int
Number of available stocks.
d: int
Numb... | 0.864982 | 0.81119 |
import unittest
import mock
from pyhpecw7.features.switchport import Switchport
from .base_feature_test import BaseFeatureCase
IFACE_INDEX = '9'
IFACE_NAME = 'FortyGigE1/0/3'
class SwitchportTestCase(BaseFeatureCase):
@mock.patch('pyhpecw7.comware.HPCOM7')
@mock.patch('pyhpecw7.features.switchport.Interfa... | test/unit/test_features/test_switchport.py | import unittest
import mock
from pyhpecw7.features.switchport import Switchport
from .base_feature_test import BaseFeatureCase
IFACE_INDEX = '9'
IFACE_NAME = 'FortyGigE1/0/3'
class SwitchportTestCase(BaseFeatureCase):
@mock.patch('pyhpecw7.comware.HPCOM7')
@mock.patch('pyhpecw7.features.switchport.Interfa... | 0.571288 | 0.30819 |
import sys
import glob
import os
from src import PARAMETERS as PM
import numpy as np
class Carla:
def __init__(self):
sys.path.insert(1, 'D:/Data/GitHub_Repos/carla_dist/WindowsNoEditor/PythonAPI/examples')
try:
sys.path.append(glob.glob
(
... | src/carla_interface.py | import sys
import glob
import os
from src import PARAMETERS as PM
import numpy as np
class Carla:
def __init__(self):
sys.path.insert(1, 'D:/Data/GitHub_Repos/carla_dist/WindowsNoEditor/PythonAPI/examples')
try:
sys.path.append(glob.glob
(
... | 0.233357 | 0.128717 |
from intcode import Intcode
with open("../input/day21.txt", 'r') as inputFile:
splitData = inputFile.read().split(",")
data = [int(x) for x in splitData]
runner = Intcode(verbose=False)
isVerbose = False
def runProgram(springscript: list, labels: str):
assert(len(springscript) <= 16)
inputStream =... | 2019/src/day21.py | from intcode import Intcode
with open("../input/day21.txt", 'r') as inputFile:
splitData = inputFile.read().split(",")
data = [int(x) for x in splitData]
runner = Intcode(verbose=False)
isVerbose = False
def runProgram(springscript: list, labels: str):
assert(len(springscript) <= 16)
inputStream =... | 0.31384 | 0.384046 |
import logging
from RouterConfiguration.Cisco.cisco_config_features import *
def get_index_from_args(router, feature, args):
"""
Generates the index (and thereby equivalence class) for parameter values passed to router feature triplets
:param router: Router for the current feature
:param feature: Con... | Evaluation/coverage.py | import logging
from RouterConfiguration.Cisco.cisco_config_features import *
def get_index_from_args(router, feature, args):
"""
Generates the index (and thereby equivalence class) for parameter values passed to router feature triplets
:param router: Router for the current feature
:param feature: Con... | 0.619932 | 0.432723 |
from django.db import models
from filingcabinet.models import (
AbstractDocument,
AbstractDocumentCollection,
DocumentManager as FCDocumentManager,
DocumentCollectionManager as FCDocumentCollectionManager,
get_page_image_filename,
Page,
)
from froide.helper.auth import (
can_read_object_au... | froide/document/models.py | from django.db import models
from filingcabinet.models import (
AbstractDocument,
AbstractDocumentCollection,
DocumentManager as FCDocumentManager,
DocumentCollectionManager as FCDocumentCollectionManager,
get_page_image_filename,
Page,
)
from froide.helper.auth import (
can_read_object_au... | 0.509276 | 0.102305 |
import pandas as pd
import numpy as np
import skimage
from tqdm import tqdm
import utils
class WindTurbinesDataset(utils.Dataset):
def load_samples(self, dataset_dir, subset, config):
"""Return the requested number of images.
count: number of images to generate.
height, width: the size o... | model/mrcnn/wind_turbines_dataset.py | import pandas as pd
import numpy as np
import skimage
from tqdm import tqdm
import utils
class WindTurbinesDataset(utils.Dataset):
def load_samples(self, dataset_dir, subset, config):
"""Return the requested number of images.
count: number of images to generate.
height, width: the size o... | 0.716516 | 0.433802 |
import struct
EOL = b"\x00"
# Integer limit unsigned short
STRING_LENGTH_MAX_VALUE = 65535
DATA_TYPE_ENCODERS = {
"float16": (16, struct.Struct("<e")),
"float32": (32, struct.Struct("<f")),
"float64": (64, struct.Struct("<d")),
"int16": (16, struct.Struct("<h")),
"int32": (32, struct.Struct("<i")... | binary/utils.py | import struct
EOL = b"\x00"
# Integer limit unsigned short
STRING_LENGTH_MAX_VALUE = 65535
DATA_TYPE_ENCODERS = {
"float16": (16, struct.Struct("<e")),
"float32": (32, struct.Struct("<f")),
"float64": (64, struct.Struct("<d")),
"int16": (16, struct.Struct("<h")),
"int32": (32, struct.Struct("<i")... | 0.76145 | 0.306903 |
import argparse
import logging
import mimetypes
import os
from pathlib import Path
from typing import Optional, Sequence
from monocat.github import AssetRequest, AssetResponse, GitHubClient, ReleaseRequest, ReleaseResponse
_logger = logging.getLogger(__name__)
class ReleaseError(RuntimeError):
"""A release erro... | monocat/__init__.py | import argparse
import logging
import mimetypes
import os
from pathlib import Path
from typing import Optional, Sequence
from monocat.github import AssetRequest, AssetResponse, GitHubClient, ReleaseRequest, ReleaseResponse
_logger = logging.getLogger(__name__)
class ReleaseError(RuntimeError):
"""A release erro... | 0.697918 | 0.050261 |
import argparse
import sys
import os
from collections import deque
from lophi.capture import CaptureReader
def parse_dcap(filename):
reader = CaptureReader(filename)
start = None
end = None
data_size = 0
window_data = deque([])
window_time = deque([])
window_sum = 0
... | experiments/artifacts/disk/parse_dcaps.py | import argparse
import sys
import os
from collections import deque
from lophi.capture import CaptureReader
def parse_dcap(filename):
reader = CaptureReader(filename)
start = None
end = None
data_size = 0
window_data = deque([])
window_time = deque([])
window_sum = 0
... | 0.216342 | 0.188866 |
import copy
from typing import List
from UM.Job import Job
from UM.Operations.GroupedOperation import GroupedOperation
from UM.Message import Message
from UM.Scene.SceneNode import SceneNode
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("cura")
from cura.Arranging.Arrange import Arrange
from cura.Arrang... | Cura/Cura/cura/MultiplyObjectsJob.py |
import copy
from typing import List
from UM.Job import Job
from UM.Operations.GroupedOperation import GroupedOperation
from UM.Message import Message
from UM.Scene.SceneNode import SceneNode
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("cura")
from cura.Arranging.Arrange import Arrange
from cura.Arrang... | 0.633637 | 0.222732 |
import torch.nn as nn
from .utils import standardize
class Conv_Block(nn.Module):
def __init__(self, input, filters, kernel_sizes, stride, padding, groups=1, name='', dilation=1,
bias=True, activation=nn.ReLU(), batch_norm=None, dropout=0, transpose=False):
super().__init__()
self.... | networks/blocks/conv_block.py | import torch.nn as nn
from .utils import standardize
class Conv_Block(nn.Module):
def __init__(self, input, filters, kernel_sizes, stride, padding, groups=1, name='', dilation=1,
bias=True, activation=nn.ReLU(), batch_norm=None, dropout=0, transpose=False):
super().__init__()
self.... | 0.955631 | 0.456652 |
import miRmedon_src
from miRmedon_src.alignment_to_emiRbase import alignment_to_emiRbase
from miRmedon_src.alignments_filter import main_alignments_filter
from miRmedon_src.count_filter import main_counts_filter
from miRmedon_src.consensus_generator import consensus_generator
from miRmedon_src.clusters_filter_bowtie im... | miRmedon.py | import miRmedon_src
from miRmedon_src.alignment_to_emiRbase import alignment_to_emiRbase
from miRmedon_src.alignments_filter import main_alignments_filter
from miRmedon_src.count_filter import main_counts_filter
from miRmedon_src.consensus_generator import consensus_generator
from miRmedon_src.clusters_filter_bowtie im... | 0.415136 | 0.102394 |
import unittest.mock as mock
import unittest
import pytest
import numpy as np
import tensorflow as tf
import yaml
from mlagents.trainers.ppo.models import PPOModel
from mlagents.trainers.ppo.trainer import PPOTrainer, discount_rewards
from mlagents.trainers.ppo.policy import PPOPolicy
from mlagents.trainers.rl_traine... | ml-agents/mlagents/trainers/tests/test_custom_layers.py | import unittest.mock as mock
import unittest
import pytest
import numpy as np
import tensorflow as tf
import yaml
from mlagents.trainers.ppo.models import PPOModel
from mlagents.trainers.ppo.trainer import PPOTrainer, discount_rewards
from mlagents.trainers.ppo.policy import PPOPolicy
from mlagents.trainers.rl_traine... | 0.636579 | 0.462837 |