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 fdb import fdb.tuple fdb.api_version(16) def nextStopToNone(gen): try: return gen.next() except StopIteration: return None class FdbSet (object): def __init__(self, path): self._path = path @fdb.transactional def length(self, tr): setLength = 0 f...
layers/containers/set.py
import fdb import fdb.tuple fdb.api_version(16) def nextStopToNone(gen): try: return gen.next() except StopIteration: return None class FdbSet (object): def __init__(self, path): self._path = path @fdb.transactional def length(self, tr): setLength = 0 f...
0.514156
0.157363
import os import numpy as np from keras import backend as K __all__ = [ 'flux2mag', 'plot_samples_one_hot', 'save_model', 'jaccard_coef' ] # TF order (n_entries, shape_0, shape_1, n_channels) AXIS = [1, 2, 3] # all but n_entries # Epsilon EPS = 1e-12 def flux2mag(flux, zeropoint): return -2.5 ...
coindeblend/utilities.py
import os import numpy as np from keras import backend as K __all__ = [ 'flux2mag', 'plot_samples_one_hot', 'save_model', 'jaccard_coef' ] # TF order (n_entries, shape_0, shape_1, n_channels) AXIS = [1, 2, 3] # all but n_entries # Epsilon EPS = 1e-12 def flux2mag(flux, zeropoint): return -2.5 ...
0.779532
0.500366
from mock_trace import MockTrace as mt import importlib from examples.fibonacci import slow_fib def test_basic(): assert slow_fib(-1) == 0 assert slow_fib(0) == 0 assert slow_fib(1) == 1 assert slow_fib(2) == 1 assert slow_fib(3) == 2 assert slow_fib(4) == 3 assert slow_fib(5) == 5 as...
tests/test_fibonacci.py
from mock_trace import MockTrace as mt import importlib from examples.fibonacci import slow_fib def test_basic(): assert slow_fib(-1) == 0 assert slow_fib(0) == 0 assert slow_fib(1) == 1 assert slow_fib(2) == 1 assert slow_fib(3) == 2 assert slow_fib(4) == 3 assert slow_fib(5) == 5 as...
0.713432
0.826607
import socket import threading from queue import Queue import subprocess import sys import os # color class class color: blue = '\033[94m' green = '\033[92m' orange = '\033[93m' underline = '\033[4m' reset = '\033[0m' # first banner def banner(): os.system('clear') print(f'{color.blue}--...
Lightscan.py
import socket import threading from queue import Queue import subprocess import sys import os # color class class color: blue = '\033[94m' green = '\033[92m' orange = '\033[93m' underline = '\033[4m' reset = '\033[0m' # first banner def banner(): os.system('clear') print(f'{color.blue}--...
0.218419
0.067301
import sys from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, \ QPushButton,QMessageBox,QDesktopWidget, QLabel from PyQt5.QtGui import QFont,QIcon,QPixmap,QImage from PyQt5.QtCore import QTimer import cv2 import picture as pic import classify as cf import numpy as np class myWindow(QWidget):...
myGUI.py
import sys from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, \ QPushButton,QMessageBox,QDesktopWidget, QLabel from PyQt5.QtGui import QFont,QIcon,QPixmap,QImage from PyQt5.QtCore import QTimer import cv2 import picture as pic import classify as cf import numpy as np class myWindow(QWidget):...
0.161386
0.106087
import numpy as np import nicenquickplotlib as nq x = [] x.append(np.linspace(0,6)) x.append(np.linspace(0,5)) x.append(np.linspace(0,4)) # Testing for data input combinations ---- nq.plot(x[0], title="data input x1") nq.plot([x[0], x[1]], title="data input [x[0], x[1]]") nq.plot(x[0], np.sin(x[0]), title="data inpu...
test_all_all.py
import numpy as np import nicenquickplotlib as nq x = [] x.append(np.linspace(0,6)) x.append(np.linspace(0,5)) x.append(np.linspace(0,4)) # Testing for data input combinations ---- nq.plot(x[0], title="data input x1") nq.plot([x[0], x[1]], title="data input [x[0], x[1]]") nq.plot(x[0], np.sin(x[0]), title="data inpu...
0.508788
0.71721
from graphql.validation import ScalarLeafsRule from graphql.validation.rules.scalar_leafs import ( no_subselection_allowed_message, required_subselection_message) from .harness import expect_fails_rule, expect_passes_rule def no_scalar_subselection(field, type_, line, column): return { 'message': no_...
tests/validation/test_scalar_leafs.py
from graphql.validation import ScalarLeafsRule from graphql.validation.rules.scalar_leafs import ( no_subselection_allowed_message, required_subselection_message) from .harness import expect_fails_rule, expect_passes_rule def no_scalar_subselection(field, type_, line, column): return { 'message': no_...
0.909542
0.406214
import shutil import requests import tempfile import string import imghdr import random from pyquery import PyQuery as pq from ebooklib import epub class RequestError(Exception): def __init__(self, message, req): super().__init__( f'{message} [Status: {req.status_code} because {req.reason}, u...
wte/src/util.py
import shutil import requests import tempfile import string import imghdr import random from pyquery import PyQuery as pq from ebooklib import epub class RequestError(Exception): def __init__(self, message, req): super().__init__( f'{message} [Status: {req.status_code} because {req.reason}, u...
0.500244
0.169097
from datetime import timedelta from typing import Any from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState from strawberry.schema import BaseSchema from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL from strawberry.subscriptions.protocols.graphql_transport_ws.handlers import...
strawberry/asgi/handlers/graphql_transport_ws_handler.py
from datetime import timedelta from typing import Any from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState from strawberry.schema import BaseSchema from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL from strawberry.subscriptions.protocols.graphql_transport_ws.handlers import...
0.683736
0.077973
from argparse import ArgumentParser def none_or_default(x, default): return x if x is not None else default class HyperParameters(): def parse(self, unknown_arg_ok=False): parser = ArgumentParser() # Enable torch.backends.cudnn.benchmark -- Faster in some cases, test in your own environment ...
util/hyper_para.py
from argparse import ArgumentParser def none_or_default(x, default): return x if x is not None else default class HyperParameters(): def parse(self, unknown_arg_ok=False): parser = ArgumentParser() # Enable torch.backends.cudnn.benchmark -- Faster in some cases, test in your own environment ...
0.680454
0.086093
ARCH_X86 = 32 ARCH_AMD64 = 64 PAGE_SIZE = 0x1000 BITS_32 = 32 BITS_64 = 64 LSTAR = 0xC0000082 X86_REG_CS = 1001 X86_REG_DS = 1002 X86_REG_EAX = 1003 X86_REG_EBP = 1004 X86_REG_EBX = 1005 X86_REG_ECX = 1006 X86_REG_EDI = 1007 X86_REG_EDX = 1008 X86_REG_EFLAGS = 1009 X86_REG_EIP = 1010 X86_REG_EIZ = 1011 X86_REG_ESI =...
speakeasy/winenv/arch.py
ARCH_X86 = 32 ARCH_AMD64 = 64 PAGE_SIZE = 0x1000 BITS_32 = 32 BITS_64 = 64 LSTAR = 0xC0000082 X86_REG_CS = 1001 X86_REG_DS = 1002 X86_REG_EAX = 1003 X86_REG_EBP = 1004 X86_REG_EBX = 1005 X86_REG_ECX = 1006 X86_REG_EDI = 1007 X86_REG_EDX = 1008 X86_REG_EFLAGS = 1009 X86_REG_EIP = 1010 X86_REG_EIZ = 1011 X86_REG_ESI =...
0.229794
0.180883
import argparse, os import tensorflow as tf import numpy as np from model.datagenerator.input_fn import read_dataset from model.datagenerator.input_fn import get_labels_for_ss from model.model_fn import model_fn from model.utils import Params from validation_function import reli parser = argparse.ArgumentParser() pa...
similarity_search.py
import argparse, os import tensorflow as tf import numpy as np from model.datagenerator.input_fn import read_dataset from model.datagenerator.input_fn import get_labels_for_ss from model.model_fn import model_fn from model.utils import Params from validation_function import reli parser = argparse.ArgumentParser() pa...
0.748628
0.185246
import datetime def Char(length, is_strict=True): # pylint: disable=invalid-name """represent a char string""" class _char: # pylint: disable=too-few-public-methods @classmethod def parse(cls, value): """normalize a char""" value = String.parse(value) if...
aiodb/model/types.py
import datetime def Char(length, is_strict=True): # pylint: disable=invalid-name """represent a char string""" class _char: # pylint: disable=too-few-public-methods @classmethod def parse(cls, value): """normalize a char""" value = String.parse(value) if...
0.777004
0.345823
import time import requests from time import sleep from mdsanima_dev.colors import get_complex_color def read_file(file_path: str) -> str: """ Function reads the file and splits it into separate lines. :param file_path: file path to read and split :type file_path: str :return: list of lines in th...
src/mdsanima_dev/utils/tools.py
import time import requests from time import sleep from mdsanima_dev.colors import get_complex_color def read_file(file_path: str) -> str: """ Function reads the file and splits it into separate lines. :param file_path: file path to read and split :type file_path: str :return: list of lines in th...
0.731155
0.425247
import os from django.core.urlresolvers import reverse_lazy BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in pr...
Socialist/settings.py
import os from django.core.urlresolvers import reverse_lazy BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in pr...
0.327346
0.056418
"exec" "`dirname $0`/opt/miniconda2/bin/python" "$0" "$@" import argparse import os import sys import logging import utils import tempfile, shutil LOGGER = None def process(args): ''' main :param args: :return: ''' # Setup logging FORMAT = '%(levelname)s %(asctime)-15s %(name)-20s %(messag...
combine_vcf.py
"exec" "`dirname $0`/opt/miniconda2/bin/python" "$0" "$@" import argparse import os import sys import logging import utils import tempfile, shutil LOGGER = None def process(args): ''' main :param args: :return: ''' # Setup logging FORMAT = '%(levelname)s %(asctime)-15s %(name)-20s %(messag...
0.235196
0.117319
code_for_A = r""" for x in [1,2,3]: print("x to", x, end=" ") print(x**2) """ code_for_B = r""" for x in range(3): print("x to", x, end=" ") print(x**2) """ code_for_C = r""" for x in range(2, 5): print("x to", x, end=" ") print(x**2) """ code_for_D = r""" for x in range(1, 9, 2): ...
LPES-video/02.03-python-petle_warunki/02.03.01-for.py
code_for_A = r""" for x in [1,2,3]: print("x to", x, end=" ") print(x**2) """ code_for_B = r""" for x in range(3): print("x to", x, end=" ") print(x**2) """ code_for_C = r""" for x in range(2, 5): print("x to", x, end=" ") print(x**2) """ code_for_D = r""" for x in range(1, 9, 2): ...
0.149842
0.450541
import logging import os import sys import time sys.path.append(os.path.join(os.path.dirname(__file__), "../")) from common import constants sys.path.append(os.path.join(os.path.dirname(__file__), "../../../AppServer")) from google.appengine.api import urlfetch from __init__ import ApiTestBase class TestUrlfetch(A...
Apps/sensor/api_tests/urlfetch.py
import logging import os import sys import time sys.path.append(os.path.join(os.path.dirname(__file__), "../")) from common import constants sys.path.append(os.path.join(os.path.dirname(__file__), "../../../AppServer")) from google.appengine.api import urlfetch from __init__ import ApiTestBase class TestUrlfetch(A...
0.52902
0.22863
from rdflib.store import Store from rdflib import Graph, ConjunctiveGraph import threading destructiveOpLocks = { 'add': None, 'remove': None, } class AuditableStore(Store): def __init__(self, store): self.store = store self.context_aware = store.context_aware # NOTE: this store c...
rdflib/plugins/stores/auditable.py
from rdflib.store import Store from rdflib import Graph, ConjunctiveGraph import threading destructiveOpLocks = { 'add': None, 'remove': None, } class AuditableStore(Store): def __init__(self, store): self.store = store self.context_aware = store.context_aware # NOTE: this store c...
0.557845
0.080213
import os import glob import sys import struct import subprocess from struct import pack, unpack class UndervoltSystem(object): def __init__(self): pass def applyUndervolt(self, mv, plane): """ Apply undervolt to system MSR for Intel-based systems :return: int error: error cod...
thinkpad_tools_assets/classes.py
import os import glob import sys import struct import subprocess from struct import pack, unpack class UndervoltSystem(object): def __init__(self): pass def applyUndervolt(self, mv, plane): """ Apply undervolt to system MSR for Intel-based systems :return: int error: error cod...
0.327561
0.112308
import copy from os import path from typing import Any, Callable, List, Optional import yaml from colored import attr, fg from opta.constants import init_template_path def load_template(template_type: str, template_name: str) -> dict: file_path = path.join(init_template_path, template_type, f"{template_name}.ya...
opta/commands/init_templates/template.py
import copy from os import path from typing import Any, Callable, List, Optional import yaml from colored import attr, fg from opta.constants import init_template_path def load_template(template_type: str, template_name: str) -> dict: file_path = path.join(init_template_path, template_type, f"{template_name}.ya...
0.769946
0.231028
import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.nn.utils import spectral_norm class LayerNorm(nn.Module): def __init__(self, num_features, eps=1e-5, affine=True): super(LayerNorm, self).__init__() self.num_features = num_features self.eps = e...
adn/networks/blocks.py
import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.nn.utils import spectral_norm class LayerNorm(nn.Module): def __init__(self, num_features, eps=1e-5, affine=True): super(LayerNorm, self).__init__() self.num_features = num_features self.eps = e...
0.960869
0.575051
# Appengine users: https://developers.google.com/appengine/docs/python/sockets/#making_httplib_use_sockets import json import logging from math import inf from platform import python_version import ssl from threading import Thread from time import sleep import requests from requests_oauthlib import OAuth1 import url...
tweepy/streaming.py
# Appengine users: https://developers.google.com/appengine/docs/python/sockets/#making_httplib_use_sockets import json import logging from math import inf from platform import python_version import ssl from threading import Thread from time import sleep import requests from requests_oauthlib import OAuth1 import url...
0.708414
0.135661
import json import mock from dashboard.pinpoint.handlers import migrate from dashboard.pinpoint.models import job from dashboard.pinpoint.models import job_state from dashboard.pinpoint import test class MigrateTest(test.TestCase): def setUp(self): super(MigrateTest, self).setUp() patcher = mock.patch....
dashboard/dashboard/pinpoint/handlers/migrate_test.py
import json import mock from dashboard.pinpoint.handlers import migrate from dashboard.pinpoint.models import job from dashboard.pinpoint.models import job_state from dashboard.pinpoint import test class MigrateTest(test.TestCase): def setUp(self): super(MigrateTest, self).setUp() patcher = mock.patch....
0.587588
0.297151
from __future__ import absolute_import, division, print_function __all__ = [ 'MY_CLSIM_TABLE_KEYS', 'CLSIM_TABLE_FNAME_PROTO', 'CLSIM_TABLE_FNAME_RE', 'CLSIM_TABLE_METANAME_PROTO', 'CLSIM_TABLE_METANAME_RE', 'CLSIM_TABLE_TILE_FNAME_PROTO', 'CLSIM_TABLE_TILE_FNAME_RE', 'CLSIM_TABLE_TILE_...
retro/tables/clsim_tables.py
from __future__ import absolute_import, division, print_function __all__ = [ 'MY_CLSIM_TABLE_KEYS', 'CLSIM_TABLE_FNAME_PROTO', 'CLSIM_TABLE_FNAME_RE', 'CLSIM_TABLE_METANAME_PROTO', 'CLSIM_TABLE_METANAME_RE', 'CLSIM_TABLE_TILE_FNAME_PROTO', 'CLSIM_TABLE_TILE_FNAME_RE', 'CLSIM_TABLE_TILE_...
0.600305
0.160398
import torch from torch.utils.data import Subset from misc import google_cloud import numpy as np import math import shutil import os class PolyOptimizer(torch.optim.SGD): def __init__(self, params, lr, weight_decay, max_step, momentum=0.9): super().__init__(params, lr, weight_decay) self.globa...
misc/torchutils.py
import torch from torch.utils.data import Subset from misc import google_cloud import numpy as np import math import shutil import os class PolyOptimizer(torch.optim.SGD): def __init__(self, params, lr, weight_decay, max_step, momentum=0.9): super().__init__(params, lr, weight_decay) self.globa...
0.480479
0.22515
from tempest.scenario.data_processing.client_tests import base from tempest import test from tempest_lib.common.utils import data_utils class NodeGroupTemplateTest(base.BaseDataProcessingTest): def _check_create_node_group_template(self): template_name = data_utils.rand_name('sahara-ng-template') ...
sahara/tests/tempest/scenario/data_processing/client_tests/test_node_group_templates.py
from tempest.scenario.data_processing.client_tests import base from tempest import test from tempest_lib.common.utils import data_utils class NodeGroupTemplateTest(base.BaseDataProcessingTest): def _check_create_node_group_template(self): template_name = data_utils.rand_name('sahara-ng-template') ...
0.457621
0.264821
import numpy as np import SimpleITK as sitk def reverse_axes(image): return np.transpose(image, tuple(reversed(range(image.ndim)))) def read_image(imagefile): image = sitk.ReadImage(imagefile) data = reverse_axes(sitk.GetArrayFromImage(image)) # switch from zyx to xyz header = { 'spacing': ...
nnunet/dataset_conversion/Task056_Verse_normalize_orientation.py
import numpy as np import SimpleITK as sitk def reverse_axes(image): return np.transpose(image, tuple(reversed(range(image.ndim)))) def read_image(imagefile): image = sitk.ReadImage(imagefile) data = reverse_axes(sitk.GetArrayFromImage(image)) # switch from zyx to xyz header = { 'spacing': ...
0.776072
0.641731
from django.db.models import Q import datetime import json from xml.etree import ElementTree from .utils import date_transfer from .abstract import AbstractApi from apps.dailytrans.models import DailyTran class Api(AbstractApi): """ Note: This Api Access Grand Total Trans Data Across App Crop, Fruits, Flower ...
src/apps/dailytrans/builders/amis.py
from django.db.models import Q import datetime import json from xml.etree import ElementTree from .utils import date_transfer from .abstract import AbstractApi from apps.dailytrans.models import DailyTran class Api(AbstractApi): """ Note: This Api Access Grand Total Trans Data Across App Crop, Fruits, Flower ...
0.501221
0.127898
from __future__ import unicode_literals from django.db import models from django.test import TestCase from wagtail.wagtailcore.models import Page from wagtail_events import abstract_models class TestAbstractPaginatedIndex(TestCase): """Tests for the AbstractPaginatedIndex model.""" def setUp(self): ...
tests/test_abstract_models.py
from __future__ import unicode_literals from django.db import models from django.test import TestCase from wagtail.wagtailcore.models import Page from wagtail_events import abstract_models class TestAbstractPaginatedIndex(TestCase): """Tests for the AbstractPaginatedIndex model.""" def setUp(self): ...
0.849097
0.324476
import errno import logging import os import uuid import networkx as nx import capacity.gtfs_reader as gtfs_reader import capacity.station as station import capacity.stats as stats import capacity.train as train import capacity.utils as utils class TransitNetwork(object): """ The master container class for the ...
capacity/network.py
import errno import logging import os import uuid import networkx as nx import capacity.gtfs_reader as gtfs_reader import capacity.station as station import capacity.stats as stats import capacity.train as train import capacity.utils as utils class TransitNetwork(object): """ The master container class for the ...
0.384681
0.294139
import datetime import logging from typing import Union, Dict, Optional from conflowgen.application.repositories.container_flow_generation_properties_repository import \ ContainerFlowGenerationPropertiesRepository from conflowgen.flow_generator.container_flow_generation_service import \ ContainerFlowGeneration...
conflowgen/api/container_flow_generation_manager.py
import datetime import logging from typing import Union, Dict, Optional from conflowgen.application.repositories.container_flow_generation_properties_repository import \ ContainerFlowGenerationPropertiesRepository from conflowgen.flow_generator.container_flow_generation_service import \ ContainerFlowGeneration...
0.911402
0.245791
from django.core.exceptions import ValidationError as DjangoValidationError from django.urls import reverse from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import ValidationError from rest_framework.settings import api_settings from salesman....
salesman/orders/serializers.py
from django.core.exceptions import ValidationError as DjangoValidationError from django.urls import reverse from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import ValidationError from rest_framework.settings import api_settings from salesman....
0.640299
0.14137
from __future__ import print_function, absolute_import from operator import add, mul import numpy as np try: import bogota.datapool from bogota.utils import action_profiles except: 'Bogota import failed...' class GameData(object): def __init__(self, filename=None, normalize=1.): # data = { (s...
deepch/data.py
from __future__ import print_function, absolute_import from operator import add, mul import numpy as np try: import bogota.datapool from bogota.utils import action_profiles except: 'Bogota import failed...' class GameData(object): def __init__(self, filename=None, normalize=1.): # data = { (s...
0.601008
0.307559
from typing import Any, Dict import pytest from werkzeug.exceptions import MethodNotAllowed, NotFound from localstack.http import Request, Response, Router from localstack.http.dispatcher import handler_dispatcher, resource_dispatcher class TestResourceDispatcher: def test_dispatch_to_correct_function(self): ...
tests/unit/http_/test_dispatcher.py
from typing import Any, Dict import pytest from werkzeug.exceptions import MethodNotAllowed, NotFound from localstack.http import Request, Response, Router from localstack.http.dispatcher import handler_dispatcher, resource_dispatcher class TestResourceDispatcher: def test_dispatch_to_correct_function(self): ...
0.71602
0.354852
import tempfile import os import urllib.request import shutil from botbuilder.core import MessageFactory from botbuilder.dialogs import ( ComponentDialog, DialogTurnResult, DialogTurnStatus, WaterfallDialog, WaterfallStepContext, ConfirmPrompt, ) from botbuilder.dialogs.prompts import PromptOpt...
Bots/Python/Skills/CodeFirst/WaterfallSkillBot/dialogs/file_upload/file_upload_dialog.py
import tempfile import os import urllib.request import shutil from botbuilder.core import MessageFactory from botbuilder.dialogs import ( ComponentDialog, DialogTurnResult, DialogTurnStatus, WaterfallDialog, WaterfallStepContext, ConfirmPrompt, ) from botbuilder.dialogs.prompts import PromptOpt...
0.344003
0.063395
import sys import torch import numpy as np import torch.nn as nn from common_utils import TestCase, run_tests from common_device_type import dtypes, instantiate_device_type_tests from util_test import create_common_tensor import os os.environ["BMMV2_ENABLE"] = "1" class TestMatMulByBmmV2(TestCase): def op_exec(se...
test/test_npu/test_network_ops/test_matmul_by_bmm_v2.py
import sys import torch import numpy as np import torch.nn as nn from common_utils import TestCase, run_tests from common_device_type import dtypes, instantiate_device_type_tests from util_test import create_common_tensor import os os.environ["BMMV2_ENABLE"] = "1" class TestMatMulByBmmV2(TestCase): def op_exec(se...
0.416797
0.57332
import sys from unittest import TestCase import unittest import os from importlib import reload from mock import Mock, call from mockextras import stub sys.path = [os.path.abspath(os.path.join('..', os.pardir))] + sys.path from digesters.confluence.confluence_notification_digester import ConfluenceNotificationDigeste...
digesters/confluence/test_confluence_notifications.py
import sys from unittest import TestCase import unittest import os from importlib import reload from mock import Mock, call from mockextras import stub sys.path = [os.path.abspath(os.path.join('..', os.pardir))] + sys.path from digesters.confluence.confluence_notification_digester import ConfluenceNotificationDigeste...
0.38168
0.242839
import matplotlib.pyplot as plt import numpy as np path = np.loadtxt(open("../map/finegrained_map.csv","rb"),delimiter=" ",skiprows=0) path_left = np.loadtxt(open("../map/leftlane_map.csv","rb"),delimiter=" ",skiprows=0) path_mid = np.loadtxt(open("../map/midlane_map.csv","rb"),delimiter=" ",skiprows=0) path_right =...
src/plotpath.py
import matplotlib.pyplot as plt import numpy as np path = np.loadtxt(open("../map/finegrained_map.csv","rb"),delimiter=" ",skiprows=0) path_left = np.loadtxt(open("../map/leftlane_map.csv","rb"),delimiter=" ",skiprows=0) path_mid = np.loadtxt(open("../map/midlane_map.csv","rb"),delimiter=" ",skiprows=0) path_right =...
0.227899
0.332907
import factory import uuid import numpy as np from pathlib import Path from zuds import DBSession, ScienceImage, Source from tempfile import mkdtemp datadir = Path(__file__).parent / 'data' TMP_DIR = mkdtemp() class BaseMeta: sqlalchemy_session = DBSession sqlalchemy_session_persistence = 'commit' def ran...
zuds/tests/fixtures.py
import factory import uuid import numpy as np from pathlib import Path from zuds import DBSession, ScienceImage, Source from tempfile import mkdtemp datadir = Path(__file__).parent / 'data' TMP_DIR = mkdtemp() class BaseMeta: sqlalchemy_session = DBSession sqlalchemy_session_persistence = 'commit' def ran...
0.229449
0.274774
import numpy as np import copy from pyorderedfuzzy.ofnumbers import ofnumber from pyorderedfuzzy.ofnumbers.ofnumber import OFNumber import matplotlib.pyplot as plt __author__ = "amarszalek" # ctype:: # linear, gauss, empirical # data:: # 'price': bid price # 'volume': # 'spread': ask - bid # params:: # 'wtype': '...
pyorderedfuzzy/ofcandles/ofcandle.py
import numpy as np import copy from pyorderedfuzzy.ofnumbers import ofnumber from pyorderedfuzzy.ofnumbers.ofnumber import OFNumber import matplotlib.pyplot as plt __author__ = "amarszalek" # ctype:: # linear, gauss, empirical # data:: # 'price': bid price # 'volume': # 'spread': ask - bid # params:: # 'wtype': '...
0.61682
0.421909
import os import os.path import json import logging from piecrust.tasks.base import TaskRunner logger = logging.getLogger(__name__) class InvalidMentionTargetError(Exception): pass class SourceDoesntLinkToTargetError(Exception): pass class DuplicateMentionError(Exception): pass class MentionTaskRu...
piecrust/tasks/mentions.py
import os import os.path import json import logging from piecrust.tasks.base import TaskRunner logger = logging.getLogger(__name__) class InvalidMentionTargetError(Exception): pass class SourceDoesntLinkToTargetError(Exception): pass class DuplicateMentionError(Exception): pass class MentionTaskRu...
0.362405
0.100702
import torch from torch.autograd import Function from torch.autograd import Variable from torch.nn.modules.module import Module import math import sys import os import numpy as np import _FullAtomModel def convertStringList(stringList): '''Converts list of strings to 0-terminated byte tensor''' maxlen = 0 for stri...
TorchProteinLibrary/FullAtomModel/Angles2Coords/Angles2Coords.py
import torch from torch.autograd import Function from torch.autograd import Variable from torch.nn.modules.module import Module import math import sys import os import numpy as np import _FullAtomModel def convertStringList(stringList): '''Converts list of strings to 0-terminated byte tensor''' maxlen = 0 for stri...
0.542863
0.350088
import tqdm import math def compute_basic_stats(recommendations, user_labels): """ recommendations: a dictionary for recommendations where keys are user_id and values are list of recommended items user_labels: a dictionary from username to items a user has actually seen during test period return: no o...
src/metrics.py
import tqdm import math def compute_basic_stats(recommendations, user_labels): """ recommendations: a dictionary for recommendations where keys are user_id and values are list of recommended items user_labels: a dictionary from username to items a user has actually seen during test period return: no o...
0.453988
0.389314
from dataclasses import InitVar, dataclass, field from typing import Optional from mite.scenario import StopScenario @dataclass class _VolumeModel: duration: int def _volume(self, start, end): raise NotImplementedError def __call__(self, start, end): if start > self.duration: ...
mite/volume_model.py
from dataclasses import InitVar, dataclass, field from typing import Optional from mite.scenario import StopScenario @dataclass class _VolumeModel: duration: int def _volume(self, start, end): raise NotImplementedError def __call__(self, start, end): if start > self.duration: ...
0.769946
0.257222
from typing import List, Tuple from clustering_algorithms.k_medoids_algorithm import KMedoidsAlgorithm from clustering_algorithms.point import Point class PAM(KMedoidsAlgorithm): def __init__( self, points: List[Point], clusters_num: int = 2, labels: List["str"] = None ): super().__init__(poi...
src/clustering_algorithms/pam.py
from typing import List, Tuple from clustering_algorithms.k_medoids_algorithm import KMedoidsAlgorithm from clustering_algorithms.point import Point class PAM(KMedoidsAlgorithm): def __init__( self, points: List[Point], clusters_num: int = 2, labels: List["str"] = None ): super().__init__(poi...
0.928813
0.693459
# Copyright: (c) 2019, <NAME> (<EMAIL>) # Copyright: (c) 2015, <NAME> (<EMAIL>) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
ansible/venv/lib/python2.7/site-packages/ansible/modules/source_control/gitlab_user.py
# Copyright: (c) 2019, <NAME> (<EMAIL>) # Copyright: (c) 2015, <NAME> (<EMAIL>) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
0.715026
0.123868
from optparse import OptionParser import config from utils import feed_utils, args_utils, ssh_utils, run_utils, file_utils from api import job def test_copy_nels_to_sbi(nels_id): feed_utils.heading("copy use case nels to sbi. nels_id: %s" % nels_id) credentail = ssh_utils.get_ssh_credentials(nels_id) ...
nels-test-integration/test_copy_nels_to_sbi.py
from optparse import OptionParser import config from utils import feed_utils, args_utils, ssh_utils, run_utils, file_utils from api import job def test_copy_nels_to_sbi(nels_id): feed_utils.heading("copy use case nels to sbi. nels_id: %s" % nels_id) credentail = ssh_utils.get_ssh_credentials(nels_id) ...
0.378459
0.11474
import json from enum import Enum from stix_shifter_utils.modules.base.stix_transmission.base_status_connector import BaseStatusConnector from stix_shifter_utils.modules.base.stix_transmission.base_status_connector import Status from stix_shifter_utils.utils.error_response import ErrorResponder from stix_shifter_utils...
stix_shifter_modules/cbcloud/stix_transmission/status_connector.py
import json from enum import Enum from stix_shifter_utils.modules.base.stix_transmission.base_status_connector import BaseStatusConnector from stix_shifter_utils.modules.base.stix_transmission.base_status_connector import Status from stix_shifter_utils.utils.error_response import ErrorResponder from stix_shifter_utils...
0.385722
0.047096
from LSD.RMQ import RangeQuery from LSD.detecter.outvalues import out_child2, out_parent2 def super_bubble_brankovice(c, toposort, reporter): """Find all superbubbles in a DAG after Brankovice at all.""" ord_id = toposort.index def report(s, t): reporter.rep(toposort[ord_id(s): ord_id(t) + 1]...
LSD/detecter/brankovic.py
from LSD.RMQ import RangeQuery from LSD.detecter.outvalues import out_child2, out_parent2 def super_bubble_brankovice(c, toposort, reporter): """Find all superbubbles in a DAG after Brankovice at all.""" ord_id = toposort.index def report(s, t): reporter.rep(toposort[ord_id(s): ord_id(t) + 1]...
0.373762
0.317611
import django.core.validators from django.db import migrations, models import jobs.validators class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='About', fields=[ ('id', models.AutoFie...
jobs/migrations/0001_initial.py
import django.core.validators from django.db import migrations, models import jobs.validators class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='About', fields=[ ('id', models.AutoFie...
0.441432
0.189821
import os import subprocess import tkinter as tk from tkinter import filedialog, messagebox PADDING = 5 class GUI(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title('kabsa Compiler') self.iconbitmap("./assets/icon.ico") self.input_filename = tk.StringVar() self.o...
gui/gui.py
import os import subprocess import tkinter as tk from tkinter import filedialog, messagebox PADDING = 5 class GUI(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title('kabsa Compiler') self.iconbitmap("./assets/icon.ico") self.input_filename = tk.StringVar() self.o...
0.377541
0.063861
import heapq import sys from collections import deque si = sys.stdin.readline dy = [-1, 1, 0, 0] dx = [0, 0, -1, 1] def bfs(y, x): que = deque() visited = [[0 for _ in range(n)] for _ in range(n)] que.append((y, x, 0)) visited[y][x] = True q = [] while que: y, x, cnt = que.popleft() ...
BOJ/review/boj_19238.py
import heapq import sys from collections import deque si = sys.stdin.readline dy = [-1, 1, 0, 0] dx = [0, 0, -1, 1] def bfs(y, x): que = deque() visited = [[0 for _ in range(n)] for _ in range(n)] que.append((y, x, 0)) visited[y][x] = True q = [] while que: y, x, cnt = que.popleft() ...
0.159479
0.272541
import pandas as pd import numpy as np import os import json from ..utils.database import dbutils def get_dwell_time_df(db_connection, table_name): query = """ SELECT cust_id, prev_cust_id, tower_id, prev_tower_id, dwell_time, near_airport, ...
src/output/cdr_fountain.py
import pandas as pd import numpy as np import os import json from ..utils.database import dbutils def get_dwell_time_df(db_connection, table_name): query = """ SELECT cust_id, prev_cust_id, tower_id, prev_tower_id, dwell_time, near_airport, ...
0.464902
0.213459
from os.path import dirname, realpath, join from pathlib import Path class Config: BASE_DIR = Path(realpath(join(dirname(realpath(__file__)), ".."))) DATA_DIR = Path(join(BASE_DIR, "data")) RUNS_DIR = Path(join(BASE_DIR, "runs")) GLOVE_DIR = Path(join(DATA_DIR, "glove.6b")) GLOVE_FILE = Path(join(G...
src/config.py
from os.path import dirname, realpath, join from pathlib import Path class Config: BASE_DIR = Path(realpath(join(dirname(realpath(__file__)), ".."))) DATA_DIR = Path(join(BASE_DIR, "data")) RUNS_DIR = Path(join(BASE_DIR, "runs")) GLOVE_DIR = Path(join(DATA_DIR, "glove.6b")) GLOVE_FILE = Path(join(G...
0.238639
0.214136
import SMBus class BME280: def __init__(self, VID=0x04D8, PID=0x00DD, devnum=0): self.bus = SMBus.SMBus(VID, PID, devnum) self.i2c_address = 0x76 self.__dig_temp = [] self.__dig_pressure = [] self.__dig_hum = [] # Public values self.temperature = 0.0 ...
ros/env_measurement_module/src/env_measurement_module/BME280.py
import SMBus class BME280: def __init__(self, VID=0x04D8, PID=0x00DD, devnum=0): self.bus = SMBus.SMBus(VID, PID, devnum) self.i2c_address = 0x76 self.__dig_temp = [] self.__dig_pressure = [] self.__dig_hum = [] # Public values self.temperature = 0.0 ...
0.32306
0.263576
from __future__ import print_function from color import Color from mock import MagicMock, patch from effects import * import os import threading import time try: from neopixel import Adafruit_NeoPixel as Adafruit_Neopixel except ImportError: print("[Neopixel][error] An error occurred importing 'neopixel.Adafru...
neopixelcontroller/lib/controller.py
from __future__ import print_function from color import Color from mock import MagicMock, patch from effects import * import os import threading import time try: from neopixel import Adafruit_NeoPixel as Adafruit_Neopixel except ImportError: print("[Neopixel][error] An error occurred importing 'neopixel.Adafru...
0.616936
0.273914
import torch.nn as nn import torch from torch.nn import functional as F from torchvision import models class ContextualModule(nn.Module): def __init__(self, features, out_features=512, sizes=(1, 2, 3, 6)): super(ContextualModule, self).__init__() self.scales = [] self.scales = nn.ModuleList...
models/mobile/contextual_layer.py
import torch.nn as nn import torch from torch.nn import functional as F from torchvision import models class ContextualModule(nn.Module): def __init__(self, features, out_features=512, sizes=(1, 2, 3, 6)): super(ContextualModule, self).__init__() self.scales = [] self.scales = nn.ModuleList...
0.915242
0.52476
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['FileSystemArgs', 'FileSystem'] @pulumi.input_type class FileSystemArgs: def __init__(__self__, *, protocol_type: pulumi.Input[str], ...
sdk/python/pulumi_alicloud/nas/file_system.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['FileSystemArgs', 'FileSystem'] @pulumi.input_type class FileSystemArgs: def __init__(__self__, *, protocol_type: pulumi.Input[str], ...
0.885885
0.164382
import sys import psycopg2 import serial import time db = "donet" server = "127.0.0.1" user = "donet" password = "<PASSWORD>" retries = 10 CMD_PING = 0x01 CMD_PWM_ONE = 0x02 CMD_PWM_THREE = 0x03 try: con = psycopg2.connect(database=db,host=server,user=user,password=password) except: print("Unable to connect to ...
worker.py
import sys import psycopg2 import serial import time db = "donet" server = "127.0.0.1" user = "donet" password = "<PASSWORD>" retries = 10 CMD_PING = 0x01 CMD_PWM_ONE = 0x02 CMD_PWM_THREE = 0x03 try: con = psycopg2.connect(database=db,host=server,user=user,password=password) except: print("Unable to connect to ...
0.160759
0.091829
import dataclasses as dt import typing as t from enum import Enum, Flag from bungieapi.json import to_json @dt.dataclass(frozen=True) class BungieFriendListResponse: friends: t.Sequence["BungieFriend"] def to_json(self) -> t.Mapping[str, t.Any]: return { "friends": to_json(self.friends),...
bungieapi/generated/components/schemas/social/friends.py
import dataclasses as dt import typing as t from enum import Enum, Flag from bungieapi.json import to_json @dt.dataclass(frozen=True) class BungieFriendListResponse: friends: t.Sequence["BungieFriend"] def to_json(self) -> t.Mapping[str, t.Any]: return { "friends": to_json(self.friends),...
0.602529
0.250709
import json import os import ui import requests import xml.etree.cElementTree import threading import ui import time import math import tarfile import plistlib import console import sqlite3 import shutil import copy from urllib.parse import urlparse from os.path import splitext, basename from objc_util import ns, Obj...
Managers/DocsetManager.py
import json import os import ui import requests import xml.etree.cElementTree import threading import ui import time import math import tarfile import plistlib import console import sqlite3 import shutil import copy from urllib.parse import urlparse from os.path import splitext, basename from objc_util import ns, Obj...
0.090168
0.063279
import os import numpy as np from astropy.table import Table from src.Data import Data from kndetect.utils import get_data_dir_path def ztf_ob_type_name(type_no: int): """ Retuens the type name in string for the type numbers in the ZTF dataset. Parameters ---------- type_no: int type nu...
pc_generation/src/io_utils.py
import os import numpy as np from astropy.table import Table from src.Data import Data from kndetect.utils import get_data_dir_path def ztf_ob_type_name(type_no: int): """ Retuens the type name in string for the type numbers in the ZTF dataset. Parameters ---------- type_no: int type nu...
0.820577
0.335841
from __future__ import print_function import os import sys from mock import patch from six import StringIO from djangocms_installer import config from djangocms_installer.install import check_install from djangocms_installer.utils import less_than_version, supported_versions from .base import BaseTestClass class T...
cms/lib/python2.7/site-packages/tests/config.py
from __future__ import print_function import os import sys from mock import patch from six import StringIO from djangocms_installer import config from djangocms_installer.install import check_install from djangocms_installer.utils import less_than_version, supported_versions from .base import BaseTestClass class T...
0.362292
0.112747
import os.path import re import pickle, hashlib from sklearn.externals import joblib from logging import debug, info from ngram import get_ngrams from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD import numpy as np def identity(x): return x def preprocess(d...
features.py
import os.path import re import pickle, hashlib from sklearn.externals import joblib from logging import debug, info from ngram import get_ngrams from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD import numpy as np def identity(x): return x def preprocess(d...
0.561455
0.152505
import pytest from alphabet_detector.alphabet_detector import AlphabetDetector @pytest.fixture def ad(): return AlphabetDetector() @pytest.fixture def ad_no_mem(): return AlphabetDetector(no_memory=True) class TestAlphabetDetector: def test_is_in_alphabet(self, ad, ad_no_mem): assert ad.is_in_...
tests/test_alphabet_detector.py
import pytest from alphabet_detector.alphabet_detector import AlphabetDetector @pytest.fixture def ad(): return AlphabetDetector() @pytest.fixture def ad_no_mem(): return AlphabetDetector(no_memory=True) class TestAlphabetDetector: def test_is_in_alphabet(self, ad, ad_no_mem): assert ad.is_in_...
0.584745
0.58261
import pandas as pd from retry import retry from google.oauth2 import service_account import gspread import gspread_dataframe as gd class googleBigQueryConnector(object): def __init__(self, google_big_query_credentials, retry_tries=3, retry_delay=3): self.retry_tries = retry_tries self.retry_delay...
pigging/connectors.py
import pandas as pd from retry import retry from google.oauth2 import service_account import gspread import gspread_dataframe as gd class googleBigQueryConnector(object): def __init__(self, google_big_query_credentials, retry_tries=3, retry_delay=3): self.retry_tries = retry_tries self.retry_delay...
0.366023
0.092565
import logging import numpy as np from .misc import normalized_correlation, homo_project, euclidean_disance class Correspond(object): def __init__(self, image1, image2, r1, r2, threshold=0, neighbor=3): self.image1 = image1 self.image2 = image2 self.r1 = r1 self.r2 = r2 ...
EECE5639-Computer-Vision/Project-2/libs/Correspondences.py
import logging import numpy as np from .misc import normalized_correlation, homo_project, euclidean_disance class Correspond(object): def __init__(self, image1, image2, r1, r2, threshold=0, neighbor=3): self.image1 = image1 self.image2 = image2 self.r1 = r1 self.r2 = r2 ...
0.715026
0.534491
from cognite.client.data_classes._base import * class TransformationSchemaType: def __init__(self, type: str = None): self.type = type class TransformationSchemaArrayType(TransformationSchemaType): def __init__(self, type: str = None, element_type: str = None, contains_null: bool = False): s...
cognite/experimental/data_classes/transformation_schema.py
from cognite.client.data_classes._base import * class TransformationSchemaType: def __init__(self, type: str = None): self.type = type class TransformationSchemaArrayType(TransformationSchemaType): def __init__(self, type: str = None, element_type: str = None, contains_null: bool = False): s...
0.872143
0.238578
from unittest import TestCase from unittest.mock import MagicMock from maintain_frontend.add_land_charge.routing.review_router import ReviewRouter from maintain_frontend import main from flask import g from maintain_frontend.models import LocalLandChargeItem REDIRECT_ROUTE = 'add_land_charge.get_charge_description' RE...
unit_tests/add_land_charge/routing/test_review_router.py
from unittest import TestCase from unittest.mock import MagicMock from maintain_frontend.add_land_charge.routing.review_router import ReviewRouter from maintain_frontend import main from flask import g from maintain_frontend.models import LocalLandChargeItem REDIRECT_ROUTE = 'add_land_charge.get_charge_description' RE...
0.761627
0.330985
import Pyro4 import os import sys import pwd import subprocess import re from dotenv import load_dotenv load_dotenv() regexCleanConsoleOutput = r"\\.*?]" os.environ["PYRO_HMAC_KEY"] = os.getenv("DAEMON_HMAC") subprocess.Popen(["python3", "-m", "Pyro4.naming"]) def runAsUser(username): uid = pwd.getpwnam(userna...
daemon/daemon.py
import Pyro4 import os import sys import pwd import subprocess import re from dotenv import load_dotenv load_dotenv() regexCleanConsoleOutput = r"\\.*?]" os.environ["PYRO_HMAC_KEY"] = os.getenv("DAEMON_HMAC") subprocess.Popen(["python3", "-m", "Pyro4.naming"]) def runAsUser(username): uid = pwd.getpwnam(userna...
0.265214
0.10079
import os import boto3 from wand.image import Image from boto3.s3.transfer import S3Transfer from settings import Config from utils.commons import utc_now_timestamp as now, utc_now_ts_ms as now_ms def thumbnail_process(file, content_type, content_id, sizes=[("sm", 50), ("lg", 75), ("xlg", 200)]): image_id = now()...
utils/image_upload.py
import os import boto3 from wand.image import Image from boto3.s3.transfer import S3Transfer from settings import Config from utils.commons import utc_now_timestamp as now, utc_now_ts_ms as now_ms def thumbnail_process(file, content_type, content_id, sizes=[("sm", 50), ("lg", 75), ("xlg", 200)]): image_id = now()...
0.279337
0.096663
import pickle import os from google_auth_oauthlib.flow import Flow, InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload from google.auth.transport.requests import Request import logging def get_credentials(client_secret_file, token_path, scopes): cred = N...
utils.py
import pickle import os from google_auth_oauthlib.flow import Flow, InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload from google.auth.transport.requests import Request import logging def get_credentials(client_secret_file, token_path, scopes): cred = N...
0.41561
0.088465
from os import access from requests.auth import _basic_auth_str from termcolor import colored import unittest import requests class SecurityTests(unittest.TestCase): API_URL = "http://127.0.0.1:5000/" customers = [{'username': 'Customer1','password':'<PASSWORD>',}, {'username': 'Customer2',...
project/tests/tests_security.py
from os import access from requests.auth import _basic_auth_str from termcolor import colored import unittest import requests class SecurityTests(unittest.TestCase): API_URL = "http://127.0.0.1:5000/" customers = [{'username': 'Customer1','password':'<PASSWORD>',}, {'username': 'Customer2',...
0.209631
0.222436
import daal4py as d4p import numpy as np class LogisticRegression: ''' ....Constructor to set LogisticRegression compute parameters ....''' def __init__( self, nClasses, dtype="float", penaltyL1=0, penaltyL2=0, interceptFlag=True, resultsToCompute="com...
aws/sagemaker/LogosticRegression/container/LogisticRegression/LogisticRegression.py
import daal4py as d4p import numpy as np class LogisticRegression: ''' ....Constructor to set LogisticRegression compute parameters ....''' def __init__( self, nClasses, dtype="float", penaltyL1=0, penaltyL2=0, interceptFlag=True, resultsToCompute="com...
0.652574
0.250941
from __future__ import annotations from typing import Optional, TYPE_CHECKING from spark_auto_mapper_fhir.fhir_types.list import FhirList from spark_auto_mapper_fhir.fhir_types.string import FhirString from spark_auto_mapper_fhir.extensions.extension_base import ExtensionBase from spark_auto_mapper_fhir.base_types.fh...
spark_auto_mapper_fhir/backbone_elements/plan_definition_target.py
from __future__ import annotations from typing import Optional, TYPE_CHECKING from spark_auto_mapper_fhir.fhir_types.list import FhirList from spark_auto_mapper_fhir.fhir_types.string import FhirString from spark_auto_mapper_fhir.extensions.extension_base import ExtensionBase from spark_auto_mapper_fhir.base_types.fh...
0.925651
0.301818
import collections import numpy as np import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import sarnet_td3.common.ops as ops RRLCellTuple = collections.namedtuple("RRLCellTuple", ("memory")) class RRLCell(tf.compat.v1.nn.rnn_cell.RNNCell): """ Input: Query: Query from the agent "i" recurren...
sarnet_td3/models/SARNet_comm.py
import collections import numpy as np import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import sarnet_td3.common.ops as ops RRLCellTuple = collections.namedtuple("RRLCellTuple", ("memory")) class RRLCell(tf.compat.v1.nn.rnn_cell.RNNCell): """ Input: Query: Query from the agent "i" recurren...
0.886844
0.529446
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import os import cv2 from .utils import scale_images, calculate_fid def sample(gan, train_dataset): """Generate and visualize sample generated by the GAN Args: gan (GAN): Compiled GAN model train_dataset (tf.data.Data...
src/gan-dogs/model/evaluation.py
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import os import cv2 from .utils import scale_images, calculate_fid def sample(gan, train_dataset): """Generate and visualize sample generated by the GAN Args: gan (GAN): Compiled GAN model train_dataset (tf.data.Data...
0.908346
0.587973
import unittest from time import sleep import os from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException class TestAddNewNodes(unittest.TestCase): def setUp(self...
FlaskTry/seleniumTests/testAddDataManually.py
import unittest from time import sleep import os from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException class TestAddNewNodes(unittest.TestCase): def setUp(self...
0.27406
0.220972
from functools import wraps from typing import Callable, List, Union, Any, TypeVar from types import TracebackType import dill import logging from tblib import Traceback from six import reraise from parsl.data_provider.files import File logger = logging.getLogger(__name__) class ParslError(Exception): """Base...
parsl/app/errors.py
from functools import wraps from typing import Callable, List, Union, Any, TypeVar from types import TracebackType import dill import logging from tblib import Traceback from six import reraise from parsl.data_provider.files import File logger = logging.getLogger(__name__) class ParslError(Exception): """Base...
0.856092
0.275318
from sys import path path.append("src") # noqa from send_notifs import * from _exec_update_all_courses import do_update_async_SOFT, do_update_async_HARD from datetime import datetime from sys import stderr import pytz from config import ( NOTIFS_INTERVAL_SECS, NOTIFS_SHEET_POLL_MINS, GLOBAL_COURSE_UPDAT...
send_notifs_cron.py
from sys import path path.append("src") # noqa from send_notifs import * from _exec_update_all_courses import do_update_async_SOFT, do_update_async_HARD from datetime import datetime from sys import stderr import pytz from config import ( NOTIFS_INTERVAL_SECS, NOTIFS_SHEET_POLL_MINS, GLOBAL_COURSE_UPDAT...
0.305594
0.107531
import numpy as np import json import argparse import glob import os parser = argparse.ArgumentParser() parser.add_argument("--full_labels_json", help="json file with full gt info (pose, camera coordinates, etc.)") parser.add_argument("--save_file", help="file to save challenge gt to") args = parser.parse_args() if ...
gt_pose_publisher/object_gt_visualization/gen_challenge_gt.py
import numpy as np import json import argparse import glob import os parser = argparse.ArgumentParser() parser.add_argument("--full_labels_json", help="json file with full gt info (pose, camera coordinates, etc.)") parser.add_argument("--save_file", help="file to save challenge gt to") args = parser.parse_args() if ...
0.35488
0.233029
import populartimes as pt import json import csv # Google API key goes here key = " " # Some places' latitudes and longditudes weybrige = (51.371647361061285, -0.45789862797850234) romford = (51.57663036646349, 0.1773901549118097) wandsworth = (51.45776244897419, -0.1876677526206532) vauxhall = (51.48631022518863,...
populartime.py
import populartimes as pt import json import csv # Google API key goes here key = " " # Some places' latitudes and longditudes weybrige = (51.371647361061285, -0.45789862797850234) romford = (51.57663036646349, 0.1773901549118097) wandsworth = (51.45776244897419, -0.1876677526206532) vauxhall = (51.48631022518863,...
0.106435
0.270065
class Node: def __init__(self,val): self.val = val self.next = None self.prev = None class MyLinkedList: def __init__(self): self.head = None self.size = 0 def get(self, index: int) -> int: if index < 0 or index >= self.size: return -1 ...
707-design-linked-list/707-design-linked-list.py
class Node: def __init__(self,val): self.val = val self.next = None self.prev = None class MyLinkedList: def __init__(self): self.head = None self.size = 0 def get(self, index: int) -> int: if index < 0 or index >= self.size: return -1 ...
0.344995
0.212171
import collections import os import sys import unittest import mock from infra.services.sysmon import system_metrics from infra_libs import ts_mon class SystemMetricsTest(unittest.TestCase): def setUp(self): ts_mon.reset_for_unittest() def assertBetween(self, lower, upper, value): self.assertGreaterEq...
infra/services/sysmon/test/system_metrics_test.py
import collections import os import sys import unittest import mock from infra.services.sysmon import system_metrics from infra_libs import ts_mon class SystemMetricsTest(unittest.TestCase): def setUp(self): ts_mon.reset_for_unittest() def assertBetween(self, lower, upper, value): self.assertGreaterEq...
0.445771
0.389372
import numpy as np import json def quadratic_bounding_box(x0, y0, width, height, imshape): # We assume that we can create a image that is quadratic without # minimizing any of the sides assert width <= min(imshape[:2]) assert height <= min(imshape[:2]) min_side = min(height, width) if height !...
deep_privacy/dataset_tools/utils.py
import numpy as np import json def quadratic_bounding_box(x0, y0, width, height, imshape): # We assume that we can create a image that is quadratic without # minimizing any of the sides assert width <= min(imshape[:2]) assert height <= min(imshape[:2]) min_side = min(height, width) if height !...
0.560614
0.778186
import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.preprocessing import normalize from tensorflow.python.framework import ops import tensorflow as tf ops.reset_default_graph() sess = tf.Session() # Load the data and split the dataset. iris = datasets.load_iris() x_vals = np.a...
4.1_LinearSVM.py
import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.preprocessing import normalize from tensorflow.python.framework import ops import tensorflow as tf ops.reset_default_graph() sess = tf.Session() # Load the data and split the dataset. iris = datasets.load_iris() x_vals = np.a...
0.834912
0.741253
import pytest from kotonoha.mecab_handler import MeCabHandler class Struct: def __init__(self, **entries): self.__dict__.update(entries) class MecabNode: def __init__(self, feature): self.feature = feature self.surface = 'aaa' self.next = None @pytest.fixture def mecab_moc...
tests/mecab_handler_test.py
import pytest from kotonoha.mecab_handler import MeCabHandler class Struct: def __init__(self, **entries): self.__dict__.update(entries) class MecabNode: def __init__(self, feature): self.feature = feature self.surface = 'aaa' self.next = None @pytest.fixture def mecab_moc...
0.416797
0.282699
import argparse import pandas as pd import numpy as np import matplotlib.pyplot as plt import lightgbm as lgb from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import KFold import datetime import gc import pickle from utils import fill_weather_dataset, reduce_mem_usage, features_engineering, ...
solutions/rank-1/kfold_model/predict.py
import argparse import pandas as pd import numpy as np import matplotlib.pyplot as plt import lightgbm as lgb from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import KFold import datetime import gc import pickle from utils import fill_weather_dataset, reduce_mem_usage, features_engineering, ...
0.460774
0.210644
from lxml import etree from tkinter import simpledialog STATUS_AL_MAL = { "A voir": "Plan to Watch", "MA voir": "Plan to Read", "En visionnement": "Watching", "MEn visionnement": "Reading", "Fini": "Completed", "Abandonné": "Dropped" } class MALExporter: def __init__(self, main): ...
alist/data/mal_export.py
from lxml import etree from tkinter import simpledialog STATUS_AL_MAL = { "A voir": "Plan to Watch", "MA voir": "Plan to Read", "En visionnement": "Watching", "MEn visionnement": "Reading", "Fini": "Completed", "Abandonné": "Dropped" } class MALExporter: def __init__(self, main): ...
0.259638
0.16872
__version__ = "$Revision-Id:$" import unittest from webdav.Connection import WebdavError from datafinder.persistence.principal_search import principal from datafinder.persistence.privileges import constants from datafinder.persistence.privileges.ace import AccessControlListEntry from datafinder.persisten...
test/unittest/datafinder_test/persistence/adapters/webdav_/privileges/adapter_test.py
__version__ = "$Revision-Id:$" import unittest from webdav.Connection import WebdavError from datafinder.persistence.principal_search import principal from datafinder.persistence.privileges import constants from datafinder.persistence.privileges.ace import AccessControlListEntry from datafinder.persisten...
0.463201
0.261767
import abc import numpy as np class HamiltonianDynamicsContext(metaclass=abc.ABCMeta): @classmethod @abc.abstractmethod def configuration_space_dimension (cls): pass @classmethod @abc.abstractmethod def H (cls, qp): """Evaluates the Hamiltonian on the (2,N)-shaped (q,p) coordin...
heisenberg/library/hamiltonian_dynamics_context.py
import abc import numpy as np class HamiltonianDynamicsContext(metaclass=abc.ABCMeta): @classmethod @abc.abstractmethod def configuration_space_dimension (cls): pass @classmethod @abc.abstractmethod def H (cls, qp): """Evaluates the Hamiltonian on the (2,N)-shaped (q,p) coordin...
0.881526
0.638751
# Author: <NAME> <<EMAIL>> # Copyright: (C) 1998-2015 by <NAME> # License: GPL 2 (see __init__.py) """ Concrete polytrig (orders 2 & 3) puzzles. """ from puzzler.puzzles import polytrigs from puzzler.puzzles.polytrigs import Polytrigs23, OneSidedPolytrigs23 from puzzler.coordsys import TriangularGrid3DCoordSet cla...
puzzler/puzzles/polytrigs23.py
# Author: <NAME> <<EMAIL>> # Copyright: (C) 1998-2015 by <NAME> # License: GPL 2 (see __init__.py) """ Concrete polytrig (orders 2 & 3) puzzles. """ from puzzler.puzzles import polytrigs from puzzler.puzzles.polytrigs import Polytrigs23, OneSidedPolytrigs23 from puzzler.coordsys import TriangularGrid3DCoordSet cla...
0.799521
0.406656
from . import Parts from . import ChipIdentifiers from . import FlashControllers import logging def _get_subclasses(classname): """Recursively obtains all subclasses of the given class.""" subclasses = [] for p in classname.__subclasses__(): subclasses.append(p) subclasses.extend(_get_s...
SAMBALoader/PartLibrary.py
from . import Parts from . import ChipIdentifiers from . import FlashControllers import logging def _get_subclasses(classname): """Recursively obtains all subclasses of the given class.""" subclasses = [] for p in classname.__subclasses__(): subclasses.append(p) subclasses.extend(_get_s...
0.772788
0.268678
import os import logging import zmq import math import traceback import datetime import time import multiprocessing import rethinkdb import utils __all__ = [ 'ImportManager', 'ImportWorker', ] LOG = logging.getLogger(__name__) class ImportManager(object): def __init__(self, controller, config): ...
shotgunCache/entityImporter.py
import os import logging import zmq import math import traceback import datetime import time import multiprocessing import rethinkdb import utils __all__ = [ 'ImportManager', 'ImportWorker', ] LOG = logging.getLogger(__name__) class ImportManager(object): def __init__(self, controller, config): ...
0.363986
0.102619
from crescent.core import Resource, Tag, AllowedValues as CoreAllowedValues from crescent.functions import AnyFn from .db_instance_role import DBInstanceRole from .processor_feature import ProcessorFeature from .constants import AllowedValues, Conditions, ResourceRequiredProperties from typing import Union class DBIn...
crescent/resources/rds/db_instance/db_instance.py
from crescent.core import Resource, Tag, AllowedValues as CoreAllowedValues from crescent.functions import AnyFn from .db_instance_role import DBInstanceRole from .processor_feature import ProcessorFeature from .constants import AllowedValues, Conditions, ResourceRequiredProperties from typing import Union class DBIn...
0.86241
0.0745
import gym import numpy as np import random from MEC_env import mec_def from MEC_env import mec_env import tensorflow as tf from tensorflow import keras import tensorboard import datetime import MAAC_agent from matplotlib import pyplot as plt import json print("TensorFlow version: ", tf.__version__) # ...
MAAC_run.py
import gym import numpy as np import random from MEC_env import mec_def from MEC_env import mec_env import tensorflow as tf from tensorflow import keras import tensorboard import datetime import MAAC_agent from matplotlib import pyplot as plt import json print("TensorFlow version: ", tf.__version__) # ...
0.38769
0.119459
import numpy as np import os import tensorflow as tf import string import random import math import sys from sentence_grouper import SentenceGrouper class NerModel: # If session is not defined than default session will be used def __init__(self, session = None, dummy_tags = None, use_contrib=True): se...
python/tensorflow/ner/ner_model.py
import numpy as np import os import tensorflow as tf import string import random import math import sys from sentence_grouper import SentenceGrouper class NerModel: # If session is not defined than default session will be used def __init__(self, session = None, dummy_tags = None, use_contrib=True): se...
0.563378
0.146697
import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='PartNumberClass', fields=[ ('id', models.AutoField(auto_cr...
parts/app/partsnumber/migrations/0001_initial.py
import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='PartNumberClass', fields=[ ('id', models.AutoField(auto_cr...
0.548915
0.174059
import functools import hashlib import hmac import subprocess from base64 import b64encode from io import BytesIO from typing import List, Any import qrcode from flask import abort from flask import request from flask import session from flask_login import current_user from flask_socketio import disconnect from ldap3 ...
home/web/utils.py
import functools import hashlib import hmac import subprocess from base64 import b64encode from io import BytesIO from typing import List, Any import qrcode from flask import abort from flask import request from flask import session from flask_login import current_user from flask_socketio import disconnect from ldap3 ...
0.53607
0.07333