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 csv
from django.contrib import admin
from vaas.manager.models import Director, Backend, Probe, TimeProfile
from vaas.manager.forms import DirectorModelForm
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from taggit.models import Tag
from taggit.admin import TagAdmin
fr... | vaas-app/src/vaas/manager/admin.py | import csv
from django.contrib import admin
from vaas.manager.models import Director, Backend, Probe, TimeProfile
from vaas.manager.forms import DirectorModelForm
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from taggit.models import Tag
from taggit.admin import TagAdmin
fr... | 0.410284 | 0.07538 |
from datetime import timedelta
import logging
from aiohttp.client_exceptions import ClientError
from pyeconet import EcoNetApiInterface
from pyeconet.equipment import EquipmentType
from pyeconet.errors import (
GenericHTTPError,
InvalidCredentialsError,
InvalidResponseFormat,
PyeconetError,
)
from ope... | openpeerpower/components/econet/__init__.py | from datetime import timedelta
import logging
from aiohttp.client_exceptions import ClientError
from pyeconet import EcoNetApiInterface
from pyeconet.equipment import EquipmentType
from pyeconet.errors import (
GenericHTTPError,
InvalidCredentialsError,
InvalidResponseFormat,
PyeconetError,
)
from ope... | 0.750553 | 0.079639 |
from flask_wtf import FlaskForm
from wtforms import SelectField, DecimalField, StringField, TextAreaField, DateField, FileField, MultipleFileField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length, Email, EqualTo
persons_choices = list(range(1,13)) # From 1 to 12 people choice
for i in ra... | ecommerce/forms.py | from flask_wtf import FlaskForm
from wtforms import SelectField, DecimalField, StringField, TextAreaField, DateField, FileField, MultipleFileField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length, Email, EqualTo
persons_choices = list(range(1,13)) # From 1 to 12 people choice
for i in ra... | 0.358129 | 0.199639 |
import ctypes
from numpy.ctypeslib import ndpointer
import os
import time
def getMatching_fast(numNodes,nodes1, nodes2, weights):
numEdges=len(nodes1);
PMlib=ctypes.CDLL("%s/PMlib.so"%"/".join((os.path.realpath(__file__)).split("/")[:-1]))
PMlib.pyMatching.argtypes = [ctypes.c_int,ctypes.c_int,ctypes.POINTER(... | project/CodePy2/extra/blossom5/pyMatch.py | import ctypes
from numpy.ctypeslib import ndpointer
import os
import time
def getMatching_fast(numNodes,nodes1, nodes2, weights):
numEdges=len(nodes1);
PMlib=ctypes.CDLL("%s/PMlib.so"%"/".join((os.path.realpath(__file__)).split("/")[:-1]))
PMlib.pyMatching.argtypes = [ctypes.c_int,ctypes.c_int,ctypes.POINTER(... | 0.119794 | 0.224013 |
# Export this package's modules as members:
from .accelerator import *
from .bandwidth_package import *
from .bandwidth_package_attachment import *
from .endpoint_group import *
from .forwarding_rule import *
from .get_accelerators import *
from .get_bandwidth_packages import *
from .get_endpoint_groups import *
from ... | sdk/python/pulumi_alicloud/ga/__init__.py |
# Export this package's modules as members:
from .accelerator import *
from .bandwidth_package import *
from .bandwidth_package_attachment import *
from .endpoint_group import *
from .forwarding_rule import *
from .get_accelerators import *
from .get_bandwidth_packages import *
from .get_endpoint_groups import *
from ... | 0.315841 | 0.066025 |
from datetime import datetime
from graph import Graph
class NearestNeighbour:
def __init__(self, start, graph):
'''
Solution of shortest path problem using nearest neighbour algorithm
'''
self.start = start
self.graph = graph
self.followedRoute = []
self.ro... | src/nearest_neighbour.py | from datetime import datetime
from graph import Graph
class NearestNeighbour:
def __init__(self, start, graph):
'''
Solution of shortest path problem using nearest neighbour algorithm
'''
self.start = start
self.graph = graph
self.followedRoute = []
self.ro... | 0.805594 | 0.495545 |
from __future__ import unicode_literals
"""Convienent utilities."""
# ## Imports
import sys
from codecs import iterencode
from inspect import isfunction, isclass
from operator import methodcaller
from collections import deque, namedtuple
from collections.abc import Sized, Iterable
from pkg_resources import iter_en... | cinje/util.py |
from __future__ import unicode_literals
"""Convienent utilities."""
# ## Imports
import sys
from codecs import iterencode
from inspect import isfunction, isclass
from operator import methodcaller
from collections import deque, namedtuple
from collections.abc import Sized, Iterable
from pkg_resources import iter_en... | 0.585694 | 0.291312 |
import hashlib
import base64
from glados.models import TinyURL
from elasticsearch_dsl import Search
from django.http import JsonResponse
from datetime import datetime, timedelta, timezone
from glados.usage_statistics import glados_server_statistics
from glados.models import ESTinyURLUsageRecord
from glados.es_connectio... | src/glados/api/chembl/url_shortening/url_shortener.py | import hashlib
import base64
from glados.models import TinyURL
from elasticsearch_dsl import Search
from django.http import JsonResponse
from datetime import datetime, timedelta, timezone
from glados.usage_statistics import glados_server_statistics
from glados.models import ESTinyURLUsageRecord
from glados.es_connectio... | 0.464416 | 0.101857 |
from __future__ import absolute_import, print_function, division
from uuid import uuid4
from random import Random
from itertools import product
from .hive import Hive
from .flower import Flower
from .game_state import rngs, GameState
from hiveminder._util import even_q_in_range as in_range
class SynchronousExecutor(o... | hiveminder/game.py | from __future__ import absolute_import, print_function, division
from uuid import uuid4
from random import Random
from itertools import product
from .hive import Hive
from .flower import Flower
from .game_state import rngs, GameState
from hiveminder._util import even_q_in_range as in_range
class SynchronousExecutor(o... | 0.621771 | 0.250638 |
from typing import Any
import pathlib
import json
import pytest
from _pytest.monkeypatch import MonkeyPatch
from django.utils import timezone
from django.conf import settings
from weather.libs.api.open_weather_map import OpenWeatherMap
from weather.libs.api.request_flow_controller import RequestFlowController
@pytest... | weather/tests/conftest.py | from typing import Any
import pathlib
import json
import pytest
from _pytest.monkeypatch import MonkeyPatch
from django.utils import timezone
from django.conf import settings
from weather.libs.api.open_weather_map import OpenWeatherMap
from weather.libs.api.request_flow_controller import RequestFlowController
@pytest... | 0.656438 | 0.239272 |
import tkinter as tk
from Data import Data
from EditClient import EditClient
class Client(tk.Frame):
def __init__(self, master=None, client_id=None):
super().__init__(master)
self.id = client_id
self.create_table()
def create_table(self):
global data
data = Data()
... | broker-manager/Client.py | import tkinter as tk
from Data import Data
from EditClient import EditClient
class Client(tk.Frame):
def __init__(self, master=None, client_id=None):
super().__init__(master)
self.id = client_id
self.create_table()
def create_table(self):
global data
data = Data()
... | 0.169303 | 0.137301 |
import numpy as np
import scipy as sp
import scipy.spatial
from ..point_set import PointSet
from ..misc.interior_points import find_interior_points
class Boundary(PointSet):
"""
Parent class for all "Boundaries"
This class should never be used directly
Always instantiate Boundaries through the child cl... | pybie2d/boundaries/boundary.py | import numpy as np
import scipy as sp
import scipy.spatial
from ..point_set import PointSet
from ..misc.interior_points import find_interior_points
class Boundary(PointSet):
"""
Parent class for all "Boundaries"
This class should never be used directly
Always instantiate Boundaries through the child cl... | 0.730866 | 0.356251 |
from __future__ import annotations
from typing import Dict
class BaseHoradricError(Exception):
"""
Base error for Horadric projects
"""
text_code: str = None
error_template: str = None
def __init_subclass__(cls, **kwargs):
if cls.text_code is None:
raise ValueError("`tex... | open_horadric_lib/base/exception.py | from __future__ import annotations
from typing import Dict
class BaseHoradricError(Exception):
"""
Base error for Horadric projects
"""
text_code: str = None
error_template: str = None
def __init_subclass__(cls, **kwargs):
if cls.text_code is None:
raise ValueError("`tex... | 0.709019 | 0.095687 |
import telebot
import socks, socket
import config
import time
import stats_getter
import image_maker
import db
import requests.exceptions as rqst_expts
print('modules imported')
bot = telebot.TeleBot(config.tg_token)
# socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '192.168.127.12', 1080)
telebot.apihelper.proxy = ... | main.py | import telebot
import socks, socket
import config
import time
import stats_getter
import image_maker
import db
import requests.exceptions as rqst_expts
print('modules imported')
bot = telebot.TeleBot(config.tg_token)
# socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '192.168.127.12', 1080)
telebot.apihelper.proxy = ... | 0.17692 | 0.142143 |
import re
class ModelInflector(object):
def __new__(cls, model):
try:
return _inflectors[cls]
except KeyError:
inflector = super(ModelInflector, cls).__new__(cls, model)
_inflectors[model] = inflector
return inflector
def __init__(self, model):
self.model = model
register_i... | src/ggrc/models/inflector.py | import re
class ModelInflector(object):
def __new__(cls, model):
try:
return _inflectors[cls]
except KeyError:
inflector = super(ModelInflector, cls).__new__(cls, model)
_inflectors[model] = inflector
return inflector
def __init__(self, model):
self.model = model
register_i... | 0.575588 | 0.168173 |
import pandas as pd
import numpy as np
from os import path
from copy import deepcopy
import argparse
import os
parser = argparse.ArgumentParser(description="Argparser for Pytorch 3D CNN")
# Mandatory arguments
parser.add_argument("generalist_model_path", type=str,
help="Path to the model trained o... | src/deep/fuse_cnn6layer.py | import pandas as pd
import numpy as np
from os import path
from copy import deepcopy
import argparse
import os
parser = argparse.ArgumentParser(description="Argparser for Pytorch 3D CNN")
# Mandatory arguments
parser.add_argument("generalist_model_path", type=str,
help="Path to the model trained o... | 0.604049 | 0.196132 |
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import kornia.augmentation as K
import pytorch_lightning as pl
import torch
import torchvision.transforms as T
from einops import rearrange
from kornia.contrib import compute_padding, extract_tensor_patches
from torch.utils.data import DataLoader, Datase... | torchgeo/datamodules/inria.py | from typing import Any, Dict, List, Optional, Tuple, Union, cast
import kornia.augmentation as K
import pytorch_lightning as pl
import torch
import torchvision.transforms as T
from einops import rearrange
from kornia.contrib import compute_padding, extract_tensor_patches
from torch.utils.data import DataLoader, Datase... | 0.962488 | 0.531027 |
__author__ = "<EMAIL> (Tim 'mithro' Ansell)"
import datetime
import json
import time
import urllib
import urllib2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--server", help="server to register on", action="store",
default="http://localhost:8000/tracker/endpoint/register")
parser.... | tools/register/fake_register.py | __author__ = "<EMAIL> (Tim 'mithro' Ansell)"
import datetime
import json
import time
import urllib
import urllib2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--server", help="server to register on", action="store",
default="http://localhost:8000/tracker/endpoint/register")
parser.... | 0.150465 | 0.081666 |
import os
import argparse
import torch
import rlcard
from rlcard.agents import RandomAgent
from rlcard.utils import get_device, set_seed, tournament, Logger, plot_curve
from Agent.HelperTwo import HelperAgent
from Utils import get_first, get_single, get_dead_actions, get_none_1_none, get_two_continue, get_1_gap, get_tw... | RLCardDQN.py | import os
import argparse
import torch
import rlcard
from rlcard.agents import RandomAgent
from rlcard.utils import get_device, set_seed, tournament, Logger, plot_curve
from Agent.HelperTwo import HelperAgent
from Utils import get_first, get_single, get_dead_actions, get_none_1_none, get_two_continue, get_1_gap, get_tw... | 0.550124 | 0.234275 |
import argparse
from colorama import Fore
import csv
import psycopg2
import psycopg2.extras
import re
import signal
import sys
def main():
# parse the command line arguments
parser = argparse.ArgumentParser(
description="Add ORCID identifiers to items for a given author name from CSV. Respects the au... | ilri/add-orcid-identifiers-csv.py |
import argparse
from colorama import Fore
import csv
import psycopg2
import psycopg2.extras
import re
import signal
import sys
def main():
# parse the command line arguments
parser = argparse.ArgumentParser(
description="Add ORCID identifiers to items for a given author name from CSV. Respects the au... | 0.380874 | 0.117623 |
from MoinMoin.script import MoinScript
class PluginScript(MoinScript):
"""\
Purpose:
========
This tool allows you to disable user accounts via a command line interface.
Detailed Instructions:
======================
General syntax: moin [options] account disable [disable-options]
[options] usually should be:
... | MoinMoin/script/account/disable.py | from MoinMoin.script import MoinScript
class PluginScript(MoinScript):
"""\
Purpose:
========
This tool allows you to disable user accounts via a command line interface.
Detailed Instructions:
======================
General syntax: moin [options] account disable [disable-options]
[options] usually should be:
... | 0.53437 | 0.113973 |
import torch
import torch.nn as nn
from hyper import cfg
class Conv2dAuto(nn.Conv2d):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.padding = (self.kernel_size[0] // 2, self.kernel_size[1] // 2)
def activation_func(activation):
return nn.ModuleDict([
[... | models.py | import torch
import torch.nn as nn
from hyper import cfg
class Conv2dAuto(nn.Conv2d):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.padding = (self.kernel_size[0] // 2, self.kernel_size[1] // 2)
def activation_func(activation):
return nn.ModuleDict([
[... | 0.923135 | 0.47524 |
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, Xilinx"
__email__ = "<EMAIL>"
from setuptools import setup, find_packages, Distribution
from setuptools.command.build_ext import build_ext
from distutils.file_util import copy_file
import os
# Requirement
required = [
'pynq>=2.6.0'
]
# Extend package files... | Pynq-ZU/packages/pcam5c/setup.py |
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, Xilinx"
__email__ = "<EMAIL>"
from setuptools import setup, find_packages, Distribution
from setuptools.command.build_ext import build_ext
from distutils.file_util import copy_file
import os
# Requirement
required = [
'pynq>=2.6.0'
]
# Extend package files... | 0.412175 | 0.067393 |
from typing import List
from .device import DeviceModel
from .gate import GateModel
from .room import RoomModel
from .sampleData import SampleDataModel
from .reciveData import ReciveDataModel
import json
import time
import copy
#Recive data format
#{"Gate":"BRAMKA2","Device":"DEVICE1","RSSI":-27}
class Tes... | src/db_interface/testData.py | from typing import List
from .device import DeviceModel
from .gate import GateModel
from .room import RoomModel
from .sampleData import SampleDataModel
from .reciveData import ReciveDataModel
import json
import time
import copy
#Recive data format
#{"Gate":"BRAMKA2","Device":"DEVICE1","RSSI":-27}
class Tes... | 0.529507 | 0.133387 |
import re,json,datetime,requests,encodings,os,weather,random
from multiprocessing import Process
from flask import Flask
from flask import request
import function,Baidu_Text_transAPI
def send_private_msg(user_id, message, group_id='', auto_escape='False'):
user_id = str(user_id)
message = str(message)
... | try.py | import re,json,datetime,requests,encodings,os,weather,random
from multiprocessing import Process
from flask import Flask
from flask import request
import function,Baidu_Text_transAPI
def send_private_msg(user_id, message, group_id='', auto_escape='False'):
user_id = str(user_id)
message = str(message)
... | 0.07922 | 0.047492 |
Modifiers = {
u'PR':0x0002,
u'PB':0x0001,
u'PRO':0x000,
u'AB':0x0400,
u'ST':0x0008,
u'FN':0x0010,
# don't think there are any with these values
u'OP':0x8000, # optional
u'HN':0x10000, # harness
u'GN':0x20000, # generator
u'AT':0x40000, # adt
}
Operators = {
u'OR'... | jskparser/ast/__init__.py | Modifiers = {
u'PR':0x0002,
u'PB':0x0001,
u'PRO':0x000,
u'AB':0x0400,
u'ST':0x0008,
u'FN':0x0010,
# don't think there are any with these values
u'OP':0x8000, # optional
u'HN':0x10000, # harness
u'GN':0x20000, # generator
u'AT':0x40000, # adt
}
Operators = {
u'OR'... | 0.401219 | 0.146789 |
import click
import torchvision.models.resnet as resnet
from artlearn.common_utils import (
LOG_DIR, MODEL_DIR,
get_dataloaders, ArtistLearner
)
@click.command()
@click.option('--mode', type=str, default='sgd',
help='Which optimizer you wish to use, currently supports '
'SGD ... | artlearn/cli/command.py | import click
import torchvision.models.resnet as resnet
from artlearn.common_utils import (
LOG_DIR, MODEL_DIR,
get_dataloaders, ArtistLearner
)
@click.command()
@click.option('--mode', type=str, default='sgd',
help='Which optimizer you wish to use, currently supports '
'SGD ... | 0.751648 | 0.109777 |
import logging
import unittest
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.executive_mock import MockExecutive2
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.common.system.systemhost_mock import MockSystemHost
from webkitpy.port import P... | Tools/Scripts/webkitpy/port/xvfbdriver_unittest.py |
import logging
import unittest
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.executive_mock import MockExecutive2
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.common.system.systemhost_mock import MockSystemHost
from webkitpy.port import P... | 0.596786 | 0.260683 |
# standard library imports
from string import ascii_uppercase, digits
from typing import Tuple
# third-party imports
from iso3166 import countries
# local imports
from .identifier import Identifier
from .luhn import luhn
from .micutils import get_mic_record
_ALPHABET = digits + ascii_uppercase
class MIC(Identifie... | src/identifiers/finance.py | # standard library imports
from string import ascii_uppercase, digits
from typing import Tuple
# third-party imports
from iso3166 import countries
# local imports
from .identifier import Identifier
from .luhn import luhn
from .micutils import get_mic_record
_ALPHABET = digits + ascii_uppercase
class MIC(Identifie... | 0.915639 | 0.540985 |
import numpy as np
import matplotlib.pyplot as plt
from . import transform
def plot_pulse(pulse, m=1000, ptype='ex', phase='linear',
omega_range=[-np.pi, np.pi],
linewidth=2, fontsize='x-large', labelsize='large'):
figs = []
n = len(pulse)
fig, ax = plt.subplots()
ax.plot... | slfrank/plot.py | import numpy as np
import matplotlib.pyplot as plt
from . import transform
def plot_pulse(pulse, m=1000, ptype='ex', phase='linear',
omega_range=[-np.pi, np.pi],
linewidth=2, fontsize='x-large', labelsize='large'):
figs = []
n = len(pulse)
fig, ax = plt.subplots()
ax.plot... | 0.682891 | 0.657525 |
"""Command line options."""
import click
from renku.core.errors import RenkuException
from .git import set_git_isolation
def install_completion(ctx, attr, value): # pragma: no cover
"""Install completion for the current shell."""
import click_completion.core
if not value or ctx.resilient_parsing:
... | renku/core/commands/options.py | """Command line options."""
import click
from renku.core.errors import RenkuException
from .git import set_git_isolation
def install_completion(ctx, attr, value): # pragma: no cover
"""Install completion for the current shell."""
import click_completion.core
if not value or ctx.resilient_parsing:
... | 0.715722 | 0.276346 |
import os
import tempfile
import time
import genomepy.utils
import pysam
import ananse.utils
# prep
test_dir = os.path.dirname(os.path.dirname(__file__))
outdir = os.path.join(test_dir, "output")
genomepy.utils.mkdir_p(outdir)
def write_file(filename, lines):
with open(filename, "w") as f:
for line in... | tests/continuous_integration/test_02_utils.py | import os
import tempfile
import time
import genomepy.utils
import pysam
import ananse.utils
# prep
test_dir = os.path.dirname(os.path.dirname(__file__))
outdir = os.path.join(test_dir, "output")
genomepy.utils.mkdir_p(outdir)
def write_file(filename, lines):
with open(filename, "w") as f:
for line in... | 0.375134 | 0.412767 |
from unittest.mock import Mock
import pytest
from fastapi import HTTPException, status
from tests.unit.time_manager.helpers import get_token_from_user
from time_manager.db.sql.user import User
from time_manager.routers.common import get_user_dao, oauth2_scheme
from time_manager.schemas.user import UserDB
from time_ma... | tests/unit/time_manager/routers/test_auth.py | from unittest.mock import Mock
import pytest
from fastapi import HTTPException, status
from tests.unit.time_manager.helpers import get_token_from_user
from time_manager.db.sql.user import User
from time_manager.routers.common import get_user_dao, oauth2_scheme
from time_manager.schemas.user import UserDB
from time_ma... | 0.707607 | 0.298095 |
import pandas as pd
import lightgbm as lgb
from sklearn.metrics import roc_auc_score
from Utils import Profiler
from IPython.display import display
from Estimators import LGBM
profile = Profiler()
profile.Start()
print("Loading resampled train data")
train_X = pd.read_csv("../input/AllData_v4_os.train")
train_X.pop("... | LightGBM_AllData_v4_OS_CV_GS.py | import pandas as pd
import lightgbm as lgb
from sklearn.metrics import roc_auc_score
from Utils import Profiler
from IPython.display import display
from Estimators import LGBM
profile = Profiler()
profile.Start()
print("Loading resampled train data")
train_X = pd.read_csv("../input/AllData_v4_os.train")
train_X.pop("... | 0.331228 | 0.141489 |
import unittest, sys
from PyQt4 import QtCore, QtGui
from datafinder.core.search_restriction import SearchRestrictionParser
from datafinder.gui.user.dialogs.search_dialog.search_query_editor import SearchQueryEditor, SearchQueryAnalyzer
__version__ = "$Revision-Id:$"
class SearchQueryEditorTestCase(unittest.Tes... | test/unittest/datafinder_test/gui/user/dialogs/search_dialog/search_query_editor_test.py | import unittest, sys
from PyQt4 import QtCore, QtGui
from datafinder.core.search_restriction import SearchRestrictionParser
from datafinder.gui.user.dialogs.search_dialog.search_query_editor import SearchQueryEditor, SearchQueryAnalyzer
__version__ = "$Revision-Id:$"
class SearchQueryEditorTestCase(unittest.Tes... | 0.502686 | 0.203727 |
from unittest import TestCase,mock
from http import HTTPStatus
from gw_proxy._to_sync.anish_agarwal.API_SaaS_VPS_Client import API_SaaS_VPS_Client
class test_Rest_API_SaaS_VPs(TestCase):
@mock.patch('requests.get')
def test_proxy_for_brotli_encoded_sites(self, mockget):
# Mock response
headers... | tests/_to_sync/anish_agarwal/test_Rest_API__SaaS_VPs.py | from unittest import TestCase,mock
from http import HTTPStatus
from gw_proxy._to_sync.anish_agarwal.API_SaaS_VPS_Client import API_SaaS_VPS_Client
class test_Rest_API_SaaS_VPs(TestCase):
@mock.patch('requests.get')
def test_proxy_for_brotli_encoded_sites(self, mockget):
# Mock response
headers... | 0.437223 | 0.153771 |
import unittest
import sys
import json
from unittest import TestCase
from ovs.lib.tests.mockups import StorageDriverModule, StorageDriverClient
from ovs.plugin.provider.configuration import Configuration
from ovs.extensions.storage.persistentfactory import PersistentFactory
from ovs.extensions.storage.persistent.dummys... | ovs/lib/tests/test_mdsservice.py | import unittest
import sys
import json
from unittest import TestCase
from ovs.lib.tests.mockups import StorageDriverModule, StorageDriverClient
from ovs.plugin.provider.configuration import Configuration
from ovs.extensions.storage.persistentfactory import PersistentFactory
from ovs.extensions.storage.persistent.dummys... | 0.459561 | 0.294481 |
from multiprocessing.sharedctypes import Value
from pprint import pprint
import cv2
import numpy as np
from functools import cached_property
from itertools import count
from collections import defaultdict
from skimage.metrics import structural_similarity as ssim
from tuning import hyperparams
# Used to assign unique i... | lib.py | from multiprocessing.sharedctypes import Value
from pprint import pprint
import cv2
import numpy as np
from functools import cached_property
from itertools import count
from collections import defaultdict
from skimage.metrics import structural_similarity as ssim
from tuning import hyperparams
# Used to assign unique i... | 0.799638 | 0.443962 |
import numpy as np
import warnings
class ObjectiveFunction( object ):
"""
The `ObjectiveFunction` class defines an objective function.
"""
def __init__(self,definition=None):
self.definition = definition
self.parameters = []
self.global_minimum = None
self.subject_to... | src/picasso/utils/optimization/objective_functions.py | import numpy as np
import warnings
class ObjectiveFunction( object ):
"""
The `ObjectiveFunction` class defines an objective function.
"""
def __init__(self,definition=None):
self.definition = definition
self.parameters = []
self.global_minimum = None
self.subject_to... | 0.62395 | 0.336195 |
from __future__ import division
import math
import types
import torch
import utils
import random
import numbers
import numpy as np
import scipy as sp
from scipy import misc
from PIL import Image, ImageOps, ImageDraw
class Compose(object):
"""Composes several transforms together.
Args:
transforms (List[Transfo... | datasets/transforms.py |
from __future__ import division
import math
import types
import torch
import utils
import random
import numbers
import numpy as np
import scipy as sp
from scipy import misc
from PIL import Image, ImageOps, ImageDraw
class Compose(object):
"""Composes several transforms together.
Args:
transforms (List[Transfo... | 0.543833 | 0.471832 |
import logging
from lxml import etree
try:
from PIL import Image
except ImportError:
import Image
import zipfile
import shutil
import os
from os.path import join
import tempfile
from namespaces import nsprefixes
from StringIO import StringIO
log = logging.getLogger(__name__)
# Record template directory's loca... | openxml/pptx.py | import logging
from lxml import etree
try:
from PIL import Image
except ImportError:
import Image
import zipfile
import shutil
import os
from os.path import join
import tempfile
from namespaces import nsprefixes
from StringIO import StringIO
log = logging.getLogger(__name__)
# Record template directory's loca... | 0.267983 | 0.084041 |
import os
import warnings
import logging
import re
from typing import Dict, Union, List, Any, NoReturn
from aitool.datasets import PATH as DATA_PATH
from aitool import is_file_exist, load_lines, prepare_data, load_json
chinese_family_name = set()
File_Bag = ['https://pcg-xyj-1258344701.cos.ap-guangzhou.myqcloud.com/a... | aitool/task_customized/ip_enhance/filter.py | import os
import warnings
import logging
import re
from typing import Dict, Union, List, Any, NoReturn
from aitool.datasets import PATH as DATA_PATH
from aitool import is_file_exist, load_lines, prepare_data, load_json
chinese_family_name = set()
File_Bag = ['https://pcg-xyj-1258344701.cos.ap-guangzhou.myqcloud.com/a... | 0.483648 | 0.10786 |
import logging
from copy import deepcopy
from typing import Optional
import numpy as np
import scipy.linalg as linalg
from ...misc import restack
from ...misc import unstack
from ...model.dynamical_system.boundary_value_problem import MultipleBoundaryValueProblem
from ...model.dynamical_system.flow_problem import Lin... | src/pymloc/solvers/dynamical_systems/multiple_shooting.py | import logging
from copy import deepcopy
from typing import Optional
import numpy as np
import scipy.linalg as linalg
from ...misc import restack
from ...misc import unstack
from ...model.dynamical_system.boundary_value_problem import MultipleBoundaryValueProblem
from ...model.dynamical_system.flow_problem import Lin... | 0.76555 | 0.282833 |
import numpy as np
import cbh
def test_fragmentation_cbh1():
test_smiles = "C1=C[C@H]2C[C@@H]1CC2"
assert sorted(cbh.get_components_scheme1(test_smiles)) == sorted("CC C=C CC CC CC CC CC CC".split())
return
def test_fragmentation_cbh2():
test_smiles = "C1=C[C@H]2C[C@@H]1CC2"
assert sorted(cbh.get_... | test.py | import numpy as np
import cbh
def test_fragmentation_cbh1():
test_smiles = "C1=C[C@H]2C[C@@H]1CC2"
assert sorted(cbh.get_components_scheme1(test_smiles)) == sorted("CC C=C CC CC CC CC CC CC".split())
return
def test_fragmentation_cbh2():
test_smiles = "C1=C[C@H]2C[C@@H]1CC2"
assert sorted(cbh.get_... | 0.760828 | 0.456834 |
import subprocess, json, re, csv, sys, functools
from jubatus.recommender import client
from jubatus.recommender import types
from jubatus.common import Datum
def partial_commit_json():
dump =subprocess.check_output( ['git', 'log', '--pretty=format:{%n \"commit\": \"%H\",%n \"author\": \"%an <%ae>\",%n \"date\... | gitlog_json_print.py |
import subprocess, json, re, csv, sys, functools
from jubatus.recommender import client
from jubatus.recommender import types
from jubatus.common import Datum
def partial_commit_json():
dump =subprocess.check_output( ['git', 'log', '--pretty=format:{%n \"commit\": \"%H\",%n \"author\": \"%an <%ae>\",%n \"date\... | 0.174868 | 0.12692 |
from django.shortcuts import render
from helpers import download
import pandas as pd
import os
cwd = os.getcwd()
perf_data_path = cwd + "/perf_data/"
current_release = [os.getenv('CUR_RELEASE')]
# Create your views here.
def monitoring_overview(request):
return render(request, "monitoring_overview.html")
def... | perf_dashboard/regressions/views.py |
from django.shortcuts import render
from helpers import download
import pandas as pd
import os
cwd = os.getcwd()
perf_data_path = cwd + "/perf_data/"
current_release = [os.getenv('CUR_RELEASE')]
# Create your views here.
def monitoring_overview(request):
return render(request, "monitoring_overview.html")
def... | 0.353205 | 0.147647 |
import argparse
import logging
from opti_models.benchmarks.imagenet_torch_benchmark import main
logging.basicConfig(level=logging.INFO)
def parse_args():
# Default args
path = "/usr/local/opti_models/imagenetv2-top-images-format-val"
parser = argparse.ArgumentParser(description='Simple speed benchmark,... | tests/t_bench_torch.py | import argparse
import logging
from opti_models.benchmarks.imagenet_torch_benchmark import main
logging.basicConfig(level=logging.INFO)
def parse_args():
# Default args
path = "/usr/local/opti_models/imagenetv2-top-images-format-val"
parser = argparse.ArgumentParser(description='Simple speed benchmark,... | 0.433022 | 0.129375 |
import discord
import datetime
import time
import psutil
import sys
from discord.ext import commands
start_time = time.time()
class Utility(commands.Cog):
def __init__(self, bot):
self.bot = bot
# def restart_program():
# python = sys.executable
# os.execl(python... | plugins/utility.py | import discord
import datetime
import time
import psutil
import sys
from discord.ext import commands
start_time = time.time()
class Utility(commands.Cog):
def __init__(self, bot):
self.bot = bot
# def restart_program():
# python = sys.executable
# os.execl(python... | 0.184915 | 0.053675 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['PipelineArgs', 'Pipeline']
@pulumi.input_type
class PipelineArgs:
def __init__(__self__, *,
is_exposed: pulumi.Input[bool],
... | sdk/python/pulumiverse_concourse/pipeline.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['PipelineArgs', 'Pipeline']
@pulumi.input_type
class PipelineArgs:
def __init__(__self__, *,
is_exposed: pulumi.Input[bool],
... | 0.832883 | 0.058158 |
import argparse
import asyncio
from datetime import datetime
import logging
from bncs import BnetClient, ChatEventType, ClientStatus, LocalHashingProvider, BncsProduct
class SampleBnetClient(BnetClient):
async def _handle_chat_event(self, packet):
event = await super()._handle_chat_event(packet)
... | scripts/bncs_client.py | import argparse
import asyncio
from datetime import datetime
import logging
from bncs import BnetClient, ChatEventType, ClientStatus, LocalHashingProvider, BncsProduct
class SampleBnetClient(BnetClient):
async def _handle_chat_event(self, packet):
event = await super()._handle_chat_event(packet)
... | 0.273671 | 0.158597 |
import sys, threading, time, random, socket
def server():
# Establish port via command-line argument
port = int(sys.argv[1])
# Create file object to read RS DNS table
RSFile = open("PROJI-DNSRS.txt", "r")
# Initialize dictionary for DNS table
DNSTable = {}
# Store RS DN... | anthonyProject1/rs.py |
import sys, threading, time, random, socket
def server():
# Establish port via command-line argument
port = int(sys.argv[1])
# Create file object to read RS DNS table
RSFile = open("PROJI-DNSRS.txt", "r")
# Initialize dictionary for DNS table
DNSTable = {}
# Store RS DN... | 0.228156 | 0.063657 |
import os
import pytest
from click.testing import CliRunner
from cogctl.cli.main import cli
from functools import partial
@pytest.fixture
def cogctl():
"""Set up a test runner from the true root of the application, instead
of testing individual commands directly.
"""
runner = CliRunner()
with run... | tests/cogctl/cli/test_profile.py | import os
import pytest
from click.testing import CliRunner
from cogctl.cli.main import cli
from functools import partial
@pytest.fixture
def cogctl():
"""Set up a test runner from the true root of the application, instead
of testing individual commands directly.
"""
runner = CliRunner()
with run... | 0.441191 | 0.297052 |
from __future__ import annotations
from bfassist.sql import *
from bfassist.master.league import LeaguePlayers, LeaguePlayer, LineUp
# noinspection PyUnusedLocal
def __preload__(forClient: bool = True):
pass
# noinspection PyUnusedLocal
def __postload__(forClient: bool = True):
pass
def pyPlayerToSQL(inP... | bfassist/master/league/teams.py | from __future__ import annotations
from bfassist.sql import *
from bfassist.master.league import LeaguePlayers, LeaguePlayer, LineUp
# noinspection PyUnusedLocal
def __preload__(forClient: bool = True):
pass
# noinspection PyUnusedLocal
def __postload__(forClient: bool = True):
pass
def pyPlayerToSQL(inP... | 0.551815 | 0.143038 |
import os
from datetime import date
from django.core.management import setup_environ
try:
from scielomanager import settings
except ImportError:
BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
BASE_PATH_APP = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '.... | scielomanager/tools/import_data/importer.py | import os
from datetime import date
from django.core.management import setup_environ
try:
from scielomanager import settings
except ImportError:
BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
BASE_PATH_APP = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '.... | 0.339061 | 0.084417 |
import copy
class Layer(object):
def __init__(self, medium, thickness, name="Unnamed Layer"):
self.thickness = thickness
self.medium = copy.deepcopy(medium)
self.name = name
self.hooks = {
'pre_update_frequency': []
}
def update_frequency(self, omega):
... | pymls/layers/layer.py |
import copy
class Layer(object):
def __init__(self, medium, thickness, name="Unnamed Layer"):
self.thickness = thickness
self.medium = copy.deepcopy(medium)
self.name = name
self.hooks = {
'pre_update_frequency': []
}
def update_frequency(self, omega):
... | 0.812682 | 0.317347 |
from Canvas import *
from math import *
def split_cities(filename):
# Reading in a file and parsing the data before storing each specific part of the data in a list of dictionaries.
city = []
f = open(filename, "r")
line = f.readline()
while line != "":
line = line[:-1]
... | nearestneighbour.py | from Canvas import *
from math import *
def split_cities(filename):
# Reading in a file and parsing the data before storing each specific part of the data in a list of dictionaries.
city = []
f = open(filename, "r")
line = f.readline()
while line != "":
line = line[:-1]
... | 0.532425 | 0.515986 |
import os
from PyQt5.QtGui import QIcon, QCloseEvent
from PyQt5.QtWidgets import QDesktopWidget, QMainWindow, QStackedWidget, QFileDialog, QWidget
from src.controller_factory import ControllerFactory
from src.message_type import MessageType
from src.rocket_packet.rocket_packet_parser_factory import RocketPacketVersio... | BaseStation/src/ui/mainwindow.py | import os
from PyQt5.QtGui import QIcon, QCloseEvent
from PyQt5.QtWidgets import QDesktopWidget, QMainWindow, QStackedWidget, QFileDialog, QWidget
from src.controller_factory import ControllerFactory
from src.message_type import MessageType
from src.rocket_packet.rocket_packet_parser_factory import RocketPacketVersio... | 0.212968 | 0.060863 |
import unittest
import webtest
import json
from models.questions import QuestionRepository
from handlers.items.items_json import ItemsJSON
from handlers.items.new_item import NewItem
from handlers.items.add_more import AddMore
from handlers.items.update import Update
from handlers.helpers import Ready
import main
c... | Support/GoogleAppEngineAppMock/handlers/items/tests/test_items.py | import unittest
import webtest
import json
from models.questions import QuestionRepository
from handlers.items.items_json import ItemsJSON
from handlers.items.new_item import NewItem
from handlers.items.add_more import AddMore
from handlers.items.update import Update
from handlers.helpers import Ready
import main
c... | 0.490968 | 0.331904 |
from __future__ import print_function
import os
import shutil
import sys
import time
from unittest import TestCase
import unittest
from sitcpy.cui import CuiServer, SessionThread, CommandClient
from sitcpy.rbcp_server import default_pseudo_arg_parser, RbcpServer,\
PseudoDevice
from sitcpy.templates.cui_project im... | tests/test_cui_project.py | from __future__ import print_function
import os
import shutil
import sys
import time
from unittest import TestCase
import unittest
from sitcpy.cui import CuiServer, SessionThread, CommandClient
from sitcpy.rbcp_server import default_pseudo_arg_parser, RbcpServer,\
PseudoDevice
from sitcpy.templates.cui_project im... | 0.301568 | 0.121842 |
import logging
import os
import time
from socket import gethostname
from flask import g, Flask, jsonify, request, send_from_directory, render_template
from werkzeug.middleware.proxy_fix import ProxyFix
from wbc.exceptions import WBCApiError, WBCHtmlError
from wbc.views.healthcheck import Healthcheck
from wbc.views.... | app/wbc/__init__.py | import logging
import os
import time
from socket import gethostname
from flask import g, Flask, jsonify, request, send_from_directory, render_template
from werkzeug.middleware.proxy_fix import ProxyFix
from wbc.exceptions import WBCApiError, WBCHtmlError
from wbc.views.healthcheck import Healthcheck
from wbc.views.... | 0.350088 | 0.047448 |
def sisalampotila():
sisanyt = tempread.read_temp_in()
return sisanyt
def main(day, month, year, hour):
# Setup-osa
import lukeminen
#Muodostetaan str-tyyppinen päiväys muodossa "dd.mm.yy" Nordpoolin hintatietojen lukemiseksi
if day < 10:
day = str(day)
day = str("0"+day)
... | tulkinta.py | def sisalampotila():
sisanyt = tempread.read_temp_in()
return sisanyt
def main(day, month, year, hour):
# Setup-osa
import lukeminen
#Muodostetaan str-tyyppinen päiväys muodossa "dd.mm.yy" Nordpoolin hintatietojen lukemiseksi
if day < 10:
day = str(day)
day = str("0"+day)
... | 0.128881 | 0.26011 |
import numpy
def fill_in_zeros(fwd_rvs_align_list, ref_len, nt):
"""
Generate alignment counts for every nucleotide in the reference
:param fwd_rvs_align_list: list of sorted forwards and reverse alignments
:param ref_len: number of nucleotides in the reference sequence (int)
:param nt: length of... | scram_modules/post_process.py | import numpy
def fill_in_zeros(fwd_rvs_align_list, ref_len, nt):
"""
Generate alignment counts for every nucleotide in the reference
:param fwd_rvs_align_list: list of sorted forwards and reverse alignments
:param ref_len: number of nucleotides in the reference sequence (int)
:param nt: length of... | 0.646125 | 0.468912 |
import collections
import boto3
import botocore
import logging
import os
import uuid
logger = logging.getLogger(__name__)
def downloadFile(srcFile, destFile):
''' Download file from S3 '''
s3 = boto3.resource('s3')
bucket, key = find_bucket_key(srcFile)
try:
s3.meta.client.download_file(bucket... | common.py | import collections
import boto3
import botocore
import logging
import os
import uuid
logger = logging.getLogger(__name__)
def downloadFile(srcFile, destFile):
''' Download file from S3 '''
s3 = boto3.resource('s3')
bucket, key = find_bucket_key(srcFile)
try:
s3.meta.client.download_file(bucket... | 0.341363 | 0.109658 |
import tensorflow as tf
import numpy as np
class PatrollerValue(object):
def __init__(self, args, scope):
with tf.variable_scope(scope):
self.args = args
self.row_num = self.args.row_num
self.column_num = self.args.column_num
self.in_channel = self.args.pa_s... | AC_patroller/patroller_value_network.py | import tensorflow as tf
import numpy as np
class PatrollerValue(object):
def __init__(self, args, scope):
with tf.variable_scope(scope):
self.args = args
self.row_num = self.args.row_num
self.column_num = self.args.column_num
self.in_channel = self.args.pa_s... | 0.819026 | 0.31258 |
import json
import math
import os
from bnlcrl import visualize as vis
from bnlcrl.utils import convert_types, defaults_file, read_json
parms = defaults_file(suffix='delta')
DAT_DIR = parms['dat_dir']
CONFIG_DIR = parms['config_dir']
DEFAULTS_FILE = parms['defaults_file']
class DeltaFinder:
def __init__(self, **... | bnlcrl/delta_finder.py | import json
import math
import os
from bnlcrl import visualize as vis
from bnlcrl.utils import convert_types, defaults_file, read_json
parms = defaults_file(suffix='delta')
DAT_DIR = parms['dat_dir']
CONFIG_DIR = parms['config_dir']
DEFAULTS_FILE = parms['defaults_file']
class DeltaFinder:
def __init__(self, **... | 0.418222 | 0.19475 |
import logging
from . import mixin
from . import core
from . import Constructs
from .decorators import (
_display_or_return,
_inplace_enabled,
_inplace_enabled_define_and_cleanup,
_manage_log_level_via_verbosity,
)
logger = logging.getLogger(__name__)
class Domain(mixin.FieldDomain, mixin.Contain... | cfdm/domain.py | import logging
from . import mixin
from . import core
from . import Constructs
from .decorators import (
_display_or_return,
_inplace_enabled,
_inplace_enabled_define_and_cleanup,
_manage_log_level_via_verbosity,
)
logger = logging.getLogger(__name__)
class Domain(mixin.FieldDomain, mixin.Contain... | 0.830525 | 0.406037 |
from unittest import TestCase, main
from tempfile import mkstemp
from os import close, remove
from os.path import exists
import pandas as pd
from qiita_core.util import qiita_test_checker
import qiita_db as qdb
@qiita_test_checker()
class TestSQL(TestCase):
"""Tests that the database triggers and procedures wo... | qiita_db/test/test_sql.py |
from unittest import TestCase, main
from tempfile import mkstemp
from os import close, remove
from os.path import exists
import pandas as pd
from qiita_core.util import qiita_test_checker
import qiita_db as qdb
@qiita_test_checker()
class TestSQL(TestCase):
"""Tests that the database triggers and procedures wo... | 0.539226 | 0.364806 |
from melody.constraints.abstract_constraint import AbstractConstraint
from structure.note import Note
from tonalmodel.chromatic_scale import ChromaticScale
from tonalmodel.diatonic_pitch import DiatonicPitch
class ScalarPitchConstraint(AbstractConstraint):
"""
Class representing constraints to ensure some one... | melody/constraints/scalar_pitch_constraint.py | from melody.constraints.abstract_constraint import AbstractConstraint
from structure.note import Note
from tonalmodel.chromatic_scale import ChromaticScale
from tonalmodel.diatonic_pitch import DiatonicPitch
class ScalarPitchConstraint(AbstractConstraint):
"""
Class representing constraints to ensure some one... | 0.93488 | 0.459197 |
import argparse
import os
from os.path import abspath, dirname, join
import re
from typing import Tuple
import pandas as pd
from ncmagics import japanmap
def parse_args() -> dict:
"""parse_args.
Set directory path from stdin.
Args:
Returns:
dict:
"""
parser = argparse.ArgumentParser()... | main/plotcyclone_loc_dir.py | import argparse
import os
from os.path import abspath, dirname, join
import re
from typing import Tuple
import pandas as pd
from ncmagics import japanmap
def parse_args() -> dict:
"""parse_args.
Set directory path from stdin.
Args:
Returns:
dict:
"""
parser = argparse.ArgumentParser()... | 0.549641 | 0.213142 |
import unittest
import logging
# project
from stackstate_checks.splunk.config import SplunkInstanceConfig, SplunkSavedSearch
from stackstate_checks.splunk.client import FinalizeException
from test_splunk_instance_config import MockedCommittableState, mock_defaults
from stackstate_checks.splunk.saved_search_helper impo... | splunk_base/tests/test_saved_search_helper.py | import unittest
import logging
# project
from stackstate_checks.splunk.config import SplunkInstanceConfig, SplunkSavedSearch
from stackstate_checks.splunk.client import FinalizeException
from test_splunk_instance_config import MockedCommittableState, mock_defaults
from stackstate_checks.splunk.saved_search_helper impo... | 0.603114 | 0.219526 |
from shutil import copytree, move
from tempfile import TemporaryDirectory
from pathlib import Path
from unittest import skip
from capanno_utils.repo_config import tools_dir_name
from tests.test_base import TestBase
from capanno_utils.add_content import main as add_content_main
from capanno_utils.helpers.get_paths impor... | tests/test_add_content.py | from shutil import copytree, move
from tempfile import TemporaryDirectory
from pathlib import Path
from unittest import skip
from capanno_utils.repo_config import tools_dir_name
from tests.test_base import TestBase
from capanno_utils.add_content import main as add_content_main
from capanno_utils.helpers.get_paths impor... | 0.386416 | 0.176476 |
import tkinter as tk
import tkinter.ttk as ttk
import TestUrl
import sys
import tkinter.filedialog
import Tools
class TestUrlFrame(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.root = master
self.param1_filepath = tk.StringVar()
self.param2_filep... | TestUrlFrame.py | import tkinter as tk
import tkinter.ttk as ttk
import TestUrl
import sys
import tkinter.filedialog
import Tools
class TestUrlFrame(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.root = master
self.param1_filepath = tk.StringVar()
self.param2_filep... | 0.145692 | 0.109135 |
import argparse
import glob
import json
import os
import shutil
from q2t.thermo import get_thermo
from q2t.qchem import QChem
from q2t.mol import str_to_rmg_mol, geo_to_rmg_mol, geo_to_xyz_str
def main():
args = parse_args()
if args.bacs is not None:
with open(args.bacs) as f:
bacs = js... | compute_thermo.py |
import argparse
import glob
import json
import os
import shutil
from q2t.thermo import get_thermo
from q2t.qchem import QChem
from q2t.mol import str_to_rmg_mol, geo_to_rmg_mol, geo_to_xyz_str
def main():
args = parse_args()
if args.bacs is not None:
with open(args.bacs) as f:
bacs = js... | 0.331877 | 0.172712 |
"""Utility code for converting between absl logging output and log protos."""
import contextlib
import datetime
import pathlib
import re
import sys
import typing
from absl import logging
from labm8.py import app
from labm8.py import labdate
from labm8.py.internal import logging_pb2
FLAGS = app.FLAGS
# A regular exp... | labm8/py/logutil.py | """Utility code for converting between absl logging output and log protos."""
import contextlib
import datetime
import pathlib
import re
import sys
import typing
from absl import logging
from labm8.py import app
from labm8.py import labdate
from labm8.py.internal import logging_pb2
FLAGS = app.FLAGS
# A regular exp... | 0.730001 | 0.442275 |
import flask
import json
import logging
import mock
import testtools
from shakenfist.daemons import external_api
logging.basicConfig(level=logging.DEBUG)
class FakeResponse(object):
def __init__(self, status_code, text):
self.status_code = status_code
self.text = text
class ExternalApiTestCa... | shakenfist/tests/test_daemons_external_api.py | import flask
import json
import logging
import mock
import testtools
from shakenfist.daemons import external_api
logging.basicConfig(level=logging.DEBUG)
class FakeResponse(object):
def __init__(self, status_code, text):
self.status_code = status_code
self.text = text
class ExternalApiTestCa... | 0.435421 | 0.080033 |
from ui_styles import Style
from Social_GUI import *
#GLOBALS USED IN UI_FUNCTIONS
GLOBAL_STATE = 0
GLOBAL_TITLE_BAR = True
#COUNT INITIAL MENU
count = 1
#LINKS GUI TOGETHER
class MainWindow(QMainWindow):
def __init__(self):
#CREATE GUI WINDOW
QMainWindow.__init__(self)
self.ui = Ui_MainW... | ui_functions.py | from ui_styles import Style
from Social_GUI import *
#GLOBALS USED IN UI_FUNCTIONS
GLOBAL_STATE = 0
GLOBAL_TITLE_BAR = True
#COUNT INITIAL MENU
count = 1
#LINKS GUI TOGETHER
class MainWindow(QMainWindow):
def __init__(self):
#CREATE GUI WINDOW
QMainWindow.__init__(self)
self.ui = Ui_MainW... | 0.224906 | 0.044995 |
import numpy as np
import sys
class Softmax:
def forward_vec(self, scores, win_idx):
"""
Compute forward propagation.
- scores: ndarray(p,). Vector of class scores
- win_idx: int. Index of ground truth
"""
# Keep scores for backprop
self.scores... | old/test/src/nodes/softmax.py |
import numpy as np
import sys
class Softmax:
def forward_vec(self, scores, win_idx):
"""
Compute forward propagation.
- scores: ndarray(p,). Vector of class scores
- win_idx: int. Index of ground truth
"""
# Keep scores for backprop
self.scores... | 0.404625 | 0.397938 |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
import time
import re
import redis
def main(key,address):
data = []
driver = webdriver.Chrome("D:/Program Files/python/chromedriver.exe")
driver2 = webdriver.Chr... | py/liepin_Craw.py | from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
import time
import re
import redis
def main(key,address):
data = []
driver = webdriver.Chrome("D:/Program Files/python/chromedriver.exe")
driver2 = webdriver.Chr... | 0.062653 | 0.049131 |
import pymongo, datetime
from bson.objectid import ObjectId
import ast
#db = pymongo.Connection('localhost', 27017)['sicki3']
db = pymongo.Connection('localhost', 3002)['meteor']
# source collections
#economics = db.economics
event = db.event
#host = db.host
#location = db.location
#'metaData': metaData = db.'metaDat... | stats2sicki.py | import pymongo, datetime
from bson.objectid import ObjectId
import ast
#db = pymongo.Connection('localhost', 27017)['sicki3']
db = pymongo.Connection('localhost', 3002)['meteor']
# source collections
#economics = db.economics
event = db.event
#host = db.host
#location = db.location
#'metaData': metaData = db.'metaDat... | 0.248443 | 0.127925 |
import dataclasses
import glob
import json
import logging
import os
import shutil
import site
import subprocess
import sys
from dataclasses import dataclass, field
from logging import Logger
from pathlib import Path
from typing import (
Any,
Dict,
Iterable,
List,
Optional,
Sequence,
Set,
... | client/configuration/configuration.py |
import dataclasses
import glob
import json
import logging
import os
import shutil
import site
import subprocess
import sys
from dataclasses import dataclass, field
from logging import Logger
from pathlib import Path
from typing import (
Any,
Dict,
Iterable,
List,
Optional,
Sequence,
Set,
... | 0.720172 | 0.126488 |
import math, os, signal, hashlib
from glob import glob
from filechunkio import FileChunkIO
from boto import connect_s3
from boto.s3.key import Key
from gevent import sleep
from gevent.pool import Pool
from gevent.event import Event
from ufyr.decorators import retry
CHUNK_SIZE = 80000000 #10Mb
pool = Pool(4)
s3 = c... | ufyr/s3_uploader.py | import math, os, signal, hashlib
from glob import glob
from filechunkio import FileChunkIO
from boto import connect_s3
from boto.s3.key import Key
from gevent import sleep
from gevent.pool import Pool
from gevent.event import Event
from ufyr.decorators import retry
CHUNK_SIZE = 80000000 #10Mb
pool = Pool(4)
s3 = c... | 0.296043 | 0.101768 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
FIN = './data/model/model_%d.npy'
FOUT = './results/rescaled_contacts.svg'
P = np.array([0.93,0.91])
S = np.array([0.72,0.81])
F = np.array([0.33,0.23])
#VAR = 4*(F*P*(1-P) + (1-F)*S*(1-S))
VAR = np.array([1,1])
mpl.rcParams['xtick.labelsize'... | scripts/model_rescale.py | import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
FIN = './data/model/model_%d.npy'
FOUT = './results/rescaled_contacts.svg'
P = np.array([0.93,0.91])
S = np.array([0.72,0.81])
F = np.array([0.33,0.23])
#VAR = 4*(F*P*(1-P) + (1-F)*S*(1-S))
VAR = np.array([1,1])
mpl.rcParams['xtick.labelsize'... | 0.195057 | 0.413951 |
from collections import namedtuple
from operator import add, contains
from typing import AbstractSet, Callable, Tuple
from unittest.mock import patch
import numpy as np
import pandas as pd
import pytest
from ... import expressions as exp, frontend
from ...datalog import DatalogProgram, Fact, Implication
from ...excep... | neurolang/frontend/tests/test_frontend.py | from collections import namedtuple
from operator import add, contains
from typing import AbstractSet, Callable, Tuple
from unittest.mock import patch
import numpy as np
import pandas as pd
import pytest
from ... import expressions as exp, frontend
from ...datalog import DatalogProgram, Fact, Implication
from ...excep... | 0.847747 | 0.589864 |
import os
import numpy as np
import pandas as pd
from detectron2.data import DatasetCatalog, MetadataCatalog
def setup_cls_data_catalog(cfg):
"""
register datasetcatalog and metadata_catalog
"""
# register dataset_catalog
dataset_dict_fn = SpineClsDatasetFunction(cfg, "train")
DatasetCatalog... | spine/classification/cls_dataset_dict.py |
import os
import numpy as np
import pandas as pd
from detectron2.data import DatasetCatalog, MetadataCatalog
def setup_cls_data_catalog(cfg):
"""
register datasetcatalog and metadata_catalog
"""
# register dataset_catalog
dataset_dict_fn = SpineClsDatasetFunction(cfg, "train")
DatasetCatalog... | 0.479747 | 0.324423 |
import numpy as np
import glob
from scipy.interpolate import interp1d
import multiprocessing as mp
from bisect import bisect
def GetWaveNumbers(StartWavelength=300, EndWavelength=30000, Resolution=100000):
'''
Returns the wavelengths corresponding to the resolution and in units
of cm.
'... | lib/CrossSectionFunctions.py | import numpy as np
import glob
from scipy.interpolate import interp1d
import multiprocessing as mp
from bisect import bisect
def GetWaveNumbers(StartWavelength=300, EndWavelength=30000, Resolution=100000):
'''
Returns the wavelengths corresponding to the resolution and in units
of cm.
'... | 0.493897 | 0.494141 |
from os import path
signature = db.Table(db,'auth_signature',
Field('created_on','datetime',default=request.now,
writable=False,readable=False, label=T('Created on')),
Field('created_by','reference %s' % auth.settings.table_user_name,default=auth.user_id,
writable=False,readable=F... | web2py-appliances-master/TinyWebsite/models/db__website.py | from os import path
signature = db.Table(db,'auth_signature',
Field('created_on','datetime',default=request.now,
writable=False,readable=False, label=T('Created on')),
Field('created_by','reference %s' % auth.settings.table_user_name,default=auth.user_id,
writable=False,readable=F... | 0.417628 | 0.094929 |
import sqlite3
import dataclasses
from typing import Generator, List
from src.helpers import helpers # type: ignore
from src.logger import config_logger #type: ignore
@dataclasses.dataclass
class BackupReader(config_logger.Logger):
"""Read data from Outlook 2016 Backup folder.
Attributes:
backup_locat... | src/backupreader/reader.py | import sqlite3
import dataclasses
from typing import Generator, List
from src.helpers import helpers # type: ignore
from src.logger import config_logger #type: ignore
@dataclasses.dataclass
class BackupReader(config_logger.Logger):
"""Read data from Outlook 2016 Backup folder.
Attributes:
backup_locat... | 0.635901 | 0.134208 |
from Bio import SeqIO
import os
import glob
import argparse
def main():
parser = argparse.ArgumentParser(description='Merges Phyluce UCEs from SPAdes and rnaSPAdes')
parser.add_argument('-o', type=str,
help='Output Folder', required=True)
parser.add_argument('-i', type=str,
... | pipeline_files/count_uces.py | from Bio import SeqIO
import os
import glob
import argparse
def main():
parser = argparse.ArgumentParser(description='Merges Phyluce UCEs from SPAdes and rnaSPAdes')
parser.add_argument('-o', type=str,
help='Output Folder', required=True)
parser.add_argument('-i', type=str,
... | 0.3492 | 0.192767 |
import time
import sys
urunler = {
"1":("su", 1),
"2":("çay", 2),
"3":("kahve", 3),
"4":("enerji içeceği", 5),
"5":("paket portakal suyu", 7),
"6":("taze portakal suyu", 11),
}
def input(mesaj):
sys.stdout.write(mesaj)
sys.stdout.flush()
girdiler = []
while True:
girdi = sys.stdin... | basit_otomat_v1.py | import time
import sys
urunler = {
"1":("su", 1),
"2":("çay", 2),
"3":("kahve", 3),
"4":("enerji içeceği", 5),
"5":("paket portakal suyu", 7),
"6":("taze portakal suyu", 11),
}
def input(mesaj):
sys.stdout.write(mesaj)
sys.stdout.flush()
girdiler = []
while True:
girdi = sys.stdin... | 0.056379 | 0.188641 |
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn.decomposition import PCA
import multiprocessing
from MulticoreTSNE import MulticoreTSNE
import numpy as np
import pandas as pd
import seaborn as sns
from collections import defaultdict
from scipy.cluster import hierarchy
from mpl_toolkits.axes_... | randomly/visualization.py | import matplotlib.pyplot as plt
from matplotlib import style
from sklearn.decomposition import PCA
import multiprocessing
from MulticoreTSNE import MulticoreTSNE
import numpy as np
import pandas as pd
import seaborn as sns
from collections import defaultdict
from scipy.cluster import hierarchy
from mpl_toolkits.axes_... | 0.840292 | 0.63484 |
import logging
from programmingtheiot.common.IDataMessageListener import IDataMessageListener
from programmingtheiot.data.ActuatorData import ActuatorData
from programmingtheiot.cda.sim.HumidifierActuatorSimTask import HumidifierActuatorSimTask
from programmingtheiot.cda.sim.HvacActuatorSimTask import HvacActuatorS... | src/main/python/programmingtheiot/cda/system/ActuatorAdapterManager.py |
import logging
from programmingtheiot.common.IDataMessageListener import IDataMessageListener
from programmingtheiot.data.ActuatorData import ActuatorData
from programmingtheiot.cda.sim.HumidifierActuatorSimTask import HumidifierActuatorSimTask
from programmingtheiot.cda.sim.HvacActuatorSimTask import HvacActuatorS... | 0.201892 | 0.192558 |
import json
from abc import ABC, abstractmethod
from argparse import ArgumentParser
from logging import Logger
from typing import Dict, Any
from pyspark.sql import SparkSession
import sys
# abstract class for jobs
class Job(ABC):
def __init__(self, spark=None, init_conf=None):
self.spark = self._prepare... | code/common.py | import json
from abc import ABC, abstractmethod
from argparse import ArgumentParser
from logging import Logger
from typing import Dict, Any
from pyspark.sql import SparkSession
import sys
# abstract class for jobs
class Job(ABC):
def __init__(self, spark=None, init_conf=None):
self.spark = self._prepare... | 0.489015 | 0.069164 |
import csv
import json
import urllib
# starting static list of universities and their locations to reduce Google Places API call frequency
univ_locations = {'Texas A&M University Corpus Christi': 'us-tx', 'University of Texas at Arlington': 'us-tx', 'University of Houston': 'us-tx',
'Michigan Technological University'... | project_organizer.py | import csv
import json
import urllib
# starting static list of universities and their locations to reduce Google Places API call frequency
univ_locations = {'Texas A&M University Corpus Christi': 'us-tx', 'University of Texas at Arlington': 'us-tx', 'University of Houston': 'us-tx',
'Michigan Technological University'... | 0.469763 | 0.412353 |
import shutil
import sklearn
import torch
from ignite.contrib.handlers import ProgressBar
from ignite.engine import Engine, Events
from ignite.handlers import ModelCheckpoint, EarlyStopping
from torch.utils.data import DataLoader
from typing import Optional
from slp.util import system
from slp.util import types
DEV... | slp/trainer/handlers_test.py | import shutil
import sklearn
import torch
from ignite.contrib.handlers import ProgressBar
from ignite.engine import Engine, Events
from ignite.handlers import ModelCheckpoint, EarlyStopping
from torch.utils.data import DataLoader
from typing import Optional
from slp.util import system
from slp.util import types
DEV... | 0.850065 | 0.259996 |
import autograd.numpy as np
from autograd import hessian
from scipy.optimize import minimize
import matplotlib.pyplot as plt
from matplotlib import rcParams, rcParamsDefault
from scipy.optimize import brentq
from autograd import grad
from experiments.visualization.visualization_utils import get_figsize
def func_sine(... | experiments/visualization/plot_sine_convex_vs_concave.py | import autograd.numpy as np
from autograd import hessian
from scipy.optimize import minimize
import matplotlib.pyplot as plt
from matplotlib import rcParams, rcParamsDefault
from scipy.optimize import brentq
from autograd import grad
from experiments.visualization.visualization_utils import get_figsize
def func_sine(... | 0.768038 | 0.566858 |
from pydeep.core import Function
import numpy as np
class Loss(Function):
def backward(self):
gx = self.cache["local_gx"]
return gx
class CrossEntropyLoss(Loss):
def forward(self, x, y):
"""
Descr.: calculate the mean loss of the batch
:param x: final layer of the... | pydeep/loss.py | from pydeep.core import Function
import numpy as np
class Loss(Function):
def backward(self):
gx = self.cache["local_gx"]
return gx
class CrossEntropyLoss(Loss):
def forward(self, x, y):
"""
Descr.: calculate the mean loss of the batch
:param x: final layer of the... | 0.905641 | 0.706558 |
import hashlib
import os
import pytest
from pex import dist_metadata, resolver, targets
from pex.fetcher import URLFetcher
from pex.pip.tool import PackageIndexConfiguration
from pex.resolve.configured_resolver import ConfiguredResolver
from pex.resolve.locked_resolve import LockConfiguration, LockedResolve, LockSty... | tests/integration/test_locked_resolve.py |
import hashlib
import os
import pytest
from pex import dist_metadata, resolver, targets
from pex.fetcher import URLFetcher
from pex.pip.tool import PackageIndexConfiguration
from pex.resolve.configured_resolver import ConfiguredResolver
from pex.resolve.locked_resolve import LockConfiguration, LockedResolve, LockSty... | 0.767516 | 0.164382 |
from lxml import etree
import os.path
import os
def rename(filepath, srcext, destext):
if os.name == 'nt':
# Can't rename to existing files, so we have to move the old one, then
# rename, then delete the old one.
if os.path.exists(filepath + destext):
if os.path.exists(filepath ... | web/xmlstore.py | from lxml import etree
import os.path
import os
def rename(filepath, srcext, destext):
if os.name == 'nt':
# Can't rename to existing files, so we have to move the old one, then
# rename, then delete the old one.
if os.path.exists(filepath + destext):
if os.path.exists(filepath ... | 0.519765 | 0.181463 |
from rdkit import Chem
from rdkit.Chem import Lipinski as LPK
import pandas as pd
def CalculateMolWeight(mol):
"""
Calculation of molecular weight. Note that not including H
Parameters:
mol: rdkit molecule
Returns:
MolWeight: Molecular weight
"""
Mo... | smdt/descriptors/constitution.py | from rdkit import Chem
from rdkit.Chem import Lipinski as LPK
import pandas as pd
def CalculateMolWeight(mol):
"""
Calculation of molecular weight. Note that not including H
Parameters:
mol: rdkit molecule
Returns:
MolWeight: Molecular weight
"""
Mo... | 0.841305 | 0.640383 |
from __future__ import print_function
import argparse
import os.path
import models.examples as ex
from config import cfg
from generic_op import *
from midap_simulator import *
from midap_software import Compiler, MidapModel
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_s... | one_layer_test.py | from __future__ import print_function
import argparse
import os.path
import models.examples as ex
from config import cfg
from generic_op import *
from midap_simulator import *
from midap_software import Compiler, MidapModel
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_s... | 0.387343 | 0.105211 |