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 mock
from oslo_context import context
from mogan.common import policy
from mogan.tests import base
from mogan.tests.unit.objects import utils
class TestAuthorizeWsgi(base.TestCase):
def setUp(self):
super(TestAuthorizeWsgi, self).setUp()
self.fake_controller = mock.MagicMock()
sel... | mogan/tests/unit/common/test_policy.py |
import mock
from oslo_context import context
from mogan.common import policy
from mogan.tests import base
from mogan.tests.unit.objects import utils
class TestAuthorizeWsgi(base.TestCase):
def setUp(self):
super(TestAuthorizeWsgi, self).setUp()
self.fake_controller = mock.MagicMock()
sel... | 0.606615 | 0.191309 |
import os, json, cv2, itertools, numpy as np
from imantics import Mask
from al_framework.utils import get_ids
from al_framework.logger import save_instances_per_class
from detectron2.structures import BoxMode
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.utils.logger import setup_logger
lo... | al_framework/dataloader.py | import os, json, cv2, itertools, numpy as np
from imantics import Mask
from al_framework.utils import get_ids
from al_framework.logger import save_instances_per_class
from detectron2.structures import BoxMode
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.utils.logger import setup_logger
lo... | 0.458349 | 0.263522 |
from __future__ import print_function
# Define packges to be used (local refers to test environment)
# ------------------------------------------------------------
local = True
if local:
import sys
sys.path.insert(1,'/home/leon/Software/magpy/')
from magpy.stream import *
from magpy.database import *
i... | magpy/test/test_transfer.py | from __future__ import print_function
# Define packges to be used (local refers to test environment)
# ------------------------------------------------------------
local = True
if local:
import sys
sys.path.insert(1,'/home/leon/Software/magpy/')
from magpy.stream import *
from magpy.database import *
i... | 0.127205 | 0.099034 |
import pytest
def pytest_addoption(parser):
"""Describe plugin specified options.
"""
group = parser.getgroup("pidchecker", "plugin pid checker")
group.addoption("--pidcheck_disable", action="store_false", dest="pidchecker",
default=True,
help="Enable pidchecke... | taf/plugins/pytest_pidchecker.py | import pytest
def pytest_addoption(parser):
"""Describe plugin specified options.
"""
group = parser.getgroup("pidchecker", "plugin pid checker")
group.addoption("--pidcheck_disable", action="store_false", dest="pidchecker",
default=True,
help="Enable pidchecke... | 0.51879 | 0.262213 |
import numpy as np
from sklearn.model_selection import cross_validate
from tqdm.autonotebook import tqdm
import warnings
from lofo.infer_defaults import infer_model
from lofo.utils import lofo_to_df, parallel_apply
class LOFOImportance:
"""
Leave One Feature Out Importance
Given a model and cross-validati... | lofo/lofo_importance.py | import numpy as np
from sklearn.model_selection import cross_validate
from tqdm.autonotebook import tqdm
import warnings
from lofo.infer_defaults import infer_model
from lofo.utils import lofo_to_df, parallel_apply
class LOFOImportance:
"""
Leave One Feature Out Importance
Given a model and cross-validati... | 0.845305 | 0.379148 |
from __future__ import print_function
import abc
import collections
from future.builtins import str
from future.utils import with_metaclass
from neptune.internal.cli.commands.neptune_command import OK_EXIT_CODE
from neptune.internal.common import NeptuneException
from neptune.internal.common.api.exceptions import N... | neptune/internal/cli/commands/framework.py |
from __future__ import print_function
import abc
import collections
from future.builtins import str
from future.utils import with_metaclass
from neptune.internal.cli.commands.neptune_command import OK_EXIT_CODE
from neptune.internal.common import NeptuneException
from neptune.internal.common.api.exceptions import N... | 0.495361 | 0.095055 |
from collections import Counter
class SharedParams:
def __init__(self):
self._grads = {}
self._params = {}
self._grad_counts = Counter()
self._transaction_ids = Counter()
self._progress = Counter()
def inc_progress(self, worker_id):
self._progress[worker_id] +=... | tmp/old/thinc_shared_params.py | from collections import Counter
class SharedParams:
def __init__(self):
self._grads = {}
self._params = {}
self._grad_counts = Counter()
self._transaction_ids = Counter()
self._progress = Counter()
def inc_progress(self, worker_id):
self._progress[worker_id] +=... | 0.612426 | 0.163245 |
import typing
from scipy.constants import mu_0, pi
from scipy.interpolate import interp1d
""" This module contains the basic calculations for a two winding transformer design and optimization."""
C_RHO = 8.9 * 1e-6 # kg/mm3
C_RHO_CU = 2.42 # resistivity constant in 75 C
C_RHO_FE = 7.65 * 1e-6 # kg/mm3
C_MU_0 = 4.0... | src/base_functions.py | import typing
from scipy.constants import mu_0, pi
from scipy.interpolate import interp1d
""" This module contains the basic calculations for a two winding transformer design and optimization."""
C_RHO = 8.9 * 1e-6 # kg/mm3
C_RHO_CU = 2.42 # resistivity constant in 75 C
C_RHO_FE = 7.65 * 1e-6 # kg/mm3
C_MU_0 = 4.0... | 0.837554 | 0.592077 |
import numpy as np
import pandas as pd
import scipy.linalg as la
import matplotlib.pyplot as plt
def main():
pass
def read_iv_csv(fname, round_30min=False):
"""Read IV-curve file from Sandia.
Data will also be cleaned to remove 'Unnamed' columns. The current and voltage values will be
compressed ... | ivcurve/utils.py | import numpy as np
import pandas as pd
import scipy.linalg as la
import matplotlib.pyplot as plt
def main():
pass
def read_iv_csv(fname, round_30min=False):
"""Read IV-curve file from Sandia.
Data will also be cleaned to remove 'Unnamed' columns. The current and voltage values will be
compressed ... | 0.676192 | 0.41117 |
"""`gcloud monitoring policies conditions update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import policies
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import... | lib/surface/monitoring/policies/conditions/update.py | """`gcloud monitoring policies conditions update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.monitoring import policies
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.monitoring import... | 0.730866 | 0.055158 |
import json
import pkgutil
import time
from datetime import date, datetime, timedelta
from typing import Any, Dict, Generator, MutableMapping, Tuple
from airbyte_cdk.logger import AirbyteLogger
from airbyte_cdk.models import AirbyteMessage, AirbyteRecordMessage, AirbyteStateMessage, AirbyteStream, Type
from dateutil ... | airbyte-integrations/connectors/source-amazon-seller-partner/source_amazon_seller_partner/client.py |
import json
import pkgutil
import time
from datetime import date, datetime, timedelta
from typing import Any, Dict, Generator, MutableMapping, Tuple
from airbyte_cdk.logger import AirbyteLogger
from airbyte_cdk.models import AirbyteMessage, AirbyteRecordMessage, AirbyteStateMessage, AirbyteStream, Type
from dateutil ... | 0.612773 | 0.071494 |
from django.shortcuts import render
import logging
import urllib
import urllib2
import json
from django.http import HttpResponseRedirect,HttpResponse
from mysite import settings
from django.core.urlresolvers import reverse
from Xromate.lib.User import Users
import logging
logger = logging.getLogger('django')
# Create... | login/views.py | from django.shortcuts import render
import logging
import urllib
import urllib2
import json
from django.http import HttpResponseRedirect,HttpResponse
from mysite import settings
from django.core.urlresolvers import reverse
from Xromate.lib.User import Users
import logging
logger = logging.getLogger('django')
# Create... | 0.126071 | 0.042147 |
from __future__ import division
import argparse
import sys
import os
# add the root of the video-analysis project to the path
script_path = os.path.split(os.path.realpath(__file__))[0]
package_path = os.path.abspath(os.path.join(script_path, '..', '..'))
sys.path.append(package_path)
video_analysis_path_guess = os.p... | mouse_burrows/scripts/get_cropped_movie.py | from __future__ import division
import argparse
import sys
import os
# add the root of the video-analysis project to the path
script_path = os.path.split(os.path.realpath(__file__))[0]
package_path = os.path.abspath(os.path.join(script_path, '..', '..'))
sys.path.append(package_path)
video_analysis_path_guess = os.p... | 0.385606 | 0.103341 |
import unittest, os, shutil, uuid
import pkg_resources
from astropy.table import Table
import numpy as np
from scipy.ndimage.measurements import center_of_mass
from gpu_specter.io import read_psf
from gpu_specter.extract.cpu import evalcoeffs, get_spots
try:
import specter.psf
specter_available = True
except ... | py/gpu_specter/test/test_spots.py | import unittest, os, shutil, uuid
import pkg_resources
from astropy.table import Table
import numpy as np
from scipy.ndimage.measurements import center_of_mass
from gpu_specter.io import read_psf
from gpu_specter.extract.cpu import evalcoeffs, get_spots
try:
import specter.psf
specter_available = True
except ... | 0.510252 | 0.499207 |
import os
import csv
election_data = os.path.join('Resources', 'election_data.csv')
#Open csv, set delimiter, and read header
with open(election_data) as csvfile:
election_reader = csv.reader(csvfile, delimiter=",")
election_header = next(election_reader)
#Create list to store the candidates who receive... | PyPoll/main.py | import os
import csv
election_data = os.path.join('Resources', 'election_data.csv')
#Open csv, set delimiter, and read header
with open(election_data) as csvfile:
election_reader = csv.reader(csvfile, delimiter=",")
election_header = next(election_reader)
#Create list to store the candidates who receive... | 0.272702 | 0.327507 |
'assign img task to members as sequence'
import os
import shutil
import random
# personal lib
from basicFun import FILES
if __name__=="__main__":
namei=0
preTitle='isle5_phase1_FengShi'
members=['p1','p2','p3','p4']
random.shuffle(members)
jpgDir='/disk2/hao.yang/project/Qin/data/isle/Fen... | divideTask.py | 'assign img task to members as sequence'
import os
import shutil
import random
# personal lib
from basicFun import FILES
if __name__=="__main__":
namei=0
preTitle='isle5_phase1_FengShi'
members=['p1','p2','p3','p4']
random.shuffle(members)
jpgDir='/disk2/hao.yang/project/Qin/data/isle/Fen... | 0.046551 | 0.060613 |
# pylint: disable=E0213
import logging
import re
from typing import NoReturn, Optional
from ops.main import main
from opslib.osm.charm import CharmedOsmBase, RelationsMissing
from opslib.osm.interfaces.kafka import KafkaClient
from opslib.osm.interfaces.mongo import MongoClient
from opslib.osm.interfaces.mysql impo... | installers/charm/pol/src/charm.py |
# pylint: disable=E0213
import logging
import re
from typing import NoReturn, Optional
from ops.main import main
from opslib.osm.charm import CharmedOsmBase, RelationsMissing
from opslib.osm.interfaces.kafka import KafkaClient
from opslib.osm.interfaces.mongo import MongoClient
from opslib.osm.interfaces.mysql impo... | 0.756807 | 0.080069 |
import unittest
from requests import codes
# project modules
import wmata
class MyTestCase(unittest.TestCase):
def test_validate_key(self):
for sub, key in wmata.API_KEYS.items():
self.assertTrue(
wmata.validate_key(api_key=key),
msg=f'Failed validating {sub}'... | tests/wmata_test.py | import unittest
from requests import codes
# project modules
import wmata
class MyTestCase(unittest.TestCase):
def test_validate_key(self):
for sub, key in wmata.API_KEYS.items():
self.assertTrue(
wmata.validate_key(api_key=key),
msg=f'Failed validating {sub}'... | 0.618896 | 0.500244 |
import os
import shutil
import dotbot
import dotbot.util
import jinja2
import yaml
from datetime import datetime
__all__ = ['JinjaRender']
def _exists(path):
'''
Returns true if the path exists.
'''
path = os.path.expanduser(path)
return os.path.lexists(path)
def _is_regular_file(path):
'... | jinja.py | import os
import shutil
import dotbot
import dotbot.util
import jinja2
import yaml
from datetime import datetime
__all__ = ['JinjaRender']
def _exists(path):
'''
Returns true if the path exists.
'''
path = os.path.expanduser(path)
return os.path.lexists(path)
def _is_regular_file(path):
'... | 0.358915 | 0.155399 |
from collections import OrderedDict
from io import BytesIO
from os.path import basename
import arrow
from dropbox.client import DropboxClient, ErrorResponse
from wsgidav.dav_error import DAVError, HTTP_NOT_FOUND, HTTP_INTERNAL_ERROR
from wsgidav.dav_provider import DAVProvider, _DAVResource
from wsgidav.util import jo... | dropbox_dav_provider.py | from collections import OrderedDict
from io import BytesIO
from os.path import basename
import arrow
from dropbox.client import DropboxClient, ErrorResponse
from wsgidav.dav_error import DAVError, HTTP_NOT_FOUND, HTTP_INTERNAL_ERROR
from wsgidav.dav_provider import DAVProvider, _DAVResource
from wsgidav.util import jo... | 0.565299 | 0.0745 |
import numpy as np
import scipy.special as sc
from ..numerical_libs import reimport_numerical_libs, xp
def kumaraswamy_invcdf(a, b, u):
"""Inverse CDF of the Kumaraswamy distribution"""
return (1.0 - (1.0 - u) ** (1.0 / b)) ** (1.0 / a)
def approx_betaincinv(alp1, alp2, u):
"""Approximate betaincinv u... | bucky/util/distributions.py |
import numpy as np
import scipy.special as sc
from ..numerical_libs import reimport_numerical_libs, xp
def kumaraswamy_invcdf(a, b, u):
"""Inverse CDF of the Kumaraswamy distribution"""
return (1.0 - (1.0 - u) ** (1.0 / b)) ** (1.0 / a)
def approx_betaincinv(alp1, alp2, u):
"""Approximate betaincinv u... | 0.742515 | 0.507568 |
from json import load
from os.path import dirname, exists, join
from pika import BlockingConnection, ConnectionParameters, PlainCredentials
from traceback import format_exc
class MessageBrokerApi:
"""
Reveals API for message broker, i.e. RabbitMQ
"""
def __init__(self, service_name):
"""
Raises Runtim... | common/message_broker_api.py | from json import load
from os.path import dirname, exists, join
from pika import BlockingConnection, ConnectionParameters, PlainCredentials
from traceback import format_exc
class MessageBrokerApi:
"""
Reveals API for message broker, i.e. RabbitMQ
"""
def __init__(self, service_name):
"""
Raises Runtim... | 0.464416 | 0.053477 |
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def smallestFromLeaf(self, root: TreeNode) -> str:
if not root:
return Non... | 988. Smallest String Starting From Leaf/solution1.py | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def smallestFromLeaf(self, root: TreeNode) -> str:
if not root:
return Non... | 0.74158 | 0.423756 |
from typing import Dict, Optional
import torch as th
import torch.nn as nn
from rls.nn.activations import Act_REGISTER, default_act
from rls.nn.represents.encoders import End_REGISTER
from rls.nn.represents.memories import Rnn_REGISTER
from rls.nn.represents.vectors import Vec_REGISTER
from rls.nn.represen... | rls/nn/networks.py |
from typing import Dict, Optional
import torch as th
import torch.nn as nn
from rls.nn.activations import Act_REGISTER, default_act
from rls.nn.represents.encoders import End_REGISTER
from rls.nn.represents.memories import Rnn_REGISTER
from rls.nn.represents.vectors import Vec_REGISTER
from rls.nn.represen... | 0.903964 | 0.298542 |
import logging
import sys
from os.path import dirname
sys.path.insert(1, f"{dirname(__file__)}/../../..")
logging.basicConfig(level=logging.DEBUG)
# ------------------
# ---------------------
# Flask App for Slack OAuth flow
# ---------------------
import os
import json
from slack import WebClient
from slack.signatu... | integration_tests/samples/workflows/steps_from_apps.py | import logging
import sys
from os.path import dirname
sys.path.insert(1, f"{dirname(__file__)}/../../..")
logging.basicConfig(level=logging.DEBUG)
# ------------------
# ---------------------
# Flask App for Slack OAuth flow
# ---------------------
import os
import json
from slack import WebClient
from slack.signatu... | 0.269133 | 0.152095 |
from django.contrib.auth.models import Permission
from django.db import connections
from django.shortcuts import render
from django.db import transaction
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.decorators import permission_classes, api_view
from rest_fra... | squealy/views.py | from django.contrib.auth.models import Permission
from django.db import connections
from django.shortcuts import render
from django.db import transaction
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.decorators import permission_classes, api_view
from rest_fra... | 0.621771 | 0.140013 |
from os import listdir
from os.path import isfile, join
import os
import json
import re
from pprint import pprint
import pandas as pd
import os
import errno
def glassnode_files_organizer():
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
... | glassnode_files_organizer.py | from os import listdir
from os.path import isfile, join
import os
import json
import re
from pprint import pprint
import pandas as pd
import os
import errno
def glassnode_files_organizer():
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
... | 0.036778 | 0.087136 |
from __future__ import annotations
import datetime
from collections import OrderedDict
from dataclasses import dataclass
from dataclasses import field
from typing import List
from typing import Optional
from patent_client import session
from patent_client.util import Model
from patent_client.util import one_to_many
f... | src/patent_client/uspto/assignment/model.py | from __future__ import annotations
import datetime
from collections import OrderedDict
from dataclasses import dataclass
from dataclasses import field
from typing import List
from typing import Optional
from patent_client import session
from patent_client.util import Model
from patent_client.util import one_to_many
f... | 0.852844 | 0.124985 |
import re
from urlparse import urlparse
from xml.sax.saxutils import escape
import httplib
class ReposSolr(object):
'''
Utility methods for common solr core operations in Repos Search handlers.
'''
def __init__(self, svnhookOptions):
self.options = svnhookOptions
def value(self, fieldValue):
'''... | hook/repossolr.py |
import re
from urlparse import urlparse
from xml.sax.saxutils import escape
import httplib
class ReposSolr(object):
'''
Utility methods for common solr core operations in Repos Search handlers.
'''
def __init__(self, svnhookOptions):
self.options = svnhookOptions
def value(self, fieldValue):
'''... | 0.434581 | 0.127816 |
from typing import List
import numpy as np
from biomass.dynamics.solver import get_steady_state, solve_ode
from .name2idx import C, V
from .set_model import DifferentialEquation
class Observable(DifferentialEquation):
"""
Correlating model simulations and experimental measurements.
Attributes
----... | biomass/models/Nakakuki_Cell_2010/observable.py | from typing import List
import numpy as np
from biomass.dynamics.solver import get_steady_state, solve_ode
from .name2idx import C, V
from .set_model import DifferentialEquation
class Observable(DifferentialEquation):
"""
Correlating model simulations and experimental measurements.
Attributes
----... | 0.890187 | 0.588594 |
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class FetchRun(models.Model):
STARTED = 0
FINISHED = 1
ERRORED = 2
STATUS_CHOICES = (
(STARTED, 'Started'),
(FINISHED, 'Finished'),
(ERRORED, 'Errored'),
)
... | fetcher/models.py | from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class FetchRun(models.Model):
STARTED = 0
FINISHED = 1
ERRORED = 2
STATUS_CHOICES = (
(STARTED, 'Started'),
(FINISHED, 'Finished'),
(ERRORED, 'Errored'),
)
... | 0.598782 | 0.055978 |
class System:
def __init__(self,alphabet="01"): #конструктор класса
if len(set(alphabet))!=len(alphabet):
raise Exception("Error: the alphabet contains repeating elements")
elif "." in alphabet:
raise Exception("Error: invalid character .")
else:
se... | __init__.py | class System:
def __init__(self,alphabet="01"): #конструктор класса
if len(set(alphabet))!=len(alphabet):
raise Exception("Error: the alphabet contains repeating elements")
elif "." in alphabet:
raise Exception("Error: invalid character .")
else:
se... | 0.110705 | 0.231701 |
from __future__ import division
import tensorflow as tf
import numpy as np
import os
import PIL.Image as pil
from core import DFLearner
flags = tf.app.flags
flags.DEFINE_integer("batch_size", 4, "The size of of a sample batch")
flags.DEFINE_integer("img_height", 160, "Image height")
flags.DEFINE_integer("img_width", 5... | test_kitti_depth.py | from __future__ import division
import tensorflow as tf
import numpy as np
import os
import PIL.Image as pil
from core import DFLearner
flags = tf.app.flags
flags.DEFINE_integer("batch_size", 4, "The size of of a sample batch")
flags.DEFINE_integer("img_height", 160, "Image height")
flags.DEFINE_integer("img_width", 5... | 0.509276 | 0.127598 |
import datetime
from typing import Dict, Optional
from .quiz import Image
MANIFEST_START = '''\
<?xml version="1.0" encoding="UTF-8"?>
<manifest identifier="{manifest_identifier}"
xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.im... | text2qti/xml_imsmanifest.py |
import datetime
from typing import Dict, Optional
from .quiz import Image
MANIFEST_START = '''\
<?xml version="1.0" encoding="UTF-8"?>
<manifest identifier="{manifest_identifier}"
xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.im... | 0.523664 | 0.103749 |
import wx
import wx.lib.newevent as wxevent
from . import bitmaptoggle
# TODO Button tooltips
class BitmapRadioBox(wx.Panel):
"""A radio control which displays a collection of :class:`wx.ToggleButton`
controls, each of which displays an image.
Each of these buttons corresponds to a mutually exclusive ... | fsleyes_widgets/bitmapradio.py | import wx
import wx.lib.newevent as wxevent
from . import bitmaptoggle
# TODO Button tooltips
class BitmapRadioBox(wx.Panel):
"""A radio control which displays a collection of :class:`wx.ToggleButton`
controls, each of which displays an image.
Each of these buttons corresponds to a mutually exclusive ... | 0.490236 | 0.354629 |
import os
from tkinter import filedialog
from tkinter import messagebox
import logging
import glob
import support_functions
from WorkbookDocumentation import workbook_documentation
import threading
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
except Imp... | processworkbookdocumentation_support.py |
import os
from tkinter import filedialog
from tkinter import messagebox
import logging
import glob
import support_functions
from WorkbookDocumentation import workbook_documentation
import threading
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
except Imp... | 0.229018 | 0.069038 |
''' imports '''
import sqlite3
import matplotlib.pyplot as plt
import numpy as np
class PlotMonkey():
''' Monkey to draw plots based on databases created by an UrlMonkey. '''
def __init__(self, db_name):
self.db_name = db_name
def packup_small_ratios(self, url_dict, min_ratio):
''' Pack... | web_monkey/plot_monkey/plot_monkey.py | ''' imports '''
import sqlite3
import matplotlib.pyplot as plt
import numpy as np
class PlotMonkey():
''' Monkey to draw plots based on databases created by an UrlMonkey. '''
def __init__(self, db_name):
self.db_name = db_name
def packup_small_ratios(self, url_dict, min_ratio):
''' Pack... | 0.80112 | 0.457985 |
from behave import *
from hamcrest import assert_that, equal_to
from vec3 import Vec3, vec3, is_vec3
from vec4 import Vec4, point, vector
from base import equal
import numpy as np
from shape import material, sphere, test_shape, point_light, plane
from base import render, translation, scaling, view_transform, world, cam... | features/steps/zz_14_patterns_steps.py | from behave import *
from hamcrest import assert_that, equal_to
from vec3 import Vec3, vec3, is_vec3
from vec4 import Vec4, point, vector
from base import equal
import numpy as np
from shape import material, sphere, test_shape, point_light, plane
from base import render, translation, scaling, view_transform, world, cam... | 0.819496 | 0.488832 |
import datetime
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.db import models
from mptt.models import MPTTModel
# Create your models here.
class Question(models.Model):
t = models.CharField(max_length=200)
question_text = models.CharField(max_length=... | polls/models.py |
import datetime
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.db import models
from mptt.models import MPTTModel
# Create your models here.
class Question(models.Model):
t = models.CharField(max_length=200)
question_text = models.CharField(max_length=... | 0.340924 | 0.06666 |
import json
import os
import pwd
import socket
import subprocess
import sys
from contextlib import closing
# Constants
WIN = os.name == "nt"
def is_base_conda():
"""Check if current env is base enviroment."""
return True
def is_root():
"""Check that current process is running as `root`."""
return o... | spyder-remote-server/spyder_remote_server/utils.py | import json
import os
import pwd
import socket
import subprocess
import sys
from contextlib import closing
# Constants
WIN = os.name == "nt"
def is_base_conda():
"""Check if current env is base enviroment."""
return True
def is_root():
"""Check that current process is running as `root`."""
return o... | 0.391988 | 0.139426 |
from collections import OrderedDict
from .cdeclparser import lines_to_statements, parse_func
def take_functions(line_gen):
return [fnc for fnc in map(parse_func, lines_to_statements(line_gen))]
def type_lines():
yield 'int getID() const;'
yield 'const std::string &getName() const;'
def parse_classes(i... | generator/parser/classes.py | from collections import OrderedDict
from .cdeclparser import lines_to_statements, parse_func
def take_functions(line_gen):
return [fnc for fnc in map(parse_func, lines_to_statements(line_gen))]
def type_lines():
yield 'int getID() const;'
yield 'const std::string &getName() const;'
def parse_classes(i... | 0.545044 | 0.29303 |
import os
from distutils import spawn
import re
import subprocess
import time
import unittest
import itertools
import asyncio
import sys
import vanir.tests
import vanir
@unittest.skipUnless(
spawn.find_executable('xprop') and
spawn.find_executable('xdotool') and
spawn.find_executable... | vanir/tests/integ/mime.py | import os
from distutils import spawn
import re
import subprocess
import time
import unittest
import itertools
import asyncio
import sys
import vanir.tests
import vanir
@unittest.skipUnless(
spawn.find_executable('xprop') and
spawn.find_executable('xdotool') and
spawn.find_executable... | 0.128936 | 0.050941 |
class FlatJSON(object):
"""
Devuelve un JSON de una sola dimensión.
Si always_string está activo devuelve todos os valores como string,
incluso los int, float.
{
"nombre": "Pepe",
"apellido": "Argento",
"hijos": [
{
"nombre": "Coki",
... | flatjson/__init__.py |
class FlatJSON(object):
"""
Devuelve un JSON de una sola dimensión.
Si always_string está activo devuelve todos os valores como string,
incluso los int, float.
{
"nombre": "Pepe",
"apellido": "Argento",
"hijos": [
{
"nombre": "Coki",
... | 0.370339 | 0.422981 |
import sys
import unittest
import wradlib.georef as georef
import wradlib.util as util
from wradlib.io import read_generic_hdf5, open_raster, gdal_create_dataset
import numpy as np
from osgeo import gdal, osr, ogr
from deprecation import fail_if_not_removed
np.set_printoptions(edgeitems=3, infstr='inf', lin... | wradlib/tests/test_georef.py |
import sys
import unittest
import wradlib.georef as georef
import wradlib.util as util
from wradlib.io import read_generic_hdf5, open_raster, gdal_create_dataset
import numpy as np
from osgeo import gdal, osr, ogr
from deprecation import fail_if_not_removed
np.set_printoptions(edgeitems=3, infstr='inf', lin... | 0.325521 | 0.398465 |
import pandas as pd
import sys
import glob
import os
import re
import numpy as np
import logging
logging.basicConfig(stream=sys.stdout,
level=logging.INFO,
format='[%(asctime)s] %(message)s',
datefmt='%Y/%m/%d %H:%M:%S')
#inside pathx (MD)
def time_freq_fi... | core/filtering.py | import pandas as pd
import sys
import glob
import os
import re
import numpy as np
import logging
logging.basicConfig(stream=sys.stdout,
level=logging.INFO,
format='[%(asctime)s] %(message)s',
datefmt='%Y/%m/%d %H:%M:%S')
#inside pathx (MD)
def time_freq_fi... | 0.060613 | 0.157008 |
class Http1xHeaderErr(Exception): pass
def build_http1x_resp_header(status, seq, version="1.1"):
tmplist = ["HTTP/%s %s\r\n" % (version,status)]
for k, v in seq:
sts = "%s: %s\r\n" % (k, v,)
tmplist.append(sts)
tmplist.append("\r\n")
return "".join(tmplist)
def build_http1x_req_hea... | pywind/web/lib/httputils.py |
class Http1xHeaderErr(Exception): pass
def build_http1x_resp_header(status, seq, version="1.1"):
tmplist = ["HTTP/%s %s\r\n" % (version,status)]
for k, v in seq:
sts = "%s: %s\r\n" % (k, v,)
tmplist.append(sts)
tmplist.append("\r\n")
return "".join(tmplist)
def build_http1x_req_hea... | 0.356671 | 0.121477 |
import struct
import ghidra.program.model.block.SimpleBlockModel as SimpleBlockModel
def get_simple_blocks_by_function(image_base, listing):
model = SimpleBlockModel(currentProgram)
entries = {}
block_iter = model.getCodeBlocks(monitor)
while block_iter.hasNext() and (not monitor.isCancelled()):
... | mesogen_scripts/ghidra.py |
import struct
import ghidra.program.model.block.SimpleBlockModel as SimpleBlockModel
def get_simple_blocks_by_function(image_base, listing):
model = SimpleBlockModel(currentProgram)
entries = {}
block_iter = model.getCodeBlocks(monitor)
while block_iter.hasNext() and (not monitor.isCancelled()):
... | 0.324663 | 0.186169 |
import json
from app.api.auth import views
from app.tests import mock_objects
# Test user registration passes
def test_user_registration(test_app, monkeypatch):
monkeypatch.setattr(
views, "get_user_by_email", mock_objects.get_no_user_by_email,
)
monkeypatch.setattr(views, "add_user", mock_objec... | services/server/app/tests/test_auth_view_unit.py | import json
from app.api.auth import views
from app.tests import mock_objects
# Test user registration passes
def test_user_registration(test_app, monkeypatch):
monkeypatch.setattr(
views, "get_user_by_email", mock_objects.get_no_user_by_email,
)
monkeypatch.setattr(views, "add_user", mock_objec... | 0.53777 | 0.345285 |
from blacksheep import Content
from blacksheep.messages import Request, Response
from blacksheep.server.bindings import ServerInfo
from blacksheep.server.routing import Router
from blacksheep.server.responses import redirect, html, bad_request,not_found
from modules.ip_todo import _ip
from modules.qq_todo import ... | app/routers.py | from blacksheep import Content
from blacksheep.messages import Request, Response
from blacksheep.server.bindings import ServerInfo
from blacksheep.server.routing import Router
from blacksheep.server.responses import redirect, html, bad_request,not_found
from modules.ip_todo import _ip
from modules.qq_todo import ... | 0.202838 | 0.119923 |
from unittest.mock import MagicMock, Mock, patch
import pytest
import ddt
from celery.states import FAILURE
from common.djangoapps.student.tests.factories import UserFactory
from common.test.utils import normalize_repr
from lms.djangoapps.bulk_email.models import SEND_TO_LEARNERS, SEND_TO_MYSELF, SEND_TO_STAFF, Cours... | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/instructor_task/tests/test_api.py | from unittest.mock import MagicMock, Mock, patch
import pytest
import ddt
from celery.states import FAILURE
from common.djangoapps.student.tests.factories import UserFactory
from common.test.utils import normalize_repr
from lms.djangoapps.bulk_email.models import SEND_TO_LEARNERS, SEND_TO_MYSELF, SEND_TO_STAFF, Cours... | 0.627723 | 0.3041 |
from __future__ import annotations
import typing
from ctc import spec
from . import erc20_metadata
async def async_normalize_erc20_quantity(
quantity: typing.SupportsFloat,
token: typing.Optional[spec.ERC20Address] = None,
provider: spec.ProviderSpec = None,
decimals: typing.Optional[typing.Support... | src/ctc/evm/erc20_utils/erc20_normalize.py | from __future__ import annotations
import typing
from ctc import spec
from . import erc20_metadata
async def async_normalize_erc20_quantity(
quantity: typing.SupportsFloat,
token: typing.Optional[spec.ERC20Address] = None,
provider: spec.ProviderSpec = None,
decimals: typing.Optional[typing.Support... | 0.829146 | 0.397851 |
from re import search, findall, split, match
def valid(line):
if any(i in line for i in INVALID) or line == '':
return False
return True
def rathena_db_parse(table, schema, file, db):
# Parse any *db.txt from rAthena
# table - table's name
# schema - [('id', 'INTEGER PRI... | dev/foo.py | from re import search, findall, split, match
def valid(line):
if any(i in line for i in INVALID) or line == '':
return False
return True
def rathena_db_parse(table, schema, file, db):
# Parse any *db.txt from rAthena
# table - table's name
# schema - [('id', 'INTEGER PRI... | 0.198763 | 0.082846 |
import os
from .mzml import MzMLLoader
from .mzxml import MzXMLLoader
from .mgf import MGFLoader
from . import _compression
guessers = []
reader_types = [MzMLLoader, MzXMLLoader, MGFLoader]
def register_type_guesser(reader_guesser):
guessers.append(reader_guesser)
return reader_guesser
@register_type_guess... | ms_deisotope/data_source/infer_type.py | import os
from .mzml import MzMLLoader
from .mzxml import MzXMLLoader
from .mgf import MGFLoader
from . import _compression
guessers = []
reader_types = [MzMLLoader, MzXMLLoader, MGFLoader]
def register_type_guesser(reader_guesser):
guessers.append(reader_guesser)
return reader_guesser
@register_type_guess... | 0.26569 | 0.068913 |
import os
import tempfile
import threading
import unittest2 as unittest
from cactus.listener import PollingListener
from cactus.tests.compat import has_symlink
try:
from cactus.listener import FSEventsListener
except ImportError:
FSEventsListener = None
def sleep(s):
# time.sleep(s)
event = threadin... | cactus/tests/test_listener.py | import os
import tempfile
import threading
import unittest2 as unittest
from cactus.listener import PollingListener
from cactus.tests.compat import has_symlink
try:
from cactus.listener import FSEventsListener
except ImportError:
FSEventsListener = None
def sleep(s):
# time.sleep(s)
event = threadin... | 0.154855 | 0.204759 |
import requests
import unittest
class GithubSearchTests(unittest.TestCase):
def test_user_search_by_followers(self):
# Test if the user's followers are until 30 followers
# This test is originally from users with at least 1k followers, but the github api only returns 30
query_users_follow... | github_api_user.py | import requests
import unittest
class GithubSearchTests(unittest.TestCase):
def test_user_search_by_followers(self):
# Test if the user's followers are until 30 followers
# This test is originally from users with at least 1k followers, but the github api only returns 30
query_users_follow... | 0.413477 | 0.264545 |
def get_options():
import argparse
description = 'Summarise k-mer annotation at the gene level'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('annotations',
help='Annotated k-mer file from annotate_hits.py')
parser.add_argument('pangenome',
... | src/summarise_annotations.py | def get_options():
import argparse
description = 'Summarise k-mer annotation at the gene level'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('annotations',
help='Annotated k-mer file from annotate_hits.py')
parser.add_argument('pangenome',
... | 0.554109 | 0.25875 |
# python3中只有urllib,且ProxyHandler和build_opener都在request中:
import urllib.request
import time
import re
import random
totalurl = {}
unusedurl = {}
#生成ProxyHandler对象
def get_proxy():
return urllib.request.ProxyHandler({'http': "localhost:8580"})
#生成指向代理的url_opener
def get_proxy_http_opener(proxy):
return urllib.... | notebooks/Python_Examples/blog_clicker_py3.py | # python3中只有urllib,且ProxyHandler和build_opener都在request中:
import urllib.request
import time
import re
import random
totalurl = {}
unusedurl = {}
#生成ProxyHandler对象
def get_proxy():
return urllib.request.ProxyHandler({'http': "localhost:8580"})
#生成指向代理的url_opener
def get_proxy_http_opener(proxy):
return urllib.... | 0.12363 | 0.122944 |
from collections import OrderedDict
import torch
from apex.optimizers import FusedAdam
from apex.contrib.sparsity import ASP
def build_model(args):
od = OrderedDict()
for i in range(args.num_layers):
if i == 0:
od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidde... | apex/contrib/sparsity/test/toy_problem.py | from collections import OrderedDict
import torch
from apex.optimizers import FusedAdam
from apex.contrib.sparsity import ASP
def build_model(args):
od = OrderedDict()
for i in range(args.num_layers):
if i == 0:
od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidde... | 0.650467 | 0.380615 |
import spydrnet as sdn
def check_nmr(netlist,all_elements_to_replicate,degree,suffix):
"""
Checks to make sure all ports/instances specified to be replicated were replicated and those not specified were not replicated
:param netlist: current netlist
:param all_elements_to_replicate: a list of hier... | spydrnet_tmr/utils/design_rule_check/drc_apply_nmr.py | import spydrnet as sdn
def check_nmr(netlist,all_elements_to_replicate,degree,suffix):
"""
Checks to make sure all ports/instances specified to be replicated were replicated and those not specified were not replicated
:param netlist: current netlist
:param all_elements_to_replicate: a list of hier... | 0.303732 | 0.376222 |
from search import Problem
def h(node):
eye, snap, star, wave, exp, hide, ymca, fist, time, goal = node.state
return goal - time
EYE, SNAP, STAR, WAVE, EXP, HIDE, YMCA, FIST, PAUSE = range(9)
TIMES = [500, 800, 360, 700, 408, 500, 936, 800, 1]
class A(Problem):
def value(self, state):
... | u2.py | from search import Problem
def h(node):
eye, snap, star, wave, exp, hide, ymca, fist, time, goal = node.state
return goal - time
EYE, SNAP, STAR, WAVE, EXP, HIDE, YMCA, FIST, PAUSE = range(9)
TIMES = [500, 800, 360, 700, 408, 500, 936, 800, 1]
class A(Problem):
def value(self, state):
... | 0.277082 | 0.444806 |
import unittest
import pandas as pd
import numpy as np
from numpyro.handlers import seed, trace
import jax
from twinify.model_loading import load_custom_numpyro_model, ModelException
from argparse import Namespace
class NumpyroModelLoadingTests(unittest.TestCase):
def test_load_numpyro_model_file_not_found(self):... | tests/model_loading_test.py | import unittest
import pandas as pd
import numpy as np
from numpyro.handlers import seed, trace
import jax
from twinify.model_loading import load_custom_numpyro_model, ModelException
from argparse import Namespace
class NumpyroModelLoadingTests(unittest.TestCase):
def test_load_numpyro_model_file_not_found(self):... | 0.378115 | 0.497009 |
import os
import yaml
import subprocess
import sys
from yaml import load, dump
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
TOP_DIR_PATH = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
YAML_FRONT_MATTER_DEL... | tools/docs-fetcher.py |
import os
import yaml
import subprocess
import sys
from yaml import load, dump
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
TOP_DIR_PATH = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
YAML_FRONT_MATTER_DEL... | 0.209955 | 0.088702 |
class ChannelPoisonException(Exception):
""" ChannelPoisonException()
Exception thrown by a read or write operation on a channel end.
In case a ChannelPoisonException is raised in a CSP process and not caught, the CSP process
will look for channel ends in the argument list and invoke a poison sign... | pycsp/parallel/exceptions.py | class ChannelPoisonException(Exception):
""" ChannelPoisonException()
Exception thrown by a read or write operation on a channel end.
In case a ChannelPoisonException is raised in a CSP process and not caught, the CSP process
will look for channel ends in the argument list and invoke a poison sign... | 0.663015 | 0.29117 |
from setuptools import setup
from distutils.core import Extension
from sys import exit as sys_exit
import versioneer
try:
from Cython.Distutils import build_ext
except ImportError:
print("ERROR - please install the cython dependency manually:")
print("pip install cython")
sys_exit( 1 )
try:
from n... | setup.py | from setuptools import setup
from distutils.core import Extension
from sys import exit as sys_exit
import versioneer
try:
from Cython.Distutils import build_ext
except ImportError:
print("ERROR - please install the cython dependency manually:")
print("pip install cython")
sys_exit( 1 )
try:
from n... | 0.294316 | 0.077169 |
__all__ = ['load_seq_model', 'featurize_context', 'predict_seq']
# Cell
import joblib
import sglearn
import pandas as pd
import os
# Cell
def load_seq_model():
"""Load rule set 3 sequence model"""
model = joblib.load(os.path.join(os.path.dirname(__file__), 'RuleSet3.pkl'))
return model
# Cell
def featur... | rs3/seq.py |
__all__ = ['load_seq_model', 'featurize_context', 'predict_seq']
# Cell
import joblib
import sglearn
import pandas as pd
import os
# Cell
def load_seq_model():
"""Load rule set 3 sequence model"""
model = joblib.load(os.path.join(os.path.dirname(__file__), 'RuleSet3.pkl'))
return model
# Cell
def featur... | 0.623721 | 0.182389 |
from utils.utils import *
def analyse_packet_arp(packet: list):
dict_hardware_type = {1: "Ethernet", 2: "Experimental Ethernet", 3: "Amateur Radio AX.25",
4: "Proteon ProNET Token Ring", 5: "Chaos", 6: "IEEE 802 Networks",
7: "ARCNET", 8: "Hyperchannel", 9: "Lan... | src/couche_network/protocol_arp.py | from utils.utils import *
def analyse_packet_arp(packet: list):
dict_hardware_type = {1: "Ethernet", 2: "Experimental Ethernet", 3: "Amateur Radio AX.25",
4: "Proteon ProNET Token Ring", 5: "Chaos", 6: "IEEE 802 Networks",
7: "ARCNET", 8: "Hyperchannel", 9: "Lan... | 0.507568 | 0.343149 |
import numpy as np
from rpi_d3m_primitives.featSelect.helperFunctions import normalize_array, joint
from rpi_d3m_primitives.featSelect.mutualInformation import mi, joint_probability
"""---------------------------- CONDITIONAL MUTUAL INFORMATION ----------------------------"""
def mergeArrays(firstVector, secondVect... | featSelect/conditionalMI.py | import numpy as np
from rpi_d3m_primitives.featSelect.helperFunctions import normalize_array, joint
from rpi_d3m_primitives.featSelect.mutualInformation import mi, joint_probability
"""---------------------------- CONDITIONAL MUTUAL INFORMATION ----------------------------"""
def mergeArrays(firstVector, secondVect... | 0.455683 | 0.655391 |
import pandas as pd
import numpy as np
from pymc3 import Model, fit, logsumexp, traceplot
from pymc3 import DensityDist, Dirichlet, HalfCauchy
import theano.tensor as tt
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
... | model_comparison.py | import pandas as pd
import numpy as np
from pymc3 import Model, fit, logsumexp, traceplot
from pymc3 import DensityDist, Dirichlet, HalfCauchy
import theano.tensor as tt
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
... | 0.537527 | 0.546859 |
from __future__ import absolute_import
import os
from numpy import load
DATADIR = os.path.join(os.path.dirname(__file__), 'data')
COEFF_CACHE = {}
def _load_from_file(basename, varnames):
filename = os.path.join(DATADIR, basename + '.npz')
try:
mat = COEFF_CACHE[filename]
except KeyError:
... | dtcwt/coeffs.py | from __future__ import absolute_import
import os
from numpy import load
DATADIR = os.path.join(os.path.dirname(__file__), 'data')
COEFF_CACHE = {}
def _load_from_file(basename, varnames):
filename = os.path.join(DATADIR, basename + '.npz')
try:
mat = COEFF_CACHE[filename]
except KeyError:
... | 0.719482 | 0.350449 |
import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.animation import FuncAnimation
import time
import numpy as np
import sys
plt.style.use('fivethirtyeight')
saveplot = False
x_vals = []
y_vals = []
index = count()
topics =... | animate_plot.py |
import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.animation import FuncAnimation
import time
import numpy as np
import sys
plt.style.use('fivethirtyeight')
saveplot = False
x_vals = []
y_vals = []
index = count()
topics =... | 0.181227 | 0.369258 |
import logging
import click
from samcli.cli.cli_config_file import TomlProvider, configuration_option
from samcli.cli.main import aws_creds_options, common_options, pass_context, print_cmdline_args
from samcli.commands._utils.options import (
capabilities_option,
guided_deploy_stack_name,
metadata_option,... | samcli/commands/deploy/command.py | import logging
import click
from samcli.cli.cli_config_file import TomlProvider, configuration_option
from samcli.cli.main import aws_creds_options, common_options, pass_context, print_cmdline_args
from samcli.commands._utils.options import (
capabilities_option,
guided_deploy_stack_name,
metadata_option,... | 0.466846 | 0.110856 |
import builtins
import math
import random
from time import sleep
import clismo.exceptions as excpt
from clismo.lang.type import Instance, Type
__BUILTINS = {}
cs_float = Type.get("float")
cs_int = Type.get("int")
cs_str = Type.get("str")
cs_bool = Type.get("bool")
cs_none = Type.get("none")
cs_list = Type.get("list"... | clismo/builtin/cs_built_in_functions.py | import builtins
import math
import random
from time import sleep
import clismo.exceptions as excpt
from clismo.lang.type import Instance, Type
__BUILTINS = {}
cs_float = Type.get("float")
cs_int = Type.get("int")
cs_str = Type.get("str")
cs_bool = Type.get("bool")
cs_none = Type.get("none")
cs_list = Type.get("list"... | 0.4917 | 0.335432 |
from abc import ABC
from typing import Optional, TYPE_CHECKING
from ufaas_dockerapi.types import DockerJSONResponse
from ufaas_dockerapi.utils import (api_delete, api_post, convert_bool,
strip_nulls)
if TYPE_CHECKING:
from ufaas_dockerapi.client import DockerClient
class Image... | ufaas_dockerapi/image.py | from abc import ABC
from typing import Optional, TYPE_CHECKING
from ufaas_dockerapi.types import DockerJSONResponse
from ufaas_dockerapi.utils import (api_delete, api_post, convert_bool,
strip_nulls)
if TYPE_CHECKING:
from ufaas_dockerapi.client import DockerClient
class Image... | 0.860706 | 0.161618 |
# Lint as: python3
"""A state of the group testing algorithm."""
from typing import Dict
import jax
import jax.numpy as np
from jax.scipy import special
class State:
"""The state of the group testing system.
Attributes:
num_patients: the number of patients to be tested.
num_tests_per_cycle: how many test... | grouptesting/state.py |
# Lint as: python3
"""A state of the group testing algorithm."""
from typing import Dict
import jax
import jax.numpy as np
from jax.scipy import special
class State:
"""The state of the group testing system.
Attributes:
num_patients: the number of patients to be tested.
num_tests_per_cycle: how many test... | 0.936022 | 0.790894 |
import numpy as np
from numba import jit
# Reference: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
@jit(nopython=True, nogil=True, cache=True, fastmath=True)
def _make_line_low(x0: int, y0: int, x1: int, y1: int):
dx = x1 - x0
dy = y1 - y0
my = max(y0, y1)
yi = 1
if dy < 0:
... | seedpod_ground_risk/pathfinding/bresenham.py | import numpy as np
from numba import jit
# Reference: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
@jit(nopython=True, nogil=True, cache=True, fastmath=True)
def _make_line_low(x0: int, y0: int, x1: int, y1: int):
dx = x1 - x0
dy = y1 - y0
my = max(y0, y1)
yi = 1
if dy < 0:
... | 0.651466 | 0.550849 |
+ Add support for Wells and Shrines
+ Add final graphics
+ Add argparse support
+ Add support for colour palettes
"""
from PIL import Image
from enum import auto, Enum
import random
from opensimplex import OpenSimplex
from datetime import datetime
__author__ = "<NAME>"
class LevelTiles(Enum):
GRASS = auto()
... | Contract 2/Contract.py | + Add support for Wells and Shrines
+ Add final graphics
+ Add argparse support
+ Add support for colour palettes
"""
from PIL import Image
from enum import auto, Enum
import random
from opensimplex import OpenSimplex
from datetime import datetime
__author__ = "<NAME>"
class LevelTiles(Enum):
GRASS = auto()
... | 0.57093 | 0.555375 |
import json
import time
from os import listdir
from os.path import isfile, join
# Discord Imports
import discord
from discord.ext import commands
from discord.ext.commands import CommandNotFound
# Importing config.json
with open("config.json") as config_file:
data = json.load(config_file)
config_file.close()
... | main.py | import json
import time
from os import listdir
from os.path import isfile, join
# Discord Imports
import discord
from discord.ext import commands
from discord.ext.commands import CommandNotFound
# Importing config.json
with open("config.json") as config_file:
data = json.load(config_file)
config_file.close()
... | 0.273477 | 0.205376 |
import typing
import requests
import logging
from datetime import datetime
from django.db.models import Q
from purplship.core import utils
from purpleserver.core.utils import identity
from purpleserver.events import models
logger = logging.getLogger(__name__)
NotificationResponse = typing.Tuple[str, requests.Response... | apps/events/purpleserver/events/tasks/webhook.py | import typing
import requests
import logging
from datetime import datetime
from django.db.models import Q
from purplship.core import utils
from purpleserver.core.utils import identity
from purpleserver.events import models
logger = logging.getLogger(__name__)
NotificationResponse = typing.Tuple[str, requests.Response... | 0.416441 | 0.086903 |
import argparse
import os
import praw
from dotenv import load_dotenv
from prettytable import PrettyTable
from urs.praw_scrapers import Subreddit
from urs.utils import Global
class MakeArgs():
"""
Making dummy args to test Comments.py methods.
"""
@staticmethod
def parser_for_testing():
p... | tests/test_praw_scrapers/test_Subreddit.py | import argparse
import os
import praw
from dotenv import load_dotenv
from prettytable import PrettyTable
from urs.praw_scrapers import Subreddit
from urs.utils import Global
class MakeArgs():
"""
Making dummy args to test Comments.py methods.
"""
@staticmethod
def parser_for_testing():
p... | 0.436622 | 0.233597 |
import asyncio
from nonebot import logger, require, get_bots
from nonebot.adapters.cqhttp import MessageSegment
from omega_miya.utils.Omega_Base import DBSubscription, DBTable
from omega_miya.utils.pixiv_utils import PixivIllust, PixivisionArticle
from .utils import pixivsion_article_parse
from .block_tag import TAG_BL... | omega_miya/plugins/pixivsion_monitor/monitor.py | import asyncio
from nonebot import logger, require, get_bots
from nonebot.adapters.cqhttp import MessageSegment
from omega_miya.utils.Omega_Base import DBSubscription, DBTable
from omega_miya.utils.pixiv_utils import PixivIllust, PixivisionArticle
from .utils import pixivsion_article_parse
from .block_tag import TAG_BL... | 0.197174 | 0.122052 |
import re
from urllib.parse import quote
from bs4 import BeautifulSoup
from django.core import mail
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpRequest
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from attendee.forms import (... | devday/attendee/tests/test_views.py | import re
from urllib.parse import quote
from bs4 import BeautifulSoup
from django.core import mail
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpRequest
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from attendee.forms import (... | 0.359364 | 0.177793 |
from pathlib import Path
import shutil
import yaml
from typing import Iterable, List
def is_subseq(x: Iterable, y: Iterable) -> bool:
"""
Check whether x is within y.
For example
registrations/deformable is in output/registration/deformable/192_12
"""
it = iter(y)
return all(c in it for ... | lama/utilities/data_clean_up.py | from pathlib import Path
import shutil
import yaml
from typing import Iterable, List
def is_subseq(x: Iterable, y: Iterable) -> bool:
"""
Check whether x is within y.
For example
registrations/deformable is in output/registration/deformable/192_12
"""
it = iter(y)
return all(c in it for ... | 0.582135 | 0.3437 |
import arrow
import pytest
from freqtrade.configuration import TimeRange
from freqtrade.exceptions import OperationalException
def test_parse_timerange_incorrect():
assert TimeRange('date', None, 1274486400, 0) == TimeRange.parse_timerange('20100522-')
assert TimeRange(None, 'date', 0, 1274486400) == TimeRa... | tests/test_timerange.py | import arrow
import pytest
from freqtrade.configuration import TimeRange
from freqtrade.exceptions import OperationalException
def test_parse_timerange_incorrect():
assert TimeRange('date', None, 1274486400, 0) == TimeRange.parse_timerange('20100522-')
assert TimeRange(None, 'date', 0, 1274486400) == TimeRa... | 0.566618 | 0.604662 |
import os, sys
import math, random, time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import imageio
import lpips
import utils.ssim as ssim_utils
lpips_alex = lpips.LPIPS(net='alex') # best forward scores
lpips_vgg = lpips.LPIPS(net='vgg') # closer to "traditional" perceptua... | utils/image.py | import os, sys
import math, random, time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import imageio
import lpips
import utils.ssim as ssim_utils
lpips_alex = lpips.LPIPS(net='alex') # best forward scores
lpips_vgg = lpips.LPIPS(net='vgg') # closer to "traditional" perceptua... | 0.538741 | 0.381738 |
import json
import requests
from http import cookiejar
import time
#没有票据,注意两个值的变量,//Referer、Cookie
headers = {'Host': 'www.huas.edu.cn:319',
'User-Agent': 'Mozilla/5.0 (Android 7.0; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'en-... | main.py |
import json
import requests
from http import cookiejar
import time
#没有票据,注意两个值的变量,//Referer、Cookie
headers = {'Host': 'www.huas.edu.cn:319',
'User-Agent': 'Mozilla/5.0 (Android 7.0; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'en-... | 0.103318 | 0.08886 |
import base64
from dash import html
import io
import json
from typing import Tuple, List
import pandas as pd
import shap
from dice_ml import Model, Dice, Data
from matplotlib import pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.manifold import TSNE
from sklearn.model_selection import tr... | heloc_app/data.py | import base64
from dash import html
import io
import json
from typing import Tuple, List
import pandas as pd
import shap
from dice_ml import Model, Dice, Data
from matplotlib import pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.manifold import TSNE
from sklearn.model_selection import tr... | 0.885724 | 0.573559 |
import os.path
import subprocess
import sys
import winreg
from typing import List, Tuple, Dict
import pytest
import pyxelrest.install_addin
def redirect_paths(monkeypatch, redirects: Dict[str, str]):
original = os.path.join
def redirect(*args) -> str:
original_path = original(*args)
return ... | tests/scripts/test_install_addin_script.py | import os.path
import subprocess
import sys
import winreg
from typing import List, Tuple, Dict
import pytest
import pyxelrest.install_addin
def redirect_paths(monkeypatch, redirects: Dict[str, str]):
original = os.path.join
def redirect(*args) -> str:
original_path = original(*args)
return ... | 0.416559 | 0.187504 |
from pyspark.conf import SparkConf
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, IntegerType, StringType, FloatType, DoubleType
from pyspark.sql.functions import monotonically_increasing_id, row_number, lit
from pyspark.sql.window import Window
import pyspark.sql.functions ... | create_train_test_data.py | from pyspark.conf import SparkConf
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, IntegerType, StringType, FloatType, DoubleType
from pyspark.sql.functions import monotonically_increasing_id, row_number, lit
from pyspark.sql.window import Window
import pyspark.sql.functions ... | 0.223038 | 0.420481 |
import pandas as pd
from sklearn import preprocessing
#path : File path
# Code starts here
# read the dataset
dataset= pd.read_csv(path)
print(dataset.head())
dataset.drop(columns=['Id'],axis=1,inplace=True)
print(dataset.describe())
# look at the first five columns
# Check if there's any column which is not u... | Forest-Type-Cover-Prediction/code.py | import pandas as pd
from sklearn import preprocessing
#path : File path
# Code starts here
# read the dataset
dataset= pd.read_csv(path)
print(dataset.head())
dataset.drop(columns=['Id'],axis=1,inplace=True)
print(dataset.describe())
# look at the first five columns
# Check if there's any column which is not u... | 0.607081 | 0.467575 |
import os
from clairmeta.settings import SEQUENCE_SETTINGS
from clairmeta.utils.sys import number_is_close
from clairmeta.utils.file import parse_name
def check_sequence(path, allowed_extensions, ignore_files=None, ignore_dirs=None):
""" Check image file sequence coherence recursively.
Args:
... | clairmeta/sequence_check.py |
import os
from clairmeta.settings import SEQUENCE_SETTINGS
from clairmeta.utils.sys import number_is_close
from clairmeta.utils.file import parse_name
def check_sequence(path, allowed_extensions, ignore_files=None, ignore_dirs=None):
""" Check image file sequence coherence recursively.
Args:
... | 0.696371 | 0.197116 |
import json
import argparse
import subprocess
from tqdm import tqdm
from nltk.stem.porter import *
from nltk.tokenize import wordpunct_tokenize
stemmer = PorterStemmer()
def count_file_lines(file_path):
"""
Counts the number of lines in a file using wc utility.
:param file_path: path to file
:return:... | retrieval/source/convert.py | import json
import argparse
import subprocess
from tqdm import tqdm
from nltk.stem.porter import *
from nltk.tokenize import wordpunct_tokenize
stemmer = PorterStemmer()
def count_file_lines(file_path):
"""
Counts the number of lines in a file using wc utility.
:param file_path: path to file
:return:... | 0.309337 | 0.169269 |
from nimblenet.activation_functions import sigmoid_function
from nimblenet.cost_functions import *
from nimblenet.learning_algorithms import *
from nimblenet.neuralnet import NeuralNet
from nimblenet.preprocessing import construct_preprocessor, standarize
from nimblenet.data_structures import Instance
from nimblenet.to... | rehearsal.py | from nimblenet.activation_functions import sigmoid_function
from nimblenet.cost_functions import *
from nimblenet.learning_algorithms import *
from nimblenet.neuralnet import NeuralNet
from nimblenet.preprocessing import construct_preprocessor, standarize
from nimblenet.data_structures import Instance
from nimblenet.to... | 0.559771 | 0.261519 |
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("form", "0001_initial")]
operations = [
migrations.AlterField(
model_name="answer",
name="crea... | caluma/form/migrations/0002_auto_20181221_1517.py | from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("form", "0001_initial")]
operations = [
migrations.AlterField(
model_name="answer",
name="crea... | 0.609175 | 0.162148 |
from silence_notifier.state import State
class SomeResponsibleState(State):
"""State for when at least one person has taken responsibility for fixing
the problems."""
def handle_timer(self, num_invocations, minutes):
"""Do not send any warning, since someone is looking into it."""
# Not wa... | silence_notifier/some_responsible_state.py | from silence_notifier.state import State
class SomeResponsibleState(State):
"""State for when at least one person has taken responsibility for fixing
the problems."""
def handle_timer(self, num_invocations, minutes):
"""Do not send any warning, since someone is looking into it."""
# Not wa... | 0.626238 | 0.283019 |
from rest_framework.test import APITestCase
from rest_framework import status
# Project
from apps.shared.utils import timezone_fix
from apps.shared.tests import ViewSetTestCase
from apps.gauth.tests import TEST_USER1
class NewsPublicTest(APITestCase, ViewSetTestCase):
fixtures = ['user.yaml', 'news.yaml']
l... | apps/news/tests/news_public.py | from rest_framework.test import APITestCase
from rest_framework import status
# Project
from apps.shared.utils import timezone_fix
from apps.shared.tests import ViewSetTestCase
from apps.gauth.tests import TEST_USER1
class NewsPublicTest(APITestCase, ViewSetTestCase):
fixtures = ['user.yaml', 'news.yaml']
l... | 0.562777 | 0.276449 |
import csv
import requests
from cachecontrol import CacheControl
from cachecontrol.caches.file_cache import FileCache
from utils import make_index
session = CacheControl(requests.session(), cache=FileCache(".cache"))
development_plans_csv = "https://raw.githubusercontent.com/digital-land/alpha-data/master/local-pla... | bin/local_plans_data.py | import csv
import requests
from cachecontrol import CacheControl
from cachecontrol.caches.file_cache import FileCache
from utils import make_index
session = CacheControl(requests.session(), cache=FileCache(".cache"))
development_plans_csv = "https://raw.githubusercontent.com/digital-land/alpha-data/master/local-pla... | 0.370112 | 0.173708 |
import random
from datetime import datetime, timedelta
from jasmin.vendor.smpp.twisted.tests.smsc_simulator import *
LOG_CATEGORY = "jasmin.smpp.tests.smsc_simulator"
message_state_map = {
'ACCEPTD': MessageState.ACCEPTED,
'UNDELIV': MessageState.UNDELIVERABLE,
'REJECTD': MessageState.REJECTED,
'DELI... | jasmin/protocols/smpp/test/smsc_simulator.py | import random
from datetime import datetime, timedelta
from jasmin.vendor.smpp.twisted.tests.smsc_simulator import *
LOG_CATEGORY = "jasmin.smpp.tests.smsc_simulator"
message_state_map = {
'ACCEPTD': MessageState.ACCEPTED,
'UNDELIV': MessageState.UNDELIVERABLE,
'REJECTD': MessageState.REJECTED,
'DELI... | 0.450601 | 0.088151 |
import itertools
import shutil
import sys
from pathlib import Path
from PIL import Image, ImageOps, ImageChops
Image.MAX_IMAGE_PIXELS = None
def check_path(path):
if not Path(path).exists():
Path(path).mkdir()
return Path(path)
def copy_tree(source, destination):
shutil.rmtree(destination)
s... | Image_Prep/flattener.py | import itertools
import shutil
import sys
from pathlib import Path
from PIL import Image, ImageOps, ImageChops
Image.MAX_IMAGE_PIXELS = None
def check_path(path):
if not Path(path).exists():
Path(path).mkdir()
return Path(path)
def copy_tree(source, destination):
shutil.rmtree(destination)
s... | 0.12062 | 0.155078 |
from datetime import datetime
from decimal import Decimal
import transaction
from urllib.parse import quote_plus
from sqlalchemy import engine_from_config
from pyramid.config import Configurator
from pyramid.request import Request, Response
from pyramid.renderers import JSON
from pyramid.authentication import AuthTkt... | Back/ecoreleve_server/__init__.py | from datetime import datetime
from decimal import Decimal
import transaction
from urllib.parse import quote_plus
from sqlalchemy import engine_from_config
from pyramid.config import Configurator
from pyramid.request import Request, Response
from pyramid.renderers import JSON
from pyramid.authentication import AuthTkt... | 0.431225 | 0.063744 |
import time
# network imports
from network.HttpResponse import HttpResponse
from network.Socket import Socket
# utils imports
from utils.constants import HTTP_UA, HTTP_CONTENTTYPE_FORMENCODED, \
HTTP_GET, HTTP_POST, HTTP_PORT, HTTP_TOO_MANY_REQ
from utils.namedtuples import StatusCode, Req... | network/HttpRequest.py | import time
# network imports
from network.HttpResponse import HttpResponse
from network.Socket import Socket
# utils imports
from utils.constants import HTTP_UA, HTTP_CONTENTTYPE_FORMENCODED, \
HTTP_GET, HTTP_POST, HTTP_PORT, HTTP_TOO_MANY_REQ
from utils.namedtuples import StatusCode, Req... | 0.723895 | 0.084493 |