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 numpy as np
import scipy.stats
from matplotlib import pyplot as plt
def signal_autocor(signal, lag=None, demean=True, method="fft", show=False):
"""**Autocorrelation (ACF)**
Compute the autocorrelation of a signal.
Parameters
-----------
signal : Union[list, np.array, pd.Series]
V... | neurokit2/signal/signal_autocor.py | import numpy as np
import scipy.stats
from matplotlib import pyplot as plt
def signal_autocor(signal, lag=None, demean=True, method="fft", show=False):
"""**Autocorrelation (ACF)**
Compute the autocorrelation of a signal.
Parameters
-----------
signal : Union[list, np.array, pd.Series]
V... | 0.924925 | 0.754599 |
from sqlalchemy import create_engine
import pandas as pd
import numpy as np
from importlib import reload
import collections
from pandas import json_normalize
import json
import argparse
import sys
from sqlalchemy import create_engine
import sqlite3
from importlib import reload
import os
def search_bypfam(dataset_path)... | patho_chembl/chembldb_pfam_mech.py | from sqlalchemy import create_engine
import pandas as pd
import numpy as np
from importlib import reload
import collections
from pandas import json_normalize
import json
import argparse
import sys
from sqlalchemy import create_engine
import sqlite3
from importlib import reload
import os
def search_bypfam(dataset_path)... | 0.233706 | 0.096663 |
import numpy as np
import sys
import random
import itertools
from datetime import datetime
def has_converged(found, current, duration):
assert current - found > 0
assert duration > 0
if current - found > 2000:
return True
if duration > 3600:
return True
return False
def print_now()... | source/set_cover.py | import numpy as np
import sys
import random
import itertools
from datetime import datetime
def has_converged(found, current, duration):
assert current - found > 0
assert duration > 0
if current - found > 2000:
return True
if duration > 3600:
return True
return False
def print_now()... | 0.38885 | 0.402803 |
import signal
from unittest import mock
import pytest
from coveralls.api import CoverallsException
import entrypoint
def patch_os_envirion(environ):
return mock.patch.dict("os.environ", environ, clear=True)
def patch_coveralls_wear():
return mock.patch("entrypoint.Coveralls.wear")
def patch_log():
r... | tests/test_entrypoint.py | import signal
from unittest import mock
import pytest
from coveralls.api import CoverallsException
import entrypoint
def patch_os_envirion(environ):
return mock.patch.dict("os.environ", environ, clear=True)
def patch_coveralls_wear():
return mock.patch("entrypoint.Coveralls.wear")
def patch_log():
r... | 0.619356 | 0.311348 |
import torch
from torch import cos, sin, sign
from .template import ControlledSystemTemplate
class CartPoleGymVersion(ControlledSystemTemplate):
'''Continuous version of the OpenAI Gym cartpole
Inspired by: https://gist.github.com/iandanforth/e3ffb67cf3623153e968f2afdfb01dc8'''
def __init__(self, *args, *... | hypersolvers-control/src/env/cartpole.py | import torch
from torch import cos, sin, sign
from .template import ControlledSystemTemplate
class CartPoleGymVersion(ControlledSystemTemplate):
'''Continuous version of the OpenAI Gym cartpole
Inspired by: https://gist.github.com/iandanforth/e3ffb67cf3623153e968f2afdfb01dc8'''
def __init__(self, *args, *... | 0.776835 | 0.434401 |
from proliantutils.redfish.resources.system import constants as sys_cons
from proliantutils.redfish.resources.system import mappings as sys_map
from sushy.resources import base
class HealthStatusField(base.CompositeField):
state = base.MappedField(
'State', sys_map.HEALTH_STATE_VALUE_MAP)
health = ba... | proliantutils/redfish/resources/system/ethernet_interface.py |
from proliantutils.redfish.resources.system import constants as sys_cons
from proliantutils.redfish.resources.system import mappings as sys_map
from sushy.resources import base
class HealthStatusField(base.CompositeField):
state = base.MappedField(
'State', sys_map.HEALTH_STATE_VALUE_MAP)
health = ba... | 0.608594 | 0.177063 |
from ... pyaz_utils import _call_az
def list(account_name, profile_name):
'''
List the instructions by billing profile id.
Required Parameters:
- account_name -- The ID that uniquely identifies a billing account.
- profile_name -- The ID that uniquely identifies a billing profile.
'''
retu... | pyaz/billing/instruction/__init__.py | from ... pyaz_utils import _call_az
def list(account_name, profile_name):
'''
List the instructions by billing profile id.
Required Parameters:
- account_name -- The ID that uniquely identifies a billing account.
- profile_name -- The ID that uniquely identifies a billing profile.
'''
retu... | 0.780997 | 0.180179 |
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework import filters, viewsets
from rest_framework import generics
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from .serializers import RecordWorkProgram... | application/records/views.py | from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework import filters, viewsets
from rest_framework import generics
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from .serializers import RecordWorkProgram... | 0.511961 | 0.232757 |
from common import *
import datetime
import argparse
import time
here = os.path.abspath(os.path.dirname(__file__))
app_dir = os.path.join(here, '../pyg/multi_gpu')
"""
if log_dir is not None, it will only parse logs
"""
def overall_perf_test(log_folder=None, mock=False):
tic = time.time()
if log_folder... | example/auto_runner/run_pyg.py | from common import *
import datetime
import argparse
import time
here = os.path.abspath(os.path.dirname(__file__))
app_dir = os.path.join(here, '../pyg/multi_gpu')
"""
if log_dir is not None, it will only parse logs
"""
def overall_perf_test(log_folder=None, mock=False):
tic = time.time()
if log_folder... | 0.374333 | 0.142769 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""Tests for results_lib."""
import contextlib
import os
import shutil
import tempfile
from six.moves import xrange
import tensorflow as tf
from single_task import results_lib # brain coder
... | research/brain_coder/single_task/results_lib_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""Tests for results_lib."""
import contextlib
import os
import shutil
import tempfile
from six.moves import xrange
import tensorflow as tf
from single_task import results_lib # brain coder
... | 0.599016 | 0.179189 |
import constant_parameters as c # pylint: disable=unused-wildcard-import
import button_listener as bl # pylint: disable=unused-wildcard-import
import session_manager as sm # pylint: disable=unused-wildcard-import
import bedtime_protocol as bp # pylint: disable=unused-wildcard-import
import light_effects as leff
inDemo... | button_logic.py | import constant_parameters as c # pylint: disable=unused-wildcard-import
import button_listener as bl # pylint: disable=unused-wildcard-import
import session_manager as sm # pylint: disable=unused-wildcard-import
import bedtime_protocol as bp # pylint: disable=unused-wildcard-import
import light_effects as leff
inDemo... | 0.222447 | 0.044848 |
import pytest
from sphinx.testing.util import etree_parse
@pytest.mark.sphinx('qthelp', testroot='basic')
def test_qthelp_basic(app, status, warning):
app.builder.build_all()
qhp = (app.outdir / 'Python.qhp').text()
assert '<customFilter name="Python ">' in qhp
assert '<filterAttribute>Python</filte... | tests/test_build_qthelp.py | import pytest
from sphinx.testing.util import etree_parse
@pytest.mark.sphinx('qthelp', testroot='basic')
def test_qthelp_basic(app, status, warning):
app.builder.build_all()
qhp = (app.outdir / 'Python.qhp').text()
assert '<customFilter name="Python ">' in qhp
assert '<filterAttribute>Python</filte... | 0.441432 | 0.585101 |
import re
from pathlib import Path
from subprocess import check_output
import click
import git
from typing import Optional
import neovim
LINE_RE = re.compile(r'^(?:\w+)\s+([0-9a-f]+)\s')
@click.command()
@click.argument('bufnr')
@click.argument('commitsha')
def main(bufnr, commitsha):
nvim = neovim.attach('std... | vim/after/ftplugin/gitrebase.py | import re
from pathlib import Path
from subprocess import check_output
import click
import git
from typing import Optional
import neovim
LINE_RE = re.compile(r'^(?:\w+)\s+([0-9a-f]+)\s')
@click.command()
@click.argument('bufnr')
@click.argument('commitsha')
def main(bufnr, commitsha):
nvim = neovim.attach('std... | 0.53048 | 0.084003 |
import argparse
import pathlib
import sqlite3
from ddht._utils import humanize_bytes
from ddht.app import BaseApplication
from ddht.boot_info import BootInfo
from ddht.v5_1.alexandria.abc import AdvertisementDatabaseAPI, ContentStorageAPI
from ddht.v5_1.alexandria.advertisement_db import AdvertisementDatabase
from ddh... | ddht/v5_1/alexandria/app.py | import argparse
import pathlib
import sqlite3
from ddht._utils import humanize_bytes
from ddht.app import BaseApplication
from ddht.boot_info import BootInfo
from ddht.v5_1.alexandria.abc import AdvertisementDatabaseAPI, ContentStorageAPI
from ddht.v5_1.alexandria.advertisement_db import AdvertisementDatabase
from ddh... | 0.316581 | 0.143158 |
from fastapi import APIRouter, Depends, WebSocket
from fastapi_websocket_pubsub import PubSubEndpoint
from opal_common.confi.confi import load_conf_if_none
from opal_common.config import opal_common_config
from opal_common.logger import logger
from opal_common.authentication.signer import JWTSigner
from opal_common.au... | opal_server/pubsub.py | from fastapi import APIRouter, Depends, WebSocket
from fastapi_websocket_pubsub import PubSubEndpoint
from opal_common.confi.confi import load_conf_if_none
from opal_common.config import opal_common_config
from opal_common.logger import logger
from opal_common.authentication.signer import JWTSigner
from opal_common.au... | 0.573559 | 0.085556 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tempfile
import numpy
from tensorflow.contrib.timeseries.python.timeseries import ar_model
from tensorflow.contrib.timeseries.python.timeseries import estimators
from tensorflow.contrib.timeseries.pyth... | tensorflow/contrib/timeseries/python/timeseries/estimators_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tempfile
import numpy
from tensorflow.contrib.timeseries.python.timeseries import ar_model
from tensorflow.contrib.timeseries.python.timeseries import estimators
from tensorflow.contrib.timeseries.pyth... | 0.800263 | 0.331525 |
from typing import Any, Generator, Union, Iterable, Tuple, List, Dict, Callable
def is_prime(n: int) -> bool:
"""Returns whether n is a prime number
Args:
n (int): The number to check
Returns:
bool: Whether n is a prime number
"""
if n <= 3:
return n > 1
if n % 2 == ... | BlockOL/__init__.py |
from typing import Any, Generator, Union, Iterable, Tuple, List, Dict, Callable
def is_prime(n: int) -> bool:
"""Returns whether n is a prime number
Args:
n (int): The number to check
Returns:
bool: Whether n is a prime number
"""
if n <= 3:
return n > 1
if n % 2 == ... | 0.932898 | 0.718681 |
# Commented out IPython magic to ensure Python compatibility.
import os, re, time, json
import PIL.Image, PIL.ImageFont, PIL.ImageDraw
import numpy as np
try:
# %tensorflow_version only exists in Colab.
# %tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
from tensorflow.keras.applications.res... | code/c3_w1_lab_2_transfer_learning_cifar_10.py | # Commented out IPython magic to ensure Python compatibility.
import os, re, time, json
import PIL.Image, PIL.ImageFont, PIL.ImageDraw
import numpy as np
try:
# %tensorflow_version only exists in Colab.
# %tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
from tensorflow.keras.applications.res... | 0.824356 | 0.620392 |
import itertools
import os
import sys
from contextlib import contextmanager
from multiprocessing.pool import ThreadPool
from twitter.common.collections.orderedset import OrderedSet
from twitter.pants.cache import create_artifact_cache
from twitter.pants.base.hash_utils import hash_file
from twitter.pants.base.build... | src/python/twitter/pants/tasks/__init__.py |
import itertools
import os
import sys
from contextlib import contextmanager
from multiprocessing.pool import ThreadPool
from twitter.common.collections.orderedset import OrderedSet
from twitter.pants.cache import create_artifact_cache
from twitter.pants.base.hash_utils import hash_file
from twitter.pants.base.build... | 0.555676 | 0.232811 |
import sys
sys.path.append('src/main/classes')
import administrador
import cafeicultor
import unittest
from unittest import TestCase
import pymongo
sys.path.append('src/main/entidades')
import mediador
import bancoDeDados
class AdministradorTest(TestCase):
@classmethod
def setUpClass(cls):
#Conf... | src/unittest/classes/testAdministrador.py | import sys
sys.path.append('src/main/classes')
import administrador
import cafeicultor
import unittest
from unittest import TestCase
import pymongo
sys.path.append('src/main/entidades')
import mediador
import bancoDeDados
class AdministradorTest(TestCase):
@classmethod
def setUpClass(cls):
#Conf... | 0.184804 | 0.185559 |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.opt import Opt
from parlai.utils.misc import Timer, round_sigfigs, set_namedtuple_defaults, nice_report
import parlai.utils.st... | tests/test_utils.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.opt import Opt
from parlai.utils.misc import Timer, round_sigfigs, set_namedtuple_defaults, nice_report
import parlai.utils.st... | 0.843154 | 0.549278 |
import functools
from typing import Callable, Any
from telegram import Update, Message, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery
from telegram.ext import (
Dispatcher,
ConversationHandler,
CommandHandler,
MessageHandler,
Filters,
CallbackQueryHandler,
CallbackContext,
)
fr... | app/handlers/admin.py | import functools
from typing import Callable, Any
from telegram import Update, Message, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery
from telegram.ext import (
Dispatcher,
ConversationHandler,
CommandHandler,
MessageHandler,
Filters,
CallbackQueryHandler,
CallbackContext,
)
fr... | 0.563018 | 0.05902 |
from __future__ import absolute_import
from sentry.models import Environment, OrganizationMember, OrganizationMemberTeam, Project, Release, ReleaseProject, ReleaseProjectEnvironment, Rule
from sentry.testutils import TestCase
class ProjectTest(TestCase):
def test_member_set_simple(self):
user = self.cre... | tests/sentry/models/test_project.py |
from __future__ import absolute_import
from sentry.models import Environment, OrganizationMember, OrganizationMemberTeam, Project, Release, ReleaseProject, ReleaseProjectEnvironment, Rule
from sentry.testutils import TestCase
class ProjectTest(TestCase):
def test_member_set_simple(self):
user = self.cre... | 0.746971 | 0.390418 |
import collections
import contextlib
import typing
from typing import Any, Union, Tuple, List
from typo.utils import type_name
class Codegen:
_v_cache_seq = {list: True, tuple: True, str: True, bytes: True,
bytearray: True, memoryview: True}
_v_cache_mut_seq = {list: True}
def __in... | typo/codegen.py |
import collections
import contextlib
import typing
from typing import Any, Union, Tuple, List
from typo.utils import type_name
class Codegen:
_v_cache_seq = {list: True, tuple: True, str: True, bytes: True,
bytearray: True, memoryview: True}
_v_cache_mut_seq = {list: True}
def __in... | 0.460774 | 0.129375 |
from __future__ import print_function, division
from sympy.matrices.dense import MutableDenseMatrix
from sympy.utilities.iterables import flatten, numbered_symbols
from sympy.core.symbol import Symbol, Dummy, symbols
from sympy import S
class NewMatrix(MutableDenseMatrix):
"""
Supports elements which can't ... | sympy/holonomic/linearsolver.py |
from __future__ import print_function, division
from sympy.matrices.dense import MutableDenseMatrix
from sympy.utilities.iterables import flatten, numbered_symbols
from sympy.core.symbol import Symbol, Dummy, symbols
from sympy import S
class NewMatrix(MutableDenseMatrix):
"""
Supports elements which can't ... | 0.83545 | 0.464598 |
import csv
import gc
import numpy as np
from pathlib import Path
from torch.utils.data import Dataset
from pytorch_pretrained_bert.tokenization import BertTokenizer
class InputExample(object):
def __init__(self, guid, text_a, text_b=None, label=None):
self.guid = guid
self.text_a = tex... | Code/HypoBertClas/pybert/io/dataset.py | import csv
import gc
import numpy as np
from pathlib import Path
from torch.utils.data import Dataset
from pytorch_pretrained_bert.tokenization import BertTokenizer
class InputExample(object):
def __init__(self, guid, text_a, text_b=None, label=None):
self.guid = guid
self.text_a = tex... | 0.550849 | 0.222742 |
import media
import fresh_tomatoes
# Movies to be shown in the page
ironman = media.Movie("Ironman",
"After being held captive in an Afghan cave, billionaire engineer <NAME> creates a unique weaponized suit of armor to fight evil.", # noqa
"https://images-na.ssl-image... | source/trailer_website.py | import media
import fresh_tomatoes
# Movies to be shown in the page
ironman = media.Movie("Ironman",
"After being held captive in an Afghan cave, billionaire engineer <NAME> creates a unique weaponized suit of armor to fight evil.", # noqa
"https://images-na.ssl-image... | 0.276691 | 0.330147 |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: oci_healthchecks_http_probe_result_facts
short_description: Fetches details about o... | plugins/modules/oci_healthchecks_http_probe_result_facts.py |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: oci_healthchecks_http_probe_result_facts
short_description: Fetches details about o... | 0.92763 | 0.358887 |
import os
import argparse
import numpy as np
from comet_ml import Experiment
import keras.backend as K
from keras.callbacks import ModelCheckpoint, TerminateOnNaN
from keras.optimizers import Adam
from model import create_model
from losses.perceptual_loss import perceptual_loss
from dataset import TrainDatasetSequence,... | src/train.py | import os
import argparse
import numpy as np
from comet_ml import Experiment
import keras.backend as K
from keras.callbacks import ModelCheckpoint, TerminateOnNaN
from keras.optimizers import Adam
from model import create_model
from losses.perceptual_loss import perceptual_loss
from dataset import TrainDatasetSequence,... | 0.803367 | 0.221256 |
import time
import xpedite.util
import logging
from xpedite.report.env import EnvReportBuilder
from xpedite.report.reportbuilder import ReportBuilder
LOGGER = logging.getLogger(__name__)
class Report(object):
"""Class to store detailed report for a profiling session"""
class Markup(object):
... | scripts/lib/xpedite/report/__init__.py | import time
import xpedite.util
import logging
from xpedite.report.env import EnvReportBuilder
from xpedite.report.reportbuilder import ReportBuilder
LOGGER = logging.getLogger(__name__)
class Report(object):
"""Class to store detailed report for a profiling session"""
class Markup(object):
... | 0.867247 | 0.203906 |
from uuid import uuid4
import requests
from contextlib import ExitStack
from gzip import GzipFile
from io import TextIOWrapper
import json
import flux
import pytest
from .utils import raises_not_found
def test_add_error(error_container, error_data, webapp):
timestamp = flux.current_timeline.time()
error_co... | tests/test_add_errors.py | from uuid import uuid4
import requests
from contextlib import ExitStack
from gzip import GzipFile
from io import TextIOWrapper
import json
import flux
import pytest
from .utils import raises_not_found
def test_add_error(error_container, error_data, webapp):
timestamp = flux.current_timeline.time()
error_co... | 0.304042 | 0.249893 |
from math import copysign
import pxng
from pxng.colors import *
from pxng.keys import *
def update(window: pxng.Window):
handle_input(window)
window.draw_grid(tint=DARK_GREY)
window.draw_text(10, 10, 'Text Rendering', tint=LIGHT_BLUE)
# Use the bitmap font as something interesting to scroll through... | examples/text_rendering.py | from math import copysign
import pxng
from pxng.colors import *
from pxng.keys import *
def update(window: pxng.Window):
handle_input(window)
window.draw_grid(tint=DARK_GREY)
window.draw_text(10, 10, 'Text Rendering', tint=LIGHT_BLUE)
# Use the bitmap font as something interesting to scroll through... | 0.617282 | 0.186706 |
# Выполнение задания Ultra Lite:
#1. Создадим два родительских класса: один класс - это 2D-классические геометрические фигуры, из которого затем,
# применив принцип полиморфизма, создадим два других класса - расчет периметра и расчет площади,
# второй родительский класс - это любое натуральное число, для которого ос... | Ultra_lite_parental_class.py |
# Выполнение задания Ultra Lite:
#1. Создадим два родительских класса: один класс - это 2D-классические геометрические фигуры, из которого затем,
# применив принцип полиморфизма, создадим два других класса - расчет периметра и расчет площади,
# второй родительский класс - это любое натуральное число, для которого ос... | 0.193948 | 0.803174 |
import sys
import matplotlib.pyplot as plt
import os.path
outputFileBaseName = 'scatter'
#plot spec file column names
colNames = ['Gene name', 'Plot or not?', 'Color', 'Marker', 'Size', 'Alpha', 'Layer', 'Label or not?',
'Label font size','Legend group'] # note gene name needs to be first entry in this ... | plotScatter.py |
import sys
import matplotlib.pyplot as plt
import os.path
outputFileBaseName = 'scatter'
#plot spec file column names
colNames = ['Gene name', 'Plot or not?', 'Color', 'Marker', 'Size', 'Alpha', 'Layer', 'Label or not?',
'Label font size','Legend group'] # note gene name needs to be first entry in this ... | 0.379263 | 0.445891 |
from modules.file_utils import *
def get_top_level_report(coin_overall: dict, coin_details: dict, coin_report: dict) -> None:
coin_report["name"] = coin_overall["name"]
coin_report["symbol"] = coin_overall["symbol"]
coin_report["current_price"] = coin_overall["current_price"]
coin_report["marke... | report.py | from modules.file_utils import *
def get_top_level_report(coin_overall: dict, coin_details: dict, coin_report: dict) -> None:
coin_report["name"] = coin_overall["name"]
coin_report["symbol"] = coin_overall["symbol"]
coin_report["current_price"] = coin_overall["current_price"]
coin_report["marke... | 0.452778 | 0.110519 |
import datetime
import re
from cifparser.errors import ConversionError
def str_to_stripped(s):
return s.strip()
def str_to_flattened(s):
return ' '.join(s.split())
def str_to_int(s):
try:
return int(s)
except:
raise ConversionError("failed to convert {0} to float".format(s))
def st... | cifparser/converters.py |
import datetime
import re
from cifparser.errors import ConversionError
def str_to_stripped(s):
return s.strip()
def str_to_flattened(s):
return ' '.join(s.split())
def str_to_int(s):
try:
return int(s)
except:
raise ConversionError("failed to convert {0} to float".format(s))
def st... | 0.345547 | 0.215289 |
from __future__ import unicode_literals
from pynodebb.api import Resource
class User(Resource):
def create(self, username, **kwargs):
"""Creates a new NodeBB user.
Args:
username (str): A unique string used to identify the new user.
If the username already exists, Nod... | pynodebb/api/users.py | from __future__ import unicode_literals
from pynodebb.api import Resource
class User(Resource):
def create(self, username, **kwargs):
"""Creates a new NodeBB user.
Args:
username (str): A unique string used to identify the new user.
If the username already exists, Nod... | 0.886592 | 0.273047 |
import re
import logging
import urllib.parse
import requests
from ox_herd.core.plugins import base
from ox_herd.core import ox_tasks
class SimpleTaskResult:
"""Class to hold task result.
Clairfying the expected return values for a task makes it easier to display
and inspect task results with other tools.
"... | ox_herd/ui/flask_web_ui/ox_herd/web_tasks.py | import re
import logging
import urllib.parse
import requests
from ox_herd.core.plugins import base
from ox_herd.core import ox_tasks
class SimpleTaskResult:
"""Class to hold task result.
Clairfying the expected return values for a task makes it easier to display
and inspect task results with other tools.
"... | 0.733833 | 0.171789 |
from collections import OrderedDict
from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
from ydk.filters import YFilter
from ydk.errors import YError, YModelError
from ydk.errors.error_handler import handle_type_error as _handle_type_error
c... | cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_nat_oper.py | from collections import OrderedDict
from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
from ydk.filters import YFilter
from ydk.errors import YError, YModelError
from ydk.errors.error_handler import handle_type_error as _handle_type_error
c... | 0.689306 | 0.12075 |
__version__ = "v1.0"
__copyright__ = "Copyright 2022"
__license__ = "MIT"
__author__ = "<NAME>"
class single(object):
def __init__(self, ):
pass
def trim(action):
def tube(deal):
def wrapper(self, **kwargs):
if action == 'leave_one_out':
res = ... | resimpy/util/sequence/symbol/Single.py | __version__ = "v1.0"
__copyright__ = "Copyright 2022"
__license__ = "MIT"
__author__ = "<NAME>"
class single(object):
def __init__(self, ):
pass
def trim(action):
def tube(deal):
def wrapper(self, **kwargs):
if action == 'leave_one_out':
res = ... | 0.378804 | 0.118589 |
class JSONBrute:
def info(self, message):
print(f"\033[94m[*]\033[0m {message}")
def success(self, message):
print(f"\033[92m[+]\033[0m {message}")
def warning(self, message):
print(f"\033[93m[!]\033[0m {message}")
def error(self, message):
print(f"\033[91m[-]\033[0m {... | src/jsonbrute.py | class JSONBrute:
def info(self, message):
print(f"\033[94m[*]\033[0m {message}")
def success(self, message):
print(f"\033[92m[+]\033[0m {message}")
def warning(self, message):
print(f"\033[93m[!]\033[0m {message}")
def error(self, message):
print(f"\033[91m[-]\033[0m {... | 0.478041 | 0.240697 |
import xml.etree.ElementTree as ET
from programy.parser.template.nodes.base import TemplateNode
from programy.parser.template.nodes.set import TemplateSetNode
from programy.parser.exceptions import ParserException
from programytest.parser.template.graph_tests.graph_test_client import TemplateGraphTestClient
class T... | test/programytest/parser/template/graph_tests/test_set.py | import xml.etree.ElementTree as ET
from programy.parser.template.nodes.base import TemplateNode
from programy.parser.template.nodes.set import TemplateSetNode
from programy.parser.exceptions import ParserException
from programytest.parser.template.graph_tests.graph_test_client import TemplateGraphTestClient
class T... | 0.464173 | 0.419291 |
from typing import Any, List, Optional
def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str:
T = []
Li = []
Lb = []
C = []
B = []
x = 0
rows_length = []
for n in rows[0]:
rows_items = []
p = 0
for items in row... | qualifier/qualifier.py | from typing import Any, List, Optional
def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str:
T = []
Li = []
Lb = []
C = []
B = []
x = 0
rows_length = []
for n in rows[0]:
rows_items = []
p = 0
for items in row... | 0.292797 | 0.428532 |
from nmigen import *
from nmigen.hdl.rec import *
from .crc import CRC
from .defs import *
from .endpoint import *
from .mux import *
__all__ = ["Device"]
class Device(Elaboratable):
"""USB 2.0 device controller.
An USB 2.0 device controller, managing transactions between its endpoints and the host.
... | lambdausb/usb/device.py | from nmigen import *
from nmigen.hdl.rec import *
from .crc import CRC
from .defs import *
from .endpoint import *
from .mux import *
__all__ = ["Device"]
class Device(Elaboratable):
"""USB 2.0 device controller.
An USB 2.0 device controller, managing transactions between its endpoints and the host.
... | 0.795261 | 0.28508 |
import io
import logging
import mistletoe
import pygments
import pygments.formatters.html
import pygments.lexers
import pygments.util
from ._misc import parameters
_logger = logging.getLogger("holocron")
def _pygmentize(code, language):
try:
formatter = _pygmentize.formatter
except AttributeError:... | src/holocron/_processors/commonmark.py |
import io
import logging
import mistletoe
import pygments
import pygments.formatters.html
import pygments.lexers
import pygments.util
from ._misc import parameters
_logger = logging.getLogger("holocron")
def _pygmentize(code, language):
try:
formatter = _pygmentize.formatter
except AttributeError:... | 0.405331 | 0.151247 |
import sys
import os
from models import *
class StoreApi(object):
def __init__(self, apiClient):
self.apiClient = apiClient
def getInventory(self, **kwargs):
"""Returns pet inventories by status
Args:
Returns: map(String, int)
"""
... | samples/client/petstore/python/client/StoreApi.py | import sys
import os
from models import *
class StoreApi(object):
def __init__(self, apiClient):
self.apiClient = apiClient
def getInventory(self, **kwargs):
"""Returns pet inventories by status
Args:
Returns: map(String, int)
"""
... | 0.503906 | 0.095814 |
import pprint
import re # noqa: F401
import six
from nucleus_api.configuration import Configuration
class Order(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attr... | atom/nucleus/python/nucleus_api/models/order.py | import pprint
import re # noqa: F401
import six
from nucleus_api.configuration import Configuration
class Order(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attr... | 0.603348 | 0.088544 |
# Synthetic data
# Precision measure: MSE
# Run: python3 test.py param
# where
# - param = 0 runs test cases with fixed n and varying eps
# - param = 1 runs test cases with fixed eps and varying n
# This program does 50-fold cross-validation.
import sys
import os
# Create a new Theano compile directory on local nod... | python/synthdata/test_rlr.py |
# Synthetic data
# Precision measure: MSE
# Run: python3 test.py param
# where
# - param = 0 runs test cases with fixed n and varying eps
# - param = 1 runs test cases with fixed eps and varying n
# This program does 50-fold cross-validation.
import sys
import os
# Create a new Theano compile directory on local nod... | 0.278747 | 0.369941 |
import json
import os
import boto3
from botocore.exceptions import ClientError
import math
import time
from MediaReplayEnginePluginHelper import OutputHelper
from MediaReplayEnginePluginHelper import PluginHelper
from MediaReplayEnginePluginHelper import Status
from MediaReplayEnginePluginHelper import DataPlane
com... | source/mre-plugin-samples/Plugins/DetectSentiment/DetectSentiment.py |
import json
import os
import boto3
from botocore.exceptions import ClientError
import math
import time
from MediaReplayEnginePluginHelper import OutputHelper
from MediaReplayEnginePluginHelper import PluginHelper
from MediaReplayEnginePluginHelper import Status
from MediaReplayEnginePluginHelper import DataPlane
com... | 0.397471 | 0.084229 |
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from fastapi import Depends
from starlette.requests import Request
from starlette.responses import JSONResponse, RedirectResponse
from starlette.routing import Mount, Route
from starlette.staticfiles import StaticFiles
from fastapi_aad_auth... | src/fastapi_aad_auth/ui/__init__.py | from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from fastapi import Depends
from starlette.requests import Request
from starlette.responses import JSONResponse, RedirectResponse
from starlette.routing import Mount, Route
from starlette.staticfiles import StaticFiles
from fastapi_aad_auth... | 0.855036 | 0.09628 |
import asyncio
import sys
from pathlib import Path
from typing import Any, AsyncIterator, Callable
import pytest
from yarl import URL
from neuro_sdk import Client
from neuro_sdk.url_utils import (
_extract_path,
normalize_local_path_uri,
normalize_storage_path_uri,
uri_from_cli,
)
@pytest.fixture
as... | neuro-sdk/tests/test_url_utils.py | import asyncio
import sys
from pathlib import Path
from typing import Any, AsyncIterator, Callable
import pytest
from yarl import URL
from neuro_sdk import Client
from neuro_sdk.url_utils import (
_extract_path,
normalize_local_path_uri,
normalize_storage_path_uri,
uri_from_cli,
)
@pytest.fixture
as... | 0.428712 | 0.450601 |
from ducktape.utils.util import wait_until
from kafkatest.services.monitor.jmx import JmxMixin
from kafkatest.services.performance import PerformanceService
from kafkatest.services.security.security_config import SecurityConfig
from kafkatest.services.kafka.directory import kafka_dir, KAFKA_TRUNK
from kafkatest.servi... | tests/kafkatest/services/performance/producer_performance.py |
from ducktape.utils.util import wait_until
from kafkatest.services.monitor.jmx import JmxMixin
from kafkatest.services.performance import PerformanceService
from kafkatest.services.security.security_config import SecurityConfig
from kafkatest.services.kafka.directory import kafka_dir, KAFKA_TRUNK
from kafkatest.servi... | 0.526343 | 0.07921 |
import pytest
import click
from click._bashcomplete import get_choices
def choices_without_help(cli, args, incomplete):
completions = get_choices(cli, "dummy", args, incomplete)
return [c[0] for c in completions]
def choices_with_help(cli, args, incomplete):
return list(get_choices(cli, "dummy", args, ... | tests/test_bashcomplete.py | import pytest
import click
from click._bashcomplete import get_choices
def choices_without_help(cli, args, incomplete):
completions = get_choices(cli, "dummy", args, incomplete)
return [c[0] for c in completions]
def choices_with_help(cli, args, incomplete):
return list(get_choices(cli, "dummy", args, ... | 0.40592 | 0.283162 |
import warnings
warnings.filterwarnings("ignore")
from pcg_gazebo.generators import WorldGenerator
from pcg_gazebo.visualization import plot_workspace, plot_occupancy_grid
from pcg_gazebo.generators.creators import box_factory
from pcg_gazebo.utils import generate_random_string
world_gen = WorldGenerator()
world_ge... | examples/gen_grid_map.py | import warnings
warnings.filterwarnings("ignore")
from pcg_gazebo.generators import WorldGenerator
from pcg_gazebo.visualization import plot_workspace, plot_occupancy_grid
from pcg_gazebo.generators.creators import box_factory
from pcg_gazebo.utils import generate_random_string
world_gen = WorldGenerator()
world_ge... | 0.599837 | 0.312265 |
import logging
import re
import traceback
import uuid
from enum import IntEnum, unique
from ._journal import send, syslog_priorities
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
_priorities = syslog_priorities()
__all__ = "write", "send", "Priority", "Journ... | cysystemd/journal.py | import logging
import re
import traceback
import uuid
from enum import IntEnum, unique
from ._journal import send, syslog_priorities
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
_priorities = syslog_priorities()
__all__ = "write", "send", "Priority", "Journ... | 0.34798 | 0.07363 |
from homeassistant.components.diagnostics import REDACTED
from homeassistant.components.guardian import (
DATA_PAIRED_SENSOR_MANAGER,
DOMAIN,
PairedSensorManager,
)
from tests.components.diagnostics import get_diagnostics_for_config_entry
async def test_entry_diagnostics(hass, config_entry, hass_client, ... | tests/components/guardian/test_diagnostics.py | from homeassistant.components.diagnostics import REDACTED
from homeassistant.components.guardian import (
DATA_PAIRED_SENSOR_MANAGER,
DOMAIN,
PairedSensorManager,
)
from tests.components.diagnostics import get_diagnostics_for_config_entry
async def test_entry_diagnostics(hass, config_entry, hass_client, ... | 0.699049 | 0.261661 |
import math
import argparse
import numpy as np
import cv2
import tensorflow as tf
from gluoncv.data import ImageNet1kAttr
from tf2cv.model_provider import get_model as tf2cv_get_model
def parse_args():
"""
Create python script parameters.
Returns
-------
ArgumentParser
Resulted args.
... | examples/demo_tf2.py | import math
import argparse
import numpy as np
import cv2
import tensorflow as tf
from gluoncv.data import ImageNet1kAttr
from tf2cv.model_provider import get_model as tf2cv_get_model
def parse_args():
"""
Create python script parameters.
Returns
-------
ArgumentParser
Resulted args.
... | 0.843477 | 0.268896 |
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views.generic import View
from django.conf import settings
from .models import Address
from .fusiontable import Fusiontable
import json
class HomeView(View):
"""
displays Home Page, connects Google.maps.api and l... | maptapp/views.py | from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views.generic import View
from django.conf import settings
from .models import Address
from .fusiontable import Fusiontable
import json
class HomeView(View):
"""
displays Home Page, connects Google.maps.api and l... | 0.552057 | 0.069069 |
r"""Order utilities for 0x applications.
Setup
-----
Install the package with pip::
pip install 0x-order-utils
Some methods require the caller to pass in a `Web3.BaseProvider`:code: object.
For local testing one may construct such a provider pointing at an instance of
`ganache-cli <https://www.npmjs.com/package... | python-packages/order_utils/src/zero_ex/order_utils/__init__.py | r"""Order utilities for 0x applications.
Setup
-----
Install the package with pip::
pip install 0x-order-utils
Some methods require the caller to pass in a `Web3.BaseProvider`:code: object.
For local testing one may construct such a provider pointing at an instance of
`ganache-cli <https://www.npmjs.com/package... | 0.901833 | 0.488039 |
__all__ = ['get_dataset_metainfo', 'get_train_data_source', 'get_val_data_source', 'get_test_data_source']
import tensorflow as tf
from .datasets.imagenet1k_cls_dataset import ImageNet1KMetaInfo
from .datasets.cub200_2011_cls_dataset import CUB200MetaInfo
from .datasets.cifar10_cls_dataset import CIFAR10MetaInfo
from ... | tensorflow2/dataset_utils.py | __all__ = ['get_dataset_metainfo', 'get_train_data_source', 'get_val_data_source', 'get_test_data_source']
import tensorflow as tf
from .datasets.imagenet1k_cls_dataset import ImageNet1KMetaInfo
from .datasets.cub200_2011_cls_dataset import CUB200MetaInfo
from .datasets.cifar10_cls_dataset import CIFAR10MetaInfo
from ... | 0.902069 | 0.284154 |
r"""
This submodule provides utility constants and functions for working with star data in GIANT.
Most of these utilities are focused on conversions of either units or of representations (ie a bearing to a unit
vector) with the exception of applying proper motion and computing the distance between 2 bearings. For m... | giant/catalogues/utilities.py |
r"""
This submodule provides utility constants and functions for working with star data in GIANT.
Most of these utilities are focused on conversions of either units or of representations (ie a bearing to a unit
vector) with the exception of applying proper motion and computing the distance between 2 bearings. For m... | 0.947113 | 0.860955 |
from typing import List, Tuple, Union
import cv2
import numpy as np
from scipy import optimize
from color_tracker.utils.tracker_object import TrackedObject
def crop_out_polygon_convex(image: np.ndarray, point_array: np.ndarray) -> np.ndarray:
"""
Crops out a convex polygon given from a list of points from a... | color_tracker/utils/helpers.py | from typing import List, Tuple, Union
import cv2
import numpy as np
from scipy import optimize
from color_tracker.utils.tracker_object import TrackedObject
def crop_out_polygon_convex(image: np.ndarray, point_array: np.ndarray) -> np.ndarray:
"""
Crops out a convex polygon given from a list of points from a... | 0.906229 | 0.637172 |
from flask import Flask, render_template, request, redirect,send_file
from werkzeug.utils import secure_filename
from functions import split,transform
import io
import os
import pdfrw
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm,mm
# 12 questions adjustments
diff = -0.45*mm#(74.7/2-9.37)*mm
d... | app.py | from flask import Flask, render_template, request, redirect,send_file
from werkzeug.utils import secure_filename
from functions import split,transform
import io
import os
import pdfrw
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm,mm
# 12 questions adjustments
diff = -0.45*mm#(74.7/2-9.37)*mm
d... | 0.179531 | 0.12234 |
from distutils.version import LooseVersion
import os
import itertools
from subprocess import CalledProcessError
from bcbio import broad
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_transaction
from bcbio.provenance.programs import get_version
from bcbio.variation.realign import h... | bcbio/variation/mutect.py |
from distutils.version import LooseVersion
import os
import itertools
from subprocess import CalledProcessError
from bcbio import broad
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_transaction
from bcbio.provenance.programs import get_version
from bcbio.variation.realign import h... | 0.362631 | 0.21389 |
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_robot_model(pkg_description):
urdf_dir = os.p... | kohm_gazebo/launch/include/state_publishers/state_publishers.launch.py | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_robot_model(pkg_description):
urdf_dir = os.p... | 0.549641 | 0.134804 |
import logging
import numbers
from typing import Callable, Union
import torch
from ignite.engine import Engine
from ignite.utils import apply_to_type
__all__ = ["TerminateOnNan"]
class TerminateOnNan:
"""TerminateOnNan handler can be used to stop the training if the `process_function`'s output
contains a N... | ignite/handlers/terminate_on_nan.py | import logging
import numbers
from typing import Callable, Union
import torch
from ignite.engine import Engine
from ignite.utils import apply_to_type
__all__ = ["TerminateOnNan"]
class TerminateOnNan:
"""TerminateOnNan handler can be used to stop the training if the `process_function`'s output
contains a N... | 0.883513 | 0.502197 |
import psycopg2
from openpyxl import load_workbook
import credentials
from os import listdir
from os.path import isfile, join
conn = psycopg2.connect(host="localhost",database="postgres", user=credentials.username, password=credentials.password, port=credentials.port)
conn.autocommit = True
cursor = conn.cursor()
# ... | algDev/db/primer.py | import psycopg2
from openpyxl import load_workbook
import credentials
from os import listdir
from os.path import isfile, join
conn = psycopg2.connect(host="localhost",database="postgres", user=credentials.username, password=credentials.password, port=credentials.port)
conn.autocommit = True
cursor = conn.cursor()
# ... | 0.091855 | 0.142291 |
class MarketReservationError(StandardError):
"""Base class for exceptions in this module."""
pass
class ReservationManager(object):
def __init__(self):
self._buy_reservations = {}
self._sell_reservations = {}
def make_reservation(self, participant):
if (participant.is_buyer()... | services/core/MarketServiceAgent/market_service/reservation_manager.py |
class MarketReservationError(StandardError):
"""Base class for exceptions in this module."""
pass
class ReservationManager(object):
def __init__(self):
self._buy_reservations = {}
self._sell_reservations = {}
def make_reservation(self, participant):
if (participant.is_buyer()... | 0.659844 | 0.101857 |
import matplotlib.pyplot as plt
from graphviz import Digraph
from matplotlib.collections import PolyCollection
def draw_DAG(dag, name=None, view=False):
"""
Draws a DAG that represents the repeater protocol to be executed
:param dag: type DAGTask
The DAGTask representing the repeater protocol to e... | code/jobscheduling/visualize.py | import matplotlib.pyplot as plt
from graphviz import Digraph
from matplotlib.collections import PolyCollection
def draw_DAG(dag, name=None, view=False):
"""
Draws a DAG that represents the repeater protocol to be executed
:param dag: type DAGTask
The DAGTask representing the repeater protocol to e... | 0.726717 | 0.592519 |
from crowdsourcing.serializers.task import *
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import detail_route, list_route
from django.shortcuts import get_object_or_404
from crowdsourcing.permissions.project import IsProjectOwnerOrCollaborator
f... | crowdsourcing/viewsets/task.py | from crowdsourcing.serializers.task import *
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.decorators import detail_route, list_route
from django.shortcuts import get_object_or_404
from crowdsourcing.permissions.project import IsProjectOwnerOrCollaborator
f... | 0.446495 | 0.059839 |
import copy
import logging
from django.conf import settings
from django.views.debug import ExceptionReporter
from behind import jarvis
class SlackExceptionHandler(logging.Handler):
"""
Code from djang-slack app
An exception log handler that sends log entries to a Slack channel.
"""
def __init__(... | behind/behind/log_handlers.py | import copy
import logging
from django.conf import settings
from django.views.debug import ExceptionReporter
from behind import jarvis
class SlackExceptionHandler(logging.Handler):
"""
Code from djang-slack app
An exception log handler that sends log entries to a Slack channel.
"""
def __init__(... | 0.482917 | 0.113138 |
from Lights.models import *
from django.http import HttpResponse, HttpResponseNotFound
from SharedFunctions.deviceControl import *
class LightApi():
def webRequest(self, request):
command = request.GET.get('command', '')
if command == "getStatus":
pageContent = "["
isNotInFirstLoop = False
for alight in ... | Api/api.py | from Lights.models import *
from django.http import HttpResponse, HttpResponseNotFound
from SharedFunctions.deviceControl import *
class LightApi():
def webRequest(self, request):
command = request.GET.get('command', '')
if command == "getStatus":
pageContent = "["
isNotInFirstLoop = False
for alight in ... | 0.188175 | 0.060585 |
from nengo.base import NengoObject, ObjView
from nengo.dists import Uniform, UniformHypersphere
from nengo.neurons import LIF, NeuronTypeParam, Direct
from nengo.params import (
Default, DistributionParam, IntParam, NumberParam,
StochasticProcessParam, StringParam)
import decimal as dc
class Ensemble(NengoObje... | nengo/ensemble.py | from nengo.base import NengoObject, ObjView
from nengo.dists import Uniform, UniformHypersphere
from nengo.neurons import LIF, NeuronTypeParam, Direct
from nengo.params import (
Default, DistributionParam, IntParam, NumberParam,
StochasticProcessParam, StringParam)
import decimal as dc
class Ensemble(NengoObje... | 0.912952 | 0.685117 |
from plotnine import *
import pandas as pd
import numpy as np
from mizani.palettes import hue_pal
df = pd.read_csv('rq4_f1.csv')
palette = hue_pal(0.01, 0.6, 0.65, color_space='hls')
pal = palette(4)
old_palette = [pal[1], pal[3], pal[0]]
def fix(model):
d = {
"Transfer-on": "1",
"Transfer-pc": "2"... | analysis/model_transfer/plot_rq4.py | from plotnine import *
import pandas as pd
import numpy as np
from mizani.palettes import hue_pal
df = pd.read_csv('rq4_f1.csv')
palette = hue_pal(0.01, 0.6, 0.65, color_space='hls')
pal = palette(4)
old_palette = [pal[1], pal[3], pal[0]]
def fix(model):
d = {
"Transfer-on": "1",
"Transfer-pc": "2"... | 0.74055 | 0.265184 |
from collections import defaultdict
from collections import OrderedDict
import datetime
import os
import sys
_REMOTE_API_DIR = os.path.join(os.path.dirname(__file__), os.path.pardir)
sys.path.insert(1, _REMOTE_API_DIR)
import remote_api
from model import analysis_status
from model.wf_swarming_task import WfSwarmingT... | appengine/findit/util_scripts/remote_queries/swarming_task_data_query.py | from collections import defaultdict
from collections import OrderedDict
import datetime
import os
import sys
_REMOTE_API_DIR = os.path.join(os.path.dirname(__file__), os.path.pardir)
sys.path.insert(1, _REMOTE_API_DIR)
import remote_api
from model import analysis_status
from model.wf_swarming_task import WfSwarmingT... | 0.608361 | 0.195786 |
import logging
import json
import os
import requests
from itertools import chain
from typing import Iterable
LOG = logging.getLogger(__name__)
DEFAULT_LABEL_API = os.environ.get("LABEL_API") \
or "https://backoffice.seattleflu.org/labels"
class LabelLayout:
"""
Layouts, based on the kind o... | lib/id3c/labelmaker.py | import logging
import json
import os
import requests
from itertools import chain
from typing import Iterable
LOG = logging.getLogger(__name__)
DEFAULT_LABEL_API = os.environ.get("LABEL_API") \
or "https://backoffice.seattleflu.org/labels"
class LabelLayout:
"""
Layouts, based on the kind o... | 0.81457 | 0.330579 |
import pytest
import pandas as pd
from pyranges import PyRanges
def pytest_configure(config):
config.addinivalue_line(
"markers", "bedtools: tests rely on",
)
config.addinivalue_line(
"markers", "explore: functionality not ready for prime-time"
)
@pytest.fixture
def names():
ret... | tests/conftest.py | import pytest
import pandas as pd
from pyranges import PyRanges
def pytest_configure(config):
config.addinivalue_line(
"markers", "bedtools: tests rely on",
)
config.addinivalue_line(
"markers", "explore: functionality not ready for prime-time"
)
@pytest.fixture
def names():
ret... | 0.547706 | 0.374133 |
import asyncio
import asynctest
import asynctest.mock as amock
from opsdroid import events
from opsdroid.core import OpsDroid
from opsdroid.connector import Connector
from opsdroid.cli.start import configure_lang
class TestEventCreator(asynctest.TestCase):
"""Test the opsdroid event creation class"""
async... | tests/test_events.py | import asyncio
import asynctest
import asynctest.mock as amock
from opsdroid import events
from opsdroid.core import OpsDroid
from opsdroid.connector import Connector
from opsdroid.cli.start import configure_lang
class TestEventCreator(asynctest.TestCase):
"""Test the opsdroid event creation class"""
async... | 0.657098 | 0.356195 |
from os import getcwd
import pickle
from PyQt5 import QtWidgets as QW
from sigman import file_manager as fm
from sigman import analyzer, EmptyPointsError
import sigman as sm
import importlib
import QtSigman
from QtSigman import DataActionWidgets, DefaultColors
from QtSigman.DataActionWidgets import DataActionStatus
f... | QtSigman/DataActions.py | from os import getcwd
import pickle
from PyQt5 import QtWidgets as QW
from sigman import file_manager as fm
from sigman import analyzer, EmptyPointsError
import sigman as sm
import importlib
import QtSigman
from QtSigman import DataActionWidgets, DefaultColors
from QtSigman.DataActionWidgets import DataActionStatus
f... | 0.236164 | 0.132206 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
__all__ = [
'ListAgentPoolQueueStatusResult',
'AwaitableListAgentPoolQueueStatusResult',
'list_agent_pool_queue_status',
]
@pulumi.output_type
class ListAgentP... | sdk/python/pulumi_azure_nextgen/containerregistry/list_agent_pool_queue_status.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
__all__ = [
'ListAgentPoolQueueStatusResult',
'AwaitableListAgentPoolQueueStatusResult',
'list_agent_pool_queue_status',
]
@pulumi.output_type
class ListAgentP... | 0.790166 | 0.060891 |
import sys
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_service import service
from oslo_utils import timeutils
from sqlalchemy.orm import exc as orm_exc
from tacker.common import topics
from tacker import context as t_context
from tacker.db.common_services import c... | tacker/conductor/conductor_server.py |
import sys
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging
from oslo_service import service
from oslo_utils import timeutils
from sqlalchemy.orm import exc as orm_exc
from tacker.common import topics
from tacker import context as t_context
from tacker.db.common_services import c... | 0.179567 | 0.047958 |
"""Tests the GRR hunt collectors."""
import unittest
import zipfile
import mock
from grr_response_proto import flows_pb2
from dftimewolf import config
from dftimewolf.lib import state
from dftimewolf.lib import errors
from dftimewolf.lib.collectors import grr_hunt
from tests.lib.collectors.test_data import mock_grr_... | tests/lib/collectors/grr_hunt.py | """Tests the GRR hunt collectors."""
import unittest
import zipfile
import mock
from grr_response_proto import flows_pb2
from dftimewolf import config
from dftimewolf.lib import state
from dftimewolf.lib import errors
from dftimewolf.lib.collectors import grr_hunt
from tests.lib.collectors.test_data import mock_grr_... | 0.661376 | 0.221814 |
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
"""
Assume:
substring
no empty
case insenstively
Intution:
1) permute all concatenations
2) lookup concats in the s
Approach:
... | practice_fall_2021/substring_with_concatentation_of_all_words.py | class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
"""
Assume:
substring
no empty
case insenstively
Intution:
1) permute all concatenations
2) lookup concats in the s
Approach:
... | 0.692018 | 0.443179 |
import random
import torch
import argparse
import hparams_registry
import datasets
import imageio
import torchvision.utils as vutils
import os
from tqdm import tqdm
def __write_images(image_outputs, display_image_num, file_name, run):
image_outputs = [images.expand(-1, 3, -1, -1) for images in image_outputs] # exp... | scripts/save_images.py | import random
import torch
import argparse
import hparams_registry
import datasets
import imageio
import torchvision.utils as vutils
import os
from tqdm import tqdm
def __write_images(image_outputs, display_image_num, file_name, run):
image_outputs = [images.expand(-1, 3, -1, -1) for images in image_outputs] # exp... | 0.408985 | 0.297553 |
import datetime
from django.utils.timezone import make_aware
from freezegun import freeze_time
from rest_framework import status
from care.facility.api.serializers.patient_sample import PatientSampleSerializer
from care.facility.models import PatientSample
from care.utils.tests.test_base import TestBase
from config.t... | care/facility/tests/test_patient_sample_api.py | import datetime
from django.utils.timezone import make_aware
from freezegun import freeze_time
from rest_framework import status
from care.facility.api.serializers.patient_sample import PatientSampleSerializer
from care.facility.models import PatientSample
from care.utils.tests.test_base import TestBase
from config.t... | 0.576423 | 0.23541 |
import sys
import logging
from webgme_bindings import PluginBase
# Setup a logger
logger = logging.getLogger('PythonBindings')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout) # By default it logs to stderr..
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s... | src/plugins/PythonBindings/PythonBindings/__init__.py | import sys
import logging
from webgme_bindings import PluginBase
# Setup a logger
logger = logging.getLogger('PythonBindings')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout) # By default it logs to stderr..
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s... | 0.274449 | 0.061791 |
import numpy as np
import scipy.stats
from ..base_parameters import (
ParamHelper, PriorHelper, PrecondHelper,
get_value_func, get_hyperparam_func, get_dim_func,
set_value_func, set_hyperparam_func,
)
from .._utils import (
normal_logpdf,
matrix_normal_logpdf,
pos... | sgmcmc_ssm/variables/matrices.py | import numpy as np
import scipy.stats
from ..base_parameters import (
ParamHelper, PriorHelper, PrecondHelper,
get_value_func, get_hyperparam_func, get_dim_func,
set_value_func, set_hyperparam_func,
)
from .._utils import (
normal_logpdf,
matrix_normal_logpdf,
pos... | 0.587115 | 0.158272 |
# Built-in libraries
import os
# External libraries
import pandas as pd
import numpy as np
#%% Functions to select specific glacier numbers
def get_same_glaciers(glac_fp):
"""
Get same 1000 glaciers for testing of priors
Parameters
----------
glac_fp : str
filepath to where netcdf files o... | pygem_input_oct19.py |
# Built-in libraries
import os
# External libraries
import pandas as pd
import numpy as np
#%% Functions to select specific glacier numbers
def get_same_glaciers(glac_fp):
"""
Get same 1000 glaciers for testing of priors
Parameters
----------
glac_fp : str
filepath to where netcdf files o... | 0.748352 | 0.425963 |
"""This module contains several functions common to all modules."""
from weresync.exception import DeviceError, InvalidVersionError
import subprocess
import logging
import logging.handlers
import os
import gettext
import sys
LOGGER = logging.getLogger(__name__)
LANGUAGES = ["en"]
"""Currently translated languages. S... | src/weresync/utils.py | """This module contains several functions common to all modules."""
from weresync.exception import DeviceError, InvalidVersionError
import subprocess
import logging
import logging.handlers
import os
import gettext
import sys
LOGGER = logging.getLogger(__name__)
LANGUAGES = ["en"]
"""Currently translated languages. S... | 0.639286 | 0.319413 |
from fastapi import APIRouter
from .library.component import *
from .library.feedback import *
from .library.module import *
from .library.utils import *
from .library.marks import *
from .library.user import *
router = APIRouter()
if (not dynamodb_select({"module_code": "ICT2103"}, "ict2x01_module")):
ict2103 = ... | backend/api/endpoints/DebuggerAPI.py | from fastapi import APIRouter
from .library.component import *
from .library.feedback import *
from .library.module import *
from .library.utils import *
from .library.marks import *
from .library.user import *
router = APIRouter()
if (not dynamodb_select({"module_code": "ICT2103"}, "ict2x01_module")):
ict2103 = ... | 0.306527 | 0.100879 |
import buildVersion
import re
from logHandler import log
"""
This module contains add-on API version information for this build of NVDA. This file provides information on
how the API has changed as well as the range of API versions supported by this build of NVDA
"""
CURRENT = (buildVersion.version_year, b... | source/addonAPIVersion.py |
import buildVersion
import re
from logHandler import log
"""
This module contains add-on API version information for this build of NVDA. This file provides information on
how the API has changed as well as the range of API versions supported by this build of NVDA
"""
CURRENT = (buildVersion.version_year, b... | 0.439507 | 0.210705 |
from datetime import datetime, timedelta
from huey import crontab
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.sql import exists
from app import create_app
from app.models.session import Session
from app.models.period import Period
from app.models.event import Event
from app.models.lesson import Lesso... | app/utils/tasks/tasks.py | from datetime import datetime, timedelta
from huey import crontab
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.sql import exists
from app import create_app
from app.models.session import Session
from app.models.period import Period
from app.models.event import Event
from app.models.lesson import Lesso... | 0.451568 | 0.099645 |
import pprint
import re # noqa: F401
import six
class HandledError(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the ... | sdks/python/appcenter_sdk/models/HandledError.py | import pprint
import re # noqa: F401
import six
class HandledError(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the ... | 0.639736 | 0.070336 |
from typing import List, Optional
import attr
from genyrator.entities.Entity import Entity
from genyrator.entities.File import create_files_from_template_config, FileList
from genyrator.template_config import create_template_config, TemplateConfig
@attr.s
class Schema(object):
module_name: str = a... | genyrator/entities/Schema.py | from typing import List, Optional
import attr
from genyrator.entities.Entity import Entity
from genyrator.entities.File import create_files_from_template_config, FileList
from genyrator.template_config import create_template_config, TemplateConfig
@attr.s
class Schema(object):
module_name: str = a... | 0.615088 | 0.134719 |
from datetime import datetime, timedelta
from functools import partial
import voluptuous as vol
from homeassistant.components import sensor
from homeassistant.const import (
ATTR_DEVICE_CLASS,
CONF_AT,
CONF_ENTITY_ID,
CONF_OFFSET,
CONF_PLATFORM,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from hom... | homeassistant/components/homeassistant/triggers/time.py | from datetime import datetime, timedelta
from functools import partial
import voluptuous as vol
from homeassistant.components import sensor
from homeassistant.const import (
ATTR_DEVICE_CLASS,
CONF_AT,
CONF_ENTITY_ID,
CONF_OFFSET,
CONF_PLATFORM,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from hom... | 0.632957 | 0.150278 |
from django.db import models
from django.contrib.auth.models import User, Group
from django.utils.translation import ugettext as _
class Room(models.Model):
"""
Représente une chambre de Maiz.
Accessoirement, il n'y a qu'une chambre par utilisateur, donc
pour les chambres du style Cyclament où on met plusieurs
r... | register/models.py | from django.db import models
from django.contrib.auth.models import User, Group
from django.utils.translation import ugettext as _
class Room(models.Model):
"""
Représente une chambre de Maiz.
Accessoirement, il n'y a qu'une chambre par utilisateur, donc
pour les chambres du style Cyclament où on met plusieurs
r... | 0.347869 | 0.237443 |
from __future__ import absolute_import
import os
import os.path
import unittest
from ... import config
from ... import logging
from ...utils import registry
_TEST_CASES = {}
def make_test_case(test_kind, *args, **kwargs):
"""
Factory function for creating TestCase instances.
"""
if test_kind not ... | buildscripts/resmokelib/testing/testcases/interface.py | from __future__ import absolute_import
import os
import os.path
import unittest
from ... import config
from ... import logging
from ...utils import registry
_TEST_CASES = {}
def make_test_case(test_kind, *args, **kwargs):
"""
Factory function for creating TestCase instances.
"""
if test_kind not ... | 0.701202 | 0.344719 |
import PhysicsMixin
import ID
BODIES = """
<dict>
<key>body</key>
<dict>
<key>x</key>
<integer>%(x)s</integer>
<key>y</key>
<integer>%(y)s</integer>
<key>width</key>
<integer>%(width)s</integer>
<key>height</key>
<integer>%(height)s</integer>
<key>firstFrame</key... | utils/scripts/OOOlevelGen/src/sprites/Enemy.py | import PhysicsMixin
import ID
BODIES = """
<dict>
<key>body</key>
<dict>
<key>x</key>
<integer>%(x)s</integer>
<key>y</key>
<integer>%(y)s</integer>
<key>width</key>
<integer>%(width)s</integer>
<key>height</key>
<integer>%(height)s</integer>
<key>firstFrame</key... | 0.195671 | 0.124479 |
from datetime import datetime
from marshmallow import fields
from .field_set import FieldSet, FieldSetSchema
class Event(FieldSet):
def __init__(self,
action: str = None,
category: str = None,
created: datetime = None,
dataset: str = None,
... | kubi_ecs_logger/models/fields/event.py | from datetime import datetime
from marshmallow import fields
from .field_set import FieldSet, FieldSetSchema
class Event(FieldSet):
def __init__(self,
action: str = None,
category: str = None,
created: datetime = None,
dataset: str = None,
... | 0.74512 | 0.116588 |
import unittest
from chirp.common import http
from chirp.stream import barix
class RemoveTagsTestCase(unittest.TestCase):
def test_basic(self):
self.assertEqual("foo bar",
barix._remove_tags("foo bar"))
self.assertEqual("foo bar baz",
barix._remove... | chirp/stream/barix_test.py | import unittest
from chirp.common import http
from chirp.stream import barix
class RemoveTagsTestCase(unittest.TestCase):
def test_basic(self):
self.assertEqual("foo bar",
barix._remove_tags("foo bar"))
self.assertEqual("foo bar baz",
barix._remove... | 0.583678 | 0.280857 |