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
def test_ada05_ok_1_adb(style_checker):
"""Style check test against ada05-ok-1.adb
"""
style_checker.set_year(2006)
p = style_checker.run_style_checker('/paris.a/cvs/Dev/toto', 'ada05-ok-1.adb')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
d... | testsuite/tests/NA17-007__Ada_units/run_test.py | import os
def test_ada05_ok_1_adb(style_checker):
"""Style check test against ada05-ok-1.adb
"""
style_checker.set_year(2006)
p = style_checker.run_style_checker('/paris.a/cvs/Dev/toto', 'ada05-ok-1.adb')
style_checker.assertEqual(p.status, 0, p.image)
style_checker.assertRunOutputEmpty(p)
d... | 0.545286 | 0.552479 |
import collections
import itertools
import typing
from typing import Iterable, Tuple
import bblfsh
from .tree import Tree
WILDCARD = '_MATCH_ANY_'
class UAST(Tree[Tuple[str,str]]):
def __init__(self, key: Tuple[str,str], children: Iterable['UAST']=tuple()) -> None:
super(UAST, self).__init__(key, c... | badcode/bblfshutil.py | import collections
import itertools
import typing
from typing import Iterable, Tuple
import bblfsh
from .tree import Tree
WILDCARD = '_MATCH_ANY_'
class UAST(Tree[Tuple[str,str]]):
def __init__(self, key: Tuple[str,str], children: Iterable['UAST']=tuple()) -> None:
super(UAST, self).__init__(key, c... | 0.738009 | 0.23001 |
from utility import process_file, parse_args, printd, \
file_exists, get_params, load_pickle, write_list
from multiprocessing import Manager
from collections import Counter
from preprocess_model import num_samples, create_kmer_sample_map, \
parse_input, similar_sample, create_disp_nodisp_dfs
import int_maps
from os.pat... | psl-gwas/preprocess.py | from utility import process_file, parse_args, printd, \
file_exists, get_params, load_pickle, write_list
from multiprocessing import Manager
from collections import Counter
from preprocess_model import num_samples, create_kmer_sample_map, \
parse_input, similar_sample, create_disp_nodisp_dfs
import int_maps
from os.pat... | 0.371593 | 0.160957 |
import yaml
from .slots_object_model import SlotsObjectModel
from .common import Undefined, Field
import importlib
import sys
PY3 = sys.version_info >= (3, 0)
if PY3:
unicode = str
# types from the open api specification (see details: https://swagger.io/docs/specification/data-models/data-types/)
TYPES = {
... | object_modeler/yaml_model.py | import yaml
from .slots_object_model import SlotsObjectModel
from .common import Undefined, Field
import importlib
import sys
PY3 = sys.version_info >= (3, 0)
if PY3:
unicode = str
# types from the open api specification (see details: https://swagger.io/docs/specification/data-models/data-types/)
TYPES = {
... | 0.376279 | 0.282162 |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from imdb import IMDb
from cinemanio.core.models import Movie, Person, Genre, Language, Country
from cinemanio.sites.exceptions import PossibleDuplicate, NothingFound, WrongValue
from cinemanio.sites.models import SitesBaseModel
cla... | cinemanio/sites/imdb/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from imdb import IMDb
from cinemanio.core.models import Movie, Person, Genre, Language, Country
from cinemanio.sites.exceptions import PossibleDuplicate, NothingFound, WrongValue
from cinemanio.sites.models import SitesBaseModel
cla... | 0.379493 | 0.115187 |
import tflite_runtime.interpreter as tflite
import numpy as np
import os
def run_mock_model(delegate, test_data_folder):
model_path = os.path.join(test_data_folder, 'mock_model.tflite')
interpreter = tflite.Interpreter(model_path=model_path,
experimental_delegates=[delega... | delegate/python/test/utils.py |
import tflite_runtime.interpreter as tflite
import numpy as np
import os
def run_mock_model(delegate, test_data_folder):
model_path = os.path.join(test_data_folder, 'mock_model.tflite')
interpreter = tflite.Interpreter(model_path=model_path,
experimental_delegates=[delega... | 0.394667 | 0.273647 |
from gimpfu import *
import math
def create_spritesheet(image, singleRow, widthCells, heightCells):
# Grab all the layers from the original image, each one of which will become an animation frame
layers = image.layers
numLayers = len(layers)
# Work out how many rows and columns we need for each of o... | GIMP/create_spritesheet.py |
from gimpfu import *
import math
def create_spritesheet(image, singleRow, widthCells, heightCells):
# Grab all the layers from the original image, each one of which will become an animation frame
layers = image.layers
numLayers = len(layers)
# Work out how many rows and columns we need for each of o... | 0.487307 | 0.597901 |
from argparse import BooleanOptionalAction
from asyncio import current_task
from msilib.schema import Directory
from tkinter.messagebox import ABORTRETRYIGNORE
from tkinter.tix import REAL
from pkg_resources import NullProvider
tipo CUENTA estructura
saldo: REAL
descubierto: REAL
invariante
#El ... | ej12.py | from argparse import BooleanOptionalAction
from asyncio import current_task
from msilib.schema import Directory
from tkinter.messagebox import ABORTRETRYIGNORE
from tkinter.tix import REAL
from pkg_resources import NullProvider
tipo CUENTA estructura
saldo: REAL
descubierto: REAL
invariante
#El ... | 0.261897 | 0.240563 |
from pathlib import Path
from unittest import mock
from cico.results import File, Directory, Badge
from cico.results.results import Result, Copy
class TestResult:
def test_return_from_to(self, dest):
returns = [Path("file"), Path("dir")]
with mock.patch.object(Result, "_to", return_value=returns)... | tests/test_results.py | from pathlib import Path
from unittest import mock
from cico.results import File, Directory, Badge
from cico.results.results import Result, Copy
class TestResult:
def test_return_from_to(self, dest):
returns = [Path("file"), Path("dir")]
with mock.patch.object(Result, "_to", return_value=returns)... | 0.672224 | 0.448004 |
import mock
from mistralclient.api.v2 import members
from mistralclient.commands.v2 import members as member_cmd
from mistralclient.tests.unit import base
MEMBER_DICT = {
'id': '123',
'resource_id': '456',
'resource_type': 'workflow',
'project_id': '1111',
'member_id': '2222',
'status': 'pend... | mistralclient/tests/unit/v2/test_cli_members.py |
import mock
from mistralclient.api.v2 import members
from mistralclient.commands.v2 import members as member_cmd
from mistralclient.tests.unit import base
MEMBER_DICT = {
'id': '123',
'resource_id': '456',
'resource_type': 'workflow',
'project_id': '1111',
'member_id': '2222',
'status': 'pend... | 0.411702 | 0.166404 |
from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
from matplotlib import pyplot as plt
from astropy.wcs import WCS
###Display a white light image
def show_whitelight(whiteim, header=None):
"""
Args:
whiteim: ndarray
header:
Returns:
... | kcwitools/plot.py | from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
from matplotlib import pyplot as plt
from astropy.wcs import WCS
###Display a white light image
def show_whitelight(whiteim, header=None):
"""
Args:
whiteim: ndarray
header:
Returns:
... | 0.710528 | 0.452354 |
from unittest import TestCase
from mock import Mock
from os import path
import time
from unit.common.mock_resources import *
from dispatcher.dispatcher_exception import DispatcherException
from dispatcher.workload_orchestration import *
from dispatcher.constants import *
from mock import patch
import logging
import m... | inbm/dispatcher-agent/tests/unit/test_workload_orchestration.py | from unittest import TestCase
from mock import Mock
from os import path
import time
from unit.common.mock_resources import *
from dispatcher.dispatcher_exception import DispatcherException
from dispatcher.workload_orchestration import *
from dispatcher.constants import *
from mock import patch
import logging
import m... | 0.512693 | 0.187393 |
from pathlib import Path
from overrides import overrides
from python import EVENT, DOCUMENT_ID
from python.handwritten_baseline.pipeline.data.loader import football_reader_utils
from python.handwritten_baseline.pipeline.data.base import Dataset
from python.handwritten_baseline.pipeline.data.loader.fcc_loader_base imp... | python/handwritten_baseline/pipeline/data/loader/fcc_loader_token.py | from pathlib import Path
from overrides import overrides
from python import EVENT, DOCUMENT_ID
from python.handwritten_baseline.pipeline.data.loader import football_reader_utils
from python.handwritten_baseline.pipeline.data.base import Dataset
from python.handwritten_baseline.pipeline.data.loader.fcc_loader_base imp... | 0.72526 | 0.267459 |
import tensorflow as tf
from tensorflow.keras.models import Model
from compression_tools.decompose.decompose_schemes import decompose_conv2d_layer
from compression_tools.decompose.rank_estimation import estimate_rank
from tools.visualization.decompose_visualization_tool import plot_rank_percentage
from tools.progress.b... | compression_tools/decompose/__init__.py | import tensorflow as tf
from tensorflow.keras.models import Model
from compression_tools.decompose.decompose_schemes import decompose_conv2d_layer
from compression_tools.decompose.rank_estimation import estimate_rank
from tools.visualization.decompose_visualization_tool import plot_rank_percentage
from tools.progress.b... | 0.706697 | 0.546254 |
from datetime import date
from io import BytesIO
import factory
import pytest
from django.core.management import call_command
from reversion.models import Version
from datahub.core.constants import InvestmentProjectStage
from datahub.investment.project.test.factories import InvestmentProjectFactory
pytestmark = pyte... | datahub/dbmaintenance/test/commands/test_update_investment_project_actual_land_date.py | from datetime import date
from io import BytesIO
import factory
import pytest
from django.core.management import call_command
from reversion.models import Version
from datahub.core.constants import InvestmentProjectStage
from datahub.investment.project.test.factories import InvestmentProjectFactory
pytestmark = pyte... | 0.72594 | 0.362066 |
import argparse
arg_lists = []
parser = argparse.ArgumentParser(description='mobilenet_classification')
def str2bool(v):
return v.lower() in ('true', '1')
def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
return arg
# data params
data_arg = a... | config.py | import argparse
arg_lists = []
parser = argparse.ArgumentParser(description='mobilenet_classification')
def str2bool(v):
return v.lower() in ('true', '1')
def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
return arg
# data params
data_arg = a... | 0.501465 | 0.089933 |
import re
import enchant
from nltk.metrics import edit_distance
from nltk.corpus import wordnet
replacement_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
(r'ain\'t', 'is not'),
... | src/Replacers.py | import re
import enchant
from nltk.metrics import edit_distance
from nltk.corpus import wordnet
replacement_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
(r'ain\'t', 'is not'),
... | 0.322526 | 0.180431 |
import os
import numpy as np
from shapely.geometry import box, Point, shape
def transform_shape_raster(infile):
"""Reads raster AOI bounds and reprojects to EPSG:4326. Returns bounds as shapely polygon.
Parameters
----------
infile : str
Path to raster AOI.
Returns
-------
shp :... | tidepods/generate_pts.py | import os
import numpy as np
from shapely.geometry import box, Point, shape
def transform_shape_raster(infile):
"""Reads raster AOI bounds and reprojects to EPSG:4326. Returns bounds as shapely polygon.
Parameters
----------
infile : str
Path to raster AOI.
Returns
-------
shp :... | 0.871297 | 0.639539 |
import os
import sys
import json
from typing import Set, Dict, Union, Optional, Tuple
import common.utils as utils
DEFAULT_LATE_PENALTY = .2
# Probably better to just look at a grades.json
GradesDictType = Dict[str, # Submitter
Dict[str, Union[bool, # is_late
... | common/grades.py | import os
import sys
import json
from typing import Set, Dict, Union, Optional, Tuple
import common.utils as utils
DEFAULT_LATE_PENALTY = .2
# Probably better to just look at a grades.json
GradesDictType = Dict[str, # Submitter
Dict[str, Union[bool, # is_late
... | 0.555918 | 0.230985 |
from http.server import BaseHTTPRequestHandler, HTTPServer
import bpy
import json
import sys
argv = sys.argv
argv = argv[argv.index("--") + 1:]
outputFolder=argv[0]
blendFolder=argv[1]
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-... | rendering/rest-api.py | from http.server import BaseHTTPRequestHandler, HTTPServer
import bpy
import json
import sys
argv = sys.argv
argv = argv[argv.index("--") + 1:]
outputFolder=argv[0]
blendFolder=argv[1]
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-... | 0.216757 | 0.086131 |
from itertools import product
def get_floorplan():
with open('day11_input.txt') as f:
return [l.strip() for l in f.readlines() if l.strip()]
class FloorPlan(object):
class Cell(object):
ALIVE = '#'
DEAD = 'L'
EMPTY = '.'
def __init__(self, l):
if l == sel... | day11.py | from itertools import product
def get_floorplan():
with open('day11_input.txt') as f:
return [l.strip() for l in f.readlines() if l.strip()]
class FloorPlan(object):
class Cell(object):
ALIVE = '#'
DEAD = 'L'
EMPTY = '.'
def __init__(self, l):
if l == sel... | 0.546012 | 0.363675 |
import json
import numpy as np
import math
import os
import copy
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from . import commons as bc
from . import climate
from . import shading
# データベースファイルの保存場所
database_directory = os.path.dirname(os.path.abspath(__file__)) + "/database/"
def calc_... | builelib/other_energy.py | import json
import numpy as np
import math
import os
import copy
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from . import commons as bc
from . import climate
from . import shading
# データベースファイルの保存場所
database_directory = os.path.dirname(os.path.abspath(__file__)) + "/database/"
def calc_... | 0.099268 | 0.153042 |
import cmath
import contextlib
import pytest
import threading
from bionic.code_hasher import CodeHasher, TypePrefix
def test_code_hasher():
def barray(value):
return bytearray(value, "utf8")
circular_dict_1_a = {"k11": "v1"}
circular_dict_1_b = {"k21": "v2"}
circular_dict_1_c = {"k31": "v3"}... | tests/test_code_hasher.py | import cmath
import contextlib
import pytest
import threading
from bionic.code_hasher import CodeHasher, TypePrefix
def test_code_hasher():
def barray(value):
return bytearray(value, "utf8")
circular_dict_1_a = {"k11": "v1"}
circular_dict_1_b = {"k21": "v2"}
circular_dict_1_c = {"k31": "v3"}... | 0.74512 | 0.444083 |
class RK4Integrator:
def __init__(self):
pass
def integrate(self, equations, t0, x0, y0, x0d, y0d, h):
f = equations.xFunc
g = equations.yFunc
# Approximation of y" in t0
l0 = g(t0, x0, y0, x0d, y0d) # = y0dd
# Approximation of x" in t0
k0 = f(t0, x0, y... | src/math/rk4_integrator.py | class RK4Integrator:
def __init__(self):
pass
def integrate(self, equations, t0, x0, y0, x0d, y0d, h):
f = equations.xFunc
g = equations.yFunc
# Approximation of y" in t0
l0 = g(t0, x0, y0, x0d, y0d) # = y0dd
# Approximation of x" in t0
k0 = f(t0, x0, y... | 0.904695 | 0.758153 |
from numpy import log2, mean, std, ceil, arange, sqrt, zeros, log
from pylab import hist, title, plot, figure, ylabel, xlabel, axis, step
from scipy.stats import norm
from statsmodels.distributions import ECDF
# Aquí simula n normales padrón, saca su media, su varianza
# y hace un histogrma
nn=1000
x=norm.rvs(... | content/courses/inf2019/0_ECDF.py | from numpy import log2, mean, std, ceil, arange, sqrt, zeros, log
from pylab import hist, title, plot, figure, ylabel, xlabel, axis, step
from scipy.stats import norm
from statsmodels.distributions import ECDF
# Aquí simula n normales padrón, saca su media, su varianza
# y hace un histogrma
nn=1000
x=norm.rvs(... | 0.399577 | 0.530297 |
import torch.nn as nn
import torch.nn.functional as F
from torchsso.utils.accumulator import TensorAccumulator
__all__ = ['alexnet', 'alexnet_mcdropout']
class AlexNet(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=11, stride=4, padd... | examples/classification/models/alexnet.py | import torch.nn as nn
import torch.nn.functional as F
from torchsso.utils.accumulator import TensorAccumulator
__all__ = ['alexnet', 'alexnet_mcdropout']
class AlexNet(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=11, stride=4, padd... | 0.946584 | 0.459804 |
import os
from ._version import __version__
from mosaik_docker.cli.create_sim_setup import create_sim_setup as md_create_sim_setup
from mosaik_docker.cli.get_sim_setup_root import get_sim_setup_root as md_get_sim_setup_root
from mosaik_docker.cli.configure_sim_setup import configure_sim_setup as md_configure_sim_setup... | mosaik_docker_jl/execute.py | import os
from ._version import __version__
from mosaik_docker.cli.create_sim_setup import create_sim_setup as md_create_sim_setup
from mosaik_docker.cli.get_sim_setup_root import get_sim_setup_root as md_get_sim_setup_root
from mosaik_docker.cli.configure_sim_setup import configure_sim_setup as md_configure_sim_setup... | 0.229622 | 0.389837 |
import struct
import typing
import rocksdb
from typing import Optional
from hub.db.common import DB_PREFIXES, COLUMN_SETTINGS
from hub.db.revertable import RevertableOpStack, RevertablePut, RevertableDelete
ROW_TYPES = {}
class PrefixRowType(type):
def __new__(cls, name, bases, kwargs):
klass = super().... | hub/db/interface.py | import struct
import typing
import rocksdb
from typing import Optional
from hub.db.common import DB_PREFIXES, COLUMN_SETTINGS
from hub.db.revertable import RevertableOpStack, RevertablePut, RevertableDelete
ROW_TYPES = {}
class PrefixRowType(type):
def __new__(cls, name, bases, kwargs):
klass = super().... | 0.711631 | 0.123339 |
import pytest
pytest.importorskip('openvino.tools.accuracy_checker.launcher.dlsdk_launcher')
import cv2
import numpy as np
from pathlib import Path
from unittest.mock import PropertyMock
from openvino.tools.accuracy_checker.config import ConfigError
from openvino.tools.accuracy_checker.launcher import DLSDKLauncher
f... | tools/accuracy_checker/tests/test_dlsdk_launcher.py | import pytest
pytest.importorskip('openvino.tools.accuracy_checker.launcher.dlsdk_launcher')
import cv2
import numpy as np
from pathlib import Path
from unittest.mock import PropertyMock
from openvino.tools.accuracy_checker.config import ConfigError
from openvino.tools.accuracy_checker.launcher import DLSDKLauncher
f... | 0.535341 | 0.272581 |
import copy
import logging
from collections import defaultdict
from google.appengine.ext import ndb
import stocks
from models import SheetStock, Sheet, Stock, User
from oauth2client import client
logger = logging.getLogger(__name__)
def process_sheet_inputs(ssheet_id, symbols, lbs, ubs, title=None):
"""
Ma... | db.py | import copy
import logging
from collections import defaultdict
from google.appengine.ext import ndb
import stocks
from models import SheetStock, Sheet, Stock, User
from oauth2client import client
logger = logging.getLogger(__name__)
def process_sheet_inputs(ssheet_id, symbols, lbs, ubs, title=None):
"""
Ma... | 0.663778 | 0.359167 |
from lost.db import model, dtype
from lost.logic.label import LabelTree
import datetime
import pandas as pd
from lost.logic.pipeline.instance import PipeInstance
def get_user(dbm):
email = '<EMAIL>'
user = None
for u in dbm.get_users():
if u.email == email:
user = u
break
... | backend/lost/utils/testils.py |
from lost.db import model, dtype
from lost.logic.label import LabelTree
import datetime
import pandas as pd
from lost.logic.pipeline.instance import PipeInstance
def get_user(dbm):
email = '<EMAIL>'
user = None
for u in dbm.get_users():
if u.email == email:
user = u
break
... | 0.541409 | 0.073897 |
import os
import argparse
import h5py
import ismrmrd
import numpy as np
from PIL import Image
def main(args):
dset = h5py.File(args.filename, 'r')
if not dset:
print("Not a valid dataset: %s" % (args.filename))
return
dsetNames = dset.keys()
print("File %s contains %d groups:" % (args... | InLine_Implementation/Code/mrd2gif.py |
import os
import argparse
import h5py
import ismrmrd
import numpy as np
from PIL import Image
def main(args):
dset = h5py.File(args.filename, 'r')
if not dset:
print("Not a valid dataset: %s" % (args.filename))
return
dsetNames = dset.keys()
print("File %s contains %d groups:" % (args... | 0.266071 | 0.219254 |
from flask_wtf import FlaskForm
from wtforms import StringField, DateField, BooleanField, RadioField, IntegerField, HiddenField, SelectField, validators, ValidationError
from datetime import datetime
class PollForm(FlaskForm):
def time_range(max=24):
r = []
for i in range(max):
t = ('{... | application/poll/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, DateField, BooleanField, RadioField, IntegerField, HiddenField, SelectField, validators, ValidationError
from datetime import datetime
class PollForm(FlaskForm):
def time_range(max=24):
r = []
for i in range(max):
t = ('{... | 0.391173 | 0.169784 |
from dataclasses import dataclass
from typing import Any, Sequence, Sized
from neodroidagent.common.memory.data_structures.expandable_circular_buffer import (
ExpandableCircularBuffer,
)
from neodroidagent.common.memory.transitions import Transition, TransitionPoint
from neodroidagent.utilities import NoData
from ... | neodroidagent/common/memory/sample_transition_buffer.py | from dataclasses import dataclass
from typing import Any, Sequence, Sized
from neodroidagent.common.memory.data_structures.expandable_circular_buffer import (
ExpandableCircularBuffer,
)
from neodroidagent.common.memory.transitions import Transition, TransitionPoint
from neodroidagent.utilities import NoData
from ... | 0.932176 | 0.237289 |
import random
from plugins import AIchat
from plugins import dataManage
# 自动回复部分
screenWords = []
unknown_reply = ['诶?', '你说的话太深奥了', '我也不是很清楚呢', '不知道哦~', '你猜', '这是什么意思呢?', '嘤嘤嘤~我听不懂']
def reply(message, be_at, config, statistics, nickname, group_id, qq, mode):
global screenWords
screenWords = dataManage.re... | src/plugins/autoReply.py | import random
from plugins import AIchat
from plugins import dataManage
# 自动回复部分
screenWords = []
unknown_reply = ['诶?', '你说的话太深奥了', '我也不是很清楚呢', '不知道哦~', '你猜', '这是什么意思呢?', '嘤嘤嘤~我听不懂']
def reply(message, be_at, config, statistics, nickname, group_id, qq, mode):
global screenWords
screenWords = dataManage.re... | 0.126326 | 0.086478 |
import re
from collections import Counter
import dash
import dash_core_components as dcc
import dash_daq as daq
import dash_html_components as html
import iso3166
import pandas as pd
import plotly.graph_objs as go
from sklearn import preprocessing
df = pd.read_pickle('brand24.pkl')
def hashtags(df, limit=10):
... | dash/application.py |
import re
from collections import Counter
import dash
import dash_core_components as dcc
import dash_daq as daq
import dash_html_components as html
import iso3166
import pandas as pd
import plotly.graph_objs as go
from sklearn import preprocessing
df = pd.read_pickle('brand24.pkl')
def hashtags(df, limit=10):
... | 0.414188 | 0.264418 |
from scipy.integrate import ode
import numpy as np
import time
from lib.likelihood import compute_eMRMS
# A default callback function
# the geodesic can be halted by the callback returning False
def callback_func(geo):
return True
# We construct a geodesic class that inherits from scipy's ode class
... | MBAM/lib/geodesic.py | from scipy.integrate import ode
import numpy as np
import time
from lib.likelihood import compute_eMRMS
# A default callback function
# the geodesic can be halted by the callback returning False
def callback_func(geo):
return True
# We construct a geodesic class that inherits from scipy's ode class
... | 0.778481 | 0.493714 |
__all__ = ["ROSAdapter"]
# BriCA imports
from .unit import Unit
# ROS imporets
import rospy
from std_msgs.msg import Int16MultiArray, MultiArrayDimension
class ROSAdapter(Unit):
"""
`ROSAdapter` is a BriCA `Unit` which is intented to provide a bridge over
the ROS Publisher/Subscriber and BriCA `Agent`.
... | brica1/ros.py | __all__ = ["ROSAdapter"]
# BriCA imports
from .unit import Unit
# ROS imporets
import rospy
from std_msgs.msg import Int16MultiArray, MultiArrayDimension
class ROSAdapter(Unit):
"""
`ROSAdapter` is a BriCA `Unit` which is intented to provide a bridge over
the ROS Publisher/Subscriber and BriCA `Agent`.
... | 0.856512 | 0.303055 |
import re;
spacere = re.compile("[ ]{2,}");
spacern = re.compile("(^\r\n?)|(\r\n?$)")
def getkeys(generator):
count=0;
s=set();
for r in generator:
s=s|r.keys();
count+=1;
if count>=20:
return list(s);
return list(s)
def ReplaceLongSpace(txt):
r = spacere.subn... | extends.py | import re;
spacere = re.compile("[ ]{2,}");
spacern = re.compile("(^\r\n?)|(\r\n?$)")
def getkeys(generator):
count=0;
s=set();
for r in generator:
s=s|r.keys();
count+=1;
if count>=20:
return list(s);
return list(s)
def ReplaceLongSpace(txt):
r = spacere.subn... | 0.13229 | 0.294624 |
from .loader import *
from .queries import *
from .services import *
from .transactions import *
from .web import *
class Context:
def __init__(self, session):
self._web = WebRequester(session)
def get(self, query: QueryBase):
if isinstance(query, ServiceRequestBase):
res = self.... | kladama/context.py | from .loader import *
from .queries import *
from .services import *
from .transactions import *
from .web import *
class Context:
def __init__(self, session):
self._web = WebRequester(session)
def get(self, query: QueryBase):
if isinstance(query, ServiceRequestBase):
res = self.... | 0.576661 | 0.076304 |
import re
from dateutil.parser import parse
from ..schema.site_base import SiteBase
def handle_join_date(value):
return parse(value).date()
def handle_share_ratio(value):
if value == 'Inf':
return '0'
else:
return value
def build_selector():
return {
'user_id': f'{re.esca... | ptsites/schema/xbt.py | import re
from dateutil.parser import parse
from ..schema.site_base import SiteBase
def handle_join_date(value):
return parse(value).date()
def handle_share_ratio(value):
if value == 'Inf':
return '0'
else:
return value
def build_selector():
return {
'user_id': f'{re.esca... | 0.316581 | 0.199405 |
import os
import re
import json
import copy
import time
from datetime import datetime, date, timedelta
import requests
import mistune
from django.db.models import Max
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.header import Header
from .models import \
ChangeHistory, CapitalStockA... | stock/controllers.py | import os
import re
import json
import copy
import time
from datetime import datetime, date, timedelta
import requests
import mistune
from django.db.models import Max
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.header import Header
from .models import \
ChangeHistory, CapitalStockA... | 0.228501 | 0.214424 |
import os
from collections import defaultdict
from functools import partial
from pathlib import Path
from typing import Sequence, Union
import numpy as np
from dpipe.commands import load_from_folder
from dpipe.io import PathLike
from dpipe.im.utils import zip_equal
import wandb
__all__ = 'Logger', 'ConsoleLogger', '... | dpipe/train/logging.py | import os
from collections import defaultdict
from functools import partial
from pathlib import Path
from typing import Sequence, Union
import numpy as np
from dpipe.commands import load_from_folder
from dpipe.io import PathLike
from dpipe.im.utils import zip_equal
import wandb
__all__ = 'Logger', 'ConsoleLogger', '... | 0.85223 | 0.275451 |
from copy import deepcopy
from unittest.mock import Mock
import pytest
from opentrons.drivers.types import MoveSplit
from tests.opentrons.conftest import fuzzy_assert
from opentrons.config.robot_configs import (
DEFAULT_GANTRY_STEPS_PER_MM, DEFAULT_PIPETTE_CONFIGS)
from opentrons.drivers import serial_communicatio... | api/tests/opentrons/drivers/test_driver.py | from copy import deepcopy
from unittest.mock import Mock
import pytest
from opentrons.drivers.types import MoveSplit
from tests.opentrons.conftest import fuzzy_assert
from opentrons.config.robot_configs import (
DEFAULT_GANTRY_STEPS_PER_MM, DEFAULT_PIPETTE_CONFIGS)
from opentrons.drivers import serial_communicatio... | 0.687735 | 0.453988 |
from ..base.backend import BackupBackend
from ..base.backup_profile import BackupProfile
from scidb.core import Database, Data
from scidb.utils.extractor import db_to_json, recover_db, get_data_list
from scidb.utils.iteration import iter_data
from typing import Tuple, List, Union, Callable
from pathlib import Path
from... | scidb/plugins/backup/implementations/local.py | from ..base.backend import BackupBackend
from ..base.backup_profile import BackupProfile
from scidb.core import Database, Data
from scidb.utils.extractor import db_to_json, recover_db, get_data_list
from scidb.utils.iteration import iter_data
from typing import Tuple, List, Union, Callable
from pathlib import Path
from... | 0.746971 | 0.084229 |
import os
import click
import numpy as np
from keras.optimizers import RMSprop
from molecules.utils import open_h5
from molecules.ml.unsupervised import (VAE, EncoderConvolution2D,
DecoderConvolution2D,
EncoderHyperparams,
... | examples/cvae_dbscan/scripts/cvae.py | import os
import click
import numpy as np
from keras.optimizers import RMSprop
from molecules.utils import open_h5
from molecules.ml.unsupervised import (VAE, EncoderConvolution2D,
DecoderConvolution2D,
EncoderHyperparams,
... | 0.698329 | 0.274686 |
import sys
from pathlib import Path
import pytest
from easyprocess import EasyProcess
from pyvirtualdisplay import Display
from pyvirtualdisplay.smartdisplay import DisplayTimeoutError, SmartDisplay
python = sys.executable
def test_disp():
with Display():
d = SmartDisplay(visible=True).start().stop()
... | tests/test_smart.py | import sys
from pathlib import Path
import pytest
from easyprocess import EasyProcess
from pyvirtualdisplay import Display
from pyvirtualdisplay.smartdisplay import DisplayTimeoutError, SmartDisplay
python = sys.executable
def test_disp():
with Display():
d = SmartDisplay(visible=True).start().stop()
... | 0.363082 | 0.323207 |
from urllib import unquote
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect
f... | openprescribing/frontend/views/bookmark_views.py | from urllib import unquote
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect
f... | 0.392803 | 0.12921 |
import argparse
import glob
from os.path import basename
import torch
import numpy as np
import matplotlib
# matplotlib.use('pgf')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.patches as patches
import matplotlib.colors as colors
matplotlib.rcParams["figure.constrained_layou... | plot_attn.py |
import argparse
import glob
from os.path import basename
import torch
import numpy as np
import matplotlib
# matplotlib.use('pgf')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.patches as patches
import matplotlib.colors as colors
matplotlib.rcParams["figure.constrained_layou... | 0.644896 | 0.463566 |
__version__ = "0.1.15"
from forecastga.helpers.ga_data import get_ga_data
from forecastga.auto import AutomatedModel
from forecastga.helpers.data import print_model_info
from forecastga.helpers.colab import plot_colab
def help():
print("Welcome to ForecastGA")
print()
print("To use:")
print()
pr... | src/forecastga/__init__.py | __version__ = "0.1.15"
from forecastga.helpers.ga_data import get_ga_data
from forecastga.auto import AutomatedModel
from forecastga.helpers.data import print_model_info
from forecastga.helpers.colab import plot_colab
def help():
print("Welcome to ForecastGA")
print()
print("To use:")
print()
pr... | 0.555435 | 0.186687 |
import numpy as np
from ..block_maps import (block_columns,
affine_transform,
block_rows)
def test_block_columns():
X1 = np.random.standard_normal((20,10))
X2 = np.random.standard_normal((23,10))
B = block_columns([X1, X2])
Z = np.random.standard... | regreg/affine/tests/test_block.py | import numpy as np
from ..block_maps import (block_columns,
affine_transform,
block_rows)
def test_block_columns():
X1 = np.random.standard_normal((20,10))
X2 = np.random.standard_normal((23,10))
B = block_columns([X1, X2])
Z = np.random.standard... | 0.64646 | 0.806205 |
import math
import numpy as np
from numpy import mean, sqrt, square
from scipy.integrate import simps
# Frequency of vibration & shock signals
FREQUENCY = 1600
DX = 5
def get_grms(data):
area = simps(data[2:(len(data) / 2) - 1], dx=DX)
# added as per prof.Changfeng Ge suggestion
return math.sqrt(area)
d... | paktrack/common/common.py | import math
import numpy as np
from numpy import mean, sqrt, square
from scipy.integrate import simps
# Frequency of vibration & shock signals
FREQUENCY = 1600
DX = 5
def get_grms(data):
area = simps(data[2:(len(data) / 2) - 1], dx=DX)
# added as per prof.Changfeng Ge suggestion
return math.sqrt(area)
d... | 0.736685 | 0.644756 |
from ultron8.utils.misc import (
lowercase_value,
rstrip_last_char,
sanitize_output,
strip_shell_chars,
)
from ultron8.utils.ujson import fast_deepcopy
__all__ = ["MiscUtilTestCase"]
class TestMiscUtilTestCase:
def test_rstrip_last_char(self):
assert rstrip_last_char(None, "\n") == None
... | tests/utils/test_misc_utils.py |
from ultron8.utils.misc import (
lowercase_value,
rstrip_last_char,
sanitize_output,
strip_shell_chars,
)
from ultron8.utils.ujson import fast_deepcopy
__all__ = ["MiscUtilTestCase"]
class TestMiscUtilTestCase:
def test_rstrip_last_char(self):
assert rstrip_last_char(None, "\n") == None
... | 0.697403 | 0.559591 |
from __future__ import division
import re
import numpy as np
class ParseError(Exception):
pass
class Symbol(object):
regex = ''
def __init__(self, token):
self.token = token
@classmethod
def match(cls, string):
match = re.match(cls.regex, string)
if match:
r... | symm.py | from __future__ import division
import re
import numpy as np
class ParseError(Exception):
pass
class Symbol(object):
regex = ''
def __init__(self, token):
self.token = token
@classmethod
def match(cls, string):
match = re.match(cls.regex, string)
if match:
r... | 0.621196 | 0.22133 |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QCoreApplication
import db
import datetime,time
class Ui_Dialog(QWidget):
def setupUi(self, Dialog,loginfo):
Dialog.setObjectName("Dialog")
Dialog.resize(401, 351)
Dialog.setFixedSi... | change.py |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QCoreApplication
import db
import datetime,time
class Ui_Dialog(QWidget):
def setupUi(self, Dialog,loginfo):
Dialog.setObjectName("Dialog")
Dialog.resize(401, 351)
Dialog.setFixedSi... | 0.211661 | 0.040999 |
import argparse
import os
import pickle
from mimic3_utils import benchmark_to_h5
from physionet2019_utils import physionet_to_h5
from sklearn.preprocessing import StandardScaler
from utils import save_to_h5_with_tasks, scaling_data_common
def build_mimic3_h5(load_path, save_path, channel_to_id, matching_dict, var_ra... | data/preprocess/build_dataset.py | import argparse
import os
import pickle
from mimic3_utils import benchmark_to_h5
from physionet2019_utils import physionet_to_h5
from sklearn.preprocessing import StandardScaler
from utils import save_to_h5_with_tasks, scaling_data_common
def build_mimic3_h5(load_path, save_path, channel_to_id, matching_dict, var_ra... | 0.777173 | 0.36523 |
from collections import defaultdict
import pytest
from day19_1 import get_overlaps, Rotation
from day19_1 import main as main1
from day19_1 import process_input
OVERLAPS = defaultdict(dict)
OVERLAPS[0][1] = { # as seen by scanner 0
(-618, -824, -621),
(-537, -823, -458),
(-447, -329, 318),
(404, -588... | 2021/python/tests/test_day19.py | from collections import defaultdict
import pytest
from day19_1 import get_overlaps, Rotation
from day19_1 import main as main1
from day19_1 import process_input
OVERLAPS = defaultdict(dict)
OVERLAPS[0][1] = { # as seen by scanner 0
(-618, -824, -621),
(-537, -823, -458),
(-447, -329, 318),
(404, -588... | 0.662687 | 0.55254 |
import subprocess as sp
import multiprocessing
import argparse
import sys
import os
import re
import time
YELLOW = '\033[93m'
ENDC = '\033[0m'
def print_progress(i, i_total, instance):
sys.stdout.write(f"\rIteration {i:>5}/{i_total} | Instance {instance:>8}")
sys.stdout.flush()
if __name__ == "__main__":... | etc/phase2_benchmark.py | import subprocess as sp
import multiprocessing
import argparse
import sys
import os
import re
import time
YELLOW = '\033[93m'
ENDC = '\033[0m'
def print_progress(i, i_total, instance):
sys.stdout.write(f"\rIteration {i:>5}/{i_total} | Instance {instance:>8}")
sys.stdout.flush()
if __name__ == "__main__":... | 0.093639 | 0.055875 |
from io import BytesIO
from py_nsbcli.config import ENC
from py_nsbcli import TransactionHeader, Wallet
from py_nsbcli.modules import Client
from py_nsbcli.util import GoJson
class Contract(object):
def __init__(self, cli, bind_address=None):
self.cli = Client(cli)
self._address = bind_address
... | py_nsbcli/modules/contract.py | from io import BytesIO
from py_nsbcli.config import ENC
from py_nsbcli import TransactionHeader, Wallet
from py_nsbcli.modules import Client
from py_nsbcli.util import GoJson
class Contract(object):
def __init__(self, cli, bind_address=None):
self.cli = Client(cli)
self._address = bind_address
... | 0.808635 | 0.184253 |
import numpy as np
import tensorflow as tf
import keras.backend as K
def calculateIdx1D(vol_length, cube_length, stride):
one_dim_pos = np.arange(0, vol_length-cube_length+1, stride)
if (vol_length - cube_length) % stride != 0:
one_dim_pos = np.concatenate([one_dim_pos, [vol_length-cube_length]])
r... | util/predict_funcs.py | import numpy as np
import tensorflow as tf
import keras.backend as K
def calculateIdx1D(vol_length, cube_length, stride):
one_dim_pos = np.arange(0, vol_length-cube_length+1, stride)
if (vol_length - cube_length) % stride != 0:
one_dim_pos = np.concatenate([one_dim_pos, [vol_length-cube_length]])
r... | 0.789599 | 0.762612 |
from pathlib import Path
from typing import cast
from typing import Iterable
from typing import List
from typing import Callable
from simple_term_menu import TerminalMenu
from potodo.po_file import is_within
IS_CURSOR_CYCLING = True
IS_SCREEN_CLEARED = True
def _directory_list_menu(directory_list: List[str]) -> in... | potodo/interactive.py | from pathlib import Path
from typing import cast
from typing import Iterable
from typing import List
from typing import Callable
from simple_term_menu import TerminalMenu
from potodo.po_file import is_within
IS_CURSOR_CYCLING = True
IS_SCREEN_CLEARED = True
def _directory_list_menu(directory_list: List[str]) -> in... | 0.605099 | 0.164785 |
import csv
import netCDF4 as NET
import numpy as NUM
import os
import re
class CreateInflowFileFromERAInterimRunoff(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Create Inflow File From ERA Interim Runoff"
self.description =... | imports/CreateInflowFileFromERAInterimRunoff.py | import csv
import netCDF4 as NET
import numpy as NUM
import os
import re
class CreateInflowFileFromERAInterimRunoff(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Create Inflow File From ERA Interim Runoff"
self.description =... | 0.432063 | 0.385866 |
import logging
import logging.handlers
import json
import os.path
import re
import sys
import yaml
from nagios_to_yaml import NagiosToYaml
ICINGA_DIR = '/etc/icinga'
LOG_FORMAT = '%(asctime)s %(levelname)-10s %(message)s'
MACHINEDB_FILE = '/etc/icinga/machines.json'
NAGIOS_DEFS_FILE = '/etc/icinga/nagios.yml'
NAGIOS... | nagios_configurator.py | import logging
import logging.handlers
import json
import os.path
import re
import sys
import yaml
from nagios_to_yaml import NagiosToYaml
ICINGA_DIR = '/etc/icinga'
LOG_FORMAT = '%(asctime)s %(levelname)-10s %(message)s'
MACHINEDB_FILE = '/etc/icinga/machines.json'
NAGIOS_DEFS_FILE = '/etc/icinga/nagios.yml'
NAGIOS... | 0.383641 | 0.066055 |
from __future__ import absolute_import
from __future__ import print_function
#!/usr/bin/python
import Parameters, Runner
import sys
#sys.path.append('/home/luholm/AAI-profiler')
if __name__ == '__main__' :
example="""
This is a customized script that performs AAI-profiling on protein fasta sequences.
Usage:
... | bin/pannzer/AAI-profiler-fasta.py | from __future__ import absolute_import
from __future__ import print_function
#!/usr/bin/python
import Parameters, Runner
import sys
#sys.path.append('/home/luholm/AAI-profiler')
if __name__ == '__main__' :
example="""
This is a customized script that performs AAI-profiling on protein fasta sequences.
Usage:
... | 0.362518 | 0.06148 |
from panda3d.core import CollisionSphere, CollisionNode
from direct.distributed.DistributedNode import DistributedNode
from direct.distributed import ClockDelta
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.fsm.ClassicFSM import ClassicFSM
from direct.fsm.State import State
from direct.int... | lib/coginvasion/cogtropolis/DistributedCityCart.py | from panda3d.core import CollisionSphere, CollisionNode
from direct.distributed.DistributedNode import DistributedNode
from direct.distributed import ClockDelta
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.fsm.ClassicFSM import ClassicFSM
from direct.fsm.State import State
from direct.int... | 0.474875 | 0.113064 |
from typing import Tuple
from cubelang.orientation import Side, Orientation, _normalize_turns
import pytest
T = Side.TOP
L = Side.LEFT
R = Side.RIGHT
D = Side.BOTTOM
F = Side.FRONT
B = Side.BACK
@pytest.mark.parametrize("current, left, top, right, bottom", [
((F, T), (L, T), (T, B), (R, T), (D, F)),
((F, R)... | test/test_orientation.py | from typing import Tuple
from cubelang.orientation import Side, Orientation, _normalize_turns
import pytest
T = Side.TOP
L = Side.LEFT
R = Side.RIGHT
D = Side.BOTTOM
F = Side.FRONT
B = Side.BACK
@pytest.mark.parametrize("current, left, top, right, bottom", [
((F, T), (L, T), (T, B), (R, T), (D, F)),
((F, R)... | 0.912964 | 0.77343 |
import numpy as np
import os
import pytest
import re
import sys
import tvm
import tvm.relay
import tvm.testing
import tvm.contrib.hexagon as hexagon
@pytest.fixture(autouse=True)
def register_linker():
original_linker = hexagon.hexagon_link()
# Register a phony linker, so that we can test codegen without a H... | tests/python/unittest/test_target_codegen_hexagon.py |
import numpy as np
import os
import pytest
import re
import sys
import tvm
import tvm.relay
import tvm.testing
import tvm.contrib.hexagon as hexagon
@pytest.fixture(autouse=True)
def register_linker():
original_linker = hexagon.hexagon_link()
# Register a phony linker, so that we can test codegen without a H... | 0.378459 | 0.252131 |
from __future__ import absolute_import, division, print_function, unicode_literals
import time
from collections import OrderedDict
from threading import RLock
_NOTSET = object()
class _Cache(object):
"""
An in-memory, FIFO cache object that supports:
- Maximum number of cache entries
- Global TTL d... | utils/feishu/internal_cache.py |
from __future__ import absolute_import, division, print_function, unicode_literals
import time
from collections import OrderedDict
from threading import RLock
_NOTSET = object()
class _Cache(object):
"""
An in-memory, FIFO cache object that supports:
- Maximum number of cache entries
- Global TTL d... | 0.901629 | 0.31076 |
"""Normal Distribution"""
import numpy as np
from mindspore.ops import operations as P
from .distribution import Distribution
from ._utils.utils import convert_to_batch, check_greater_equal_zero
from ...common import dtype as mstype
from ...context import get_context
class Normal(Distribution):
"""
Example cla... | mindspore/nn/distribution/normal.py | """Normal Distribution"""
import numpy as np
from mindspore.ops import operations as P
from .distribution import Distribution
from ._utils.utils import convert_to_batch, check_greater_equal_zero
from ...common import dtype as mstype
from ...context import get_context
class Normal(Distribution):
"""
Example cla... | 0.935861 | 0.617311 |
import torch
from torch.nn.utils.clip_grad import clip_grad_norm_, clip_grad_value_
from maml.utils import accuracy
def get_grad_norm(parameters, norm_type=2):
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = list(filter(lambda p: p.grad is not None, parameters))
no... | maml/metalearner.py | import torch
from torch.nn.utils.clip_grad import clip_grad_norm_, clip_grad_value_
from maml.utils import accuracy
def get_grad_norm(parameters, norm_type=2):
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = list(filter(lambda p: p.grad is not None, parameters))
no... | 0.923523 | 0.385866 |
try:
from urllib.request import urlopen
except:
from urllib2 import urlopen
from bs4 import BeautifulSoup as soup
import re, datetime, csv, time, random
class divend_info:
def __init__(self, full_list_filename, ah_list_filename, divend_filename):
self.full_dict = self.load_full_list(full_list_filename)
self.ah_... | scraping_divend/divend_sina_getter.py | try:
from urllib.request import urlopen
except:
from urllib2 import urlopen
from bs4 import BeautifulSoup as soup
import re, datetime, csv, time, random
class divend_info:
def __init__(self, full_list_filename, ah_list_filename, divend_filename):
self.full_dict = self.load_full_list(full_list_filename)
self.ah_... | 0.141786 | 0.18228 |
from setuptools import setup, find_packages
from setuptools.extension import Extension
from glob import glob
import numpy
from Cython.Distutils import build_ext
ext_modules = [
Extension("taggd.core.demultiplex_core_functions", ["taggd/core/demultiplex_core_functions.pyx"]),
Extension("taggd.core.demultiplex... | setup.py | from setuptools import setup, find_packages
from setuptools.extension import Extension
from glob import glob
import numpy
from Cython.Distutils import build_ext
ext_modules = [
Extension("taggd.core.demultiplex_core_functions", ["taggd/core/demultiplex_core_functions.pyx"]),
Extension("taggd.core.demultiplex... | 0.289773 | 0.131452 |
from mscraper import Mscraper
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import ... | mscraper/linkedin_scraper.py | from mscraper import Mscraper
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import ... | 0.379608 | 0.110231 |
from io import IOBase
import os
from tempfile import SpooledTemporaryFile
from zipfile import ZipFile
from osgeo import osr
from werkzeug.datastructures import FileStorage
def validate_mappings(mappings):
"""
Validates a class mappings of Data sets
A mapping consists in a dictionary which maps the expect... | bdc_sample/core/utils.py | from io import IOBase
import os
from tempfile import SpooledTemporaryFile
from zipfile import ZipFile
from osgeo import osr
from werkzeug.datastructures import FileStorage
def validate_mappings(mappings):
"""
Validates a class mappings of Data sets
A mapping consists in a dictionary which maps the expect... | 0.847905 | 0.317453 |
import torch
from typing import Callable, Union
from deep500.lv2.optimizer import FirstOrderOptimizer
from .pytorch_graph_executor import PyTorchGraphExecutor
class PyTorchOptimizer(FirstOrderOptimizer):
def __init__(self, executor: PyTorchGraphExecutor, loss: str,
with_outputs=True, **kwargs):
... | deep500/frameworks/pytorch/pytorch_optimizers.py | import torch
from typing import Callable, Union
from deep500.lv2.optimizer import FirstOrderOptimizer
from .pytorch_graph_executor import PyTorchGraphExecutor
class PyTorchOptimizer(FirstOrderOptimizer):
def __init__(self, executor: PyTorchGraphExecutor, loss: str,
with_outputs=True, **kwargs):
... | 0.941014 | 0.480844 |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import torch
import torch.nn.functional as F
from pytoda.transforms import LeftPadding
from .reinforce import Reinforce
class ReinforceOmic(Reinforce):
def __init__(
self, generator, encoder, predictor, gep_df, params, model_name,... | paccmann_generator/reinforce_omics.py | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import torch
import torch.nn.functional as F
from pytoda.transforms import LeftPadding
from .reinforce import Reinforce
class ReinforceOmic(Reinforce):
def __init__(
self, generator, encoder, predictor, gep_df, params, model_name,... | 0.819821 | 0.564819 |
from urllib.parse import parse_qsl
import time, hmac, hashlib
class Utils:
@staticmethod
def verify_request(requestBody, signatureHeader, signingSecret, tolerance=5*60*1000):
"""Verify a request's signature.
:param requestBody: The request's body after the json is stringified without traili... | freeclimb/utils.py | from urllib.parse import parse_qsl
import time, hmac, hashlib
class Utils:
@staticmethod
def verify_request(requestBody, signatureHeader, signingSecret, tolerance=5*60*1000):
"""Verify a request's signature.
:param requestBody: The request's body after the json is stringified without traili... | 0.777384 | 0.268149 |
import os
import time
import numpy as np
import tensorflow as tf
from stable_baselines.common import logger
from stable_baselines.common.base_class import BaseRLModel
from stable_baselines.common.buffers import RolloutBuffer
from stable_baselines.common.utils import explained_variance, get_schedule_fn
from stable_base... | stable_baselines/ppo/ppo.py | import os
import time
import numpy as np
import tensorflow as tf
from stable_baselines.common import logger
from stable_baselines.common.base_class import BaseRLModel
from stable_baselines.common.buffers import RolloutBuffer
from stable_baselines.common.utils import explained_variance, get_schedule_fn
from stable_base... | 0.778481 | 0.177027 |
import sys, socket, threading, time, abc, re, queue, string, random
from . import utils, ns, msg
class stream(threading.Thread):
""" class XmppStream(threading.Thread): """
def nf(self,s,m):
pass
def __init__(self):
threading.Thread.__init__(self)
self.setDaemon(True)
self.... | xmpp/stream.py |
import sys, socket, threading, time, abc, re, queue, string, random
from . import utils, ns, msg
class stream(threading.Thread):
""" class XmppStream(threading.Thread): """
def nf(self,s,m):
pass
def __init__(self):
threading.Thread.__init__(self)
self.setDaemon(True)
self.... | 0.125132 | 0.061565 |
from __future__ import division, unicode_literals, print_function, absolute_import
import operator
class Measurement(object):
"""Implements a class to describe a quantity with uncertainty.
:param value: The most likely value of the measurement.
:type value: Quantity or Number
:param error: The erro... | pint/measurement.py | from __future__ import division, unicode_literals, print_function, absolute_import
import operator
class Measurement(object):
"""Implements a class to describe a quantity with uncertainty.
:param value: The most likely value of the measurement.
:type value: Quantity or Number
:param error: The erro... | 0.88765 | 0.421969 |
import wx
import numpy as np
from ColorButton import ColorButton
from ColormapperSettings import ColormapperSettings
class RemixPanel(wx.Panel):
# Default Settings
settings = ColormapperSettings()
# Other variables
recomputeRemix = False
def __init__(self, parent, settings = settings, id =... | lib/RemixPanel.py | import wx
import numpy as np
from ColorButton import ColorButton
from ColormapperSettings import ColormapperSettings
class RemixPanel(wx.Panel):
# Default Settings
settings = ColormapperSettings()
# Other variables
recomputeRemix = False
def __init__(self, parent, settings = settings, id =... | 0.538983 | 0.138374 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
import sys
CARDS_LIST = ['A'] + map(str, range(2, 11)) + map(str, [10]*3)
ACTIONS = ['H', 'S']
tr = []
init = True
MAX_ITER = 10000*50
iter = 0
G = {}
V = {}
CARD_INT = {}
for i, v in enumerate(CARDS_LI... | chapter-5/example-5.1/main.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
import sys
CARDS_LIST = ['A'] + map(str, range(2, 11)) + map(str, [10]*3)
ACTIONS = ['H', 'S']
tr = []
init = True
MAX_ITER = 10000*50
iter = 0
G = {}
V = {}
CARD_INT = {}
for i, v in enumerate(CARDS_LI... | 0.228931 | 0.404625 |
import os
from dotenv import load_dotenv
import psycopg2
class TickerStore:
CHAT_ID_UNINITIALIZED = -1
def __init__(self):
self._chat_id = self.CHAT_ID_UNINITIALIZED
self._tickers = set()
load_dotenv()
def open_db(self):
self._conn = psycopg2.connect(os.environ["TT_DATABA... | tickerstore.py | import os
from dotenv import load_dotenv
import psycopg2
class TickerStore:
CHAT_ID_UNINITIALIZED = -1
def __init__(self):
self._chat_id = self.CHAT_ID_UNINITIALIZED
self._tickers = set()
load_dotenv()
def open_db(self):
self._conn = psycopg2.connect(os.environ["TT_DATABA... | 0.248899 | 0.105902 |
import httplib
import json
import os
import shutil
import urllib2
import logging
import logging.handlers
TAG = "lib"
def setup_logger(log_path, name, verbosity):
"""Setup logging functionality to both console and a rotating log file."""
logger = logging.getLogger('opencache')
logger.setLevel(logging.DEBUG... | opencache/lib/opencachelib.py | import httplib
import json
import os
import shutil
import urllib2
import logging
import logging.handlers
TAG = "lib"
def setup_logger(log_path, name, verbosity):
"""Setup logging functionality to both console and a rotating log file."""
logger = logging.getLogger('opencache')
logger.setLevel(logging.DEBUG... | 0.498291 | 0.079818 |
__author__ = 'jidong'
from django.shortcuts import render,render_to_response
# Create your views here.
from itam.api import *
from inetwork import models
from iservice.models import ServiceInfo
from iuser.models import User
@require_role(role='user')
def network_ip(request):
header_title, path1, path2 = u'IP列表', ... | inetwork/views.py | __author__ = 'jidong'
from django.shortcuts import render,render_to_response
# Create your views here.
from itam.api import *
from inetwork import models
from iservice.models import ServiceInfo
from iuser.models import User
@require_role(role='user')
def network_ip(request):
header_title, path1, path2 = u'IP列表', ... | 0.221435 | 0.076064 |
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
from urllib.parse import urlparse
import Domino
import random
class DominoHTTPHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path=urlparse(self.path)
if(parsed_path.path == "/flag"):
self.flag(parsed_p... | Domino_server.py | from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
from urllib.parse import urlparse
import Domino
import random
class DominoHTTPHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path=urlparse(self.path)
if(parsed_path.path == "/flag"):
self.flag(parsed_p... | 0.333503 | 0.098686 |
import pygame
from pygame.sprite import Sprite
import os
import models
from models import *
pygame.init()
pygame.display.set_mode()
pygame.display.set_caption('Emate\'s Arc')
WIDTH = 1000
HEIGHT = 800
music = pygame.mixer.music.load(models.main_menu_music)
running = True
x = 2
screenSelect = 0
... | game.py | import pygame
from pygame.sprite import Sprite
import os
import models
from models import *
pygame.init()
pygame.display.set_mode()
pygame.display.set_caption('Emate\'s Arc')
WIDTH = 1000
HEIGHT = 800
music = pygame.mixer.music.load(models.main_menu_music)
running = True
x = 2
screenSelect = 0
... | 0.086019 | 0.142799 |
import argparse
import re
import google.protobuf.text_format as tf
from p4.config.v1 import p4info_pb2
copyright = """/*
SPDX-License-Identifier: LicenseRef-ONF-Member-1.0
SPDX-FileCopyrightText: 2021-present Open Networking Foundation <<EMAIL>>
*/
// Do not modify this file manually, use `make constants` to gene... | util/gen-p4-constants.py | import argparse
import re
import google.protobuf.text_format as tf
from p4.config.v1 import p4info_pb2
copyright = """/*
SPDX-License-Identifier: LicenseRef-ONF-Member-1.0
SPDX-FileCopyrightText: 2021-present Open Networking Foundation <<EMAIL>>
*/
// Do not modify this file manually, use `make constants` to gene... | 0.497803 | 0.054651 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from icnnmodel import FaceModel, Stage2FaceModel
class Stage1Model(nn.Module):
def __init__(self):
super(Stage1Model, self).__init__()
self.model = FaceModel()
def forward(self, x):
y = self.model(x)
return y
... | model1.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from icnnmodel import FaceModel, Stage2FaceModel
class Stage1Model(nn.Module):
def __init__(self):
super(Stage1Model, self).__init__()
self.model = FaceModel()
def forward(self, x):
y = self.model(x)
return y
... | 0.943996 | 0.52756 |
import json
import os
from inspect import getmembers, isfunction
from uuid import uuid4
from cc_container_worker.commons import downloaders
from cc_container_worker.commons import uploaders
try:
import cc_custom_downloaders
downloader_modules = [downloaders, cc_custom_downloaders]
except ImportError:
down... | cc_container_worker/commons/data.py | import json
import os
from inspect import getmembers, isfunction
from uuid import uuid4
from cc_container_worker.commons import downloaders
from cc_container_worker.commons import uploaders
try:
import cc_custom_downloaders
downloader_modules = [downloaders, cc_custom_downloaders]
except ImportError:
down... | 0.201342 | 0.079675 |
from trainloops.train_loop import TrainLoop
import torch
import torch.nn.functional as F
class FRSTrainLoop(TrainLoop):
def __init__(
self,
listeners: list,
model,
optimizer,
dataloader: torch.utils.data.DataLoader,
cuda=False,
ep... | trainloops/frs_trainloop.py | from trainloops.train_loop import TrainLoop
import torch
import torch.nn.functional as F
class FRSTrainLoop(TrainLoop):
def __init__(
self,
listeners: list,
model,
optimizer,
dataloader: torch.utils.data.DataLoader,
cuda=False,
ep... | 0.881136 | 0.309454 |
import pytest
import pygit2
import sys
from unittest.mock import patch, Mock
from tempfile import TemporaryDirectory
from pathlib import Path
MODULE_UNDER_TEST = __import__('git-to-freshports-xml')
@pytest.fixture(scope='module')
def git_repo() -> pygit2.Repository:
with TemporaryDirectory() as repo_dir:
... | git-to-freshports/tests/test_git-to-freshports-xml.py | import pytest
import pygit2
import sys
from unittest.mock import patch, Mock
from tempfile import TemporaryDirectory
from pathlib import Path
MODULE_UNDER_TEST = __import__('git-to-freshports-xml')
@pytest.fixture(scope='module')
def git_repo() -> pygit2.Repository:
with TemporaryDirectory() as repo_dir:
... | 0.270288 | 0.338323 |
import chess
import pygame
from os.path import dirname
from typing import Iterable
pygame.init()
infoObject = pygame.display.Info()
RESOURCESPATH = (dirname(__file__)) + "/Resources/"
SCREENWIDTH = 60*8
SCREENHEIGHT = 60*8
IMAGESNAME = ["wK","wQ","wR","wB","wN","wP","bk","bq","br","bb","bn","bp"]
images = [... | main.py | import chess
import pygame
from os.path import dirname
from typing import Iterable
pygame.init()
infoObject = pygame.display.Info()
RESOURCESPATH = (dirname(__file__)) + "/Resources/"
SCREENWIDTH = 60*8
SCREENHEIGHT = 60*8
IMAGESNAME = ["wK","wQ","wR","wB","wN","wP","bk","bq","br","bb","bn","bp"]
images = [... | 0.204501 | 0.132767 |
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import _name_estimators
class ColumnTransformerNoStack(ColumnTransformer):
"""Applies transformers to columns of an array, and does not stack them.
This estimator allows different columns or column subsets of the input to
be transformed ... | himalaya/ridge/_column.py | from sklearn.compose import ColumnTransformer
from sklearn.pipeline import _name_estimators
class ColumnTransformerNoStack(ColumnTransformer):
"""Applies transformers to columns of an array, and does not stack them.
This estimator allows different columns or column subsets of the input to
be transformed ... | 0.967256 | 0.805709 |
import bandit
import bandit_tools.custom_report
import pytest
import argparse
import sys
import os
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
class ExitMock(object):
CALL_ARGS = None
CALL_KWARGS = None
def exit(self, *args, **kwargs):
self.CALL_ARGS = args
self.CALL_KWARGS =... | bandit_tools/test/test_custom_report.py | import bandit
import bandit_tools.custom_report
import pytest
import argparse
import sys
import os
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
class ExitMock(object):
CALL_ARGS = None
CALL_KWARGS = None
def exit(self, *args, **kwargs):
self.CALL_ARGS = args
self.CALL_KWARGS =... | 0.279533 | 0.291851 |
class Errors(object):
FILE_DIR_PATH = {
'gauss_0101': '[GAUSS_0101] The directory [%s] is not exist.',
'gauss_0102': '[GAUSS_0102] The file [%s] is not exist.',
'gauss_0103': '[GAUSS_0103] Getting install path [%s] failed.',
'gauss_0104': '[GAUSS_0104] The path [%s] should b... | src/gausskernel/dbmind/tools/ai_manager/definitions/errors.py |
class Errors(object):
FILE_DIR_PATH = {
'gauss_0101': '[GAUSS_0101] The directory [%s] is not exist.',
'gauss_0102': '[GAUSS_0102] The file [%s] is not exist.',
'gauss_0103': '[GAUSS_0103] Getting install path [%s] failed.',
'gauss_0104': '[GAUSS_0104] The path [%s] should b... | 0.397704 | 0.317744 |
import numpy as np
import pandas as pd
import matplotlib as mpl
from matplotlib.colors import same_color, to_rgb, to_rgba
import pytest
from numpy.testing import assert_array_equal
from seaborn.external.version import Version
from seaborn._core.rules import categorical_order
from seaborn._core.scales import Nominal, ... | seaborn/tests/_core/test_properties.py | import numpy as np
import pandas as pd
import matplotlib as mpl
from matplotlib.colors import same_color, to_rgb, to_rgba
import pytest
from numpy.testing import assert_array_equal
from seaborn.external.version import Version
from seaborn._core.rules import categorical_order
from seaborn._core.scales import Nominal, ... | 0.760651 | 0.553505 |
import pandas as pd
import numpy as np
import argparse
import sys
import os
import pdb
import rpy2
import pprint
sys.path.append('../common/')
import utilities as util
import analysis
import tumor_stage_util
import mutation_base
cancer_type = 'BRCA'
age_r = 'patient.age_at_initial_pathologic_diagnosis'
er_r = 'patien... | tumor-stage/breast_analysis.py | import pandas as pd
import numpy as np
import argparse
import sys
import os
import pdb
import rpy2
import pprint
sys.path.append('../common/')
import utilities as util
import analysis
import tumor_stage_util
import mutation_base
cancer_type = 'BRCA'
age_r = 'patient.age_at_initial_pathologic_diagnosis'
er_r = 'patien... | 0.247805 | 0.151592 |
import asyncio
import os
from uuid import uuid4
from pydantic import BaseModel, Field
import pytest
from pynocular.database_model import database_model, UUID_STR
from pynocular.db_util import create_new_database, create_table, drop_table
from pynocular.engines import DBEngine, DBInfo
db_user_password = str(os.enviro... | tests/functional/test_transactions.py | import asyncio
import os
from uuid import uuid4
from pydantic import BaseModel, Field
import pytest
from pynocular.database_model import database_model, UUID_STR
from pynocular.db_util import create_new_database, create_table, drop_table
from pynocular.engines import DBEngine, DBInfo
db_user_password = str(os.enviro... | 0.484868 | 0.295027 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import kstest, norm
from astropy.stats import kuiper as kuiper_reference
def common_test(points, func):
"""
Common code to KS Test and Kuiper Test
:param points:
:return:
"""
number_of_bins = 100
values, bins = np.histogr... | one_d.py | import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import kstest, norm
from astropy.stats import kuiper as kuiper_reference
def common_test(points, func):
"""
Common code to KS Test and Kuiper Test
:param points:
:return:
"""
number_of_bins = 100
values, bins = np.histogr... | 0.809314 | 0.760962 |