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
__docformat__ = 'epytext en' import os, re from codebay.l2tpserver import constants from codebay.l2tpserver import helpers # list of pci hw files _hwdata_sources = constants.PCI_HWDATA_SOURCES # NB: some pci data has broken IDs, e.g. '003' instead of '0003' or # '01234' instead of '1234' We need to fix these or ski...
src/python/codebay/l2tpserver/netidentify.py
__docformat__ = 'epytext en' import os, re from codebay.l2tpserver import constants from codebay.l2tpserver import helpers # list of pci hw files _hwdata_sources = constants.PCI_HWDATA_SOURCES # NB: some pci data has broken IDs, e.g. '003' instead of '0003' or # '01234' instead of '1234' We need to fix these or ski...
0.296552
0.088702
import tensorflow as tf from tensorflow.contrib import slim from tensorflow import keras FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_integer('image_height', 28, 'the height of image') tf.app.flags.DEFINE_integer('image_width', 28, 'the width of image') tf.app.flags.DEFINE_integer('batch_size', 128, 'Number of image...
mnist.py
import tensorflow as tf from tensorflow.contrib import slim from tensorflow import keras FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_integer('image_height', 28, 'the height of image') tf.app.flags.DEFINE_integer('image_width', 28, 'the width of image') tf.app.flags.DEFINE_integer('batch_size', 128, 'Number of image...
0.896455
0.371023
################################################################################ ## Form generated from reading UI file 'UIiEDzGo.ui' ## ## Created by: Qt User Interface Compiler version 5.15.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ##################################...
UI.py
################################################################################ ## Form generated from reading UI file 'UIiEDzGo.ui' ## ## Created by: Qt User Interface Compiler version 5.15.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ##################################...
0.385953
0.05715
import logging import cv2 import numpy as np import pandas as pd from torchvision import datasets, transforms import torch import random from facenet_pytorch import MTCNN from PIL import Image from multiprocessing import cpu_count class MTCNN_Model: def __init__(self, model_parameters, inference_parameters): ...
tasks/cv-mtcnn-face-detection/mtcnn.py
import logging import cv2 import numpy as np import pandas as pd from torchvision import datasets, transforms import torch import random from facenet_pytorch import MTCNN from PIL import Image from multiprocessing import cpu_count class MTCNN_Model: def __init__(self, model_parameters, inference_parameters): ...
0.654564
0.32146
import tensorflow as tf from ...data import fields from ...layers import Layer from ...structures import ImageList, box_list from ..backbone import build_backbone from ..necks import build_neck from ..proposal_generator import build_proposal_generator from ..roi_heads import build_roi_heads from ..postprocessing impor...
lib/modeling/meta_arch/rcnn.py
import tensorflow as tf from ...data import fields from ...layers import Layer from ...structures import ImageList, box_list from ..backbone import build_backbone from ..necks import build_neck from ..proposal_generator import build_proposal_generator from ..roi_heads import build_roi_heads from ..postprocessing impor...
0.892445
0.366165
import tkinter as tk window = tk.Tk() window.title('Claculator') numbers = ['0'] action = ['null'] ### FUNCTIONS ### # OUTPUT def output_update(text): value = lbl_output['text'] if len(numbers)==1: if numbers[0]=='0': value = value[:-1] numbers.clear() ...
tkinter calculator v1.py
import tkinter as tk window = tk.Tk() window.title('Claculator') numbers = ['0'] action = ['null'] ### FUNCTIONS ### # OUTPUT def output_update(text): value = lbl_output['text'] if len(numbers)==1: if numbers[0]=='0': value = value[:-1] numbers.clear() ...
0.081095
0.147893
from numpy import * from pytrain.lib import convert from pytrain.lib import ptmath import operator class HierarchicalClustering: def __init__(self, mat_data, K, dist_func): self.mat_data = convert.list2npfloat(mat_data) self.dist_func = ptmath.distfunc(dist_func) self.K = K self.c...
pytrain/HierarchicalClustering/HierarchicalClustering.py
from numpy import * from pytrain.lib import convert from pytrain.lib import ptmath import operator class HierarchicalClustering: def __init__(self, mat_data, K, dist_func): self.mat_data = convert.list2npfloat(mat_data) self.dist_func = ptmath.distfunc(dist_func) self.K = K self.c...
0.458591
0.226217
from django.contrib.auth import get_user_model from django.db import models, transaction from django.db.models.signals import pre_delete, pre_save from django.dispatch import receiver from django.utils.translation import gettext_lazy as _ from rules.contrib.models import RulesModel from booking import rules from booki...
booking/models/game.py
from django.contrib.auth import get_user_model from django.db import models, transaction from django.db.models.signals import pre_delete, pre_save from django.dispatch import receiver from django.utils.translation import gettext_lazy as _ from rules.contrib.models import RulesModel from booking import rules from booki...
0.688049
0.179279
import unittest from ..pygraph import (UndirectedGraph, find_biconnected_components, find_articulation_vertices, merge_graphs, build_triangle_graph, build_square_graph, build_diamond_graph, build_tetrahedral_graph, build_5_cycle_graph, build_gem_graph) from . import utility_...
tests/test_biconnected_components.py
import unittest from ..pygraph import (UndirectedGraph, find_biconnected_components, find_articulation_vertices, merge_graphs, build_triangle_graph, build_square_graph, build_diamond_graph, build_tetrahedral_graph, build_5_cycle_graph, build_gem_graph) from . import utility_...
0.757436
0.64777
from __future__ import print_function # PyDSTool imports from PyDSTool import * from PyDSTool.Toolbox.ParamEst import BoundMin, L2_feature_1D from PyDSTool.common import metric_float_1D import HH_model, IF_squarespike_model # ---------------------------------------------------------------- trange = [0, 15] par_args...
examples/pest_test2.py
from __future__ import print_function # PyDSTool imports from PyDSTool import * from PyDSTool.Toolbox.ParamEst import BoundMin, L2_feature_1D from PyDSTool.common import metric_float_1D import HH_model, IF_squarespike_model # ---------------------------------------------------------------- trange = [0, 15] par_args...
0.474631
0.335759
""" Presence detection (determine if an occupant is present in the house) """ import time import wifi from server.ping import async_ping from server.notifier import Notifier from server.server import Server from tools import useful, jsonconfig, lang, tasking class PresenceConfig(jsonconfig.JsonConfig): """ Configurat...
modules/lib/server/presence.py
""" Presence detection (determine if an occupant is present in the house) """ import time import wifi from server.ping import async_ping from server.notifier import Notifier from server.server import Server from tools import useful, jsonconfig, lang, tasking class PresenceConfig(jsonconfig.JsonConfig): """ Configurat...
0.384219
0.144662
from __future__ import annotations import os import typing from ..blockchain.network_type import OptionalNetworkType from ... import util __all__ = ['MosaicNonce'] RawNonceType = typing.Union[int, bytes, str] def nonce_as_bytes(nonce: RawNonceType): """Convert nonce to underlying byte array.""" if isinstan...
xpxchain/models/mosaic/mosaic_nonce.py
from __future__ import annotations import os import typing from ..blockchain.network_type import OptionalNetworkType from ... import util __all__ = ['MosaicNonce'] RawNonceType = typing.Union[int, bytes, str] def nonce_as_bytes(nonce: RawNonceType): """Convert nonce to underlying byte array.""" if isinstan...
0.773302
0.375134
import pprint import sgtk HookBaseClass = sgtk.get_hook_baseclass() class ShellActions(HookBaseClass): """ Stub implementation of the shell actions, used for testing. """ def generate_actions(self, sg_publish_data, actions, ui_area): """ Return a list of action instances for a partic...
install/app_store/tk-multi-loader2/v1.18.0/hooks/tk-shell_actions.py
import pprint import sgtk HookBaseClass = sgtk.get_hook_baseclass() class ShellActions(HookBaseClass): """ Stub implementation of the shell actions, used for testing. """ def generate_actions(self, sg_publish_data, actions, ui_area): """ Return a list of action instances for a partic...
0.724188
0.466359
import pycurl try: from io import BytesIO except ImportError: from StringIO import StringIO as BytesIO try: from urllib.parse import urlencode except ImportError: from urllib import urlencode import json # Version 1.0.0 # This class is written to be compatible with Python 2 and Python 3 class CDNsunCd...
cdn_api_client.py
import pycurl try: from io import BytesIO except ImportError: from StringIO import StringIO as BytesIO try: from urllib.parse import urlencode except ImportError: from urllib import urlencode import json # Version 1.0.0 # This class is written to be compatible with Python 2 and Python 3 class CDNsunCd...
0.424293
0.085175
#<NAME> '''Takes a base oligo or generates one. Chains mutations in sequentially, have any number of forks''' #Imports import argparse import random #Functions def generate_random_seq(alpha,l=20): '''Generates a random nucleotide sequence''' return ''.join([random.choice(alpha) for z in range(0,l)]) def add...
oligo_permutations.py
#<NAME> '''Takes a base oligo or generates one. Chains mutations in sequentially, have any number of forks''' #Imports import argparse import random #Functions def generate_random_seq(alpha,l=20): '''Generates a random nucleotide sequence''' return ''.join([random.choice(alpha) for z in range(0,l)]) def add...
0.345989
0.230422
from molmodmt.utils.exceptions import * from os.path import basename as _basename from mdtraj.core.topology import Topology as _mdtraj_Topology form_name=_basename(__file__).split('.')[0].replace('api_','').replace('_','.') is_form={ _mdtraj_Topology : form_name, 'mdtraj.Topology': form_name } def to_aminoac...
molmodmt/forms/classes/api_mdtraj_Topology.py
from molmodmt.utils.exceptions import * from os.path import basename as _basename from mdtraj.core.topology import Topology as _mdtraj_Topology form_name=_basename(__file__).split('.')[0].replace('api_','').replace('_','.') is_form={ _mdtraj_Topology : form_name, 'mdtraj.Topology': form_name } def to_aminoac...
0.330903
0.15084
from sklearn.ensemble import AdaBoostRegressor from sklearn.ensemble import GradientBoostingRegressor from xgboost import XGBRegressor from sklearn.model_selection import RandomizedSearchCV import pandas as pd import warnings warnings.filterwarnings('ignore') from logger.LoggerClass import LoggerFileClass logger = Lo...
algo/BoostingModels.py
from sklearn.ensemble import AdaBoostRegressor from sklearn.ensemble import GradientBoostingRegressor from xgboost import XGBRegressor from sklearn.model_selection import RandomizedSearchCV import pandas as pd import warnings warnings.filterwarnings('ignore') from logger.LoggerClass import LoggerFileClass logger = Lo...
0.860823
0.618176
# External Modules import logging import os logger = logging.getLogger('logger') current_dir = os.path.dirname(os.path.realpath(__file__)) class FileProvider(object): def __init__(self, directory_to_search): self.exclude_files = [ "ccf_ctl.v", "design_error.inc", "fl...
hdk/tests/validate_file_headers/fileprovider.py
# External Modules import logging import os logger = logging.getLogger('logger') current_dir = os.path.dirname(os.path.realpath(__file__)) class FileProvider(object): def __init__(self, directory_to_search): self.exclude_files = [ "ccf_ctl.v", "design_error.inc", "fl...
0.324342
0.08617
class Operation(object): # no doc @staticmethod def AddToPourUnit(inputPour,objectsToBeAdded): """ AddToPourUnit(inputPour: PourObject,objectsToBeAdded: List[ModelObject]) -> bool """ pass @staticmethod def CreateBasePoint(basePoint): """ CreateBasePoint(basePoint: BasePoint) -> bool """ pass @s...
release/stubs.min/Tekla/Structures/ModelInternal_parts/Operation.py
class Operation(object): # no doc @staticmethod def AddToPourUnit(inputPour,objectsToBeAdded): """ AddToPourUnit(inputPour: PourObject,objectsToBeAdded: List[ModelObject]) -> bool """ pass @staticmethod def CreateBasePoint(basePoint): """ CreateBasePoint(basePoint: BasePoint) -> bool """ pass @s...
0.542136
0.179495
import matplotlib.pyplot as plt import seaborn as sns from particle.plotting import ( plot_averaged_convergence_from_clusters, plot_averaged_avg_vel, # plot_avg_vel, ) # rc("text", usetex=True) sns.set(style="white", context="talk") search_parameters = { "particle_count": 480, "G": "Smooth", ...
noisysystem_temp/Analysis/CutoffPhiAnalysis.py
import matplotlib.pyplot as plt import seaborn as sns from particle.plotting import ( plot_averaged_convergence_from_clusters, plot_averaged_avg_vel, # plot_avg_vel, ) # rc("text", usetex=True) sns.set(style="white", context="talk") search_parameters = { "particle_count": 480, "G": "Smooth", ...
0.580352
0.561395
import numpy as np import pandas as pd import rdt from sklearn.model_selection import train_test_split from sdmetrics.goal import Goal from sdmetrics.timeseries.base import TimeSeriesMetric class TimeSeriesEfficacyMetric(TimeSeriesMetric): """Base class for Machine Learning Efficacy based metrics on time series...
sdmetrics/timeseries/efficacy/base.py
import numpy as np import pandas as pd import rdt from sklearn.model_selection import train_test_split from sdmetrics.goal import Goal from sdmetrics.timeseries.base import TimeSeriesMetric class TimeSeriesEfficacyMetric(TimeSeriesMetric): """Base class for Machine Learning Efficacy based metrics on time series...
0.943712
0.592254
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'),...
mdid3/core/access/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'),...
0.607314
0.154153
from PIL import Image import os import glob class CleanImages: def __init__(self, path: str, output_path: str) -> None: """Creates the CleanImages object and sets the path to the images. Args: path (str): path to the images. """ self.path = path self.out...
classes/clean_images.py
from PIL import Image import os import glob class CleanImages: def __init__(self, path: str, output_path: str) -> None: """Creates the CleanImages object and sets the path to the images. Args: path (str): path to the images. """ self.path = path self.out...
0.63861
0.317876
import json import time import requests import os import sys reload(sys) sys.setdefaultencoding('utf-8') # zabbix认证信息 zabbix_url = "http://52.80.127.55/zabbix/api_jsonrpc.php" zabbix_username = "Admin" zabbix_password = "<PASSWORD>" #全局变量定义 local_path = os.path.split(os.path.realpath(__file__))[0] log_file = local_path...
zabbixapi.py
import json import time import requests import os import sys reload(sys) sys.setdefaultencoding('utf-8') # zabbix认证信息 zabbix_url = "http://52.80.127.55/zabbix/api_jsonrpc.php" zabbix_username = "Admin" zabbix_password = "<PASSWORD>" #全局变量定义 local_path = os.path.split(os.path.realpath(__file__))[0] log_file = local_path...
0.118742
0.118105
import docx import re import pandas as pd import os def get_filelist(dir_path): filelist = [] for file in os.scandir(dir_path): filelist.append(file.path) return filelist def read_tplt(tplt_word): dic_fill = {} # 记录信息位置与要填写位置的映射字典 pattern = '{\d+}' # 设定模式 document = d...
CoolTurnProject/WordToExcel/word_to_excel.py
import docx import re import pandas as pd import os def get_filelist(dir_path): filelist = [] for file in os.scandir(dir_path): filelist.append(file.path) return filelist def read_tplt(tplt_word): dic_fill = {} # 记录信息位置与要填写位置的映射字典 pattern = '{\d+}' # 设定模式 document = d...
0.10179
0.165526
import pickle as pkl from collections import Iterable import os import logging import io import numpy as np try: xrange except NameError: # python3 xrange = range logger = logging.getLogger('LineCache') class LineCache(object): ''' LineCache caches the line position of a file in the memory. Everytim...
linecache_light/linecache_light.py
import pickle as pkl from collections import Iterable import os import logging import io import numpy as np try: xrange except NameError: # python3 xrange = range logger = logging.getLogger('LineCache') class LineCache(object): ''' LineCache caches the line position of a file in the memory. Everytim...
0.392104
0.087175
from rest_framework import generics, views from rest_framework import status from rest_framework.parsers import MultiPartParser from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from src.apps.core.views import BaseModelViewSet from src.apps.core.utilities.response_uti...
src/apps/user_profile/api/views.py
from rest_framework import generics, views from rest_framework import status from rest_framework.parsers import MultiPartParser from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from src.apps.core.views import BaseModelViewSet from src.apps.core.utilities.response_uti...
0.767167
0.118742
from thinglang.utils.exception_utils import ThinglangException class TargetNotCallable(ThinglangException): """ An attempt was made to call a target which is not a method, or is not callable. For example, attempting to call a class member """ class CapturedVoidMethod(ThinglangException): """ ...
thinglang/compiler/errors.py
from thinglang.utils.exception_utils import ThinglangException class TargetNotCallable(ThinglangException): """ An attempt was made to call a target which is not a method, or is not callable. For example, attempting to call a class member """ class CapturedVoidMethod(ThinglangException): """ ...
0.901487
0.278649
import shutil import subprocess import webbrowser from pathlib import Path from typing import Union import typer from rich import print from rich.table import Table from clumper import Clumper from skedulord import __version__ as lord_version from skedulord.job import JobRunner from skedulord.common import SKEDULORD_...
skedulord/__main__.py
import shutil import subprocess import webbrowser from pathlib import Path from typing import Union import typer from rich import print from rich.table import Table from clumper import Clumper from skedulord import __version__ as lord_version from skedulord.job import JobRunner from skedulord.common import SKEDULORD_...
0.691602
0.154312
from __future__ import print_function import os import getopt import sys import subprocess import re def exit_with_usage(error=0, msg=""): if error != 0: print("Error: " + msg) print("usage: ./skrm [OPTIONS] [COMMANDS] [TAGS]") print("skrm stands for simple keyring manager, it stores keys with tag...
skrm/keyring_manager.py
from __future__ import print_function import os import getopt import sys import subprocess import re def exit_with_usage(error=0, msg=""): if error != 0: print("Error: " + msg) print("usage: ./skrm [OPTIONS] [COMMANDS] [TAGS]") print("skrm stands for simple keyring manager, it stores keys with tag...
0.343782
0.167968
from __future__ import print_function, division from pathlib import Path import numpy as np import random import json import sys import os import argparse from shutil import copyfile import networkx as nx from networkx.readwrite import json_graph import pdb def parse_args(): parser = argparse.ArgumentParser(desc...
utils/get_sub_graph.py
from __future__ import print_function, division from pathlib import Path import numpy as np import random import json import sys import os import argparse from shutil import copyfile import networkx as nx from networkx.readwrite import json_graph import pdb def parse_args(): parser = argparse.ArgumentParser(desc...
0.291283
0.159872
import os from unittest.mock import patch, mock_open import psutil from rucio_jupyterlab.rucio.download import RucioFileDownloader def test_rucio_file_downloader_is_downloading__lockfile_not_exists__should_return_false(mocker): mocker.patch.object(os.path, 'isfile', return_value=False) result = RucioFileDown...
rucio_jupyterlab/tests/test_rucio_file_downloader.py
import os from unittest.mock import patch, mock_open import psutil from rucio_jupyterlab.rucio.download import RucioFileDownloader def test_rucio_file_downloader_is_downloading__lockfile_not_exists__should_return_false(mocker): mocker.patch.object(os.path, 'isfile', return_value=False) result = RucioFileDown...
0.491456
0.205695
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from contextlib import contextmanager import logging import re import subprocess from octoeb.utils.config import get_config from octoeb.utils.config import get_config_va...
octoeb/utils/git.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from contextlib import contextmanager import logging import re import subprocess from octoeb.utils.config import get_config from octoeb.utils.config import get_config_va...
0.740362
0.08218
from matplotlib.pyplot import draw import numpy as np import pandas as pd import skfuzzy as fz from skfuzzy import control as ctrl import matplotlib.pyplot as plt class FIS: def __init__(self): evoparation = ctrl.Antecedent(np.arange(0, 15, 0.2), 'evoparation') # chia độ bốc hơi từ 0-15 với khoảng các...
src/FuzzyLogic.py
from matplotlib.pyplot import draw import numpy as np import pandas as pd import skfuzzy as fz from skfuzzy import control as ctrl import matplotlib.pyplot as plt class FIS: def __init__(self): evoparation = ctrl.Antecedent(np.arange(0, 15, 0.2), 'evoparation') # chia độ bốc hơi từ 0-15 với khoảng các...
0.173989
0.435301
from typing import Callable, Tuple, Union, Optional, Dict import numpy as np from inspect import signature class Op: def __init__(self, name: str, description: str, op: Callable, partial_difs: Tuple[Callable]): assert len(signature(op).parameters) == len(partial_difs) self._name = name se...
ibtd/operations.py
from typing import Callable, Tuple, Union, Optional, Dict import numpy as np from inspect import signature class Op: def __init__(self, name: str, description: str, op: Callable, partial_difs: Tuple[Callable]): assert len(signature(op).parameters) == len(partial_difs) self._name = name se...
0.948965
0.5083
__version__ = '0.8.1' __date__ = '$Date: 16 Dec 2011 $' no_blue = False; try: import bluetooth except ImportError: no_blue = True; no_serial = False; try: import serial except ImportError: no_serial = True; import math import time uuid = "00...
libs/emant.py
__version__ = '0.8.1' __date__ = '$Date: 16 Dec 2011 $' no_blue = False; try: import bluetooth except ImportError: no_blue = True; no_serial = False; try: import serial except ImportError: no_serial = True; import math import time uuid = "00...
0.267026
0.0809
import time import os import argparse import cv2 import glob def calculate_flow(use_gpu=True, device_id=None, vid_file=None, flow_x=None, flow_y=None, image=None, boundary=20, opt_type=1, step=1, out_type='dir'): command = '' if use_gpu: command += './extract_gpu ' else: command += './...
extract_flow.py
import time import os import argparse import cv2 import glob def calculate_flow(use_gpu=True, device_id=None, vid_file=None, flow_x=None, flow_y=None, image=None, boundary=20, opt_type=1, step=1, out_type='dir'): command = '' if use_gpu: command += './extract_gpu ' else: command += './...
0.353205
0.078961
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Attachment' db.create_table('mail_attachment', ( ('id', self.gf('django.db.models.fields.AutoField')(pri...
foiamachine/apps/mail/migrations/0001_initial.py
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Attachment' db.create_table('mail_attachment', ( ('id', self.gf('django.db.models.fields.AutoField')(pri...
0.446012
0.087175
import logging as log log.basicConfig(level=log.INFO) try: from .speech2text import Transcriber except: log.warning("Transcriber not imported!") from .ontology import FoodOntology from .analysis import Analyzer from .dialog_management import DialogManager, Utterance, State from .generation import G...
src/pipeline.py
import logging as log log.basicConfig(level=log.INFO) try: from .speech2text import Transcriber except: log.warning("Transcriber not imported!") from .ontology import FoodOntology from .analysis import Analyzer from .dialog_management import DialogManager, Utterance, State from .generation import G...
0.188212
0.044974
import numpy from numpy import * class ProcessingSequence: def __init__(self, mimo_demodulation, array_preprocessing, fourier_transformations, noise_power_estimation, peak_finding, Tsl_r,Tsl_v,Tsl_a,Tsl_e, ...
pre_processing.py
import numpy from numpy import * class ProcessingSequence: def __init__(self, mimo_demodulation, array_preprocessing, fourier_transformations, noise_power_estimation, peak_finding, Tsl_r,Tsl_v,Tsl_a,Tsl_e, ...
0.587115
0.454714
import functools from absl import app from absl import flags from acme.agents.jax import pwil from acme.agents.jax import sac from acme.datasets import tfds import helpers import launchpad as lp FLAGS = flags.FLAGS flags.DEFINE_string('task', 'HalfCheetah-v2', 'GYM environment task (str).') flags.DEFINE_string( '...
examples/gym/lp_local_pwil_jax.py
import functools from absl import app from absl import flags from acme.agents.jax import pwil from acme.agents.jax import sac from acme.datasets import tfds import helpers import launchpad as lp FLAGS = flags.FLAGS flags.DEFINE_string('task', 'HalfCheetah-v2', 'GYM environment task (str).') flags.DEFINE_string( '...
0.666171
0.257193
import numpy as np import operator import json import os import tree_plotter def create_test_dataset(): dataset = [[1,1,'yes'], [1,1,'yes'], [1,0,'no'], [0,1,'no'], [0,1,'no']]; feature_names = ['no surfacing','flippers'] return dataset,featur...
trees.py
import numpy as np import operator import json import os import tree_plotter def create_test_dataset(): dataset = [[1,1,'yes'], [1,1,'yes'], [1,0,'no'], [0,1,'no'], [0,1,'no']]; feature_names = ['no surfacing','flippers'] return dataset,featur...
0.147371
0.342681
from sap.pet_impl import * from sap.battle import Battle from test_helpers import dummy_pet, TestRandom, DummyPlayer import logging class TestPetImplBattle: def test_solo_mosquito(self): b = Battle( [Mosquito.spawn()], [dummy_pet(toughness=1)] ) b.battle() assert len(b.t...
tests/test_pet_impl_battle.py
from sap.pet_impl import * from sap.battle import Battle from test_helpers import dummy_pet, TestRandom, DummyPlayer import logging class TestPetImplBattle: def test_solo_mosquito(self): b = Battle( [Mosquito.spawn()], [dummy_pet(toughness=1)] ) b.battle() assert len(b.t...
0.608129
0.65736
import time import json import logging import threading from urllib.request import urlopen from urllib.error import HTTPError, URLError class Observer: def __init__(self, host, event_callback): logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(threadName)s\t%(levelname)-8s\t%(message)s') ...
observer.py
import time import json import logging import threading from urllib.request import urlopen from urllib.error import HTTPError, URLError class Observer: def __init__(self, host, event_callback): logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(threadName)s\t%(levelname)-8s\t%(message)s') ...
0.322633
0.075756
from .UartStream import * from ..Exceptions import * from ..Manager import * from ..StreamDevice import * from ..StreamParserGenerator import * from ..StreamProtocol import * class UartManager(Manager): """Serial device manager for abstracting stream and parser management. This class implements a comprehensiv...
perilib/hal/UartManager.py
from .UartStream import * from ..Exceptions import * from ..Manager import * from ..StreamDevice import * from ..StreamParserGenerator import * from ..StreamProtocol import * class UartManager(Manager): """Serial device manager for abstracting stream and parser management. This class implements a comprehensiv...
0.812719
0.235493
from darwinexapis.API.InfoAPI.DWX_Info_API import DWX_Info_API from telegramBot import NotificationsTelegramBot # Import the logger: import logging, json logger = logging.getLogger() class DRefresherClass(object): '''Service to be executed at X timeframe and refresh the tokens. Ex (execute every 30 min)...
D-Refresher/D_Refresher.py
from darwinexapis.API.InfoAPI.DWX_Info_API import DWX_Info_API from telegramBot import NotificationsTelegramBot # Import the logger: import logging, json logger = logging.getLogger() class DRefresherClass(object): '''Service to be executed at X timeframe and refresh the tokens. Ex (execute every 30 min)...
0.538498
0.112065
import unittest from yookassa_payout.domain.exceptions.api_error import ApiError from yookassa_payout.domain.response.deposition_response_builder import DepositionResponseBuilder from yookassa_payout.domain.response.make_deposition_response import MakeDepositionResponse from yookassa_payout.domain.response.test_deposi...
tests/unit/test_deposition_response_builder.py
import unittest from yookassa_payout.domain.exceptions.api_error import ApiError from yookassa_payout.domain.response.deposition_response_builder import DepositionResponseBuilder from yookassa_payout.domain.response.make_deposition_response import MakeDepositionResponse from yookassa_payout.domain.response.test_deposi...
0.587352
0.286821
from __future__ import print_function from collections import OrderedDict import itertools def test_config(python, chainer, target, chainerx): if chainerx: s_chainerx = '.chx' else: s_chainerx = '' key = 'chainerch.py{}.{}.{}{}'.format(python, chainer, target, s_chainerx) value = Ord...
.flexci/gen_config.py
from __future__ import print_function from collections import OrderedDict import itertools def test_config(python, chainer, target, chainerx): if chainerx: s_chainerx = '.chx' else: s_chainerx = '' key = 'chainerch.py{}.{}.{}{}'.format(python, chainer, target, s_chainerx) value = Ord...
0.455925
0.101056
from styx_msgs.msg import TrafficLight import csv import cv2 import numpy as np from math import ceil, exp, log from enum import Enum from keras.models import load_model # I had to make TWO totally ugly and disgusting hack because of a Keras bugs: # a) https://github.com/keras-team/keras/issues/7431 # b) https://g...
ros/src/tl_detector/light_classification/tl_classifier_site.py
from styx_msgs.msg import TrafficLight import csv import cv2 import numpy as np from math import ceil, exp, log from enum import Enum from keras.models import load_model # I had to make TWO totally ugly and disgusting hack because of a Keras bugs: # a) https://github.com/keras-team/keras/issues/7431 # b) https://g...
0.762159
0.203549
import logging from time import tzname from subprocess import call SYSTEM_SITE_ID = "system" LOGGER = logging.getLogger("timevortex") KEY_SITE_ID = "siteID" KEY_VARIABLE_ID = "variableID" KEY_VALUE = "value" KEY_DATE = "date" KEY_DST_TIMEZONE = "dstTimezone" KEY_NON_DST_TIMEZONE = "nonDstTimezone" KEY_ERROR = "error" ...
timevortex/utils/globals.py
import logging from time import tzname from subprocess import call SYSTEM_SITE_ID = "system" LOGGER = logging.getLogger("timevortex") KEY_SITE_ID = "siteID" KEY_VARIABLE_ID = "variableID" KEY_VALUE = "value" KEY_DATE = "date" KEY_DST_TIMEZONE = "dstTimezone" KEY_NON_DST_TIMEZONE = "nonDstTimezone" KEY_ERROR = "error" ...
0.344333
0.03949
import torch.nn as nn import torch from tensorboardX import SummaryWriter from torchsummary import summary class Net(nn.Module): def __init__(self, features): super(Net, self).__init__() self.layer0 = nn.Sequential(nn.Linear(features, 16), nn.ReLU(),nn.BatchNorm1d(16)) self.layer1 = nn....
Net/model.py
import torch.nn as nn import torch from tensorboardX import SummaryWriter from torchsummary import summary class Net(nn.Module): def __init__(self, features): super(Net, self).__init__() self.layer0 = nn.Sequential(nn.Linear(features, 16), nn.ReLU(),nn.BatchNorm1d(16)) self.layer1 = nn....
0.932199
0.475727
__description__ = \ """ Compute the positions of nodes in a flattened genotype-phenotype map. This goes into the core NetworkX DiGraph object as the "pos" call. """ __author__ = "<NAME>" from gpgraph import check import numpy as np def flattened(G, node_list=None, scale=1, vertical=False): """ Get flattened ...
gpgraph/pyplot/pos.py
__description__ = \ """ Compute the positions of nodes in a flattened genotype-phenotype map. This goes into the core NetworkX DiGraph object as the "pos" call. """ __author__ = "<NAME>" from gpgraph import check import numpy as np def flattened(G, node_list=None, scale=1, vertical=False): """ Get flattened ...
0.817829
0.604049
import argparse import errno import http.server import os import socketserver import sys from datetime import date from pathlib import Path import helpers from builder import Builder __version__ = '3.2.0' CONFIG_FILE = 'config.yaml' def show_statistics(): articles = 0 drafts = 0 word_count_total = 0 ...
blogy.py
import argparse import errno import http.server import os import socketserver import sys from datetime import date from pathlib import Path import helpers from builder import Builder __version__ = '3.2.0' CONFIG_FILE = 'config.yaml' def show_statistics(): articles = 0 drafts = 0 word_count_total = 0 ...
0.157622
0.071138
import numpy as np from scipy import ndimage from loguru import logger from skimage.morphology import skeletonize as skeletonize_skimage def erode(I, num_iter, thresh=0.5): I -= np.min(I) I = I / np.max(I) I = (I >= thresh) * 1.0 struct2 = ndimage.generate_binary_structure(3, 2) for i in range(...
survos2/server/filtering/morph.py
import numpy as np from scipy import ndimage from loguru import logger from skimage.morphology import skeletonize as skeletonize_skimage def erode(I, num_iter, thresh=0.5): I -= np.min(I) I = I / np.max(I) I = (I >= thresh) * 1.0 struct2 = ndimage.generate_binary_structure(3, 2) for i in range(...
0.514156
0.493531
from datetime import datetime import os import socket import json from sqlite3 import Timestamp from celery import shared_task from progressui.backend import ProgressSend from git.repo.base import Repo from tools import shell, git, bbcommand, patch, bbfile, dishes from tools import migration from tools.migration import...
src/projects/tasks.py
from datetime import datetime import os import socket import json from sqlite3 import Timestamp from celery import shared_task from progressui.backend import ProgressSend from git.repo.base import Repo from tools import shell, git, bbcommand, patch, bbfile, dishes from tools import migration from tools.migration import...
0.109135
0.066327
import unittest import mock from google.api_core import exceptions from google.cloud import datacatalog from google.datacatalog_connectors.commons_test import utils from google.protobuf import timestamp_pb2 from google.datacatalog_connectors import commons class DataCatalogFacadeTestCase(unittest.TestCase): __...
google-datacatalog-connectors-commons/tests/google/datacatalog_connectors/commons/datacatalog_facade_test.py
import unittest import mock from google.api_core import exceptions from google.cloud import datacatalog from google.datacatalog_connectors.commons_test import utils from google.protobuf import timestamp_pb2 from google.datacatalog_connectors import commons class DataCatalogFacadeTestCase(unittest.TestCase): __...
0.512693
0.14734
import warnings import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union from .. import _utilities, _tables __all__ = [ 'HookAuthArgs', 'HookChannelArgs', 'HookHeaderArgs', ] @pulumi.input_type class HookAuthArgs: def __init__(__self__, *, ...
sdk/python/pulumi_okta/inline/_inputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union from .. import _utilities, _tables __all__ = [ 'HookAuthArgs', 'HookChannelArgs', 'HookHeaderArgs', ] @pulumi.input_type class HookAuthArgs: def __init__(__self__, *, ...
0.881558
0.091951
import logging import os from collections import Counter from typing import Dict, List, Optional import click import mlflow import numpy as np import pandas as pd import torch from sklearn.metrics import f1_score from sklearn.model_selection import KFold, StratifiedShuffleSplit from transformers import ( AutoModel...
src/stonkgs/models/nlp_baseline_model.py
import logging import os from collections import Counter from typing import Dict, List, Optional import click import mlflow import numpy as np import pandas as pd import torch from sklearn.metrics import f1_score from sklearn.model_selection import KFold, StratifiedShuffleSplit from transformers import ( AutoModel...
0.839142
0.336195
import pytest from silene.crawl_request import CrawlRequest from silene.crawler_configuration import CrawlerConfiguration def test_constructor_should_raise_value_error_when_invalid_domain_in_allowed_domains() -> None: with pytest.raises(ValueError) as exc_info: CrawlerConfiguration([], allowed_domains=[...
tests/unit/test_crawler_configuration.py
import pytest from silene.crawl_request import CrawlRequest from silene.crawler_configuration import CrawlerConfiguration def test_constructor_should_raise_value_error_when_invalid_domain_in_allowed_domains() -> None: with pytest.raises(ValueError) as exc_info: CrawlerConfiguration([], allowed_domains=[...
0.79956
0.554229
from __future__ import unicode_literals # To use a consistent encoding import codecs from setuptools import setup, find_packages import sys, os.path def parse_reqs(req_path="./requirements.txt"): """Recursively parse requirements from nested pip files.""" install_requires = [] with codecs.open(req_path, ...
setup.py
from __future__ import unicode_literals # To use a consistent encoding import codecs from setuptools import setup, find_packages import sys, os.path def parse_reqs(req_path="./requirements.txt"): """Recursively parse requirements from nested pip files.""" install_requires = [] with codecs.open(req_path, ...
0.481698
0.140248
from user import User from credentials import Credentials def create_user(login_username, password): ''' Function to create new user ''' new_user = User(login_username,password) return new_user def create_credentials(account_name,account_username, account_password): ''' Function to create new credentia...
run.py
from user import User from credentials import Credentials def create_user(login_username, password): ''' Function to create new user ''' new_user = User(login_username,password) return new_user def create_credentials(account_name,account_username, account_password): ''' Function to create new credentia...
0.192236
0.069954
from __future__ import print_function import os import cv2 import json import lmdb import numpy as np from matplotlib import pyplot class USCISI_CMD_API( object ) : """ Simple API for reading the USCISI CMD dataset This API simply loads and parses CMD samples from LMDB # Example: ```python ...
Data/USCISI-CMFD-Small/api.py
from __future__ import print_function import os import cv2 import json import lmdb import numpy as np from matplotlib import pyplot class USCISI_CMD_API( object ) : """ Simple API for reading the USCISI CMD dataset This API simply loads and parses CMD samples from LMDB # Example: ```python ...
0.759047
0.678976
from datetime import datetime from pathlib import PosixPath from typing import List, Tuple, Any, Optional, Dict from dateutil.tz import tzutc from blurr.core.store_key import Key, KeyType from blurr.runner.spark_runner import SparkRunner, get_spark_session def execute_runner(stream_bts_file: str, ...
tests/runner/spark_runner_test.py
from datetime import datetime from pathlib import PosixPath from typing import List, Tuple, Any, Optional, Dict from dateutil.tz import tzutc from blurr.core.store_key import Key, KeyType from blurr.runner.spark_runner import SparkRunner, get_spark_session def execute_runner(stream_bts_file: str, ...
0.743308
0.406921
import torch.nn.functional as F from util.util import compute_tensor_iu def get_new_iou_hook(values, size): return 'iou/new_iou_%s'%size, values['iou/new_i_%s'%size]/values['iou/new_u_%s'%size] def get_orig_iou_hook(values): return 'iou/orig_iou', values['iou/orig_i']/values['iou/orig_u'] def get_iou_gain(v...
util/metrics_compute.py
import torch.nn.functional as F from util.util import compute_tensor_iu def get_new_iou_hook(values, size): return 'iou/new_iou_%s'%size, values['iou/new_i_%s'%size]/values['iou/new_u_%s'%size] def get_orig_iou_hook(values): return 'iou/orig_iou', values['iou/orig_i']/values['iou/orig_u'] def get_iou_gain(v...
0.695855
0.342791
import logging class Tiling(object): def __init__(self, tiles): logging.debug("Initializing tiling - tiles: %s" % (tiles,)) self.tiles = tiles self.squares = [sq for tile in tiles for sq in tile] logging.debug("Initializing tiling - squares: %s" % (self.squares,)) self.min_...
pretty_poly/tiling.py
import logging class Tiling(object): def __init__(self, tiles): logging.debug("Initializing tiling - tiles: %s" % (tiles,)) self.tiles = tiles self.squares = [sq for tile in tiles for sq in tile] logging.debug("Initializing tiling - squares: %s" % (self.squares,)) self.min_...
0.551091
0.427695
# ----------------------------------------------------------------------------- # Module Import # ----------------------------------------------------------------------------- import argparse import atexit from .serial_ifc import get_serial # --------------------------------------------------------------------------...
power_counter/capture_cmd.py
# ----------------------------------------------------------------------------- # Module Import # ----------------------------------------------------------------------------- import argparse import atexit from .serial_ifc import get_serial # --------------------------------------------------------------------------...
0.568416
0.192103
from __future__ import division import numpy as np import scipy.ndimage as ndi from sklearn import mixture def twoPointStencil2D(data, h=1): """ Compute two-Pooints stencil on each axis: f(x+h)-f(x-h) 1Dconvolve([1, 0, -1]) f'(x) = ------------- = ---------------------- ...
ILA/code/predictLayout.py
from __future__ import division import numpy as np import scipy.ndimage as ndi from sklearn import mixture def twoPointStencil2D(data, h=1): """ Compute two-Pooints stencil on each axis: f(x+h)-f(x-h) 1Dconvolve([1, 0, -1]) f'(x) = ------------- = ---------------------- ...
0.696062
0.628151
import mock from nova import context as nova_context from nova import exception from nova import objects from nova.scheduler import weights from nova.tests import fixtures as nova_fixtures from nova.tests.functional import integrated_helpers from nova.tests.unit import fake_notifier from nova.tests.unit.image import ...
nova/tests/functional/test_cross_cell_migrate.py
import mock from nova import context as nova_context from nova import exception from nova import objects from nova.scheduler import weights from nova.tests import fixtures as nova_fixtures from nova.tests.functional import integrated_helpers from nova.tests.unit import fake_notifier from nova.tests.unit.image import ...
0.630116
0.281668
class SamplePlayer: """ Sample Player class """ def __init__(self, xpos, ypos, step, lives, symbol="#"): """ Function which inits a Sample Player :param xpos: X position of the Player :param ypos: Y position of the Player :param step: How many steps should the Pla...
clge/plugs/DefaultAssets/sample_player.py
class SamplePlayer: """ Sample Player class """ def __init__(self, xpos, ypos, step, lives, symbol="#"): """ Function which inits a Sample Player :param xpos: X position of the Player :param ypos: Y position of the Player :param step: How many steps should the Pla...
0.894424
0.673128
import battle import jsonobject import logging import model logger = logging.getLogger('kcaa.kcsapi.expedition') class Expedition(model.KCAAObject): """Information about the current expedition.""" fleet_id = jsonobject.JSONProperty('fleet_id', value_type=int) """ID of the fleet which is going on exped...
server/kcaa/kcsapi/expedition.py
import battle import jsonobject import logging import model logger = logging.getLogger('kcaa.kcsapi.expedition') class Expedition(model.KCAAObject): """Information about the current expedition.""" fleet_id = jsonobject.JSONProperty('fleet_id', value_type=int) """ID of the fleet which is going on exped...
0.591133
0.169991
import outputters import inputters import psucontrol import time import yaml import os, random, shlex, sys def boot(): display.cls(); display.line(0, "Time machine is"); display.line(1, "starting ..."); time.sleep(1) display.cls(); display.line(0, "Casostroj startuje"); time.sleep(1) display.cls(); displa...
timemachine.py
import outputters import inputters import psucontrol import time import yaml import os, random, shlex, sys def boot(): display.cls(); display.line(0, "Time machine is"); display.line(1, "starting ..."); time.sleep(1) display.cls(); display.line(0, "Casostroj startuje"); time.sleep(1) display.cls(); displa...
0.190197
0.119923
import json from typing import ClassVar, Dict, Optional from pydantic import BaseModel, Field from emulation_system.compose_file_creator.input.hardware_models.hardware_model import ( EmulationLevelNotSupportedError, HardwareModel, ) from emulation_system.compose_file_creator.settings.config_file_settings impo...
emulation_system/emulation_system/compose_file_creator/input/hardware_models/modules/module_model.py
import json from typing import ClassVar, Dict, Optional from pydantic import BaseModel, Field from emulation_system.compose_file_creator.input.hardware_models.hardware_model import ( EmulationLevelNotSupportedError, HardwareModel, ) from emulation_system.compose_file_creator.settings.config_file_settings impo...
0.848533
0.181444
import pytest from opencadd.structure.pocket import PocketBase class TestPocketBase: """ Test PocketBase class methods. """ @pytest.mark.parametrize( "residue_ids, residue_ixs, residue_ids_formatted, residue_ixs_formatted", [ ([1, 2, 3], None, [1, 2, 3], [None, None, None...
opencadd/tests/structure/test_pocket_base.py
import pytest from opencadd.structure.pocket import PocketBase class TestPocketBase: """ Test PocketBase class methods. """ @pytest.mark.parametrize( "residue_ids, residue_ixs, residue_ids_formatted, residue_ixs_formatted", [ ([1, 2, 3], None, [1, 2, 3], [None, None, None...
0.61659
0.634741
import tensorflow as tf pi = 3.141592653589793 U = 32768.0 tfand = tf.logical_and class TutorialBotOutput: def __init__(self, batch_size): self.batch_size = batch_size global zero,zeros3 zero = tf.zeros(self.batch_size, tf.float32) zeros3 = [zero,zero,zero] def get_output_ve...
bot_code/models/fake_models/TutorialBot/atba2_demo_output_reg.py
import tensorflow as tf pi = 3.141592653589793 U = 32768.0 tfand = tf.logical_and class TutorialBotOutput: def __init__(self, batch_size): self.batch_size = batch_size global zero,zeros3 zero = tf.zeros(self.batch_size, tf.float32) zeros3 = [zero,zero,zero] def get_output_ve...
0.69285
0.577674
import pygame pygame.display.init() pygame.mixer.init() pygame.font.init() pygame.mixer.music.load('pong_sound.mp3') font = pygame.font.SysFont('optimattc', 25, 0, 0) class Game: width = 640 height = 400 running = True movementY = 6 movementX = 6 white = (255, 255, 255, 255) playerWidth...
pong.py
import pygame pygame.display.init() pygame.mixer.init() pygame.font.init() pygame.mixer.music.load('pong_sound.mp3') font = pygame.font.SysFont('optimattc', 25, 0, 0) class Game: width = 640 height = 400 running = True movementY = 6 movementX = 6 white = (255, 255, 255, 255) playerWidth...
0.213295
0.192255
import testtools from os_apply_config import config_exception from os_apply_config import value_types class ValueTypeTestCase(testtools.TestCase): def test_unknown_type(self): self.assertRaises( ValueError, value_types.ensure_type, "foo", "badtype") def test_int(self): self.ass...
os_apply_config/tests/test_value_type.py
import testtools from os_apply_config import config_exception from os_apply_config import value_types class ValueTypeTestCase(testtools.TestCase): def test_unknown_type(self): self.assertRaises( ValueError, value_types.ensure_type, "foo", "badtype") def test_int(self): self.ass...
0.548432
0.440289
import math import threading import time from bmconfigparser import BMConfigParser from singleton import Singleton import state class Throttle(object): minChunkSize = 4096 maxChunkSize = 131072 def __init__(self, limit=0): self.limit = limit self.speed = 0 self.chunkSize = Throttl...
src/throttle.py
import math import threading import time from bmconfigparser import BMConfigParser from singleton import Singleton import state class Throttle(object): minChunkSize = 4096 maxChunkSize = 131072 def __init__(self, limit=0): self.limit = limit self.speed = 0 self.chunkSize = Throttl...
0.332527
0.096919
from abc import ABC, abstractmethod import copy from ..PlayerStructs import * import json class PlayerDataTrimAlg(ABC): def __init__(self): pass @abstractmethod def trimmedList(self, pastModelIncs): pass # ---------------------- KNNRegression stuff --------------------------- class AgeSortPlayerDataTrimAlg(...
GIMMECore/AlgDefStructs/PlayerDataTrimAlg.py
from abc import ABC, abstractmethod import copy from ..PlayerStructs import * import json class PlayerDataTrimAlg(ABC): def __init__(self): pass @abstractmethod def trimmedList(self, pastModelIncs): pass # ---------------------- KNNRegression stuff --------------------------- class AgeSortPlayerDataTrimAlg(...
0.390127
0.273765
from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ...
app/migrations/0001_initial.py
from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ...
0.413359
0.130258
import pygame class Settings: """ Una clase para almacenar la configuración de celdaTP """ def __init__(self): """ Inicializa la configuración del juego """ # Configuración de pantalla self.screen_width = 960 self.screen_height = 540 self.screen = pygame.display.set_mod...
settings.py
import pygame class Settings: """ Una clase para almacenar la configuración de celdaTP """ def __init__(self): """ Inicializa la configuración del juego """ # Configuración de pantalla self.screen_width = 960 self.screen_height = 540 self.screen = pygame.display.set_mod...
0.334155
0.178562
import json import numpy as np from lib.skeleton.skeleton import Skeleton from lib.dataset.mocap_dataset import MocapDataset from lib.camera.camera import CameraInfoPacket h36m_skeleton = Skeleton(parents=[-1, 0, 1, 2, 3, 4, 0, 6, 7, 8, 9, 0, 11, 12, 13, 14, 12, 16, 17, 18, 19, 20, 1...
lib/dataset/h36m_aug_dataset.py
import json import numpy as np from lib.skeleton.skeleton import Skeleton from lib.dataset.mocap_dataset import MocapDataset from lib.camera.camera import CameraInfoPacket h36m_skeleton = Skeleton(parents=[-1, 0, 1, 2, 3, 4, 0, 6, 7, 8, 9, 0, 11, 12, 13, 14, 12, 16, 17, 18, 19, 20, 1...
0.592667
0.204839
"""Test cases for style/* checks.""" from test.warnings_test_common import DEFINITION_TYPES from test.warnings_test_common import FUNCTIONS_SETTING_VARS from test.warnings_test_common import LinterFailure from test.warnings_test_common import format_with_args from test.warnings_test_common import format_with_command f...
test/test_style_warnings.py
"""Test cases for style/* checks.""" from test.warnings_test_common import DEFINITION_TYPES from test.warnings_test_common import FUNCTIONS_SETTING_VARS from test.warnings_test_common import LinterFailure from test.warnings_test_common import format_with_args from test.warnings_test_common import format_with_command f...
0.741393
0.479808
import traceback import json import botutils from discord.ext import commands from ._gameplay import Gameplay from botutils import start_votes_timer with open('botutils/bot_text.json') as json_file: language = json.load(json_file) error_str = language["system"]["error"] fstart_min = language["errors"]["fstart_mi...
cmd/gameplay/start.py
import traceback import json import botutils from discord.ext import commands from ._gameplay import Gameplay from botutils import start_votes_timer with open('botutils/bot_text.json') as json_file: language = json.load(json_file) error_str = language["system"]["error"] fstart_min = language["errors"]["fstart_mi...
0.363082
0.075075
from __future__ import absolute_import __version__ = "0.1.1" from id_card_detector.cv_utils import (read_image, visualize_prediction, export_predicted_bboxes, fit_quads_over_masks, ...
id_card_detector/__init__.py
from __future__ import absolute_import __version__ = "0.1.1" from id_card_detector.cv_utils import (read_image, visualize_prediction, export_predicted_bboxes, fit_quads_over_masks, ...
0.834069
0.278576
from collections import deque import copy drow = [0, -1, -1, 0, 1, 1, 1, 0, -1] dcol = [0, 0, -1, -1, -1, 0, 1, 1, 1] def updateTable(table, sharkRow, sharkCol): smallestFish = float('inf') fishRow, fishCol = 0, 0 biggestFish = 0 for i in range(4): for j in range(4): curFish = ta...
practices/teen_shark.py
from collections import deque import copy drow = [0, -1, -1, 0, 1, 1, 1, 0, -1] dcol = [0, 0, -1, -1, -1, 0, 1, 1, 1] def updateTable(table, sharkRow, sharkCol): smallestFish = float('inf') fishRow, fishCol = 0, 0 biggestFish = 0 for i in range(4): for j in range(4): curFish = ta...
0.368178
0.304843
from behave import * import requests from django.contrib.auth.models import User from rest_framework.authtoken.models import Token use_step_matcher("re") @given("that I am a unregistered participant of a event") def step_impl(context): context.username = "12thMan" context.password = "<PASSWORD>" context...
behave_tests/steps/participant_register.py
from behave import * import requests from django.contrib.auth.models import User from rest_framework.authtoken.models import Token use_step_matcher("re") @given("that I am a unregistered participant of a event") def step_impl(context): context.username = "12thMan" context.password = "<PASSWORD>" context...
0.396886
0.21101
from dataclasses import dataclass from typing import Any, Dict, Final, List, Optional from boto3.dynamodb.conditions import Attr import boto3 @dataclass(frozen=True) class User: user_id: str name: str face_ids: List[str] @classmethod def parse(cls, data: Dict): return User(user_id=data['...
amazon_rekognition/user_database.py
from dataclasses import dataclass from typing import Any, Dict, Final, List, Optional from boto3.dynamodb.conditions import Attr import boto3 @dataclass(frozen=True) class User: user_id: str name: str face_ids: List[str] @classmethod def parse(cls, data: Dict): return User(user_id=data['...
0.689201
0.157396
import numpy as np from math import factorial, sqrt, cos, sin fact = lambda x: factorial(int(x)) def choose(n, k): return fact(n)/fact(k)/fact(n-k) def dmat_entry(j,m_,m,beta): #real valued. implemented according to wikipedia partA = sqrt(fact(j+m_)*fact(j-m_)*fact(j+m)*fact(j-m)) partB = 0. for s ...
utils/WignerD.py
import numpy as np from math import factorial, sqrt, cos, sin fact = lambda x: factorial(int(x)) def choose(n, k): return fact(n)/fact(k)/fact(n-k) def dmat_entry(j,m_,m,beta): #real valued. implemented according to wikipedia partA = sqrt(fact(j+m_)*fact(j-m_)*fact(j+m)*fact(j-m)) partB = 0. for s ...
0.211417
0.55923
from django import forms from .models import Category from .models import Location from .models import Organization ''' Forms for the landing page dropdowns. The category dropdown is a choice field which displays all categories in the queryset. It also excludes the empty string and . characters from categories since...
volDB/forms.py
from django import forms from .models import Category from .models import Location from .models import Organization ''' Forms for the landing page dropdowns. The category dropdown is a choice field which displays all categories in the queryset. It also excludes the empty string and . characters from categories since...
0.552057
0.117876
# Copyright 2020-2021 Blue Brain Project / EPFL # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicab...
cord19kg/apps/resources.py
# Copyright 2020-2021 Blue Brain Project / EPFL # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicab...
0.821367
0.415136
from sqlalchemy import Column, Float, String, Integer, ForeignKey, create_engine, inspect from sqlalchemy.engine import Engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from utils.constants import WEBTEXT_DB Base = declarative_base() Session = sessio...
utils/db.py
from sqlalchemy import Column, Float, String, Integer, ForeignKey, create_engine, inspect from sqlalchemy.engine import Engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from utils.constants import WEBTEXT_DB Base = declarative_base() Session = sessio...
0.663887
0.217732
from __future__ import print_function from __future__ import unicode_literals import time import sys import os import shutil import csv import boto3 import pyspark import zipfile import tarfile from time import gmtime, strftime from awsglue.utils import getResolvedOptions import mleap.pyspark from pyspark.sql import...
02_data_exploration_and_feature_eng/endtoendml_etl.py
from __future__ import print_function from __future__ import unicode_literals import time import sys import os import shutil import csv import boto3 import pyspark import zipfile import tarfile from time import gmtime, strftime from awsglue.utils import getResolvedOptions import mleap.pyspark from pyspark.sql import...
0.451327
0.225811
import asyncio import copy import contextlib import time import os import random import re import json import logging import tempfile import uuid from xml.etree import ElementTree as et import aiohttp from aiohttp import web from rallyci import utils from rallyci.common import asyncssh LOG = logging.getLogger(__nam...
rallyci/providers/virsh.py
import asyncio import copy import contextlib import time import os import random import re import json import logging import tempfile import uuid from xml.etree import ElementTree as et import aiohttp from aiohttp import web from rallyci import utils from rallyci.common import asyncssh LOG = logging.getLogger(__nam...
0.283583
0.101947
import json from hashlib import sha1 from hmac import HMAC import redis from redis_benchmarks_specification.__api__.app import ( create_app, SIG_HEADER, should_action, ) from redis_benchmarks_specification.__common__.env import ( STREAM_KEYNAME_GH_EVENTS_COMMIT, ) def test_create_app(): try: ...
utils/tests/test_app.py
import json from hashlib import sha1 from hmac import HMAC import redis from redis_benchmarks_specification.__api__.app import ( create_app, SIG_HEADER, should_action, ) from redis_benchmarks_specification.__common__.env import ( STREAM_KEYNAME_GH_EVENTS_COMMIT, ) def test_create_app(): try: ...
0.395484
0.190065
from __future__ import annotations import argparse import json import os import re from typing import List, Tuple, Sequence, Dict, Iterator, Optional import boto3 import requests # type: ignore import yaml # type: ignore REGION = "us-east-1" ORG_NAME = "<NAME>" R53_STACK_NAME = "nextflow-r53-alias-record" R53_STA...
bin/configure-tower-projects.py
from __future__ import annotations import argparse import json import os import re from typing import List, Tuple, Sequence, Dict, Iterator, Optional import boto3 import requests # type: ignore import yaml # type: ignore REGION = "us-east-1" ORG_NAME = "<NAME>" R53_STACK_NAME = "nextflow-r53-alias-record" R53_STA...
0.792464
0.182025
llimport streamlit as st import pickle st.sidebar.image("img.jpg",use_column_width=True) st.sidebar.title("FAKE NEWS AI") st.header("Fake news Classification".upper()) st.empty() option2 = st.sidebar.checkbox("creator info") if option2: st.info("### project by <NAME>") st.info("KIET, MCA") option...
app.py
llimport streamlit as st import pickle st.sidebar.image("img.jpg",use_column_width=True) st.sidebar.title("FAKE NEWS AI") st.header("Fake news Classification".upper()) st.empty() option2 = st.sidebar.checkbox("creator info") if option2: st.info("### project by <NAME>") st.info("KIET, MCA") option...
0.234056
0.196209
import matplotlib.pyplot as plt import sys import os import json import numpy as np import matplotlib.patches as mpatches import math import matplotlib.ticker as ticker from plot_utility import plot_figure from plot_utility import plot_stars_figure from plot_utility import get_Xcent_node from plot_utility import get_X...
sim/script/plot_single.py
import matplotlib.pyplot as plt import sys import os import json import numpy as np import matplotlib.patches as mpatches import math import matplotlib.ticker as ticker from plot_utility import plot_figure from plot_utility import plot_stars_figure from plot_utility import get_Xcent_node from plot_utility import get_X...
0.177454
0.269214
import json import argparse from pathlib import Path def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('--data_dir', default="/deep/group/xray4all") parser.add_argument('--experiment_dir', default=None) parser.add_argument('--old_final', action="store_true") parser.add_arg...
scripts/write_configs.py
import json import argparse from pathlib import Path def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('--data_dir', default="/deep/group/xray4all") parser.add_argument('--experiment_dir', default=None) parser.add_argument('--old_final', action="store_true") parser.add_arg...
0.271638
0.159446
from djinni.support import MultiSet # default imported in all files from djinni.exception import CPyException # default imported in all files from djinni.pycffi_marshal import CPyBoxedBool, CPyBoxedF32, CPyBoxedF64, CPyBoxedI16, CPyBoxedI32, CPyBoxedI64, CPyBoxedI8, CPyPrimitive, CPyRecord, CPyString from constant_re...
test-suite/generated-src/python/constants.py
from djinni.support import MultiSet # default imported in all files from djinni.exception import CPyException # default imported in all files from djinni.pycffi_marshal import CPyBoxedBool, CPyBoxedF32, CPyBoxedF64, CPyBoxedI16, CPyBoxedI32, CPyBoxedI64, CPyBoxedI8, CPyPrimitive, CPyRecord, CPyString from constant_re...
0.547464
0.085251
import matplotlib.pyplot as plt # Measurements from happy-path.data expt = [ ('HotStuff',[ (14.917,11.54), (41.649,12.6), (62.075,14.15), (94.362,18.69), (112.436,23.72), (124.599,28.59), (129.521,33.79), (135.073,39.175), (140.052,48.7), ...
plot/happy-path/happy-path.py
import matplotlib.pyplot as plt # Measurements from happy-path.data expt = [ ('HotStuff',[ (14.917,11.54), (41.649,12.6), (62.075,14.15), (94.362,18.69), (112.436,23.72), (124.599,28.59), (129.521,33.79), (135.073,39.175), (140.052,48.7), ...
0.280616
0.445228