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 os
from typing import Any, Dict, List, Optional
import numpy as np
from OpenGL.GL import (
GL_BLEND,
GL_CULL_FACE,
GL_LINEAR,
GL_LINEAR_MIPMAP_LINEAR,
GL_ONE,
GL_ONE_MINUS_SRC_ALPHA,
GL_REPEAT,
GL_RGB,
GL_RGBA,
GL_SRC_ALPHA,
GL_TEXTURE0,
GL_TEXTURE_2D,
GL_TEXT... | payton/scene/material.py | import os
from typing import Any, Dict, List, Optional
import numpy as np
from OpenGL.GL import (
GL_BLEND,
GL_CULL_FACE,
GL_LINEAR,
GL_LINEAR_MIPMAP_LINEAR,
GL_ONE,
GL_ONE_MINUS_SRC_ALPHA,
GL_REPEAT,
GL_RGB,
GL_RGBA,
GL_SRC_ALPHA,
GL_TEXTURE0,
GL_TEXTURE_2D,
GL_TEXT... | 0.818918 | 0.291006 |
config={}
with open('etc/pkg/config', 'r') as config_file:
exec(config_file.read(), config)
print('pkg for FreeBSD %s %s' % (config['DIST'], config['ARCHITECTURE'][1]))
import os
import subprocess
import sys
import re
import io
import shutil
import copy
try:
import urllib2
except ImportError:
... | pc-freebsd-ppc64/sysroot/pkg.py | config={}
with open('etc/pkg/config', 'r') as config_file:
exec(config_file.read(), config)
print('pkg for FreeBSD %s %s' % (config['DIST'], config['ARCHITECTURE'][1]))
import os
import subprocess
import sys
import re
import io
import shutil
import copy
try:
import urllib2
except ImportError:
... | 0.087737 | 0.062245 |
__all__ = [
"MAX_RANGE",
"OrdinalError",
"__all__",
"__version__",
"decode",
"dump",
"encode",
"get_delimiter",
"load",
"parse",
"safeparse",
"set_delimiter",
"temporary_delimiter",
]
import contextlib
from typing import Literal, Generator, Optional
MAX_RANGE = 1114... | ordinary.py | __all__ = [
"MAX_RANGE",
"OrdinalError",
"__all__",
"__version__",
"decode",
"dump",
"encode",
"get_delimiter",
"load",
"parse",
"safeparse",
"set_delimiter",
"temporary_delimiter",
]
import contextlib
from typing import Literal, Generator, Optional
MAX_RANGE = 1114... | 0.890032 | 0.216632 |
from unittest import TestCase
from flowers.person import Person
from flowers.task import Task, OtherPhaseException
from tests import builder
from tests.builder import build_developer
class TestTask(TestCase):
def test_task_completed(self):
p: Person = build_developer()
p.effort_available = 10
... | tests/test_tasks.py | from unittest import TestCase
from flowers.person import Person
from flowers.task import Task, OtherPhaseException
from tests import builder
from tests.builder import build_developer
class TestTask(TestCase):
def test_task_completed(self):
p: Person = build_developer()
p.effort_available = 10
... | 0.490724 | 0.642531 |
import os
from abc import ABCMeta
from fnmatch import filter as fnfilter
from typing import Optional, Mapping, Union
from hbutils.model import get_repr_info
from hbutils.string import truncate
from ..base import _process_environ
from ...control.model import Identification, ResourceLimit
class _IGlobalConfig(metacla... | pji/service/dispatch/global_.py | import os
from abc import ABCMeta
from fnmatch import filter as fnfilter
from typing import Optional, Mapping, Union
from hbutils.model import get_repr_info
from hbutils.string import truncate
from ..base import _process_environ
from ...control.model import Identification, ResourceLimit
class _IGlobalConfig(metacla... | 0.763307 | 0.114072 |
from pprint import pformat
from six import iteritems
class IscsiInterfaceChangeableProperties(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
IscsiInterfaceChangeableProperties - a mo... | netapp/santricity/models/symbol/iscsi_interface_changeable_properties.py | from pprint import pformat
from six import iteritems
class IscsiInterfaceChangeableProperties(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
IscsiInterfaceChangeableProperties - a mo... | 0.742328 | 0.139426 |
import argparse
import datetime as dt
import json
from collections import defaultdict
from pathlib import Path
from typing import Dict
import pip._vendor.pkg_resources as pkg_resources
import pip._vendor.toml as toml
from dnevnik2 import Dnevnik2
def get_subject(item, subjects: Dict[str, str]) -> str:
subject_i... | dnevnik2/scripts/render_marks_for_current_quarter.py | import argparse
import datetime as dt
import json
from collections import defaultdict
from pathlib import Path
from typing import Dict
import pip._vendor.pkg_resources as pkg_resources
import pip._vendor.toml as toml
from dnevnik2 import Dnevnik2
def get_subject(item, subjects: Dict[str, str]) -> str:
subject_i... | 0.500732 | 0.103295 |
from torch.utils import data
import utils.utils as uu
import torch
import pandas as pd
class TabularDataset(data.Dataset):
def __init__(self, df, dep_var, cont_inputs, int_inputs, test_size, seed=None):
"""
Generates train/test and arr/tensor versions of the data.
Input data is raw.
... | CSDGAN/classes/tabular/TabularDataset.py | from torch.utils import data
import utils.utils as uu
import torch
import pandas as pd
class TabularDataset(data.Dataset):
def __init__(self, df, dep_var, cont_inputs, int_inputs, test_size, seed=None):
"""
Generates train/test and arr/tensor versions of the data.
Input data is raw.
... | 0.776581 | 0.514827 |
from initial import gen, undirected
from bijective import is_bijective
from itertools import permutations as per
from test import value_nonl
from datetime import datetime
from json import dumps
from data import limit1, limit
def getfilename():
"""
Returns the current timestamp and will be used as filename.
... | travel.py | from initial import gen, undirected
from bijective import is_bijective
from itertools import permutations as per
from test import value_nonl
from datetime import datetime
from json import dumps
from data import limit1, limit
def getfilename():
"""
Returns the current timestamp and will be used as filename.
... | 0.540681 | 0.419291 |
import argparse
import os
import random
import sys
from enum import Enum
from collections import deque
from ezcode.heap import PriorityMap
class Square:
class State(Enum):
Void = 0
Obstacle = 1
Path = 2
Searched = 3
colors = [
"\033[107m", # White 0 - Void
... | src/ezcode/matrix/maze.py | import argparse
import os
import random
import sys
from enum import Enum
from collections import deque
from ezcode.heap import PriorityMap
class Square:
class State(Enum):
Void = 0
Obstacle = 1
Path = 2
Searched = 3
colors = [
"\033[107m", # White 0 - Void
... | 0.415136 | 0.194291 |
import os
from pymongo import MongoClient
from bson.objectid import ObjectId
import datetime
import psycopg2
import psycopg2.extras
from collections import OrderedDict
from yuntu.core.datastore.utils import hashDict
def datastoreGetSpec(ds):
dSpec = {}
dSpec["hash"] = ds.getHash()
dSpec["type"] = ds.getTy... | yuntu/core/datastore/methods.py | import os
from pymongo import MongoClient
from bson.objectid import ObjectId
import datetime
import psycopg2
import psycopg2.extras
from collections import OrderedDict
from yuntu.core.datastore.utils import hashDict
def datastoreGetSpec(ds):
dSpec = {}
dSpec["hash"] = ds.getHash()
dSpec["type"] = ds.getTy... | 0.312685 | 0.122418 |
from manual_test.manual_test_base import \
ManualTestBase, \
handle_command_line, \
CLEAN_SERVER_RECORD_TYPE, \
POPULATED_SERVER_RECORD_TYPE
from manual_test.utilities.notification_utilities import NotificationUtilities
from manual_test.utilities.workspace_utilities import WorkspaceUtilities
from typing... | manual_test/test_tag_rule.py | from manual_test.manual_test_base import \
ManualTestBase, \
handle_command_line, \
CLEAN_SERVER_RECORD_TYPE, \
POPULATED_SERVER_RECORD_TYPE
from manual_test.utilities.notification_utilities import NotificationUtilities
from manual_test.utilities.workspace_utilities import WorkspaceUtilities
from typing... | 0.740174 | 0.291516 |
import sys, os, getopt, json
def main(argv):
layer_names = ['**conv1**',
'**relu1**',
'**pool1**',
'**lrn1**',
'**conv2**',
'**relu2**',
'**pool2**',
'**lrn2**',
... | scripts/json2md.py |
import sys, os, getopt, json
def main(argv):
layer_names = ['**conv1**',
'**relu1**',
'**pool1**',
'**lrn1**',
'**conv2**',
'**relu2**',
'**pool2**',
'**lrn2**',
... | 0.258794 | 0.084304 |
import unittest
import pandas as pd
from pandas.testing import assert_frame_equal
from styleframe import StyleFrame, Styler, Container, Series, utils
class SeriesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.pandas_series = pd.Series((None, 1))
cls.sf_series = Series((Contai... | styleframe/tests/series_tests.py | import unittest
import pandas as pd
from pandas.testing import assert_frame_equal
from styleframe import StyleFrame, Styler, Container, Series, utils
class SeriesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.pandas_series = pd.Series((None, 1))
cls.sf_series = Series((Contai... | 0.607896 | 0.552057 |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__maintainer__ = "<NAME>"
__status__ = "Production"
import time
from rpi_ws281x import *
from control.ledstrip import set_brightness_depending_on_daytime
from functions.effects import clear
from logger import LOGGER
COLOR_HOUR = Color(200, 0, 0)
COLOR_HOUR_DIMMED = Color... | functions/clock2.py |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__maintainer__ = "<NAME>"
__status__ = "Production"
import time
from rpi_ws281x import *
from control.ledstrip import set_brightness_depending_on_daytime
from functions.effects import clear
from logger import LOGGER
COLOR_HOUR = Color(200, 0, 0)
COLOR_HOUR_DIMMED = Color... | 0.351422 | 0.07393 |
from dcf_test_app.models import Brand, Product
from django.test import TestCase
from rest_framework.test import APIClient
from django_client_framework import permissions as p
from django_client_framework.models import get_user_model
class TestPostPerms(TestCase):
"""POSTing to the related collection api creates ... | unit-tests/dcf_test_suites/related_collection_api/post_related_collection_perms.py | from dcf_test_app.models import Brand, Product
from django.test import TestCase
from rest_framework.test import APIClient
from django_client_framework import permissions as p
from django_client_framework.models import get_user_model
class TestPostPerms(TestCase):
"""POSTing to the related collection api creates ... | 0.66769 | 0.185357 |
from le_utils.constants import format_presets, licenses, exercises
from le_utils.constants.languages import getlang # see also getlang_by_name, getlang_by_alpha2
from ricecooker.chefs import SushiChef
from ricecooker.classes.nodes import TopicNode
from ricecooker.classes.nodes import DocumentNode, AudioNode, VideoNo... | channels/contentnode_dependency/sushichef.py |
from le_utils.constants import format_presets, licenses, exercises
from le_utils.constants.languages import getlang # see also getlang_by_name, getlang_by_alpha2
from ricecooker.chefs import SushiChef
from ricecooker.classes.nodes import TopicNode
from ricecooker.classes.nodes import DocumentNode, AudioNode, VideoNo... | 0.561575 | 0.21102 |
from blinkenlights import setup, cleanup
from fourleds import light, clear
from time import sleep
import random
pins = [37, 33, 31, 29, 36, 32, 22, 18]
# yp ym gp gm rp rm bp bm
setup(pins)
### Test pattern
clear(pins)
for i in pins:
light(i)
sleep(0.1)
clear(pins)
#### Definitions
class ... | pong.py | from blinkenlights import setup, cleanup
from fourleds import light, clear
from time import sleep
import random
pins = [37, 33, 31, 29, 36, 32, 22, 18]
# yp ym gp gm rp rm bp bm
setup(pins)
### Test pattern
clear(pins)
for i in pins:
light(i)
sleep(0.1)
clear(pins)
#### Definitions
class ... | 0.302803 | 0.271674 |
import json
from datetime import datetime, timedelta
import pathlib
import pandas as pd
import networkx as nx
from statistics import median, mean
from itertools import combinations
from minepy import MINE
import warnings
warnings.simplefilter("ignore", UserWarning)
from sklearn.metrics import mutual_info_score
def l... | src/Parsing.py | import json
from datetime import datetime, timedelta
import pathlib
import pandas as pd
import networkx as nx
from statistics import median, mean
from itertools import combinations
from minepy import MINE
import warnings
warnings.simplefilter("ignore", UserWarning)
from sklearn.metrics import mutual_info_score
def l... | 0.425844 | 0.187765 |
from typing import List, Union, Optional, Dict, Tuple, Iterable
from requests import Session, Response
from datetime import datetime, timezone, timedelta
from .model import Alarm, AlarmLevel, AlarmKind, AlarmDetail
import ast
from bidict import bidict
import json
__all__ = ('AlarmCrawler')
class AlarmCrawler():
"... | weather_com_cn/alarm.py | from typing import List, Union, Optional, Dict, Tuple, Iterable
from requests import Session, Response
from datetime import datetime, timezone, timedelta
from .model import Alarm, AlarmLevel, AlarmKind, AlarmDetail
import ast
from bidict import bidict
import json
__all__ = ('AlarmCrawler')
class AlarmCrawler():
"... | 0.775987 | 0.101634 |
from qtpy import QtCore
from qtpy.QtWidgets import *
class ROIItemWidget(QWidget):
"""
Item in the ROI list, takes care of everything except for color part which is
handled by ROIItemModule
"""
def __init__(self, roi_tab, color, roi_list, id, roi_num, parent=None,
display_time=Tr... | cidan/GUI/ListWidgets/ROIItemWidget.py | from qtpy import QtCore
from qtpy.QtWidgets import *
class ROIItemWidget(QWidget):
"""
Item in the ROI list, takes care of everything except for color part which is
handled by ROIItemModule
"""
def __init__(self, roi_tab, color, roi_list, id, roi_num, parent=None,
display_time=Tr... | 0.498047 | 0.106598 |
import pexpect
import unittest
import PexpectTestCase
import time
import os
class TestCtrlChars(PexpectTestCase.PexpectTestCase):
def test_control_chars (self):
'''FIXME: Python unicode was too hard to figure out, so
this tests only the true ASCII characters. This is lame
and should be fi... | tests/test_ctrl_chars.py | import pexpect
import unittest
import PexpectTestCase
import time
import os
class TestCtrlChars(PexpectTestCase.PexpectTestCase):
def test_control_chars (self):
'''FIXME: Python unicode was too hard to figure out, so
this tests only the true ASCII characters. This is lame
and should be fi... | 0.168344 | 0.372962 |
import argparse
import json
import numpy as np
import paho.mqtt.client as mqtt
from PIL import Image
SAVED_IMAGE_DIR = 'images'
IMAGE_DATA_TOPIC = "image/data"
device_door_map = {
"web_61f3442604cb": "door1", # Samsung Galaxy
"web_4342e44ea8da": "door2", # Dorcas' iPhone
"web_40cf1dd6a603": "door2", ... | storage/image_storage.py | import argparse
import json
import numpy as np
import paho.mqtt.client as mqtt
from PIL import Image
SAVED_IMAGE_DIR = 'images'
IMAGE_DATA_TOPIC = "image/data"
device_door_map = {
"web_61f3442604cb": "door1", # Samsung Galaxy
"web_4342e44ea8da": "door2", # Dorcas' iPhone
"web_40cf1dd6a603": "door2", ... | 0.254972 | 0.07989 |
try :
from . import cudaext
except :
import sys
if sys.version_info[0] == 2 :
del cudaext
raise
import numpy as np
import weakref
from .native_qubit_processor import NativeQubitProcessor
from .native_qubit_states import NativeQubitStates
from .native_qubits_states_getter import NativeQ... | qgate/simulator/cudaruntime.py | try :
from . import cudaext
except :
import sys
if sys.version_info[0] == 2 :
del cudaext
raise
import numpy as np
import weakref
from .native_qubit_processor import NativeQubitProcessor
from .native_qubit_states import NativeQubitStates
from .native_qubits_states_getter import NativeQ... | 0.347316 | 0.220542 |
from __future__ import print_function
from pandas import option_context
from ..externals.colored import stylize, fg, attr
# Dictionary of term colors used for printing to terminal
fg_colors = {
'official_train': 'light_green',
'official_valid': 'light_blue',
'official_test': 'red',
'train': 'dark_sea_... | rampwf/utils/pretty_print.py | from __future__ import print_function
from pandas import option_context
from ..externals.colored import stylize, fg, attr
# Dictionary of term colors used for printing to terminal
fg_colors = {
'official_train': 'light_green',
'official_valid': 'light_blue',
'official_test': 'red',
'train': 'dark_sea_... | 0.658857 | 0.149252 |
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.learning_curve import validation_curve
from sklearn.linear_model import LogisticRegression
from sk... | mushroom_wen.py | import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.learning_curve import validation_curve
from sklearn.linear_model import LogisticRegression
from sk... | 0.377541 | 0.329904 |
SERVICES_TABLE_ID = 'central_services'
SERVICES_TABLE_ROWS_XPATH = '//table[@id="central_services"]//tbody/tr'
SERVICES_TABLE_ROW_CSS = '#central_services tbody tr'
SERVICE_ADD_BUTTON_ID = 'central_service_add'
SERVICE_EDIT_BUTTON_ID = 'central_service_details'
SERVICE_DELETE_BUTTON_ID = 'central_service_delete'... | common/xrd-ui-tests-python/view_models/central_services.py | SERVICES_TABLE_ID = 'central_services'
SERVICES_TABLE_ROWS_XPATH = '//table[@id="central_services"]//tbody/tr'
SERVICES_TABLE_ROW_CSS = '#central_services tbody tr'
SERVICE_ADD_BUTTON_ID = 'central_service_add'
SERVICE_EDIT_BUTTON_ID = 'central_service_details'
SERVICE_DELETE_BUTTON_ID = 'central_service_delete'... | 0.281801 | 0.112942 |
from random import random
from PyQt5.QtCore import QSize, Qt, QPoint
from PyQt5.QtGui import QColor, QBrush, QPen
from PyQt5.QtWidgets import (QLabel, QVBoxLayout, QTableWidget, QWidget, QHBoxLayout, QHeaderView,
QCheckBox, QTableWidgetItem, QComboBox, QStyledItemDelegate, QStyle)
from s... | src/serialbox-python/sdb/sdbgui/resulttablewidget.py |
from random import random
from PyQt5.QtCore import QSize, Qt, QPoint
from PyQt5.QtGui import QColor, QBrush, QPen
from PyQt5.QtWidgets import (QLabel, QVBoxLayout, QTableWidget, QWidget, QHBoxLayout, QHeaderView,
QCheckBox, QTableWidgetItem, QComboBox, QStyledItemDelegate, QStyle)
from s... | 0.334698 | 0.087058 |
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy_utils.expressions import explain, explain_analyze
from tests import TestCase
class ExpressionTestCase(TestCase):
dns = 'postgres://postgres@localhost/sqlalchemy_utils_test'
def create_models(self):
class Article(self.... | tests/test_expressions.py | import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy_utils.expressions import explain, explain_analyze
from tests import TestCase
class ExpressionTestCase(TestCase):
dns = 'postgres://postgres@localhost/sqlalchemy_utils_test'
def create_models(self):
class Article(self.... | 0.512693 | 0.457137 |
from __future__ import division
from collections import namedtuple
def _mixin_alpha(colors, alpha):
ratio = alpha / 255
return [int(round(color * ratio)) for color in colors]
class Color(object):
__slots__ = 'red', 'green', 'blue', 'alpha'
def __init__(self, red, green, blue, alpha=255):
se... | pymaging/colors.py | from __future__ import division
from collections import namedtuple
def _mixin_alpha(colors, alpha):
ratio = alpha / 255
return [int(round(color * ratio)) for color in colors]
class Color(object):
__slots__ = 'red', 'green', 'blue', 'alpha'
def __init__(self, red, green, blue, alpha=255):
se... | 0.918187 | 0.416915 |
import lx, modo, replay
from replay import message as message
"""A simple example of a blessed MODO command using the commander module.
https://github.com/adamohern/commander for details"""
class CommandClass(replay.commander.CommanderClass):
"""Saves the current Macro() object to the destination stored in its
... | lxserv/replay_fileSaveAs.py |
import lx, modo, replay
from replay import message as message
"""A simple example of a blessed MODO command using the commander module.
https://github.com/adamohern/commander for details"""
class CommandClass(replay.commander.CommanderClass):
"""Saves the current Macro() object to the destination stored in its
... | 0.620507 | 0.373362 |
from pyspark import SparkContext, keyword_only
from pyspark.ml.common import _java2py
from pyspark.ml.param import Param
from pyspark.ml.param.shared import HasFeaturesCol, HasLabelCol, HasPredictionCol, HasWeightCol, HasCheckpointInterval
from pyspark.ml.util import JavaMLWritable, JavaPredictionModel
from pyspark.ml... | docker/bdse_pyspark/main/module/sparkxgb/xgboost.py |
from pyspark import SparkContext, keyword_only
from pyspark.ml.common import _java2py
from pyspark.ml.param import Param
from pyspark.ml.param.shared import HasFeaturesCol, HasLabelCol, HasPredictionCol, HasWeightCol, HasCheckpointInterval
from pyspark.ml.util import JavaMLWritable, JavaPredictionModel
from pyspark.ml... | 0.906146 | 0.301426 |
from django.core.management.base import BaseCommand, CommandError
from gwasdb.models import Phenotype
import requests
class Command(BaseCommand):
help = 'Index AraPheno phenotypes in AraGWASCatalog'
def add_arguments(self, parser):
parser.add_argument('--id',
dest='phenoty... | aragwas_server/gwasdb/management/commands/import_phenotypes.py | from django.core.management.base import BaseCommand, CommandError
from gwasdb.models import Phenotype
import requests
class Command(BaseCommand):
help = 'Index AraPheno phenotypes in AraGWASCatalog'
def add_arguments(self, parser):
parser.add_argument('--id',
dest='phenoty... | 0.223462 | 0.063222 |
from pycket import config
from pycket import values, values_string
from pycket.base import SingletonMeta, UnhashableType
from pycket.hash.base import W_HashTable, get_dict_item, next_valid_index, w_missing
from pycket.error import SchemeException
from... | pycket/hash/equal.py | from pycket import config
from pycket import values, values_string
from pycket.base import SingletonMeta, UnhashableType
from pycket.hash.base import W_HashTable, get_dict_item, next_valid_index, w_missing
from pycket.error import SchemeException
from... | 0.46393 | 0.164215 |
import unittest
import ActionUserCounter as action
import copy
import os
import json
class TestSomething(unittest.TestCase) :
def test_splitActionOwnerName(self) :
cases = [
"user/action",
"user/action-name",
"user/longer-action-name",
"action",
... | tests/tests.py |
import unittest
import ActionUserCounter as action
import copy
import os
import json
class TestSomething(unittest.TestCase) :
def test_splitActionOwnerName(self) :
cases = [
"user/action",
"user/action-name",
"user/longer-action-name",
"action",
... | 0.498535 | 0.394201 |
import glob
import pathlib
import re
import shutil
from collections import Counter
import ase
import ase.symbols
import numpy as np
from bandapi.dispatcher.dpdispatcher import Task
from bandapi.flow.abacus import default_settings
from bandapi.flow.state import FlowStateControl
from bandapi.flow.task_content import Nam... | src/bandapi/flow/abacus/calculation_state.py | import glob
import pathlib
import re
import shutil
from collections import Counter
import ase
import ase.symbols
import numpy as np
from bandapi.dispatcher.dpdispatcher import Task
from bandapi.flow.abacus import default_settings
from bandapi.flow.state import FlowStateControl
from bandapi.flow.task_content import Nam... | 0.58676 | 0.182717 |
from uuid import uuid4
import pytest
from django.contrib.auth import get_user_model
from django.test import RequestFactory
from zapier.auth import authenticate_request, authorize_request
from zapier.exceptions import (
MissingTokenHeader,
TokenAuthError,
TokenScopeError,
TokenUserError,
UnknownTok... | tests/test_auth.py | from uuid import uuid4
import pytest
from django.contrib.auth import get_user_model
from django.test import RequestFactory
from zapier.auth import authenticate_request, authorize_request
from zapier.exceptions import (
MissingTokenHeader,
TokenAuthError,
TokenScopeError,
TokenUserError,
UnknownTok... | 0.485356 | 0.307787 |
import numpy as np
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = 'input.txt'
with open(filename, 'r') as f:
data = f.read()
# All unique characters / entities in the data set.
chars = list(set(data))
chars.sort()
data_size, vocab_size = len(data), len(chars)
print('data has %d ... | min-char-rnn/min_char_rnn_lstm.py | import numpy as np
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = 'input.txt'
with open(filename, 'r') as f:
data = f.read()
# All unique characters / entities in the data set.
chars = list(set(data))
chars.sort()
data_size, vocab_size = len(data), len(chars)
print('data has %d ... | 0.45302 | 0.485234 |
import pytest
from bitvector import BitVector, BitField, ReadOnlyBitField
from itertools import combinations
def test_bitfield_create_no_args():
with pytest.raises(TypeError):
BitField()
@pytest.mark.parametrize("offset", list(range(0, 128)))
def test_bitfield_create_with_offset(offset: int):
tes... | tests/test_bitfield.py | import pytest
from bitvector import BitVector, BitField, ReadOnlyBitField
from itertools import combinations
def test_bitfield_create_no_args():
with pytest.raises(TypeError):
BitField()
@pytest.mark.parametrize("offset", list(range(0, 128)))
def test_bitfield_create_with_offset(offset: int):
tes... | 0.752195 | 0.885086 |
import pygame
import constants as cons
from dungeon import Dungeon
class StatView():
def __init__(self, surface, pos_rect):
self.surface = surface
self.topleft = pos_rect
self.dirty = True
def draw(self, screen):
if self.dirty:
self.surface.fill(pygame.color.Color... | python/architecture-test/game.py | import pygame
import constants as cons
from dungeon import Dungeon
class StatView():
def __init__(self, surface, pos_rect):
self.surface = surface
self.topleft = pos_rect
self.dirty = True
def draw(self, screen):
if self.dirty:
self.surface.fill(pygame.color.Color... | 0.397237 | 0.194119 |
from packageManager import *
# this command enables us to download torch models
ssl._create_default_https_context = ssl._create_unverified_context
class ImageFolderWithPaths(datasets.ImageFolder):
"""Custom dataset that includes image file paths. Extends torchvision.datasets.ImageFolder
"""
# override the... | WebScraper/buildIndex.py | from packageManager import *
# this command enables us to download torch models
ssl._create_default_https_context = ssl._create_unverified_context
class ImageFolderWithPaths(datasets.ImageFolder):
"""Custom dataset that includes image file paths. Extends torchvision.datasets.ImageFolder
"""
# override the... | 0.897156 | 0.597549 |
import random
from contextlib import contextmanager
import six
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import (
rcParams,
colors
)
from mpl_toolkits.mplot3d import Axes3D
__all__ = [
"zoom_plot",
"plot",
"plot_predictions_3d",
'Palette',
'plot_clusters',
]
def... | isaac/plots/basic.py | import random
from contextlib import contextmanager
import six
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import (
rcParams,
colors
)
from mpl_toolkits.mplot3d import Axes3D
__all__ = [
"zoom_plot",
"plot",
"plot_predictions_3d",
'Palette',
'plot_clusters',
]
def... | 0.781372 | 0.541894 |
import time
import curses
import sys
from math import sqrt
try:
from rpi.burnin.ADCPi import ADCPi
except Exception:
sys.path.insert(0, "..")
from rpi.burnin.ADCPi import ADCPi
def main():
stdscr = curses.initscr()
"""
Main program function
"""
start_time = time.time()
try:
... | bin/LvrMon.py |
import time
import curses
import sys
from math import sqrt
try:
from rpi.burnin.ADCPi import ADCPi
except Exception:
sys.path.insert(0, "..")
from rpi.burnin.ADCPi import ADCPi
def main():
stdscr = curses.initscr()
"""
Main program function
"""
start_time = time.time()
try:
... | 0.208662 | 0.333598 |
import subprocess
import pathlib
import os
import shutil
# When you move on versions you can change the values here
MAJOR_VERSION = 0
MINOR_VERSION = 1
# What the name of your app should be
APP_NAME = "simple_folder"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def get_build_version():
'''
If there ... | installer_build.py | import subprocess
import pathlib
import os
import shutil
# When you move on versions you can change the values here
MAJOR_VERSION = 0
MINOR_VERSION = 1
# What the name of your app should be
APP_NAME = "simple_folder"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def get_build_version():
'''
If there ... | 0.311008 | 0.111265 |
import copy
import itertools
from axelrod.action import Action, str_to_actions
from axelrod.player import Player
C, D = Action.C, Action.D
class AntiCycler(Player):
"""
A player that follows a sequence of plays that contains no cycles:
CDD CD CCD CCCD CCCCD ...
Names:
- Anti Cycler: Original... | axelrod/strategies/cycler.py | import copy
import itertools
from axelrod.action import Action, str_to_actions
from axelrod.player import Player
C, D = Action.C, Action.D
class AntiCycler(Player):
"""
A player that follows a sequence of plays that contains no cycles:
CDD CD CCD CCCD CCCCD ...
Names:
- Anti Cycler: Original... | 0.802323 | 0.307722 |
import psycopg2
from entityservice.cache import progress as progress_cache
from entityservice.cache.active_runs import set_run_state_active, is_run_missing
from entityservice.database import DBConn, check_project_exists, get_run, get_run_state_for_update
from entityservice.database import update_run_set_started
from e... | anonlink-entity-service/backend/entityservice/tasks/run.py | import psycopg2
from entityservice.cache import progress as progress_cache
from entityservice.cache.active_runs import set_run_state_active, is_run_missing
from entityservice.database import DBConn, check_project_exists, get_run, get_run_state_for_update
from entityservice.database import update_run_set_started
from e... | 0.316053 | 0.067886 |
import json
import os
import glob
import pickle
import re
import time
import wget
import tarfile
import numpy as np
import tensorflow as tf
import matplotlib.image as mpimg
from skimage.transform import resize
from sklearn.decomposition import PCA
from tensorflow.python.keras.preprocessing.image import ImageDataGenera... | src/scripts/run_imagenette.py | import json
import os
import glob
import pickle
import re
import time
import wget
import tarfile
import numpy as np
import tensorflow as tf
import matplotlib.image as mpimg
from skimage.transform import resize
from sklearn.decomposition import PCA
from tensorflow.python.keras.preprocessing.image import ImageDataGenera... | 0.68595 | 0.334399 |
from user import User
from login import Login
import random
def create_user(fname,lname,phone,email,username,password):
'''
function to create new user
'''
new_user = User(fname,lname,phone,email,username,password)
return new_user
def create_login(social, firstname, lastname, username,password):
... | run.py | from user import User
from login import Login
import random
def create_user(fname,lname,phone,email,username,password):
'''
function to create new user
'''
new_user = User(fname,lname,phone,email,username,password)
return new_user
def create_login(social, firstname, lastname, username,password):
... | 0.124639 | 0.081996 |
import torch.nn.functional
import typing as _typing
import torch_geometric
from torch_geometric.nn.conv import GraphConv
from torch_geometric.nn.pool import TopKPooling
from torch_geometric.nn.glob import (
global_add_pool, global_max_pool, global_mean_pool
)
from ...encoders import base_encoder
from .. import base... | autogl/module/model/decoders/_pyg/_pyg_decoders.py | import torch.nn.functional
import typing as _typing
import torch_geometric
from torch_geometric.nn.conv import GraphConv
from torch_geometric.nn.pool import TopKPooling
from torch_geometric.nn.glob import (
global_add_pool, global_max_pool, global_mean_pool
)
from ...encoders import base_encoder
from .. import base... | 0.92367 | 0.37014 |
import math
import heapq
import numba as nb
import numpy as np
import copy
def get_id():
i = 0
while True:
yield i
i += 1
def graph_parse(adj_matrix):
g_num_nodes = adj_matrix.shape[0]
adj_table = {}
VOL = 0
node_vol = []
for i in range(g_num_nodes):
n_v = 0
... | lib/encoding_tree.py | import math
import heapq
import numba as nb
import numpy as np
import copy
def get_id():
i = 0
while True:
yield i
i += 1
def graph_parse(adj_matrix):
g_num_nodes = adj_matrix.shape[0]
adj_table = {}
VOL = 0
node_vol = []
for i in range(g_num_nodes):
n_v = 0
... | 0.139045 | 0.173288 |
from actstream import action
from actstream.models import any_stream
from apollo.forms import ToggleStaffForm
from applications.business.models import Business
from django.contrib import messages
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
def base(request):
... | apollo/views.py | from actstream import action
from actstream.models import any_stream
from apollo.forms import ToggleStaffForm
from applications.business.models import Business
from django.contrib import messages
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
def base(request):
... | 0.470007 | 0.069668 |
import numpy as np
from skimage.measure import marching_cubes_lewiner
from tqdm import tqdm
import trimesh
import torch
def decode_feature_grid(
nerf,
volume,
weight_mask,
num_hits,
sdf_delta,
min_coords,
max_coords,
volume_resolution,
voxel_size,
step_size=0.25,
batch_siz... | src/models/fusion/utils.py | import numpy as np
from skimage.measure import marching_cubes_lewiner
from tqdm import tqdm
import trimesh
import torch
def decode_feature_grid(
nerf,
volume,
weight_mask,
num_hits,
sdf_delta,
min_coords,
max_coords,
volume_resolution,
voxel_size,
step_size=0.25,
batch_siz... | 0.433981 | 0.417746 |
from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from ..models import DatabaseResize
from .factory import DatabaseResizeFactory
class DatabaseResizeTestCase(TestCase):
def setUp(self):
self.database_resize = DatabaseResizeFactory()
def tearDown(self):
... | dbaas/maintenance/tests/test_database_resize_model.py | from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from ..models import DatabaseResize
from .factory import DatabaseResizeFactory
class DatabaseResizeTestCase(TestCase):
def setUp(self):
self.database_resize = DatabaseResizeFactory()
def tearDown(self):
... | 0.60964 | 0.294133 |
import requests
from bs4 import BeautifulSoup
from proxy import Random_Proxy
def getMovies(query, page, proxie):
moviesDictionary = {
'success': True,
'query': query,
'data': [],
}
proxy = Random_Proxy()
try:
if proxie == 'true':
if page != None:
... | search.py | import requests
from bs4 import BeautifulSoup
from proxy import Random_Proxy
def getMovies(query, page, proxie):
moviesDictionary = {
'success': True,
'query': query,
'data': [],
}
proxy = Random_Proxy()
try:
if proxie == 'true':
if page != None:
... | 0.165965 | 0.068133 |
import pickle
import time
import discord
from discord import Game
from discord.ext.commands import Bot
from lstm_network import create
NEURAL_NET = create()
BOT_PREFIX = '!'
# Get at https://discordapp.com/developers/applications/me
TOKEN = open('../Bot/token.txt', 'r').readline().rstrip()
client = Bot(command_pr... | Bot/bot.py |
import pickle
import time
import discord
from discord import Game
from discord.ext.commands import Bot
from lstm_network import create
NEURAL_NET = create()
BOT_PREFIX = '!'
# Get at https://discordapp.com/developers/applications/me
TOKEN = open('../Bot/token.txt', 'r').readline().rstrip()
client = Bot(command_pr... | 0.386995 | 0.096621 |
from typing import TYPE_CHECKING
from msrest import Serializer
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.r... | sdk/storage/azure-storage-queue/azure/storage/queue/_generated/operations/_messages_operations.py | from typing import TYPE_CHECKING
from msrest import Serializer
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.r... | 0.786336 | 0.073364 |
import builtins
import os
from os.path import join
import sys
import time
import argparse
import random
import pdb
import json
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import numpy as np
from PIL import Image
from PIL import ImageFilter
from simreg import SimReg
from dataloader import g... | main.py | import builtins
import os
from os.path import join
import sys
import time
import argparse
import random
import pdb
import json
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import numpy as np
from PIL import Image
from PIL import ImageFilter
from simreg import SimReg
from dataloader import g... | 0.608361 | 0.070752 |
import re
import subprocess
import os.path
def extractFileFromIncludes( include ):
return re.match('#include \"(.+)\"(.*)\n', include).group(1)
def extractFilesFromIncludes( fileContent ):
res = []
for line in fileContent:
if line.startswith('#include \"'):
res.append(extractFileFro... | devel/tools/makeSingleHeaderHelpers.py | import re
import subprocess
import os.path
def extractFileFromIncludes( include ):
return re.match('#include \"(.+)\"(.*)\n', include).group(1)
def extractFilesFromIncludes( fileContent ):
res = []
for line in fileContent:
if line.startswith('#include \"'):
res.append(extractFileFro... | 0.103601 | 0.177098 |
from import_export import resources
from import_export.fields import Field
from import_export.admin import ImportExportModelAdmin
from apps.import_excel.models import PartsAuthority,Shopify
class PartsAuthorityResource(resources.ModelResource):
class Meta:
model = PartsAuthority
class ShopifyResource(resource... | apps/import_excel/resources.py |
from import_export import resources
from import_export.fields import Field
from import_export.admin import ImportExportModelAdmin
from apps.import_excel.models import PartsAuthority,Shopify
class PartsAuthorityResource(resources.ModelResource):
class Meta:
model = PartsAuthority
class ShopifyResource(resource... | 0.482673 | 0.098469 |
from ConversionUtil import wrapClass
from RegisterContext import registerContext
from pyspark.sql import DataFrame,SQLContext
class CaffeOnSpark:
"""CaffeOnSpark is the main class for distributed deep learning.
It will launch multiple Caffe cores within Spark executors, and conduct coordinated learning from H... | caffe-grid/src/main/python/com/yahoo/ml/caffe/CaffeOnSpark.py | from ConversionUtil import wrapClass
from RegisterContext import registerContext
from pyspark.sql import DataFrame,SQLContext
class CaffeOnSpark:
"""CaffeOnSpark is the main class for distributed deep learning.
It will launch multiple Caffe cores within Spark executors, and conduct coordinated learning from H... | 0.830388 | 0.394318 |
from __future__ import print_function #pylint bug workaround
import argparse
import os
import numpy as np
import pandas
import obj_tools
import neuralnets.grammar as grammar
SMILES_COL_NAME = "structure"
MAX_WORD_LENGTH = 120
ITERATIONS = 2
def get_arguments():
parser = argparse.ArgumentParser(description="Wavefr... | augment_dataset.py | from __future__ import print_function #pylint bug workaround
import argparse
import os
import numpy as np
import pandas
import obj_tools
import neuralnets.grammar as grammar
SMILES_COL_NAME = "structure"
MAX_WORD_LENGTH = 120
ITERATIONS = 2
def get_arguments():
parser = argparse.ArgumentParser(description="Wavefr... | 0.228587 | 0.084455 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import os
import re
import six
import json
import requests
import jsonpointer
from . import config
from . import exceptions
# Get descriptor base path
def ge... | datapackage/helpers.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import os
import re
import six
import json
import requests
import jsonpointer
from . import config
from . import exceptions
# Get descriptor base path
def ge... | 0.436502 | 0.050941 |
import pprint
from nose.tools import eq_
from .. import doi
from ...identifier import Identifier
INPUT_TEXT = """
This is a doi randomly placed in the text 10.0000/m1
Here's a typo that might be construed as a doi 10.60 people were there.
{{cite|...|doi=10.0000/m2|pmid=10559875}}
<ref><NAME>., <NAME>., <NAME>., & <N... | mwcites/extractors/tests/test_doi.py | import pprint
from nose.tools import eq_
from .. import doi
from ...identifier import Identifier
INPUT_TEXT = """
This is a doi randomly placed in the text 10.0000/m1
Here's a typo that might be construed as a doi 10.60 people were there.
{{cite|...|doi=10.0000/m2|pmid=10559875}}
<ref><NAME>., <NAME>., <NAME>., & <N... | 0.47317 | 0.36139 |
import os
import cv2
import math
import numpy as np
from typing import Optional, Tuple
__all__ = ['HeadPoseEstimator']
class HeadPoseEstimator(object):
def __init__(self, mean_shape_path: str = os.path.join(os.path.dirname(__file__),
'data', 'bfm_lms.np... | ibug/face_detection/utils/head_pose_estimator.py | import os
import cv2
import math
import numpy as np
from typing import Optional, Tuple
__all__ = ['HeadPoseEstimator']
class HeadPoseEstimator(object):
def __init__(self, mean_shape_path: str = os.path.join(os.path.dirname(__file__),
'data', 'bfm_lms.np... | 0.871721 | 0.505554 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import glob
import random
import collections
import math
from helper import *
from layer import *
from consts import *
Examples = collections.namedtuple("E... | dataloader.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import glob
import random
import collections
import math
from helper import *
from layer import *
from consts import *
Examples = collections.namedtuple("E... | 0.860149 | 0.341953 |
import argparse
import pandas as pd
from preprocessing.labels import encode_label
from preprocessing.tcga.utils import read_clinical_file
def main(
valid_tiles_file,
clinical_file,
output_tiles_labels_file,
patient_col_tiles_file,
patient_col_clinical_file,
label_cols,
):
tiles = pd.rea... | preprocessing_prepare_labels_tcga.py | import argparse
import pandas as pd
from preprocessing.labels import encode_label
from preprocessing.tcga.utils import read_clinical_file
def main(
valid_tiles_file,
clinical_file,
output_tiles_labels_file,
patient_col_tiles_file,
patient_col_clinical_file,
label_cols,
):
tiles = pd.rea... | 0.570331 | 0.387516 |
import docker
from twisted.python import log
RETRIES = 5
class NeverLocked(Exception):
pass
class AlreadyLocked(Exception):
pass
class Containers(object):
"""
Operations on the set of containers which pertain to dvol. Also maintain
state on which containers we stopped so that we can start them ... | dvol_python/dockercontainers.py | import docker
from twisted.python import log
RETRIES = 5
class NeverLocked(Exception):
pass
class AlreadyLocked(Exception):
pass
class Containers(object):
"""
Operations on the set of containers which pertain to dvol. Also maintain
state on which containers we stopped so that we can start them ... | 0.481454 | 0.256116 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim.lr_scheduler import StepLR
import numpy as np
import sar_data as sd
import test_sar_data as tsd
import os
import math
import time
import argparse
import scipy as sp
import scipy.stats
import scipy.io
... | optical/test.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim.lr_scheduler import StepLR
import numpy as np
import sar_data as sd
import test_sar_data as tsd
import os
import math
import time
import argparse
import scipy as sp
import scipy.stats
import scipy.io
... | 0.665628 | 0.159217 |
import unittest
from unittest import TestCase, mock
from unittest.mock import MagicMock
from http.client import HTTPResponse
from vivino.geocoder.helpers import get_coordinates
class TestHelpers(TestCase):
@mock.patch('helpers.urllib.request.urlopen')
def test_get_coordinates_valid_json_response(self, mo... | vivino/geocoder/test_helpers.py | import unittest
from unittest import TestCase, mock
from unittest.mock import MagicMock
from http.client import HTTPResponse
from vivino.geocoder.helpers import get_coordinates
class TestHelpers(TestCase):
@mock.patch('helpers.urllib.request.urlopen')
def test_get_coordinates_valid_json_response(self, mo... | 0.656768 | 0.493897 |
from datetime import datetime, date
from uuid import uuid4
from django.db.models import Model
from elasticsearch.exceptions import NotFoundError
from django_elasticsearch_model_binder.exceptions import (
ElasticSearchFailure,
UnableToCastESNominatedFieldException,
UnableToDeleteModelFromElasticSearch,
... | django_elasticsearch_model_binder/models.py | from datetime import datetime, date
from uuid import uuid4
from django.db.models import Model
from elasticsearch.exceptions import NotFoundError
from django_elasticsearch_model_binder.exceptions import (
ElasticSearchFailure,
UnableToCastESNominatedFieldException,
UnableToDeleteModelFromElasticSearch,
... | 0.751375 | 0.162579 |
import numpy as np
import matplotlib.pyplot as plt
class SnapshotProcessing:
def __init__(self,y,chem_obj,grid):
self.y = y
self.y_eq = chem_obj.equilibrate()
self.gas = chem_obj.gas
self.grid = grid
self.x = np.zeros((self.gas.n_species,self.grid.N))
self.x_eq = self.x.copy()
for i in range(self.gr... | diffusion_kinetics/snapshot_processing.py | import numpy as np
import matplotlib.pyplot as plt
class SnapshotProcessing:
def __init__(self,y,chem_obj,grid):
self.y = y
self.y_eq = chem_obj.equilibrate()
self.gas = chem_obj.gas
self.grid = grid
self.x = np.zeros((self.gas.n_species,self.grid.N))
self.x_eq = self.x.copy()
for i in range(self.gr... | 0.386185 | 0.452838 |
import base64
import getopt
import os
import json
import re
import sys
import urllib
from urllib import request
import bakthread
import requests
banner = '''
_ _ _ _
| |_ ___ | |__ ___ | |_ ___ ___ | |__
| . \<_> || / // | '| . |/ ._>/ | '| / /
|___/<___||_\_\\_|_.|_|_|\___.\_|_.|_\... | bakscan.py | import base64
import getopt
import os
import json
import re
import sys
import urllib
from urllib import request
import bakthread
import requests
banner = '''
_ _ _ _
| |_ ___ | |__ ___ | |_ ___ ___ | |__
| . \<_> || / // | '| . |/ ._>/ | '| / /
|___/<___||_\_\\_|_.|_|_|\___.\_|_.|_\... | 0.035153 | 0.067824 |
from decimal import Decimal
class VaultHelper(object):
def __init__(self, context):
self.tenants = dict()
self.context = context
def reset(self):
self.tenants = dict()
def get_account(self, tenant, account):
if not self.account_exist(tenant, account):
return {}
return self.tenants[... | bbtest/helpers/vault.py |
from decimal import Decimal
class VaultHelper(object):
def __init__(self, context):
self.tenants = dict()
self.context = context
def reset(self):
self.tenants = dict()
def get_account(self, tenant, account):
if not self.account_exist(tenant, account):
return {}
return self.tenants[... | 0.613237 | 0.085633 |
import asyncio
import json
import random
import secrets
from email.message import EmailMessage
import aiosmtplib
import discord
from redbot.core import Config, commands
from redbot.core.data_manager import bundled_data_path, cog_data_path
from redbot.core.utils.chat_formatting import pagify
from redbot.core.utils.menu... | verify/verify.py | import asyncio
import json
import random
import secrets
from email.message import EmailMessage
import aiosmtplib
import discord
from redbot.core import Config, commands
from redbot.core.data_manager import bundled_data_path, cog_data_path
from redbot.core.utils.chat_formatting import pagify
from redbot.core.utils.menu... | 0.468061 | 0.102125 |
import argparse
import sys
import random
from pathlib import Path
import sampling.conll as conll
import sampling.wikiner as wikiner
import sampling.wikinews as wikinews
import sampling.text as text
import sampling.apil as apil
def guess_format(pathname):
if pathname.is_dir():
return "wikinews"
if str... | sampling/sample.py | import argparse
import sys
import random
from pathlib import Path
import sampling.conll as conll
import sampling.wikiner as wikiner
import sampling.wikinews as wikinews
import sampling.text as text
import sampling.apil as apil
def guess_format(pathname):
if pathname.is_dir():
return "wikinews"
if str... | 0.298287 | 0.202621 |
import pytest
from flask import url_for
from . import days_from_now_millis
@pytest.mark.options(PAGE_SIZE=2)
def test_get_paginated(client, config, event_factory):
event_factory.create_batch(5)
url = url_for("api.event_collection")
rv = client.get(url)
assert rv.status_code == 200
assert len(rv.j... | tests/test_resource_event_collection.py | import pytest
from flask import url_for
from . import days_from_now_millis
@pytest.mark.options(PAGE_SIZE=2)
def test_get_paginated(client, config, event_factory):
event_factory.create_batch(5)
url = url_for("api.event_collection")
rv = client.get(url)
assert rv.status_code == 200
assert len(rv.j... | 0.420957 | 0.390185 |
from datetime import date, datetime, timezone
from unittest import TestCase
import pandas
from freezegun import freeze_time
from pandas.testing import assert_frame_equal
from petri_dish.app import Dish
from petri_dish.connectors import DummyConnector
class GetAllSubjectsTestCase(TestCase):
@freeze_time('2017-10... | tests/test_app.py | from datetime import date, datetime, timezone
from unittest import TestCase
import pandas
from freezegun import freeze_time
from pandas.testing import assert_frame_equal
from petri_dish.app import Dish
from petri_dish.connectors import DummyConnector
class GetAllSubjectsTestCase(TestCase):
@freeze_time('2017-10... | 0.692122 | 0.327144 |
from typing import Any, ByteString
from aimm.plugins import common
from aimm.plugins import decorators
def exec_data_access(name: str,
state_cb: common.StateCallback = lambda state: None,
*args: Any,
**kwargs: Any) -> Any:
"""Uses a loaded plugin to ... | aimm/plugins/execute.py | from typing import Any, ByteString
from aimm.plugins import common
from aimm.plugins import decorators
def exec_data_access(name: str,
state_cb: common.StateCallback = lambda state: None,
*args: Any,
**kwargs: Any) -> Any:
"""Uses a loaded plugin to ... | 0.848549 | 0.231028 |
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Car(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
na... | carsell/models.py | from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Car(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
na... | 0.589953 | 0.17824 |
from __future__ import annotations
import asyncio
from collections.abc import Callable
from contextlib import AbstractAsyncContextManager
import random
from typing import Any, cast
from aiohttp import ClientResponse, ClientSession, ClientTimeout
from .consts import API_URL, LOGIN_KEY, TIMEOUT
from .except... | asyncsleepiq/api.py | from __future__ import annotations
import asyncio
from collections.abc import Callable
from contextlib import AbstractAsyncContextManager
import random
from typing import Any, cast
from aiohttp import ClientResponse, ClientSession, ClientTimeout
from .consts import API_URL, LOGIN_KEY, TIMEOUT
from .except... | 0.730001 | 0.055209 |
from math import sqrt
from typing import Dict, Union
import pandas as pd
from gs_quant.api.gs.data import GsDataApi
from gs_quant.data.core import DataContext
from gs_quant.datetime import date
from gs_quant.errors import MqValueError
from gs_quant.models.risk_model import FactorRiskModel, ReturnFormat
from gs_quant.... | gs_quant/markets/factor.py | from math import sqrt
from typing import Dict, Union
import pandas as pd
from gs_quant.api.gs.data import GsDataApi
from gs_quant.data.core import DataContext
from gs_quant.datetime import date
from gs_quant.errors import MqValueError
from gs_quant.models.risk_model import FactorRiskModel, ReturnFormat
from gs_quant.... | 0.914367 | 0.36108 |
from worker import Crawler
import pymysql
from selenium import webdriver
baseUrl = "http://www.sxfj.gov.cn/"
indexUrl = baseUrl + "PageShowNext.aspx?ID=24"
browser = webdriver.Chrome("d:/chromedriver.exe")
class HNCrawler(Crawler.CrawlerInterface):
def get_num(self):
soup = self.get_soup(indexUrl)
... | worker/HuNanCrawler.py | from worker import Crawler
import pymysql
from selenium import webdriver
baseUrl = "http://www.sxfj.gov.cn/"
indexUrl = baseUrl + "PageShowNext.aspx?ID=24"
browser = webdriver.Chrome("d:/chromedriver.exe")
class HNCrawler(Crawler.CrawlerInterface):
def get_num(self):
soup = self.get_soup(indexUrl)
... | 0.168241 | 0.067824 |
from pyvdp.visadirect import VisaDirectDispatcher
def send(data):
"""Submits a MultiPullFundsTransactions (AFT) request.
:param data: **Required**.
Instance of :func:`~pyvdp.visadirect.fundstransfer.MultiPullFundsTransactionsModel`.
:return: Dictionary with VDP API response.
**Us... | pyvdp/visadirect/fundstransfer/multipullfundstransactions.py | from pyvdp.visadirect import VisaDirectDispatcher
def send(data):
"""Submits a MultiPullFundsTransactions (AFT) request.
:param data: **Required**.
Instance of :func:`~pyvdp.visadirect.fundstransfer.MultiPullFundsTransactionsModel`.
:return: Dictionary with VDP API response.
**Us... | 0.819569 | 0.197348 |
import logging
import numpy as np
try:
from scipy.optimize import curve_fit
enable_scipy = True
except:
enable_scipy = False
from chainerpruner import Graph
from chainerpruner.masks import NormMask
from chainerpruner.rebuild.rebuild import rebuild
logger = logging.getLogger(__name__)
class Progressi... | chainerpruner/pruning/psfp/psfp.py |
import logging
import numpy as np
try:
from scipy.optimize import curve_fit
enable_scipy = True
except:
enable_scipy = False
from chainerpruner import Graph
from chainerpruner.masks import NormMask
from chainerpruner.rebuild.rebuild import rebuild
logger = logging.getLogger(__name__)
class Progressi... | 0.733165 | 0.345906 |
import logging
from pprint import pprint
import boto3
from botocore.exceptions import ClientError
import boto3
logger = logging.getLogger(__name__)
rekognition_client = boto3.client('rekognition')
class RekognitionText:
"""Encapsulates an Amazon Rekognition text element."""
def __init__(self, text_data):
... | card_determiner.py | import logging
from pprint import pprint
import boto3
from botocore.exceptions import ClientError
import boto3
logger = logging.getLogger(__name__)
rekognition_client = boto3.client('rekognition')
class RekognitionText:
"""Encapsulates an Amazon Rekognition text element."""
def __init__(self, text_data):
... | 0.727879 | 0.209854 |
import os
import docker
import socket
import logging
from docker.utils import kwargs_from_env
class SAIDaemon:
"""
The appearence of the SIA
"""
def build(self, path_dockerfile=''):
if path_dockerfile == '':
path_dockerfile = os.getcwd()
client = None
api_client =... | SAIDaemon.py | import os
import docker
import socket
import logging
from docker.utils import kwargs_from_env
class SAIDaemon:
"""
The appearence of the SIA
"""
def build(self, path_dockerfile=''):
if path_dockerfile == '':
path_dockerfile = os.getcwd()
client = None
api_client =... | 0.161717 | 0.066206 |
import os
class QTRun(object):
"""Run Ixia QuickTest.
"""
def __init__(self, request, tg):
"""Initialize QTRun class.
Args:
request(pytest.request): pytest request
tg(Environment instance): Ixia TG object
Raises:
Exception: Incorrect fixtu... | taf/testlib/Ixia/ixia_fixtures.py | import os
class QTRun(object):
"""Run Ixia QuickTest.
"""
def __init__(self, request, tg):
"""Initialize QTRun class.
Args:
request(pytest.request): pytest request
tg(Environment instance): Ixia TG object
Raises:
Exception: Incorrect fixtu... | 0.589835 | 0.210665 |
import argparse
import random
import socket
import sys
import urlparse
import json
from wsgiref.simple_server import make_server
TIMEZONE = "US/Central"
def validate_parameters(query_dict, parameters):
"""
Check parameters in query_dict using the parameters specified
:param query_dict: a dictionary with... | wsgi/freesurfer_test.py |
import argparse
import random
import socket
import sys
import urlparse
import json
from wsgiref.simple_server import make_server
TIMEZONE = "US/Central"
def validate_parameters(query_dict, parameters):
"""
Check parameters in query_dict using the parameters specified
:param query_dict: a dictionary with... | 0.340376 | 0.25508 |
import numpy as np
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
from PIL import Image
import cv2
def affine_elastic_transform(image, mask=None, alpha=100, sigma=11,
alpha_affine=40, random_state=None):
image = np.array(image... | elastic_transform.py | import numpy as np
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
from PIL import Image
import cv2
def affine_elastic_transform(image, mask=None, alpha=100, sigma=11,
alpha_affine=40, random_state=None):
image = np.array(image... | 0.654343 | 0.670541 |
from datetime import datetime
from flask import Flask, render_template, redirect, url_for, flash, request
from flask_sqlalchemy import SQLAlchemy
from forms import SubmissionForm
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
SECRET_KEY = 'hrifrgtkghgt'
UPLOAD_FOLDER = '/uploads'... | main.py | from datetime import datetime
from flask import Flask, render_template, redirect, url_for, flash, request
from flask_sqlalchemy import SQLAlchemy
from forms import SubmissionForm
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
SECRET_KEY = 'hrifrgtkghgt'
UPLOAD_FOLDER = '/uploads'... | 0.399929 | 0.044369 |
import distutils.cmd
import distutils.log
import os
from shutil import rmtree
import pip
from setuptools import find_packages, setup
if tuple(map(int, pip.__version__.split("."))) >= (19, 3, 0):
from pip._internal.network.session import PipSession
from pip._internal.req import parse_requirements
elif tuple(ma... | setup.py | import distutils.cmd
import distutils.log
import os
from shutil import rmtree
import pip
from setuptools import find_packages, setup
if tuple(map(int, pip.__version__.split("."))) >= (19, 3, 0):
from pip._internal.network.session import PipSession
from pip._internal.req import parse_requirements
elif tuple(ma... | 0.278061 | 0.15511 |
import argparse
import numpy as np
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import inputparser
import mutphi
import common
def sort_mutphi(mphi):
sorted_vids = common.sort_vids(mphi.vids)
mapping = [mphi.vids.index(V) for V in sorted_vids]
assert sorted_vids == ... | comparison/impute_missing_mutphis.py | import argparse
import numpy as np
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import inputparser
import mutphi
import common
def sort_mutphi(mphi):
sorted_vids = common.sort_vids(mphi.vids)
mapping = [mphi.vids.index(V) for V in sorted_vids]
assert sorted_vids == ... | 0.251005 | 0.44342 |
import os
import platform
import shutil
from conans import ConanFile, tools
class AndroidtoolchainConan(ConanFile):
name = "android-toolchain"
version = "r17b"
license = "GPL/APACHE2"
url = "https://github.com/lasote/conan-android-toolchain"
settings = "os", "arch", "compiler"
options = {"use... | android-toolchain/conanfile.py | import os
import platform
import shutil
from conans import ConanFile, tools
class AndroidtoolchainConan(ConanFile):
name = "android-toolchain"
version = "r17b"
license = "GPL/APACHE2"
url = "https://github.com/lasote/conan-android-toolchain"
settings = "os", "arch", "compiler"
options = {"use... | 0.425486 | 0.090534 |
__author__ = 'wittawat'
from abc import ABCMeta, abstractmethod
import numpy as np
import scipy.signal as sig
from mskernel import util
class Kernel(object):
"""Abstract class for kernels"""
__metaclass__ = ABCMeta
@abstractmethod
def eval(self, X1, X2):
"""Evalute the kernel on data X1 and ... | mskernel/kernel.py |
__author__ = 'wittawat'
from abc import ABCMeta, abstractmethod
import numpy as np
import scipy.signal as sig
from mskernel import util
class Kernel(object):
"""Abstract class for kernels"""
__metaclass__ = ABCMeta
@abstractmethod
def eval(self, X1, X2):
"""Evalute the kernel on data X1 and ... | 0.816223 | 0.692642 |
import pytest
from tape import Tape
def test_get_content_of_non_empty_tape():
tape = Tape('B', ['a', 'b', 'X', 'B'], ['a', 'b'])
assert tape.get_content() == 'a'
def test_get_content_of_empty_tape():
tape = Tape('B', ['a', 'b', 'X', 'B'], [])
assert tape.get_content() == 'B'
def test_get_content_of_... | test_tape.py | import pytest
from tape import Tape
def test_get_content_of_non_empty_tape():
tape = Tape('B', ['a', 'b', 'X', 'B'], ['a', 'b'])
assert tape.get_content() == 'a'
def test_get_content_of_empty_tape():
tape = Tape('B', ['a', 'b', 'X', 'B'], [])
assert tape.get_content() == 'B'
def test_get_content_of_... | 0.59561 | 0.567577 |
# cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=2018133209
from school_sdk.client.api import BaseCrawler
class Score(BaseCrawler):
def __init__(self, user_client) -> None:
super().__init__(user_client)
self.endpoints: dict = self.school.config['url_endpoints']
self.raw_score = N... | school_sdk/client/api/score.py | # cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=2018133209
from school_sdk.client.api import BaseCrawler
class Score(BaseCrawler):
def __init__(self, user_client) -> None:
super().__init__(user_client)
self.endpoints: dict = self.school.config['url_endpoints']
self.raw_score = N... | 0.531696 | 0.202561 |
from musurgia.random import Random
class ReadAList(object):
##mode in forwards, backwards, zickzack, random
def __init__(self, pool=None, mode='random', seed=None):
self._pool = None
self._mode = None
self._random = None
self._index = None
self._direction = 1
se... | musurgia/readalist.py | from musurgia.random import Random
class ReadAList(object):
##mode in forwards, backwards, zickzack, random
def __init__(self, pool=None, mode='random', seed=None):
self._pool = None
self._mode = None
self._random = None
self._index = None
self._direction = 1
se... | 0.480722 | 0.215021 |
import numpy as np
from scipy.special import lpmv, gamma, hyp1f1, legendre
from scipy.special.orthogonal import genlaguerre
from scipy.misc import factorial
_default_rank = 4
class SphericalHarmonics:
"""This class describes a real, antipodally symmetric spherical function by
its spherical harmonics coeff... | qspace/bases/sh.py |
import numpy as np
from scipy.special import lpmv, gamma, hyp1f1, legendre
from scipy.special.orthogonal import genlaguerre
from scipy.misc import factorial
_default_rank = 4
class SphericalHarmonics:
"""This class describes a real, antipodally symmetric spherical function by
its spherical harmonics coeff... | 0.913621 | 0.72113 |
import collections
import re
from copy import copy
from decimal import Decimal
from beancount.core.data import Custom, Transaction
from beancount.core.amount import Amount, add, sub, mul, div
from beancount.core import account, getters, realization
__plugins__ = ['balexpr']
BalExprError = collections.namedtuple('Ba... | beancount_balexpr/balexpr.py |
import collections
import re
from copy import copy
from decimal import Decimal
from beancount.core.data import Custom, Transaction
from beancount.core.amount import Amount, add, sub, mul, div
from beancount.core import account, getters, realization
__plugins__ = ['balexpr']
BalExprError = collections.namedtuple('Ba... | 0.38549 | 0.41253 |
# see scripts/percentiletest.py for an example
from typing import Tuple, Mapping, Callable, Optional, Any, cast
from typing_extensions import TypedDict
import numpy as np
from . import accel
from . import tune
from .abc import AbstractContext, AbstractCommandQueue
_TuningDict = TypedDict('_TuningDict', {'size': in... | katsdpsigproc/percentile.py | # see scripts/percentiletest.py for an example
from typing import Tuple, Mapping, Callable, Optional, Any, cast
from typing_extensions import TypedDict
import numpy as np
from . import accel
from . import tune
from .abc import AbstractContext, AbstractCommandQueue
_TuningDict = TypedDict('_TuningDict', {'size': in... | 0.865352 | 0.558748 |