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 |
|---|---|---|---|---|
from __future__ import absolute_import, division, print_function
__metaclass__ = type
"""
The Logging_global parser templates file. This contains
a list of parser definitions and associated functions that
facilitates both facts gathering and native command generation for
the given network resource.
"""
import re
fr... | venv/lib/python3.8/site-packages/ansible_collections/arista/eos/plugins/module_utils/network/eos/rm_templates/logging_global.py |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
"""
The Logging_global parser templates file. This contains
a list of parser definitions and associated functions that
facilitates both facts gathering and native command generation for
the given network resource.
"""
import re
fr... | 0.576423 | 0.133896 |
from plyer.facades import GPS
from plyer.platforms.android import activity
from jnius import autoclass, java_method, PythonJavaClass
Looper = autoclass('android.os.Looper')
LocationManager = autoclass('android.location.LocationManager')
Context = autoclass('android.content.Context')
class _LocationListener(PythonJav... | plyer/platforms/android/gps.py | from plyer.facades import GPS
from plyer.platforms.android import activity
from jnius import autoclass, java_method, PythonJavaClass
Looper = autoclass('android.os.Looper')
LocationManager = autoclass('android.location.LocationManager')
Context = autoclass('android.content.Context')
class _LocationListener(PythonJav... | 0.722037 | 0.070081 |
import argparse
###### modified from github.com/kevinzakka/recurrent-visual-attention
arg_lists = []
parser = argparse.ArgumentParser(description='RAM')
def str2bool(v):
return v.lower() in ('true', '1')
def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
re... | config.py | import argparse
###### modified from github.com/kevinzakka/recurrent-visual-attention
arg_lists = []
parser = argparse.ArgumentParser(description='RAM')
def str2bool(v):
return v.lower() in ('true', '1')
def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
re... | 0.520009 | 0.176033 |
import os
import h5py
import numpy as np
from PIL import Image
def make_positive_index_market1501(train_or_test = 'train',user_name = 'ubuntu'):
f = h5py.File('market1501_positive_index.h5')
path_list = get_image_path_list(train_or_test = train_or_test, system_user_name = user_name)
index = []
... | market1501/make_hdf5_for_market1501.py | import os
import h5py
import numpy as np
from PIL import Image
def make_positive_index_market1501(train_or_test = 'train',user_name = 'ubuntu'):
f = h5py.File('market1501_positive_index.h5')
path_list = get_image_path_list(train_or_test = train_or_test, system_user_name = user_name)
index = []
... | 0.080115 | 0.195671 |
from typing import Union
import numpy as np
from torch.utils.data import Subset
from torchvision.datasets import VisionDataset
from config_schema import ConfigSchema
DatasetTypes = Union[VisionDataset, Subset]
class WeakLabelManager:
def __init__(self, num_classes: int, **kwargs):
self.num_classes = nu... | data/weak_labels.py | from typing import Union
import numpy as np
from torch.utils.data import Subset
from torchvision.datasets import VisionDataset
from config_schema import ConfigSchema
DatasetTypes = Union[VisionDataset, Subset]
class WeakLabelManager:
def __init__(self, num_classes: int, **kwargs):
self.num_classes = nu... | 0.912683 | 0.559832 |
from grow.pods import catalog_holder
from grow.pods import pods
from grow.pods import storage
import click
import os
@click.command()
@click.argument('pod_path', default='.')
@click.option('--include-obsolete/--no-include-obsolete', default=None,
is_flag=True,
help='Whether to include obso... | grow/commands/extract.py | from grow.pods import catalog_holder
from grow.pods import pods
from grow.pods import storage
import click
import os
@click.command()
@click.argument('pod_path', default='.')
@click.option('--include-obsolete/--no-include-obsolete', default=None,
is_flag=True,
help='Whether to include obso... | 0.622918 | 0.124932 |
import time
import jwt
from django.contrib.auth import get_user_model
from django.utils.translation import gettext as _
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication, jwt_get_username_fr... | FasterRunner/auth.py | import time
import jwt
from django.contrib.auth import get_user_model
from django.utils.translation import gettext as _
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication, jwt_get_username_fr... | 0.402275 | 0.054424 |
import json
import os
class MapObj:
def __init__(self, minx=0, maxx=0, miny=0, maxy=0, minz=0, maxz=0, type=None, value=None):
self.minx = minx
self.maxx = maxx
self.miny = miny
self.maxy = maxy
self.minz = minz
self.maxz = maxz
self.type = type
self.... | mapjson/__init__.py | import json
import os
class MapObj:
def __init__(self, minx=0, maxx=0, miny=0, maxy=0, minz=0, maxz=0, type=None, value=None):
self.minx = minx
self.maxx = maxx
self.miny = miny
self.maxy = maxy
self.minz = minz
self.maxz = maxz
self.type = type
self.... | 0.475605 | 0.172241 |
# Utilidades
import json
# Django REST Framework
from rest_framework import status
from rest_framework.authtoken.models import Token
# Modelos
from andromeda.modules.technical_support.models import Support
from andromeda.roles.assistant.models import Assistant
# Mocks
from andromeda.modules.test_model.mocks import ... | andromeda/modules/technical_support/tests.py |
# Utilidades
import json
# Django REST Framework
from rest_framework import status
from rest_framework.authtoken.models import Token
# Modelos
from andromeda.modules.technical_support.models import Support
from andromeda.roles.assistant.models import Assistant
# Mocks
from andromeda.modules.test_model.mocks import ... | 0.558809 | 0.147156 |
from collections import deque
import gym
import numpy as np
# Adapted from the link below.
# https://github.com/openai/baselines/blob/master/baselines/common/atari_wrappers.py
class WarpFrame(gym.ObservationWrapper):
"""Wrap a frame."""
def __init__(self, env):
"""Warp frames to 84x84 as done in the Nature... | tensor2tensor/rl/envs/atari_wrappers.py | from collections import deque
import gym
import numpy as np
# Adapted from the link below.
# https://github.com/openai/baselines/blob/master/baselines/common/atari_wrappers.py
class WarpFrame(gym.ObservationWrapper):
"""Wrap a frame."""
def __init__(self, env):
"""Warp frames to 84x84 as done in the Nature... | 0.957058 | 0.58886 |
from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.contrib import messages
from django.http import HttpResponseForbidden
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from .models i... | posts/views.py | from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.contrib import messages
from django.http import HttpResponseForbidden
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from .models i... | 0.490968 | 0.089773 |
from enum import Enum
__all__ = [
'ScanConfigTargetPlatformsItem',
'ScanConfigUserAgent',
'ScanRunExecutionState',
'ScanRunResultState',
]
class ScanConfigTargetPlatformsItem(str, Enum):
TARGET_PLATFORM_UNSPECIFIED = "TARGET_PLATFORM_UNSPECIFIED"
"""
The target platform is unknown. Reque... | sdk/python/pulumi_google_native/websecurityscanner/v1alpha/_enums.py |
from enum import Enum
__all__ = [
'ScanConfigTargetPlatformsItem',
'ScanConfigUserAgent',
'ScanRunExecutionState',
'ScanRunResultState',
]
class ScanConfigTargetPlatformsItem(str, Enum):
TARGET_PLATFORM_UNSPECIFIED = "TARGET_PLATFORM_UNSPECIFIED"
"""
The target platform is unknown. Reque... | 0.553023 | 0.101768 |
import logging
import argparse
from os import getenv
from pprint import pprint
from dotenv import load_dotenv
from ghapi.all import GhApi
from ghsearcher.helpers import RateLimiter
from ghsearcher.helpers import paginator, output_json_file
from fastcore.xtras import obj2dict
load_dotenv()
GH_TOKEN = getenv('GH_TOKEN'... | ghsearcher/searcher.py | import logging
import argparse
from os import getenv
from pprint import pprint
from dotenv import load_dotenv
from ghapi.all import GhApi
from ghsearcher.helpers import RateLimiter
from ghsearcher.helpers import paginator, output_json_file
from fastcore.xtras import obj2dict
load_dotenv()
GH_TOKEN = getenv('GH_TOKEN'... | 0.335786 | 0.062474 |
from cardinal.system.cardinal_sys import cardinalSql
from flask import Blueprint
from flask import render_template
from flask import redirect
from flask import session
from flask import url_for
cardinal_visuals = Blueprint('cardinal_visuals_bp', __name__)
@cardinal_visuals.route("/total-ap-clients", methods=["GET"])
... | webapp/cardinal/views/cardinal_visuals.py | from cardinal.system.cardinal_sys import cardinalSql
from flask import Blueprint
from flask import render_template
from flask import redirect
from flask import session
from flask import url_for
cardinal_visuals = Blueprint('cardinal_visuals_bp', __name__)
@cardinal_visuals.route("/total-ap-clients", methods=["GET"])
... | 0.388386 | 0.045331 |
import os
import io
import sys
import math
import numpy as np
from PIL import Image, ImageStat, ImageFilter
_PIXWEIGHT = np.concatenate((np.arange(128, 0, -1), np.arange(0, 128))) / 128
def otsu_threshold(hist):
total = sum(hist)
sumB = 0
wB = 0
maximum = 0.0
sum1 = np.dot(np.arange(256), hist)
... | imgautocompress.py |
import os
import io
import sys
import math
import numpy as np
from PIL import Image, ImageStat, ImageFilter
_PIXWEIGHT = np.concatenate((np.arange(128, 0, -1), np.arange(0, 128))) / 128
def otsu_threshold(hist):
total = sum(hist)
sumB = 0
wB = 0
maximum = 0.0
sum1 = np.dot(np.arange(256), hist)
... | 0.390941 | 0.276611 |
from unittest import TestCase
import mock
from model_mommy import mommy
from celery_persistent_revokes.models import CeleryTaskRevoke
from celery_persistent_revokes.decorators import revokable_task
class RevokableTaskDecoratorTests(TestCase):
def test_function_not_called_if_task_is_revoked(self):
origin... | tests/test_decorators.py | from unittest import TestCase
import mock
from model_mommy import mommy
from celery_persistent_revokes.models import CeleryTaskRevoke
from celery_persistent_revokes.decorators import revokable_task
class RevokableTaskDecoratorTests(TestCase):
def test_function_not_called_if_task_is_revoked(self):
origin... | 0.516108 | 0.266089 |
# # Instant Recognition with Caffe
#
# In this example we'll classify an image with the bundled CaffeNet model based on the network architecture of Krizhevsky et al. for ImageNet. We'll compare CPU and GPU operation then reach into the model to inspect features and the output.
#
# (These feature visualizations follo... | examples/00-classification.py |
# # Instant Recognition with Caffe
#
# In this example we'll classify an image with the bundled CaffeNet model based on the network architecture of Krizhevsky et al. for ImageNet. We'll compare CPU and GPU operation then reach into the model to inspect features and the output.
#
# (These feature visualizations follo... | 0.725065 | 0.650079 |
from typing import List
import re
import math
import nltk
import spacy
from wordfreq import word_frequency
from aristomini.common.solver import SolverBase
from aristomini.common.models import MultipleChoiceQuestion, MultipleChoiceAnswer, ChoiceConfidence
from quasimodo.spacy_accessor import SpacyAccessor
nlp = spa... | evaluation/custom_aristo_mini_solvers/basic_csk_solver.py | from typing import List
import re
import math
import nltk
import spacy
from wordfreq import word_frequency
from aristomini.common.solver import SolverBase
from aristomini.common.models import MultipleChoiceQuestion, MultipleChoiceAnswer, ChoiceConfidence
from quasimodo.spacy_accessor import SpacyAccessor
nlp = spa... | 0.654453 | 0.25703 |
import json
import logging
from django.conf import settings
from django.utils.encoding import filepath_to_uri
from rest_framework import viewsets
from rest_framework.serializers import HyperlinkedModelSerializer, \
ReadOnlyField, Serializer
from rest_framework.authentication import SessionAuthentication, BasicAut... | jmbo/api/__init__.py | import json
import logging
from django.conf import settings
from django.utils.encoding import filepath_to_uri
from rest_framework import viewsets
from rest_framework.serializers import HyperlinkedModelSerializer, \
ReadOnlyField, Serializer
from rest_framework.authentication import SessionAuthentication, BasicAut... | 0.603932 | 0.097433 |
from concurrent import futures
import time
import grpc
import logging
import os
import sys
import socket
import traceback
sys.path.append(os.path.join(os.path.dirname(__file__), '../rpc_stubs'))
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
import worker_to_scheduler_pb2 as w2s_pb2
impo... | scheduler/runtime/rpc/scheduler_server.py | from concurrent import futures
import time
import grpc
import logging
import os
import sys
import socket
import traceback
sys.path.append(os.path.join(os.path.dirname(__file__), '../rpc_stubs'))
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
import worker_to_scheduler_pb2 as w2s_pb2
impo... | 0.197522 | 0.076615 |
def cf_teams_beta_cl(cli_ctx, *_):
from msgraph.cli.core.commands.client_factory import get_mgmt_service_client
from azext_teams_beta.vendored_sdks.teams import Teams
return get_mgmt_service_client(cli_ctx,
Teams,
subscription_bo... | msgraph-cli-extensions/beta/teams_beta/azext_teams_beta/generated/_client_factory.py |
def cf_teams_beta_cl(cli_ctx, *_):
from msgraph.cli.core.commands.client_factory import get_mgmt_service_client
from azext_teams_beta.vendored_sdks.teams import Teams
return get_mgmt_service_client(cli_ctx,
Teams,
subscription_bo... | 0.400515 | 0.061199 |
import collections
from functools import reduce
from django import template
from django.utils import timezone
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from ephios.core.models import AbstractParticipation, EventType, LocalParticipation
from ephios.core.signals import regi... | ephios/core/templatetags/event_extras.py | import collections
from functools import reduce
from django import template
from django.utils import timezone
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from ephios.core.models import AbstractParticipation, EventType, LocalParticipation
from ephios.core.signals import regi... | 0.477311 | 0.177134 |
from __future__ import division
from __future__ import print_function
import numpy as np
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
from sklearn.utils import column_or_1d
from .base import Base
from utils.utilities import check_parameter
from numpy import percentile
cl... | algo/hbos.py | from __future__ import division
from __future__ import print_function
import numpy as np
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
from sklearn.utils import column_or_1d
from .base import Base
from utils.utilities import check_parameter
from numpy import percentile
cl... | 0.958596 | 0.686015 |
import unittest
import wellcad.com
from ._sample_path import SamplePath
from ._extra_asserts import ExtraAsserts
class TestDepth(unittest.TestCase, SamplePath, ExtraAsserts):
@classmethod
def setUpClass(cls):
cls.app = wellcad.com.Application()
cls.sample_path = cls._find_sample_path()
... | test/test_depth.py | import unittest
import wellcad.com
from ._sample_path import SamplePath
from ._extra_asserts import ExtraAsserts
class TestDepth(unittest.TestCase, SamplePath, ExtraAsserts):
@classmethod
def setUpClass(cls):
cls.app = wellcad.com.Application()
cls.sample_path = cls._find_sample_path()
... | 0.663669 | 0.661226 |
# we'll switch over to pyperclip if this ever gets fixed
# https://github.com/asweigart/pyperclip/issues/18
import BaseHTTPServer
import argparse
import ast
import logging
import os
import re
import subprocess
import threading
import time
import AppKit
import Foundation
def ParseArgs():
"""Parse all the command l... | copyclipper.py | # we'll switch over to pyperclip if this ever gets fixed
# https://github.com/asweigart/pyperclip/issues/18
import BaseHTTPServer
import argparse
import ast
import logging
import os
import re
import subprocess
import threading
import time
import AppKit
import Foundation
def ParseArgs():
"""Parse all the command l... | 0.390011 | 0.14262 |
import os
import pytest
from django.utils.text import slugify
from base_functional_tests import click_obscured, find_and_click_add_button, find_and_click_toggle_button, fill_content_editor_block, TEST_DATA_DIR, view_live_page
from iati.urls import ADMIN_SLUG
EVENT_INDEX_PAGE = {
'title': 'Events',
'heading': ... | iati/tests/events_functional_tests.py | import os
import pytest
from django.utils.text import slugify
from base_functional_tests import click_obscured, find_and_click_add_button, find_and_click_toggle_button, fill_content_editor_block, TEST_DATA_DIR, view_live_page
from iati.urls import ADMIN_SLUG
EVENT_INDEX_PAGE = {
'title': 'Events',
'heading': ... | 0.519278 | 0.13925 |
# Project: VUT FIT ATA Project - Řízení vozíku v robotické továrně
# Author: <NAME> <<EMAIL>>
# Year: 2021
# Description: Cart controller implementation testing.
import unittest
from cart import Cart, CargoReq, Status as CartStatus, CartError
from cartctl import CartCtl, Status as CartCtlStatus, LongPrioRequestError... | cartctl/cartctl_test.py |
# Project: VUT FIT ATA Project - Řízení vozíku v robotické továrně
# Author: <NAME> <<EMAIL>>
# Year: 2021
# Description: Cart controller implementation testing.
import unittest
from cart import Cart, CargoReq, Status as CartStatus, CartError
from cartctl import CartCtl, Status as CartCtlStatus, LongPrioRequestError... | 0.797596 | 0.544922 |
import sys
import io
import base64
class SourceMap(object):
"""
5 fields: output column, file index, input line, input column, name index
4 fields: output column, file index, input line, input column,
1 fields: column
"""
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy... | daedalus/sourcemap.py | import sys
import io
import base64
class SourceMap(object):
"""
5 fields: output column, file index, input line, input column, name index
4 fields: output column, file index, input line, input column,
1 fields: column
"""
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy... | 0.253861 | 0.204779 |
from itertools import groupby, tee
from itertools import groupby
def separador():
return "-="*30
alunos = [
{"Nome": "Luiz", "nota": "A"},
{"Nome": "Letícia", "nota": "B"},
{"Nome": "Fabrício", "nota": "A"},
{"Nome": "Rosemary", "nota": "C"},
{"Nome": "Joana", "nota": "D"},
{"Nome": "Joã... | Curso Udemy 2022/Curso_Luiz_Otavio/79_aula_groupby.py | from itertools import groupby, tee
from itertools import groupby
def separador():
return "-="*30
alunos = [
{"Nome": "Luiz", "nota": "A"},
{"Nome": "Letícia", "nota": "B"},
{"Nome": "Fabrício", "nota": "A"},
{"Nome": "Rosemary", "nota": "C"},
{"Nome": "Joana", "nota": "D"},
{"Nome": "Joã... | 0.289874 | 0.53206 |
import logging
from copy import deepcopy
from typing import Dict, List
class NodeExecutionFailure(Exception):
"""
Is executed whenever the node functions failed (setup, actions, ...)
"""
pass
class IncorrectResponse(NodeExecutionFailure):
pass
class FiniteStateMachine:
def __init__(self, e... | any_board_game/state.py | import logging
from copy import deepcopy
from typing import Dict, List
class NodeExecutionFailure(Exception):
"""
Is executed whenever the node functions failed (setup, actions, ...)
"""
pass
class IncorrectResponse(NodeExecutionFailure):
pass
class FiniteStateMachine:
def __init__(self, e... | 0.766643 | 0.292608 |
from logging import getLogger
from os import path
from typing import Union
from sqlalchemy.engine import Engine
from ahjo.database_utilities import (create_conn_info,
create_sqlalchemy_engine,
create_sqlalchemy_url)
from ahjo.interface_methods... | src/ahjo/context.py |
from logging import getLogger
from os import path
from typing import Union
from sqlalchemy.engine import Engine
from ahjo.database_utilities import (create_conn_info,
create_sqlalchemy_engine,
create_sqlalchemy_url)
from ahjo.interface_methods... | 0.706697 | 0.148047 |
import conf,email_conf, json, time, math, statistics
from boltiot import Sms, Bolt,Email
def compute_bounds(history_data,frame_size,factor):
if len(history_data)<frame_size :
return None
if len(history_data)>frame_size :
del history_data[0:len(history_data)-frame_size]
Mn=statistics.mean(hi... | anomalydetection.py | import conf,email_conf, json, time, math, statistics
from boltiot import Sms, Bolt,Email
def compute_bounds(history_data,frame_size,factor):
if len(history_data)<frame_size :
return None
if len(history_data)>frame_size :
del history_data[0:len(history_data)-frame_size]
Mn=statistics.mean(hi... | 0.330147 | 0.216695 |
import logging
from requests import Session, Timeout
class DynatraceClient:
def __init__(self, token, verify=False, cert=None, keyfile=None, timeout=None):
"""
Client for Dynatrace rest API. It's used by dynatrace_topology and dynatrace_health check.
:param token: token from Dynatrace pl... | dynatrace_base/stackstate_checks/dynatrace/dynatrance_client.py |
import logging
from requests import Session, Timeout
class DynatraceClient:
def __init__(self, token, verify=False, cert=None, keyfile=None, timeout=None):
"""
Client for Dynatrace rest API. It's used by dynatrace_topology and dynatrace_health check.
:param token: token from Dynatrace pl... | 0.63477 | 0.15059 |
from CIM15.CDPSM.Asset.IEC61968.AssetModels.ConductorInfo import ConductorInfo
class CableInfo(ConductorInfo):
"""Cable data.
"""
def __init__(self, diameterOverJacket=0.0, constructionKind="sector", shieldMaterial="lead", outerJacketKind="pvc", isStrandFill=False, diameterOverInsulation=0.0, diameterOve... | CIM15/CDPSM/Asset/IEC61968/AssetModels/CableInfo.py |
from CIM15.CDPSM.Asset.IEC61968.AssetModels.ConductorInfo import ConductorInfo
class CableInfo(ConductorInfo):
"""Cable data.
"""
def __init__(self, diameterOverJacket=0.0, constructionKind="sector", shieldMaterial="lead", outerJacketKind="pvc", isStrandFill=False, diameterOverInsulation=0.0, diameterOve... | 0.851181 | 0.492066 |
import numpy as np
def bolcor(teff):
"""
Calculate the bolometric correction, given the temperature
"""
lteff = np.log10(teff)
bcflow=np.nan
if lteff < 3.7:
bcflow = -0.190537291496456e+05 + 0.155144866764412e+05 * lteff -\
0.421278819301717e+04 * (lteff * lteff) +\
... | ParallaxSpec.py | import numpy as np
def bolcor(teff):
"""
Calculate the bolometric correction, given the temperature
"""
lteff = np.log10(teff)
bcflow=np.nan
if lteff < 3.7:
bcflow = -0.190537291496456e+05 + 0.155144866764412e+05 * lteff -\
0.421278819301717e+04 * (lteff * lteff) +\
... | 0.359926 | 0.407864 |
import unittest
from pyquilted.quilted.contact import *
class TestContact(unittest.TestCase):
def setUp(self):
self.email = EmailContact('<EMAIL>')
self.phone = PhoneContact('555-123-4567')
social_dict = {
"handle": "@jonsnow",
"sites": ['twitter', 'instagra... | test/test_quilted_contact.py | import unittest
from pyquilted.quilted.contact import *
class TestContact(unittest.TestCase):
def setUp(self):
self.email = EmailContact('<EMAIL>')
self.phone = PhoneContact('555-123-4567')
social_dict = {
"handle": "@jonsnow",
"sites": ['twitter', 'instagra... | 0.539469 | 0.525673 |
import math
import random
import numpy as np
import pandas as pd
from contextlib import contextmanager
from copy import deepcopy
import torch.utils.data
from ..custom_types import *
from ..utils import *
class RandomShuffler(object):
"""
Use random functions while keeping track of the random state to make i... | torchtable/loader/core.py | import math
import random
import numpy as np
import pandas as pd
from contextlib import contextmanager
from copy import deepcopy
import torch.utils.data
from ..custom_types import *
from ..utils import *
class RandomShuffler(object):
"""
Use random functions while keeping track of the random state to make i... | 0.751101 | 0.375477 |
import numpy as np
from typing import List, Tuple
from structures.gamestructure import EstimatedGame
from structures.bounds import Bound
def global_sampling(estimated_game: EstimatedGame, bound: Bound, m: int, delta: float, c: float) -> Tuple[float, int]:
"""
Implementation of global sampling.
:param esti... | algorithms/algorithms.py | import numpy as np
from typing import List, Tuple
from structures.gamestructure import EstimatedGame
from structures.bounds import Bound
def global_sampling(estimated_game: EstimatedGame, bound: Bound, m: int, delta: float, c: float) -> Tuple[float, int]:
"""
Implementation of global sampling.
:param esti... | 0.800224 | 0.844216 |
from textwrap import dedent
from typing import Optional, Sequence
import libcst as cst
import libcst.matchers as m
import libcst.metadata as meta
from libcst.matchers import extractall, findall
from libcst.testing.utils import UnitTest
class MatchersFindAllTest(UnitTest):
def assertNodeSequenceEqual(
se... | libcst/matchers/tests/test_findall.py |
from textwrap import dedent
from typing import Optional, Sequence
import libcst as cst
import libcst.matchers as m
import libcst.metadata as meta
from libcst.matchers import extractall, findall
from libcst.testing.utils import UnitTest
class MatchersFindAllTest(UnitTest):
def assertNodeSequenceEqual(
se... | 0.876152 | 0.447581 |
import re
from lxml import html
from searx.engines.xpath import extract_text
from datetime import datetime
from searx.url_utils import urlencode
from searx.utils import get_torrent_size, int_or_zero
# engine dependent config
categories = ['files', 'videos', 'music']
paging = True
# search-url
base_url = 'https://www.... | searx/engines/tokyotoshokan.py | import re
from lxml import html
from searx.engines.xpath import extract_text
from datetime import datetime
from searx.url_utils import urlencode
from searx.utils import get_torrent_size, int_or_zero
# engine dependent config
categories = ['files', 'videos', 'music']
paging = True
# search-url
base_url = 'https://www.... | 0.220007 | 0.217234 |
import numpy as np
import theano
import theano.tensor as T
from smartlearner.tasks import stopping_criteria
from smartlearner.utils import sharedX
from smartlearner import Trainer
from smartlearner.optimizers import SGD, AdaGrad
from smartlearner.tasks import tasks
from numpy.testing import assert_array_almost_equ... | smartlearner/optimizers/tests/tests_optimizers.py | import numpy as np
import theano
import theano.tensor as T
from smartlearner.tasks import stopping_criteria
from smartlearner.utils import sharedX
from smartlearner import Trainer
from smartlearner.optimizers import SGD, AdaGrad
from smartlearner.tasks import tasks
from numpy.testing import assert_array_almost_equ... | 0.895013 | 0.637031 |
import os
import shutil
import sys
import time
from itertools import chain
from pathlib import Path
from typing import Dict, List, Set
import yaml
from click.testing import CliRunner
from aea.cli import cli
from aea.configurations.base import PackageId, PackageType, PublicId
from aea.configurations.constants import (... | scripts/deploy_to_registry.py | import os
import shutil
import sys
import time
from itertools import chain
from pathlib import Path
from typing import Dict, List, Set
import yaml
from click.testing import CliRunner
from aea.cli import cli
from aea.configurations.base import PackageId, PackageType, PublicId
from aea.configurations.constants import (... | 0.545286 | 0.178705 |
import unittest
import pdb
def squared_vw():
'''return squared error squashed for label values, as a scalar'''
def output(prediction, label, min_label, max_label):
'''ARGS all scalars numbers'''
# follow vw loss_functions squaredLoss
if prediction <= max_label and prediction >= min_lab... | loss_squared_vw.py | import unittest
import pdb
def squared_vw():
'''return squared error squashed for label values, as a scalar'''
def output(prediction, label, min_label, max_label):
'''ARGS all scalars numbers'''
# follow vw loss_functions squaredLoss
if prediction <= max_label and prediction >= min_lab... | 0.762336 | 0.628208 |
import bpy
import bmesh
import mathutils
from mathutils import Vector
import itertools
import os
class XPlaneImport(bpy.types.Operator):
bl_label = "Import X-Plane OBJ"
bl_idname = "import.xplane_obj"
filepath = bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
print(... | XP_import.py |
import bpy
import bmesh
import mathutils
from mathutils import Vector
import itertools
import os
class XPlaneImport(bpy.types.Operator):
bl_label = "Import X-Plane OBJ"
bl_idname = "import.xplane_obj"
filepath = bpy.props.StringProperty(subtype="FILE_PATH")
def execute(self, context):
print(... | 0.33928 | 0.267994 |
import numpy as np
import argparse
#Argument parser for ease of use
parser = argparse.ArgumentParser()
#Capacitance
parser.add_argument("--capacitance", "-C", type = np.double)
#Conductance through menbranes channel
parser.add_argument("--conductance_L", "-g_L", type = np.double)
parser.add_argument("--conductance_C... | MorrisLecar.py | import numpy as np
import argparse
#Argument parser for ease of use
parser = argparse.ArgumentParser()
#Capacitance
parser.add_argument("--capacitance", "-C", type = np.double)
#Conductance through menbranes channel
parser.add_argument("--conductance_L", "-g_L", type = np.double)
parser.add_argument("--conductance_C... | 0.328099 | 0.184841 |
_base_ = ['./coco_data_pipeline.py']
model = dict(
type='VFNet',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch'),
ne... | configs/ote/custom-object-detection/gen3_resnet50_VFNet/model.py | _base_ = ['./coco_data_pipeline.py']
model = dict(
type='VFNet',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch'),
ne... | 0.72027 | 0.197212 |
logger.info("Loading 86 objects to table topics_interest...")
# fields: id, owner_type, owner_id, topic, remark, partner
loader.save(create_topics_interest(1,None,None,1,u'',1))
loader.save(create_topics_interest(2,None,None,2,u'',1))
loader.save(create_topics_interest(3,None,None,3,u'',2))
loader.save(create_topics_in... | lino_book/projects/lydia/tests/dumps/18.12.0/topics_interest.py | logger.info("Loading 86 objects to table topics_interest...")
# fields: id, owner_type, owner_id, topic, remark, partner
loader.save(create_topics_interest(1,None,None,1,u'',1))
loader.save(create_topics_interest(2,None,None,2,u'',1))
loader.save(create_topics_interest(3,None,None,3,u'',2))
loader.save(create_topics_in... | 0.21305 | 0.169234 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from hpOneView.resources.resource import Resource
INVALID_VOLUME_URI = "When no snapshot uri i... | hpOneView/resources/storage/volumes.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from hpOneView.resources.resource import Resource
INVALID_VOLUME_URI = "When no snapshot uri i... | 0.924116 | 0.172869 |
import argparse
import re
parser = argparse.ArgumentParser(description='Merge CCS reports.')
parser.add_argument('ccs_report', metavar='R', type=str, nargs='+', help='CCS report(s)')
args = parser.parse_args()
d = {}
for ccs_report in args.ccs_report:
file = open(ccs_report, "r")
for line in file:
if... | docker/lr-bri/merge_ccs_reports.py | import argparse
import re
parser = argparse.ArgumentParser(description='Merge CCS reports.')
parser.add_argument('ccs_report', metavar='R', type=str, nargs='+', help='CCS report(s)')
args = parser.parse_args()
d = {}
for ccs_report in args.ccs_report:
file = open(ccs_report, "r")
for line in file:
if... | 0.463201 | 0.252122 |
import os, sys, re
import json
import getopt
from pprint import pprint
import pyvbcc
import pyvbcc.config
class Validator( object ):
def __init__( self, valmap, **opt ):
if 'debug' in opt and opt['debug'] in (True, False):
self._debug = opt['debug']
if not type( valmap ).__name__ ... | pyvbcc/validate.py |
import os, sys, re
import json
import getopt
from pprint import pprint
import pyvbcc
import pyvbcc.config
class Validator( object ):
def __init__( self, valmap, **opt ):
if 'debug' in opt and opt['debug'] in (True, False):
self._debug = opt['debug']
if not type( valmap ).__name__ ... | 0.125936 | 0.183191 |
from __future__ import absolute_import, division, print_function
import sys
import warnings
from glue.core import BaseData
from glue.utils import defer_draw, color2hex
from glue.viewers.profile.state import ProfileLayerState
from glue.core.exceptions import IncompatibleAttribute, IncompatibleDataException
import bqp... | glue_jupyter/bqplot/profile/layer_artist.py | from __future__ import absolute_import, division, print_function
import sys
import warnings
from glue.core import BaseData
from glue.utils import defer_draw, color2hex
from glue.viewers.profile.state import ProfileLayerState
from glue.core.exceptions import IncompatibleAttribute, IncompatibleDataException
import bqp... | 0.427994 | 0.28393 |
import io
import os
import re
import pytest
from h5glance import terminal
@pytest.fixture(scope='module', autouse=True)
def no_color():
os.environ['H5GLANCE_COLORS'] = '0'
def test_tree_view(simple_h5_file):
sio = io.StringIO()
tvb = terminal.TreeViewBuilder()
tree = tvb.object_node(simple_h5_file, s... | tests/test_terminal.py | import io
import os
import re
import pytest
from h5glance import terminal
@pytest.fixture(scope='module', autouse=True)
def no_color():
os.environ['H5GLANCE_COLORS'] = '0'
def test_tree_view(simple_h5_file):
sio = io.StringIO()
tvb = terminal.TreeViewBuilder()
tree = tvb.object_node(simple_h5_file, s... | 0.413951 | 0.452536 |
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import numpy as np
import glob
import pandas as pd
from collections import defaultdict
from argparse import Namespace
import os
import sys
sys.path.append('/w... | sopa/src/models/odenet_mnist/attacks_runner.py | import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import numpy as np
import glob
import pandas as pd
from collections import defaultdict
from argparse import Namespace
import os
import sys
sys.path.append('/w... | 0.397704 | 0.233095 |
import json
from unittest import mock
from unittest.mock import patch
from vulcan import Account
from vulcan.model import Student
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.vulcan import config_flow, const, register
from homeassistant.components.vulcan.config_flow import (... | tests/components/vulcan/test_config_flow.py | import json
from unittest import mock
from unittest.mock import patch
from vulcan import Account
from vulcan.model import Student
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.vulcan import config_flow, const, register
from homeassistant.components.vulcan.config_flow import (... | 0.707708 | 0.361446 |
import array
import pynodegl as ngl
from pynodegl_utils.misc import scene
from pynodegl_utils.toolbox.colors import COLORS
from pynodegl_utils.tests.cmp_cuepoints import test_cuepoints
from pynodegl_utils.tests.cmp_fingerprint import test_fingerprint
from pynodegl_utils.tests.debug import get_debug_points
from pynode... | tests/data.py |
import array
import pynodegl as ngl
from pynodegl_utils.misc import scene
from pynodegl_utils.toolbox.colors import COLORS
from pynodegl_utils.tests.cmp_cuepoints import test_cuepoints
from pynodegl_utils.tests.cmp_fingerprint import test_fingerprint
from pynodegl_utils.tests.debug import get_debug_points
from pynode... | 0.225417 | 0.410402 |
import urllib
import urllib.request
from urllib.request import HTTPPasswordMgrWithDefaultRealm
from urllib.request import HTTPBasicAuthHandler, HTTPCookieProcessor
from http.cookiejar import CookieJar
import re
__all__ = ['URLOpenerWithRedirect', 'MODISHtmlParser', 'VIIRSHtmlParser']
class URLOpenerWithRedirect:
... | wildfirepy/net/util/usgs.py | import urllib
import urllib.request
from urllib.request import HTTPPasswordMgrWithDefaultRealm
from urllib.request import HTTPBasicAuthHandler, HTTPCookieProcessor
from http.cookiejar import CookieJar
import re
__all__ = ['URLOpenerWithRedirect', 'MODISHtmlParser', 'VIIRSHtmlParser']
class URLOpenerWithRedirect:
... | 0.689828 | 0.175998 |
from credential import Credential
from user import User
import random
def create_user(fullname,email,mobilenumber):
"""
This function generates username
"""
new_user = User(fullname,email,mobilenumber)
return new_user
def create_credential(username, password, email):
"""
This function ge... | run.py | from credential import Credential
from user import User
import random
def create_user(fullname,email,mobilenumber):
"""
This function generates username
"""
new_user = User(fullname,email,mobilenumber)
return new_user
def create_credential(username, password, email):
"""
This function ge... | 0.348978 | 0.183118 |
import math
import nltk
import numpy as np
import re
from collections import Counter
from utils import lemmatize, embed_phrase
from evaluation import get_ranked_kplist, get_ranked_kpidx
from scipy.spatial.distance import cosine
from sklearn.metrics import silhouette_score,davies_bouldin_score
from spherecluster impo... | src/clustering.py | import math
import nltk
import numpy as np
import re
from collections import Counter
from utils import lemmatize, embed_phrase
from evaluation import get_ranked_kplist, get_ranked_kpidx
from scipy.spatial.distance import cosine
from sklearn.metrics import silhouette_score,davies_bouldin_score
from spherecluster impo... | 0.305076 | 0.20201 |
import json
from django.db import transaction
from channels.auth import channel_session_user
from manage_room.consumers import check_admin
from manage_room.utils import get_room_or_error, catch_client_error
from .models import ChatAndReply, Notice, Poll
@channel_session_user
@catch_client_error
def new_chat(messag... | manage_chat/consumers.py | import json
from django.db import transaction
from channels.auth import channel_session_user
from manage_room.consumers import check_admin
from manage_room.utils import get_room_or_error, catch_client_error
from .models import ChatAndReply, Notice, Poll
@channel_session_user
@catch_client_error
def new_chat(messag... | 0.195556 | 0.063978 |
from typing import List
from src.mapping.columns.column_relation import ColumnRelation
from src.mapping.values.value_matching_configuration import ValueMatchingConfiguration
from src.mapping.values.value_matching_model_factory import ValueMatchingModelFactory
from src.mapping.values.value_matching_target import ValueM... | src/mapping/columns/column_relation_builder.py | from typing import List
from src.mapping.columns.column_relation import ColumnRelation
from src.mapping.values.value_matching_configuration import ValueMatchingConfiguration
from src.mapping.values.value_matching_model_factory import ValueMatchingModelFactory
from src.mapping.values.value_matching_target import ValueM... | 0.926295 | 0.506103 |
import datetime
import json
import re
import urlparse
import pytest
import httmock
from peregrine import test_settings
class Config(object):
ADMIN_USERNAME = 'iama_username'
ADMIN_PASSWORD = '<PASSWORD>'
ADMIN_TOKEN = 'admin_token'
MEMBER_TOKEN = 'member_token'
SUBMITTER_TOKEN_A = 'submitter_a... | tests/auth_mock.py | import datetime
import json
import re
import urlparse
import pytest
import httmock
from peregrine import test_settings
class Config(object):
ADMIN_USERNAME = 'iama_username'
ADMIN_PASSWORD = '<PASSWORD>'
ADMIN_TOKEN = 'admin_token'
MEMBER_TOKEN = 'member_token'
SUBMITTER_TOKEN_A = 'submitter_a... | 0.12166 | 0.111773 |
import status
from datetime import date
from tornado import web, escape, ioloop, httpclient, gen
from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor
from drone import Altimeter, Drone, Hexacopter, LightEmittingDiode
thread_pool = ThreadPoolExecutor()
drone = Drone()
clas... | Chapter 10/restful_python_chapter_10_04/async_api.py | import status
from datetime import date
from tornado import web, escape, ioloop, httpclient, gen
from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor
from drone import Altimeter, Drone, Hexacopter, LightEmittingDiode
thread_pool = ThreadPoolExecutor()
drone = Drone()
clas... | 0.482429 | 0.093388 |
import networkx as nx
import pytest
from cortexpy.graph import interactor
from cortexpy.test.builder.graph.cortex import CortexGraphBuilder
class TestMultiDiGraph(object):
def test_prunes_three_tips_of_length_1(self):
# given
graph = nx.MultiDiGraph()
nx.add_path(graph, [0, 1, 2])
... | tests/test_unit/test_graph/test_interactor/test_prune_tips.py | import networkx as nx
import pytest
from cortexpy.graph import interactor
from cortexpy.test.builder.graph.cortex import CortexGraphBuilder
class TestMultiDiGraph(object):
def test_prunes_three_tips_of_length_1(self):
# given
graph = nx.MultiDiGraph()
nx.add_path(graph, [0, 1, 2])
... | 0.669745 | 0.610773 |
import os
from rock4.common import p_env
from rock4.common.p_log import CaseLog
from rock4.common.p_applog import AppLog
class Tracer(CaseLog):
def __init__(self, case_result_path = None, sys_log_path = None, device_id="", module_name = ""):
''' Parameter
case_result_path: 测试日志路径... | rock4/softtest/common/Tracer.py | import os
from rock4.common import p_env
from rock4.common.p_log import CaseLog
from rock4.common.p_applog import AppLog
class Tracer(CaseLog):
def __init__(self, case_result_path = None, sys_log_path = None, device_id="", module_name = ""):
''' Parameter
case_result_path: 测试日志路径... | 0.121921 | 0.10226 |
import os, sys
import argparse
from tensorflow.keras.models import load_model
import tensorflow as tf
import time
import numpy as np
is_input_2d = False
parser = argparse.ArgumentParser()
parser.add_argument("-model", type = str)
parser.add_argument("-datadir", type = str)
parser.add_argument("-dest", type = str, de... | arachne/record_misclf_indices.py | import os, sys
import argparse
from tensorflow.keras.models import load_model
import tensorflow as tf
import time
import numpy as np
is_input_2d = False
parser = argparse.ArgumentParser()
parser.add_argument("-model", type = str)
parser.add_argument("-datadir", type = str)
parser.add_argument("-dest", type = str, de... | 0.183155 | 0.282321 |
import re, os, os.path
unv_types = (
('u8', 'uint8_t'),
('s8', 'int8_t'),
('u16', 'uint16_t'),
('s16', 'int16_t'),
('u32', 'uint32_t'),
('s32', 'int32_t'),
('u64', 'uint64_t'),
('s64', 'int64_t'),
('f32', 'float'),
('f64', 'double'),
('c32', 'std::complex<float>'),
('c6... | gnuradio-3.7.13.4/gnuradio-runtime/lib/pmt/generate_unv.py | import re, os, os.path
unv_types = (
('u8', 'uint8_t'),
('s8', 'int8_t'),
('u16', 'uint16_t'),
('s16', 'int16_t'),
('u32', 'uint32_t'),
('s32', 'int32_t'),
('u64', 'uint64_t'),
('s64', 'int64_t'),
('f32', 'float'),
('f64', 'double'),
('c32', 'std::complex<float>'),
('c6... | 0.253491 | 0.056522 |
from tir import Webapp
import unittest
from datetime import datetime
DateSystem = datetime.today().strftime('%d/%m/%Y')
class FISA001(unittest.TestCase):
@classmethod
def setUpClass(inst):
'''
SETUP
Test Case Initial Setup
'''
#Endereco do webapp e o nome do Browser
... | Protheus_WebApp/Modules/SIGAFIS/FISA001TESTCASE.py | from tir import Webapp
import unittest
from datetime import datetime
DateSystem = datetime.today().strftime('%d/%m/%Y')
class FISA001(unittest.TestCase):
@classmethod
def setUpClass(inst):
'''
SETUP
Test Case Initial Setup
'''
#Endereco do webapp e o nome do Browser
... | 0.296858 | 0.130341 |
from numba.core.errors import TypingError
from sumo.modes.prepare import similarity
from sumo.utils import check_matrix_symmetry
from sumo.constants import SIMILARITY_METHODS
import numpy as np
import pytest
def _test_assumptions_no_numba(func):
with pytest.raises(AssertionError):
func(np.array([1]), np.a... | test/sumo/test_modes/test_prepare/test_similarity.py | from numba.core.errors import TypingError
from sumo.modes.prepare import similarity
from sumo.utils import check_matrix_symmetry
from sumo.constants import SIMILARITY_METHODS
import numpy as np
import pytest
def _test_assumptions_no_numba(func):
with pytest.raises(AssertionError):
func(np.array([1]), np.a... | 0.841109 | 0.795062 |
from typing import List
def landing_pos(start_pos: int, steps: int):
final = (start_pos + steps) % 10
return 10 if final == 0 else final
def find_win_count(p1_pos: int, p2_pos: int, p1_score: int, p2_score: int, turn: int) -> List[int]:
if p1_score >= 21:
return [1, 0]
elif p2_score >= 21:
... | day21/main.py | from typing import List
def landing_pos(start_pos: int, steps: int):
final = (start_pos + steps) % 10
return 10 if final == 0 else final
def find_win_count(p1_pos: int, p2_pos: int, p1_score: int, p2_score: int, turn: int) -> List[int]:
if p1_score >= 21:
return [1, 0]
elif p2_score >= 21:
... | 0.532668 | 0.687221 |
from __future__ import unicode_literals
class BinaryHeap(object):
"""A class for a binary heap."""
def __init__(self, iterable=(), minheap=True):
"""Initializes a binary heap, optionally with items from an iterable.
By default, the binary will sort as a minheap, with smallest values
a... | binary_heap.py | from __future__ import unicode_literals
class BinaryHeap(object):
"""A class for a binary heap."""
def __init__(self, iterable=(), minheap=True):
"""Initializes a binary heap, optionally with items from an iterable.
By default, the binary will sort as a minheap, with smallest values
a... | 0.891566 | 0.506774 |
from tkinter import *
import tkinter.ttk as tk
"""
For those unfamiliar with Tk
A frame is a box, similar to a DIV in html, for formatting
A label is a text object
Pack puts an object into its frame
"""
class Object_Interface:
"""
The object handling the window created when the user adds an object
"""
... | gui.py | from tkinter import *
import tkinter.ttk as tk
"""
For those unfamiliar with Tk
A frame is a box, similar to a DIV in html, for formatting
A label is a text object
Pack puts an object into its frame
"""
class Object_Interface:
"""
The object handling the window created when the user adds an object
"""
... | 0.652131 | 0.152127 |
import torch
import torch.nn as nn
class BasicDiscriminatorBlock(nn.Module):
def __init__(self, in_channel, out_channel):
super(BasicDiscriminatorBlock, self).__init__()
self.block = nn.Sequential(
nn.utils.weight_norm(nn.Conv1d(
in_channel,
out_channel,
... | model/freq_discriminator.py | import torch
import torch.nn as nn
class BasicDiscriminatorBlock(nn.Module):
def __init__(self, in_channel, out_channel):
super(BasicDiscriminatorBlock, self).__init__()
self.block = nn.Sequential(
nn.utils.weight_norm(nn.Conv1d(
in_channel,
out_channel,
... | 0.937697 | 0.209167 |
import datetime
import requests
import json
import re
import os
import csv
from src.models.Uploads import Uploads
from src.models import Emails as Email
from src.views import Logger
BASE = os.getcwd()
LOGGER = Logger.init_logger(__name__)
def clean_filename(course_id: str, fname: str):
"""Cleans up given filenam... | src/models/Utilities.py | import datetime
import requests
import json
import re
import os
import csv
from src.models.Uploads import Uploads
from src.models import Emails as Email
from src.views import Logger
BASE = os.getcwd()
LOGGER = Logger.init_logger(__name__)
def clean_filename(course_id: str, fname: str):
"""Cleans up given filenam... | 0.571527 | 0.1585 |
class Properties(object):
def __init__(self, id_header, id_column, property_names, property_columns,
property_table):
self.id_header = id_header
self.id_column = id_column
self.property_names = property_names
self.property_columns = property_columns
self.pr... | mmpdblib/properties_io.py |
class Properties(object):
def __init__(self, id_header, id_column, property_names, property_columns,
property_table):
self.id_header = id_header
self.id_column = id_column
self.property_names = property_names
self.property_columns = property_columns
self.pr... | 0.525369 | 0.237742 |
import unittest
from testcommon import replicate_sample_view
from lib.buildlogger import getLogger
from replicationunittest import ReplicationTestCaseWithDocker
logger = getLogger(__name__)
class SampleDepotTestStream(ReplicationTestCaseWithDocker):
def replicate_sample_dir_withdocker(self, depot_dir, **kwargs... | test/testsampledepot_streams.py | import unittest
from testcommon import replicate_sample_view
from lib.buildlogger import getLogger
from replicationunittest import ReplicationTestCaseWithDocker
logger = getLogger(__name__)
class SampleDepotTestStream(ReplicationTestCaseWithDocker):
def replicate_sample_dir_withdocker(self, depot_dir, **kwargs... | 0.276593 | 0.224045 |
from datetime import datetime
from itertools import count
from unittest import TestCase, skip
from mock import patch, Mock
from icommons_common.models import Course, CourseInstance, Term, School, TermCode
from canvas_course_site_wizard.models import (
BulkCanvasCourseCreationJob as BulkJob,
CanvasCourseGenerati... | canvas_course_site_wizard/tests/test_models.py | from datetime import datetime
from itertools import count
from unittest import TestCase, skip
from mock import patch, Mock
from icommons_common.models import Course, CourseInstance, Term, School, TermCode
from canvas_course_site_wizard.models import (
BulkCanvasCourseCreationJob as BulkJob,
CanvasCourseGenerati... | 0.727007 | 0.333937 |
from functools import partial
import tensorflow as tf
from tensorflow import keras
from tensorflow.python import ipu
from data import CIFAR10_Data
from model import get_staged_model
from utils import parse_params, create_ipu_config
def estimator_model(opts, mode):
stage0, stage1 = get_staged_model(is_training=mo... | code_examples/tensorflow2/cifar10/cifar10_ipu_pipeline_estimator.py | from functools import partial
import tensorflow as tf
from tensorflow import keras
from tensorflow.python import ipu
from data import CIFAR10_Data
from model import get_staged_model
from utils import parse_params, create_ipu_config
def estimator_model(opts, mode):
stage0, stage1 = get_staged_model(is_training=mo... | 0.864854 | 0.333232 |
import asyncio
import random
import re
from cloudbot import hook
BUFFER_SIZE = 5000
MAX_STEPS = 1000000
@asyncio.coroutine
@hook.command("brainfuck", "bf")
def bf(text):
"""<prog> - executes <prog> as Brainfuck code
:type text: str
"""
program = re.sub('[^][<>+-.,]', '', text)
# create a dict ... | plugins/brainfuck.py | import asyncio
import random
import re
from cloudbot import hook
BUFFER_SIZE = 5000
MAX_STEPS = 1000000
@asyncio.coroutine
@hook.command("brainfuck", "bf")
def bf(text):
"""<prog> - executes <prog> as Brainfuck code
:type text: str
"""
program = re.sub('[^][<>+-.,]', '', text)
# create a dict ... | 0.324985 | 0.246329 |
# Copyright 2022 Tampere University
# This software was developed as a part of the VISDOM project: https://iteavisdom.org/
# This source code is licensed under the MIT license. See LICENSE in the repository root directory.
# Author(s): <NAME> <<EMAIL>>
from dataclasses import dataclass
from datetime import datetime, ... | python/dataset-fetcher/converter.py |
# Copyright 2022 Tampere University
# This software was developed as a part of the VISDOM project: https://iteavisdom.org/
# This source code is licensed under the MIT license. See LICENSE in the repository root directory.
# Author(s): <NAME> <<EMAIL>>
from dataclasses import dataclass
from datetime import datetime, ... | 0.835316 | 0.325701 |
import abc
import dataclasses
import inspect
import itertools
import warnings
from typing import Any, Callable, List, Mapping, Optional, Type
from .code import Code, indent
__all__ = ["CommonArg",
"PosArg", "VarPosArg", "KWArg", "PosOrKWArg", "VarKWArg",
"GetterArg",
"args_from_signat... | aiowamp/templ/entry_point/args.py | import abc
import dataclasses
import inspect
import itertools
import warnings
from typing import Any, Callable, List, Mapping, Optional, Type
from .code import Code, indent
__all__ = ["CommonArg",
"PosArg", "VarPosArg", "KWArg", "PosOrKWArg", "VarKWArg",
"GetterArg",
"args_from_signat... | 0.52342 | 0.171928 |
from typing import Any
import gin
from gym import spaces
import numpy as np
from pybullet_envs.minitaur.agents.baseline_controller import com_velocity_estimator
from pybullet_envs.minitaur.agents.baseline_controller import locomotion_controller
from pybullet_envs.minitaur.agents.baseline_controller import openloop_ga... | examples/pybullet/gym/pybullet_envs/minitaur/envs_v2/env_wrappers/walking_wrapper.py |
from typing import Any
import gin
from gym import spaces
import numpy as np
from pybullet_envs.minitaur.agents.baseline_controller import com_velocity_estimator
from pybullet_envs.minitaur.agents.baseline_controller import locomotion_controller
from pybullet_envs.minitaur.agents.baseline_controller import openloop_ga... | 0.926545 | 0.243429 |
from mock import MagicMock, patch
from tests.unit import UnitTestCase
from app.api_1_0.errors import api_exception_handler, error_handler
class ErrorsTestCase(UnitTestCase):
@patch('app.api_1_0.errors.api_exception_handler')
def test_value_error_handler(self, mock_api_exception_handler):
from app.a... | tests/unit/app/api_1_0/test_errors.py | from mock import MagicMock, patch
from tests.unit import UnitTestCase
from app.api_1_0.errors import api_exception_handler, error_handler
class ErrorsTestCase(UnitTestCase):
@patch('app.api_1_0.errors.api_exception_handler')
def test_value_error_handler(self, mock_api_exception_handler):
from app.a... | 0.734405 | 0.077657 |
from __future__ import absolute_import, division, print_function, unicode_literals
import mmh3
from lru import LRU # pylint: disable=no-name-in-module
from cosrlib.url import tld_extract
# TODO: run analytics on common crawl to get a larger list
COMMON_URLS = {
"": 0,
"/index.html": 1
}
URL_DOMAIN_IDS_CACH... | urlserver/id_generator.py | from __future__ import absolute_import, division, print_function, unicode_literals
import mmh3
from lru import LRU # pylint: disable=no-name-in-module
from cosrlib.url import tld_extract
# TODO: run analytics on common crawl to get a larger list
COMMON_URLS = {
"": 0,
"/index.html": 1
}
URL_DOMAIN_IDS_CACH... | 0.365343 | 0.150528 |
from csv import DictReader
import sys
import os
# Script to generate a Latex table of the multibeta results
step_size = 2
columns = 4
table_x_sep = '0.64mm'
table_y_stretch = '1.1'
instances = ['ft53', 'ft70', 'ftv170', 'ftv33', 'ftv35', 'ftv38', 'ftv44', 'ftv47', 'ftv55',
'ftv64', 'ftv70', 'kro124p', '... | src/scripts/table.py | from csv import DictReader
import sys
import os
# Script to generate a Latex table of the multibeta results
step_size = 2
columns = 4
table_x_sep = '0.64mm'
table_y_stretch = '1.1'
instances = ['ft53', 'ft70', 'ftv170', 'ftv33', 'ftv35', 'ftv38', 'ftv44', 'ftv47', 'ftv55',
'ftv64', 'ftv70', 'kro124p', '... | 0.174621 | 0.281918 |
import fugashi
import srt
import re
import ebooklib
from collections import Counter
from tqdm import tqdm
from pathlib import Path
from zipfile import ZipFile
from ebooklib import epub
import ass
from ass_tag_parser import parse_ass, AssText
class DictMaker:
"""docstring for DictMaker"""
def __init__(self):
... | yomidict/dictmaker.py | import fugashi
import srt
import re
import ebooklib
from collections import Counter
from tqdm import tqdm
from pathlib import Path
from zipfile import ZipFile
from ebooklib import epub
import ass
from ass_tag_parser import parse_ass, AssText
class DictMaker:
"""docstring for DictMaker"""
def __init__(self):
... | 0.32896 | 0.163345 |
import logging
from django import template
from django.conf import settings
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.template.defaultfilters import linebreaksbr
from django.core.cache import cache
from django.contrib.sites.models import Site
from opps.contrib.middlew... | opps/containers/templatetags/container_tags.py | import logging
from django import template
from django.conf import settings
from django.utils import timezone
from django.utils.safestring import mark_safe
from django.template.defaultfilters import linebreaksbr
from django.core.cache import cache
from django.contrib.sites.models import Site
from opps.contrib.middlew... | 0.505127 | 0.159054 |
import os
from tempfile import mkstemp
from flask import request, flash, url_for
from conekt.extensions import admin_required
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from conekt.controllers.admin.controls import admin_controls
from conekt.forms.admin.add_species import AddSpeciesForm... | conekt/controllers/admin/controls/species.py | import os
from tempfile import mkstemp
from flask import request, flash, url_for
from conekt.extensions import admin_required
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from conekt.controllers.admin.controls import admin_controls
from conekt.forms.admin.add_species import AddSpeciesForm... | 0.384334 | 0.101056 |
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser
from .utilities import get_timestamp_path, send_new_comment_notification
class AdvUser(AbstractUser):
is_activated = models.BooleanField(default=True, db_index=True,
... | main/models.py | from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser
from .utilities import get_timestamp_path, send_new_comment_notification
class AdvUser(AbstractUser):
is_activated = models.BooleanField(default=True, db_index=True,
... | 0.347094 | 0.111048 |
from pettingzoo.atari import basketball_pong_v3
from pettingzoo.atari import boxing_v2
from pettingzoo.atari import combat_plane_v2
from pettingzoo.atari import combat_tank_v2
from pettingzoo.atari import double_dunk_v3
from pettingzoo.atari import entombed_competitive_v3
from pettingzoo.atari import entombed_cooperati... | test/all_modules.py | from pettingzoo.atari import basketball_pong_v3
from pettingzoo.atari import boxing_v2
from pettingzoo.atari import combat_plane_v2
from pettingzoo.atari import combat_tank_v2
from pettingzoo.atari import double_dunk_v3
from pettingzoo.atari import entombed_competitive_v3
from pettingzoo.atari import entombed_cooperati... | 0.395368 | 0.661745 |
import numpy as np
import cv2
import scipy.fftpack as fp
from matplotlib import pyplot as plt
from copy import deepcopy
video = "1tagvideo.mp4"
Timage_ = "testudo.png"
# create video capture object
video_ = cv2.VideoCapture(video)
Timage=cv2.imread(Timage_)
def EdgeDetect(frame):
# To obtain cleaner segmentati... | TestudoSuperimpose.py | import numpy as np
import cv2
import scipy.fftpack as fp
from matplotlib import pyplot as plt
from copy import deepcopy
video = "1tagvideo.mp4"
Timage_ = "testudo.png"
# create video capture object
video_ = cv2.VideoCapture(video)
Timage=cv2.imread(Timage_)
def EdgeDetect(frame):
# To obtain cleaner segmentati... | 0.263315 | 0.401923 |
import wtforms
from wtforms import validators
from ..i18n import _
from . import BaseSecureForm, ChoicesManager
class AllocateIPsForm(BaseSecureForm):
"""Allocate IP Addresses form, used on IP Addresses landing page in modal dialog"""
domain = wtforms.SelectField(label=_(u'Scope'))
ipcount_error_msg = _(... | eucaconsole/forms/ipaddresses.py | import wtforms
from wtforms import validators
from ..i18n import _
from . import BaseSecureForm, ChoicesManager
class AllocateIPsForm(BaseSecureForm):
"""Allocate IP Addresses form, used on IP Addresses landing page in modal dialog"""
domain = wtforms.SelectField(label=_(u'Scope'))
ipcount_error_msg = _(... | 0.617282 | 0.182899 |
import logging
import sys
import click
import pkg_resources
import seslib
from seslib.exceptions import SesDevException
logger = logging.getLogger(__name__)
def sesdev_main():
try:
# pylint: disable=unexpected-keyword-arg
cli(prog_name='sesdev')
except SesDevException as ex:
logger.... | sesdev.py | import logging
import sys
import click
import pkg_resources
import seslib
from seslib.exceptions import SesDevException
logger = logging.getLogger(__name__)
def sesdev_main():
try:
# pylint: disable=unexpected-keyword-arg
cli(prog_name='sesdev')
except SesDevException as ex:
logger.... | 0.397588 | 0.082217 |
import csv
import os
import re
from datetime import datetime
from os.path import expanduser
from sys import exit
import ipaddress
from ipaddress import IPv4Network
from getpass import getpass
from netmiko import Netmiko
################# Variables to change dependant on environment #################
# Se... | zzz/asa_acl_report_v1.py |
import csv
import os
import re
from datetime import datetime
from os.path import expanduser
from sys import exit
import ipaddress
from ipaddress import IPv4Network
from getpass import getpass
from netmiko import Netmiko
################# Variables to change dependant on environment #################
# Se... | 0.201263 | 0.1335 |
import asyncio
import contextlib
import json
import jsonpickle
import os
import requests
import sys
import time
import traceback
import websockets
from a2ml.api.utils import fsclient, dict_dig
from a2ml.api.a2ml_credentials import A2MLCredentials
from a2ml.api.utils.file_uploader import FileUploader, OnelineProgressPe... | a2ml/api/utils/remote_runner.py | import asyncio
import contextlib
import json
import jsonpickle
import os
import requests
import sys
import time
import traceback
import websockets
from a2ml.api.utils import fsclient, dict_dig
from a2ml.api.a2ml_credentials import A2MLCredentials
from a2ml.api.utils.file_uploader import FileUploader, OnelineProgressPe... | 0.319865 | 0.053849 |
import time
import inspect
import uuid
import atexit
import asyncio
import warnings
import requests
from flask import current_app, request, jsonify, abort
from nacl.exceptions import BadSignatureError
from nacl.signing import VerifyKey
from flask_discord_interactions.models.autocomplete import AutocompleteResult
t... | flask_discord_interactions/discord.py | import time
import inspect
import uuid
import atexit
import asyncio
import warnings
import requests
from flask import current_app, request, jsonify, abort
from nacl.exceptions import BadSignatureError
from nacl.signing import VerifyKey
from flask_discord_interactions.models.autocomplete import AutocompleteResult
t... | 0.668772 | 0.112844 |
import os
import math
import platform
import pkg_resources
from datetime import datetime
from collections import namedtuple
from jinja2 import Environment, PackageLoader
PAGE_SIZE = 15
RANGE = 3
PADDING = 'unkown'
IGNORE_FIELDS = ['levelno', 'ts', 'processName', 'filename',
'levelname', 'message', '... | scrapekit/reporting/render.py | import os
import math
import platform
import pkg_resources
from datetime import datetime
from collections import namedtuple
from jinja2 import Environment, PackageLoader
PAGE_SIZE = 15
RANGE = 3
PADDING = 'unkown'
IGNORE_FIELDS = ['levelno', 'ts', 'processName', 'filename',
'levelname', 'message', '... | 0.156105 | 0.094052 |
from numba import cuda
import numpy as np
from math import tan, sqrt
KB = None
PX_KB = None
SECTOR_LEN = None
NUM_SECTOR = None
FLT_EPSILON = 0.000001
# ppx, ppy, fx, fy, coeffs[0...3]
PPX = 0.0
PPY = 0.0
FX = 0.0
FY = 0.0
#COEFFS = [0.0, 0.0, 0.0, 0.0]
def configure(kb, num_sector, intrinsics=None):
global KB, PX... | depth/rvl/rvl_cuda.py | from numba import cuda
import numpy as np
from math import tan, sqrt
KB = None
PX_KB = None
SECTOR_LEN = None
NUM_SECTOR = None
FLT_EPSILON = 0.000001
# ppx, ppy, fx, fy, coeffs[0...3]
PPX = 0.0
PPY = 0.0
FX = 0.0
FY = 0.0
#COEFFS = [0.0, 0.0, 0.0, 0.0]
def configure(kb, num_sector, intrinsics=None):
global KB, PX... | 0.280321 | 0.274734 |
import random
from typing import Dict, Tuple, List, Any, Optional, Union, Sequence, cast
import gym
import numpy as np
from allenact.base_abstractions.misc import RLStepResult
from allenact.base_abstractions.sensor import Sensor
from allenact.base_abstractions.task import Task
from allenact.utils.system import get_lo... | allenact_plugins/ithor_plugin/ithor_tasks.py | import random
from typing import Dict, Tuple, List, Any, Optional, Union, Sequence, cast
import gym
import numpy as np
from allenact.base_abstractions.misc import RLStepResult
from allenact.base_abstractions.sensor import Sensor
from allenact.base_abstractions.task import Task
from allenact.utils.system import get_lo... | 0.886402 | 0.456713 |
import numpy as np
import pandas as pd
import pytest
from gmpy2 import mpz, bit_mask
from rulelist.datastructure.data import Data
from rulelist.rulelistmodel.rulesetmodel import RuleSetModel
@pytest.fixture
def constant_parameters():
input_n_cutpoints = 5
input_discretization = "static"
input_target_data... | tests/rulelistmodel/test_rulelsetmodel.py | import numpy as np
import pandas as pd
import pytest
from gmpy2 import mpz, bit_mask
from rulelist.datastructure.data import Data
from rulelist.rulelistmodel.rulesetmodel import RuleSetModel
@pytest.fixture
def constant_parameters():
input_n_cutpoints = 5
input_discretization = "static"
input_target_data... | 0.606732 | 0.437103 |
import json
import yaml
import pandas as pd
import numpy as np
def testNanInList(test_list : list):
'''
test code for lists to check Nans
'''
if np.nan in test_list:
print('list contains nans,cant process\nplease update the config')
return
else:
print('Nan test ... | tests/test_code.py | import json
import yaml
import pandas as pd
import numpy as np
def testNanInList(test_list : list):
'''
test code for lists to check Nans
'''
if np.nan in test_list:
print('list contains nans,cant process\nplease update the config')
return
else:
print('Nan test ... | 0.095371 | 0.265434 |