code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from functools import partial from flask import Blueprint, request from wrf.api.base import BaseAPI, api_view from wrf.base import APIError from wrf.framework.flask import FlaskFrameworkComponent from wrf.orm.peewee import PeeweeORMComponent from wrf.pagination.base import NoPaginationComponent, PagePaginationCompone...
tests/flask_peewee_marshmallow/api.py
from functools import partial from flask import Blueprint, request from wrf.api.base import BaseAPI, api_view from wrf.base import APIError from wrf.framework.flask import FlaskFrameworkComponent from wrf.orm.peewee import PeeweeORMComponent from wrf.pagination.base import NoPaginationComponent, PagePaginationCompone...
0.542136
0.069038
import errno import sys import MySQLdb as mysql import MySQLdb.cursors import time import glob import re import socket import os import select import psutil import subprocess def readconfig( config ): """Reads parameters from a config file. Args: config (str): path to config file If config does not exist t...
access/db.py
import errno import sys import MySQLdb as mysql import MySQLdb.cursors import time import glob import re import socket import os import select import psutil import subprocess def readconfig( config ): """Reads parameters from a config file. Args: config (str): path to config file If config does not exist t...
0.145996
0.092442
import os # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 # os.environ["CUDA_VISIBLE_DEVICES"]="0" import torch import torch.nn as nn import torch.nn.utils.prune as prune import torch.optim as optim from torch.optim import lr_scheduler import numpy as np from torch.utils.tensorboard impor...
src/prune.py
import os # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 # os.environ["CUDA_VISIBLE_DEVICES"]="0" import torch import torch.nn as nn import torch.nn.utils.prune as prune import torch.optim as optim from torch.optim import lr_scheduler import numpy as np from torch.utils.tensorboard impor...
0.511473
0.105211
from __future__ import absolute_import import unittest import cons3rt from cons3rt.api.deployments_api import DeploymentsApi # noqa: E501 from cons3rt.rest import ApiException class TestDeploymentsApi(unittest.TestCase): """DeploymentsApi unit test stubs""" def setUp(self): self.api = cons3rt.api....
test/test_deployments_api.py
from __future__ import absolute_import import unittest import cons3rt from cons3rt.api.deployments_api import DeploymentsApi # noqa: E501 from cons3rt.rest import ApiException class TestDeploymentsApi(unittest.TestCase): """DeploymentsApi unit test stubs""" def setUp(self): self.api = cons3rt.api....
0.558086
0.147279
import base64 from unittest.mock import patch import pytest from koris.provision.cloud_init import NthMasterInit, NodeInit, FirstMasterInit from koris.ssl import (create_certs, CertBundle, create_key, create_ca) from koris.cloud.openstack import OSCloudConfig class DummyServer: # pylint: disable=too-few-public-met...
tests/test_cloud_init.py
import base64 from unittest.mock import patch import pytest from koris.provision.cloud_init import NthMasterInit, NodeInit, FirstMasterInit from koris.ssl import (create_certs, CertBundle, create_key, create_ca) from koris.cloud.openstack import OSCloudConfig class DummyServer: # pylint: disable=too-few-public-met...
0.427277
0.175962
import numpy as np from BDSpace import Space from BDSpace.Figure.Sphere import Sphere from BDSpace.Curve.Parametric import Arc from BDSpace.Field import SuperposedField from BDSpace.Field import HyperbolicPotentialSphericalConservativeField from BDSpace.Field import HyperbolicPotentialCurveConservativeField import BD...
demo/08_superposed_fields_demo.py
import numpy as np from BDSpace import Space from BDSpace.Figure.Sphere import Sphere from BDSpace.Curve.Parametric import Arc from BDSpace.Field import SuperposedField from BDSpace.Field import HyperbolicPotentialSphericalConservativeField from BDSpace.Field import HyperbolicPotentialCurveConservativeField import BD...
0.655667
0.512693
"""Tests for tensorflow_data_validation.statistics.constituents.count_missing_generator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import absltest import pyarrow as pa from tensorflow_data_validation import types from tensorflow_d...
tensorflow_data_validation/statistics/generators/constituents/count_missing_generator_test.py
"""Tests for tensorflow_data_validation.statistics.constituents.count_missing_generator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import absltest import pyarrow as pa from tensorflow_data_validation import types from tensorflow_d...
0.868757
0.556701
from __future__ import unicode_literals from django.db import models, migrations import powerdns.utils import django.core.validators import powerdns.models.powerdns import dj.choices.fields from django.conf import settings import powerdns.models.requests class Migration(migrations.Migration): dependencies = [ ...
powerdns/migrations/0013_auto_20151124_0301.py
from __future__ import unicode_literals from django.db import models, migrations import powerdns.utils import django.core.validators import powerdns.models.powerdns import dj.choices.fields from django.conf import settings import powerdns.models.requests class Migration(migrations.Migration): dependencies = [ ...
0.512937
0.129706
import time from datetime import datetime from decimal import Decimal import json from src.utils import get_last_week_ref_timestamp, get_ref_timestamp,\ calc_nas_ranking_this_week, bring_slack_id_from_slack_name, bring_slack_name_from_slack_id def test_get_ref_timestamp(): """Get a time stamp at the start of...
tests/test_utils.py
import time from datetime import datetime from decimal import Decimal import json from src.utils import get_last_week_ref_timestamp, get_ref_timestamp,\ calc_nas_ranking_this_week, bring_slack_id_from_slack_name, bring_slack_name_from_slack_id def test_get_ref_timestamp(): """Get a time stamp at the start of...
0.676086
0.740433
import numpy as np from sklearn.tree import DecisionTreeClassifier class Tree(): # all_node_list = list() root = None fields = list() classes = list() class Node(): def __init__(self): self.field = '' self.value = -2 self.score = -2 self.lef...
zmk/nyokaBase/reconstruct/tree.py
import numpy as np from sklearn.tree import DecisionTreeClassifier class Tree(): # all_node_list = list() root = None fields = list() classes = list() class Node(): def __init__(self): self.field = '' self.value = -2 self.score = -2 self.lef...
0.646349
0.293262
import re import json import requests from . import base from . import config import logging import logging.config # FIXME logging should be properly ported using the new config logging.basicConfig() log = logging.getLogger('scitran.api.centralclient') logging.getLogger('urllib3').setLevel(logging.WARNING) # silenc...
api/centralclient.py
import re import json import requests from . import base from . import config import logging import logging.config # FIXME logging should be properly ported using the new config logging.basicConfig() log = logging.getLogger('scitran.api.centralclient') logging.getLogger('urllib3').setLevel(logging.WARNING) # silenc...
0.23144
0.081483
import sys import json import os import numpy as np from scipy.optimize import linear_sum_assignment import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d, Axes3D import cv2 import pylab as pl from numpy import linalg as LA import random import math from mpl_toolkits.mplot3d import axes3d, Axes3D from...
matching/AccomodateAllWildtrack.py
import sys import json import os import numpy as np from scipy.optimize import linear_sum_assignment import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d, Axes3D import cv2 import pylab as pl from numpy import linalg as LA import random import math from mpl_toolkits.mplot3d import axes3d, Axes3D from...
0.204501
0.288182
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['AssessmentArgs', 'Assessment'] @pulumi.input_type class AssessmentArgs: def __init__(_...
sdk/python/pulumi_azure_native/security/v20190101preview/assessment.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['AssessmentArgs', 'Assessment'] @pulumi.input_type class AssessmentArgs: def __init__(_...
0.820037
0.059374
import sqlite3 PATH_DB = "C:/DEV/PillData/Sqlite_DB/pills_5_filtered.db" SIZE_TOLERANCE = 1 # margin of error of pill size (in milimeters) def query_pills(pill_properties): """ Queries pill information from DB Query is constructed dynamically, input values are checked to avoid SQL injection Input ...
experiments/sql/sqlit_qry2.py
import sqlite3 PATH_DB = "C:/DEV/PillData/Sqlite_DB/pills_5_filtered.db" SIZE_TOLERANCE = 1 # margin of error of pill size (in milimeters) def query_pills(pill_properties): """ Queries pill information from DB Query is constructed dynamically, input values are checked to avoid SQL injection Input ...
0.21158
0.171477
from PyQt5.QtWidgets import QPushButton from .results_base import ResultsBase class Results(ResultsBase): def __init__(self, parent=None, button_func=None, params=None): super().__init__(parent, 'Results', params) self.button_func = button_func self.make_tables(self.params.re...
malss/app/results.py
from PyQt5.QtWidgets import QPushButton from .results_base import ResultsBase class Results(ResultsBase): def __init__(self, parent=None, button_func=None, params=None): super().__init__(parent, 'Results', params) self.button_func = button_func self.make_tables(self.params.re...
0.428712
0.057705
from argparse import ArgumentParser import torch import torch.multiprocessing import pytorch_lightning as pl from pytorch_lightning import loggers as pl_loggers import numpy as np from neural_clbf.controllers import NeuralCLBFController from neural_clbf.datamodules.episodic_datamodule import ( EpisodicDataModule,...
neural_clbf/training/devel/train_quad2d_obstacles.py
from argparse import ArgumentParser import torch import torch.multiprocessing import pytorch_lightning as pl from pytorch_lightning import loggers as pl_loggers import numpy as np from neural_clbf.controllers import NeuralCLBFController from neural_clbf.datamodules.episodic_datamodule import ( EpisodicDataModule,...
0.808181
0.508056
from alfred.utils.config import * from alfred.utils.directory_tree import * from alfred.utils.misc import create_logger, select_storage_dirs from alfred.prepare_schedule import create_experiment_dir from importlib import import_module def my_type_func(add_arg): name, val_type = add_arg.split("=", 1) val, typ ...
alfred/copy_config.py
from alfred.utils.config import * from alfred.utils.directory_tree import * from alfred.utils.misc import create_logger, select_storage_dirs from alfred.prepare_schedule import create_experiment_dir from importlib import import_module def my_type_func(add_arg): name, val_type = add_arg.split("=", 1) val, typ ...
0.424651
0.140425
# TobiaC 2015-12-02 import numpy import matplotlib.pyplot as plt import matplotlib.dates from antpat.reps.sphgridfun import pntsonsphere, tvecfun from antpat.io.feko_ffe import FEKOffe from antpat.radfarfield import RadFarField class DualPolElem(object): """Main class for a dual-pol antenna element. It can be co...
antpat/dualpolelem.py
# TobiaC 2015-12-02 import numpy import matplotlib.pyplot as plt import matplotlib.dates from antpat.reps.sphgridfun import pntsonsphere, tvecfun from antpat.io.feko_ffe import FEKOffe from antpat.radfarfield import RadFarField class DualPolElem(object): """Main class for a dual-pol antenna element. It can be co...
0.586523
0.358016
import tensorflow as tf from tensorflow.keras.utils import to_categorical from tensorflow.keras.metrics import MeanIoU from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt n_classes = 3 train_images = np.load(r"C:\Users\Lincoln\Desktop\images_encoded.npy") train_ma...
evaluate.py
import tensorflow as tf from tensorflow.keras.utils import to_categorical from tensorflow.keras.metrics import MeanIoU from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt n_classes = 3 train_images = np.load(r"C:\Users\Lincoln\Desktop\images_encoded.npy") train_ma...
0.772101
0.667608
import os import json import matplotlib import matplotlib.pyplot as plt import numpy as np import seaborn as sns; colors = sns.color_palette("hls", n_colors=11) ''' Get the range of hyperparameters from a list of labels. ''' def get_range(labels, p=True): keywords = [] for i in labels[0].split('-'): ...
python/data-visualization/roofline/roofline.py
import os import json import matplotlib import matplotlib.pyplot as plt import numpy as np import seaborn as sns; colors = sns.color_palette("hls", n_colors=11) ''' Get the range of hyperparameters from a list of labels. ''' def get_range(labels, p=True): keywords = [] for i in labels[0].split('-'): ...
0.192463
0.240953
import torch import torch.nn as nn class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) class Model(torch.nn.Module): def __init__(self, input_shape, outputs_count): super(Model, self).__init__() self.device = torch.device("cuda" if torch.cuda.is_av...
src/models/net_1/model.py
import torch import torch.nn as nn class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) class Model(torch.nn.Module): def __init__(self, input_shape, outputs_count): super(Model, self).__init__() self.device = torch.device("cuda" if torch.cuda.is_av...
0.928506
0.369799
import math from fisica.Punto import Punto class Colisiones: """ Calcula algunas colisiones basicas entre objetos 2D """ def _init_(self, mundo): self.Mundo = mundo def ColisionCirculoRectangulo(self, circulo, rectangulo): """ Comprueba si un circulo colisiona con un rectangulo. No func...
fisica/Colisiones.py
import math from fisica.Punto import Punto class Colisiones: """ Calcula algunas colisiones basicas entre objetos 2D """ def _init_(self, mundo): self.Mundo = mundo def ColisionCirculoRectangulo(self, circulo, rectangulo): """ Comprueba si un circulo colisiona con un rectangulo. No func...
0.602412
0.742071
import neoml.PythonWrapper as PythonWrapper from .Dnn import Layer from neoml.Utils import check_input_layers import neoml.Blob as Blob class Irnn(Layer): """IRNN implementation from this article: https://arxiv.org/pdf/1504.00941.pdf It's a simple recurrent unit with the following formula: :math:`Y_t = R...
NeoML/Python/neoml/Dnn/Irnn.py
import neoml.PythonWrapper as PythonWrapper from .Dnn import Layer from neoml.Utils import check_input_layers import neoml.Blob as Blob class Irnn(Layer): """IRNN implementation from this article: https://arxiv.org/pdf/1504.00941.pdf It's a simple recurrent unit with the following formula: :math:`Y_t = R...
0.917686
0.675745
__author__ = "Group 03, CS 212, Lanzhou University" __copyright__ = "Copyright (c) 2020, Study Project in Lanzhou University , China" __license__ = "GPL V3" __version__ = "0.1" __maintainer__ = "ZhaoHaoran" __email__ = "<EMAIL>" __status__ = "Experimental" import pandas as pd import numpy as np import random import sc...
Homework/data4/Data4.py
__author__ = "Group 03, CS 212, Lanzhou University" __copyright__ = "Copyright (c) 2020, Study Project in Lanzhou University , China" __license__ = "GPL V3" __version__ = "0.1" __maintainer__ = "ZhaoHaoran" __email__ = "<EMAIL>" __status__ = "Experimental" import pandas as pd import numpy as np import random import sc...
0.627495
0.449513
import contextlib import os from libpb import env, event, job, mk, pkg from libpb.stacks import base, mutators __all__ = ["Config", "Depend"] class Lock(object): """A simple Uniprocessor lock.""" def __init__(self): """Initialise lock.""" self._locked = False def acquire(self): ...
libpb/stacks/common.py
import contextlib import os from libpb import env, event, job, mk, pkg from libpb.stacks import base, mutators __all__ = ["Config", "Depend"] class Lock(object): """A simple Uniprocessor lock.""" def __init__(self): """Initialise lock.""" self._locked = False def acquire(self): ...
0.41324
0.09401
# stdlib from types import ListType from nose.plugins.skip import SkipTest # project from checks import AgentCheck from tests.checks.common import load_check from tests.checks.common import AgentCheckTest class TestCouchbase(AgentCheckTest): """Basic Test for couchbase integration.""" CHECK_NAME = 'couchbas...
couchbase/test/test_couchbase.py
# stdlib from types import ListType from nose.plugins.skip import SkipTest # project from checks import AgentCheck from tests.checks.common import load_check from tests.checks.common import AgentCheckTest class TestCouchbase(AgentCheckTest): """Basic Test for couchbase integration.""" CHECK_NAME = 'couchbas...
0.58676
0.451024
import logging import os from git.exc import NoSuchPathError from assigner.roster_util import get_filtered_roster from assigner.backends import RepoError from assigner.backends.decorators import requires_config_and_backend from assigner import progress help = "Push changes to student repos" logger = logging.getLogg...
assigner/commands/push.py
import logging import os from git.exc import NoSuchPathError from assigner.roster_util import get_filtered_roster from assigner.backends import RepoError from assigner.backends.decorators import requires_config_and_backend from assigner import progress help = "Push changes to student repos" logger = logging.getLogg...
0.14814
0.068631
from pyquaternion import Quaternion import inverse_kinematics from visual_mpc.envs.util.interpolation import QuinticSpline import logging from intera_core_msgs.msg import EndpointState from threading import Condition import rospy import numpy as np from geometry_msgs.msg import Quaternion as Quaternion_msg CONTROL_RA...
visual_mpc/envs/robot_envs/sawyer/control_util.py
from pyquaternion import Quaternion import inverse_kinematics from visual_mpc.envs.util.interpolation import QuinticSpline import logging from intera_core_msgs.msg import EndpointState from threading import Condition import rospy import numpy as np from geometry_msgs.msg import Quaternion as Quaternion_msg CONTROL_RA...
0.505127
0.336835
import logging from django.conf import settings from obj_update import obj_update_or_create import boto.ec2 import boto.vpc from .models import Region, Instance, SecurityGroup, SecurityGroupRule, VPC logger = logging.getLogger(__name__) def pull_vpcs(region=None): if region is None: region = Region.ob...
aws_admin/utils.py
import logging from django.conf import settings from obj_update import obj_update_or_create import boto.ec2 import boto.vpc from .models import Region, Instance, SecurityGroup, SecurityGroupRule, VPC logger = logging.getLogger(__name__) def pull_vpcs(region=None): if region is None: region = Region.ob...
0.153105
0.081886
import wx from src.wizard.view.clsResultPage import ResultPageView from src.wizard.controller.frmSampFeatSelectPanel \ import SampFeatSelectPanel from src.wizard.controller.frmProcLevelSelectPanel \ import ProcLevelSelectPanel from src.wizard.controller.frmActionsSelectPanel \ import ActionsSelectPanel from...
src/wizard/controller/linked_dialog/PanelNode.py
import wx from src.wizard.view.clsResultPage import ResultPageView from src.wizard.controller.frmSampFeatSelectPanel \ import SampFeatSelectPanel from src.wizard.controller.frmProcLevelSelectPanel \ import ProcLevelSelectPanel from src.wizard.controller.frmActionsSelectPanel \ import ActionsSelectPanel from...
0.265024
0.052716
import collections from absl import app from absl import flags from optimization.cifar100 import centralized_cifar100 from optimization.emnist import centralized_emnist from optimization.emnist_ae import centralized_emnist_ae from optimization.shakespeare import centralized_shakespeare from optimization.shared import...
optimization/main/centralized_trainer.py
import collections from absl import app from absl import flags from optimization.cifar100 import centralized_cifar100 from optimization.emnist import centralized_emnist from optimization.emnist_ae import centralized_emnist_ae from optimization.shakespeare import centralized_shakespeare from optimization.shared import...
0.660063
0.290503
from ..service import Service from ..exception import AppwriteException class Storage(Service): def __init__(self, client): super(Storage, self).__init__(client) def list_files(self, search = None, limit = None, offset = None, cursor = None, cursor_direction = None, order_type = None): """Lis...
appwrite/services/storage.py
from ..service import Service from ..exception import AppwriteException class Storage(Service): def __init__(self, client): super(Storage, self).__init__(client) def list_files(self, search = None, limit = None, offset = None, cursor = None, cursor_direction = None, order_type = None): """Lis...
0.509032
0.07843
import abc import re from pathvalidate.error import ErrorReason, ValidationError from typepy import is_null_string from ._interface import NameSanitizer def _preprocess(name: str) -> str: return name.strip() class VarNameSanitizer(NameSanitizer): @abc.abstractproperty def _invalid_var_name_head_re(sel...
pytablewriter/sanitizer/_base.py
import abc import re from pathvalidate.error import ErrorReason, ValidationError from typepy import is_null_string from ._interface import NameSanitizer def _preprocess(name: str) -> str: return name.strip() class VarNameSanitizer(NameSanitizer): @abc.abstractproperty def _invalid_var_name_head_re(sel...
0.376738
0.078572
from volumedriver.storagerouter.storagerouterclient import StorageRouterClient as SRClient from volumedriver.storagerouter.storagerouterclient import ClusterContact, Statistics, VolumeInfo from ovs.plugin.provider.configuration import Configuration from ovs.extensions.generic.system import System import json import os ...
ovs/extensions/storageserver/storagedriver.py
from volumedriver.storagerouter.storagerouterclient import StorageRouterClient as SRClient from volumedriver.storagerouter.storagerouterclient import ClusterContact, Statistics, VolumeInfo from ovs.plugin.provider.configuration import Configuration from ovs.extensions.generic.system import System import json import os ...
0.567457
0.069795
"""Tests for inventory reading.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import unittest import numpy as np import six import deepmind_lab GADGETS = { 'IMPULSE': 2, ## Contact gadget. 'RAPID': 3, ## Rapid fire gadget. '...
python/tests/update_inventory_test.py
"""Tests for inventory reading.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import unittest import numpy as np import six import deepmind_lab GADGETS = { 'IMPULSE': 2, ## Contact gadget. 'RAPID': 3, ## Rapid fire gadget. '...
0.651909
0.253159
from __future__ import print_function, with_statement import logging import os from contextlib import contextmanager from file_utils import temporary_file from subprocess import Popen, PIPE from urllib2 import urlopen logger = logging.getLogger(__name__) class CommandError(Exception): """Problem executing or ini...
src/python/squarepants/binary_utils.py
from __future__ import print_function, with_statement import logging import os from contextlib import contextmanager from file_utils import temporary_file from subprocess import Popen, PIPE from urllib2 import urlopen logger = logging.getLogger(__name__) class CommandError(Exception): """Problem executing or ini...
0.680879
0.105027
from typing import Optional, Sequence import torch from rising.transforms import BaseTransform from rising.transforms.functional import one_hot_batch __all__ = ["OneHot", "ArgMax"] class OneHot(BaseTransform): """ Convert to one hot encoding. One hot encoding is applied in first dimension which results...
rising/transforms/channel.py
from typing import Optional, Sequence import torch from rising.transforms import BaseTransform from rising.transforms.functional import one_hot_batch __all__ = ["OneHot", "ArgMax"] class OneHot(BaseTransform): """ Convert to one hot encoding. One hot encoding is applied in first dimension which results...
0.964514
0.558086
from highlight import analyze_python, build_html_page import os, re from glob import glob from html import escape from pathlib import Path from itertools import chain from subprocess import getoutput index_html = '''\ <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html;charset=U...
Beginner/notes/publish.py
from highlight import analyze_python, build_html_page import os, re from glob import glob from html import escape from pathlib import Path from itertools import chain from subprocess import getoutput index_html = '''\ <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html;charset=U...
0.306838
0.047492
import abc import pandas as pd import copy from .timeframe import TimeFrame class Results(object): """Stats results from each node need to be assigned to a specific class so we know how to combine results from multiple chunks. For example, Energy can be simply summed; while dropout rate should be aver...
nilmtk/results.py
import abc import pandas as pd import copy from .timeframe import TimeFrame class Results(object): """Stats results from each node need to be assigned to a specific class so we know how to combine results from multiple chunks. For example, Energy can be simply summed; while dropout rate should be aver...
0.918274
0.656803
from bui.layout.attr import Attr from bui.layout.component import Component class Dialog(Component): """ Custom dialog tag, to encompass widgets. The dialog tag allows to create a custom dialog box. Contrary to the window tag, it doesn't describe a window and its elements. Usually, a dialog is...
bui/layout/dialog.py
from bui.layout.attr import Attr from bui.layout.component import Component class Dialog(Component): """ Custom dialog tag, to encompass widgets. The dialog tag allows to create a custom dialog box. Contrary to the window tag, it doesn't describe a window and its elements. Usually, a dialog is...
0.852045
0.792022
from tools.utils.platform import ICTYPE_2_MGDTYPE #========================================================================== def _invert_dict(dict_): bins = {} for key, value in dict_.items(): bin = bins.setdefault(value, []) bin.append(key) return bins def _choose_best_name...
tools/utils/ictypes.py
from tools.utils.platform import ICTYPE_2_MGDTYPE #========================================================================== def _invert_dict(dict_): bins = {} for key, value in dict_.items(): bin = bins.setdefault(value, []) bin.append(key) return bins def _choose_best_name...
0.338405
0.218523
import time import torch from torch.utils.data import Dataset, DataLoader from data import LJspeechDataset, collate_fn_synthesize from model import WaveVAE from torch.distributions.normal import Normal import librosa import os import argparse parser = argparse.ArgumentParser(description='Synthesize WaveVAE of LJSpeec...
synthesize.py
import time import torch from torch.utils.data import Dataset, DataLoader from data import LJspeechDataset, collate_fn_synthesize from model import WaveVAE from torch.distributions.normal import Normal import librosa import os import argparse parser = argparse.ArgumentParser(description='Synthesize WaveVAE of LJSpeec...
0.549157
0.193376
import unittest import numpy as np from scipy import stats import PySeismoSoil.helper_mkz_model as mkz import PySeismoSoil.helper_site_response as sr class Test_Helper_MKZ_Model(unittest.TestCase): ''' Unit tests for helper functions in helper_mkz_model.py ''' def __init__(self, methodName='runTest')...
PySeismoSoil/tests/test_helper_mkz_model.py
import unittest import numpy as np from scipy import stats import PySeismoSoil.helper_mkz_model as mkz import PySeismoSoil.helper_site_response as sr class Test_Helper_MKZ_Model(unittest.TestCase): ''' Unit tests for helper functions in helper_mkz_model.py ''' def __init__(self, methodName='runTest')...
0.488039
0.602793
import os from os import getcwd import glob from convert_bbox_for_anno_extraction import convert_bbox #将要生成的三个文件,可以改年份,其他最好不变 sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')] #按照上一步对数据集的划分结果,即按照Main生成的4个txt文件(里面全是文件名,不带后缀) #中的顺序提取标注中的信息。还是那个问题,本数据集的图片、标注均不在一个文件夹 #这带来了麻烦,当前只采用简便处理。就把第一类当作验证集 wd...
annotations_extraction.py
import os from os import getcwd import glob from convert_bbox_for_anno_extraction import convert_bbox #将要生成的三个文件,可以改年份,其他最好不变 sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')] #按照上一步对数据集的划分结果,即按照Main生成的4个txt文件(里面全是文件名,不带后缀) #中的顺序提取标注中的信息。还是那个问题,本数据集的图片、标注均不在一个文件夹 #这带来了麻烦,当前只采用简便处理。就把第一类当作验证集 wd...
0.049474
0.191196
import os import re #Definitions def run(files=None,verbose=True,overwrite=None,output=None,macros={},build=''): l=create_file_objs(files,macros) mod2fil=file_objs_to_mod_dict(file_objs=l) depends=get_depends(fob=l,m2f=mod2fil) if verbose: for i in depends.keys(): print "\033[032m...
Source/Fortran/Hamiltonian/fort_depend.py
import os import re #Definitions def run(files=None,verbose=True,overwrite=None,output=None,macros={},build=''): l=create_file_objs(files,macros) mod2fil=file_objs_to_mod_dict(file_objs=l) depends=get_depends(fob=l,m2f=mod2fil) if verbose: for i in depends.keys(): print "\033[032m...
0.186576
0.085978
import sys import os import glob import shutil import jinja2 import nbformat from nbconvert.exporters import HTMLExporter INDEX_TEMPLATE = jinja2.Template(""" .. _{{ sphinx_tag }}: Notebook Examples ================= .. toctree:: {% for notebook in notebooks %} ./{{ notebook }} {% endfor %} """) RST_TE...
doc/sphinxext/notebook_converter.py
import sys import os import glob import shutil import jinja2 import nbformat from nbconvert.exporters import HTMLExporter INDEX_TEMPLATE = jinja2.Template(""" .. _{{ sphinx_tag }}: Notebook Examples ================= .. toctree:: {% for notebook in notebooks %} ./{{ notebook }} {% endfor %} """) RST_TE...
0.446495
0.224597
import cv2 import numpy as np try: import OpenImageIO as oiio except ImportError: print("OpenImageIO is required!") class RenderImage(object): def __init__(self, size=(20, 20)): self._img = np.zeros((size[0], size[1], 4), dtype=np.uint16) def Image(self, data_type="numpy"): """ Retur...
src/gimelstudio/core/datatypes.py
import cv2 import numpy as np try: import OpenImageIO as oiio except ImportError: print("OpenImageIO is required!") class RenderImage(object): def __init__(self, size=(20, 20)): self._img = np.zeros((size[0], size[1], 4), dtype=np.uint16) def Image(self, data_type="numpy"): """ Retur...
0.642769
0.344871
class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = str(first + '.' + last + '@<EMAIL>').lower() # see that we don't need to input all the # attributes. Some of the...
Class10-Classes Variables.py
class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = str(first + '.' + last + '@<EMAIL>').lower() # see that we don't need to input all the # attributes. Some of the...
0.627038
0.424114
class ModifiedMixin: """ Class to allow a Tkinter Text widget to notice when it's modified. To use this mixin, subclass from Tkinter.Text and the mixin, then write an __init__() method for the new class that calls _init(). Then override the beenModified() method to implement the behavior that ...
src/lib/ModifiedMixin.py
class ModifiedMixin: """ Class to allow a Tkinter Text widget to notice when it's modified. To use this mixin, subclass from Tkinter.Text and the mixin, then write an __init__() method for the new class that calls _init(). Then override the beenModified() method to implement the behavior that ...
0.677261
0.429968
import os from parglare import Grammar, Parser this_folder = os.path.dirname(__file__) model_str = ''' modelID 42 component myComponent { in SomeInputSlot out SomeOutputSlot } ''' def test_imported_actions_connect_by_symbol_name(): g = Grammar.from_file(os.path.join(this_folder, 'by_symbol_name/model.pg...
tests/func/import/imported_actions/test_imported_actions.py
import os from parglare import Grammar, Parser this_folder = os.path.dirname(__file__) model_str = ''' modelID 42 component myComponent { in SomeInputSlot out SomeOutputSlot } ''' def test_imported_actions_connect_by_symbol_name(): g = Grammar.from_file(os.path.join(this_folder, 'by_symbol_name/model.pg...
0.554229
0.425904
def load_global_step_from_predefined_list(exp): global_step_dict = {'20180124_max20_2M': '1155015', } if exp not in global_step_dict.keys(): global_step_dict[exp] = '0' global_step = global_step_dict[exp] return global_step def fancy_exp_name(exp): fancy_dict = {'A...
functions/setting/experiment_setting.py
def load_global_step_from_predefined_list(exp): global_step_dict = {'20180124_max20_2M': '1155015', } if exp not in global_step_dict.keys(): global_step_dict[exp] = '0' global_step = global_step_dict[exp] return global_step def fancy_exp_name(exp): fancy_dict = {'A...
0.377541
0.23292
import os import pathlib import PIL from colorama import init, Fore from resources.screencap_thread import start_screencap_thread, stop_screencap_threads init() class ScreencapsManager: screencaps_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'screencaps') @staticmethod def get_screen...
src-py/resources/screencaps_manager.py
import os import pathlib import PIL from colorama import init, Fore from resources.screencap_thread import start_screencap_thread, stop_screencap_threads init() class ScreencapsManager: screencaps_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'screencaps') @staticmethod def get_screen...
0.323915
0.168925
import os import torch import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np @torch.enable_grad() def grad_cam(model, x, hooks, cls_idx=None): """ cf CheXpert: Test Results / Visualization; visualize final conv layer, using grads of final linear layer as weights, and performing a ...
utils/visualize_utils.py
import os import torch import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np @torch.enable_grad() def grad_cam(model, x, hooks, cls_idx=None): """ cf CheXpert: Test Results / Visualization; visualize final conv layer, using grads of final linear layer as weights, and performing a ...
0.845974
0.657538
import boto3 import unittest from unittest.mock import patch from PIL import Image from io import BytesIO, StringIO import sys sys.path.insert(1, '../../lambdas/moderate_content/handler') from censor import evaluate_profanity, blur_text class TestCensor(unittest.TestCase): @patch('censor.get_profanity_score')...
tests/unit/test_censor.py
import boto3 import unittest from unittest.mock import patch from PIL import Image from io import BytesIO, StringIO import sys sys.path.insert(1, '../../lambdas/moderate_content/handler') from censor import evaluate_profanity, blur_text class TestCensor(unittest.TestCase): @patch('censor.get_profanity_score')...
0.610221
0.475544
from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship from database import Base from mod_test.models import Test from mod_regression.models import RegressionTest from mod_auth.models import User class TestFork(Base): __tablename__ = 'test_fork' __table_args__ = {'mysql_en...
mod_customized/models.py
from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship from database import Base from mod_test.models import Test from mod_regression.models import RegressionTest from mod_auth.models import User class TestFork(Base): __tablename__ = 'test_fork' __table_args__ = {'mysql_en...
0.603348
0.331823
from compiler import Lexer from compiler import Parser from compiler import Facility_Domain_Compiler from compiler import Imitation_Compiler import difflib def lexer_print_tokens(lexer): token = lexer.get_next_token() while token.type != 'EOF': print (token) token = lexer.get_next_token() def test(textname, res...
python_causal_compiler/test.py
from compiler import Lexer from compiler import Parser from compiler import Facility_Domain_Compiler from compiler import Imitation_Compiler import difflib def lexer_print_tokens(lexer): token = lexer.get_next_token() while token.type != 'EOF': print (token) token = lexer.get_next_token() def test(textname, res...
0.219756
0.120206
from rest_framework import serializers from api.models import Author, Book class AuthorSerializer(serializers.ModelSerializer): """ Сериализатор для получения авторов книг. """ class Meta: model = Author fields = ( 'id', 'author_name', 'additional_...
api/serializers.py
from rest_framework import serializers from api.models import Author, Book class AuthorSerializer(serializers.ModelSerializer): """ Сериализатор для получения авторов книг. """ class Meta: model = Author fields = ( 'id', 'author_name', 'additional_...
0.513181
0.200264
import tokenize # I don't think this is a minimized state machine, but it's clearer this # way. Namely, the class vs. function states can be merged # In the start of the module when we're expecting possibly a string that gets marked as a docstring STATE_EXPECT_MODULE_DOCSTRING = 0 # After seeing the class keyword, we...
flake8_quotes/docstring_detection.py
import tokenize # I don't think this is a minimized state machine, but it's clearer this # way. Namely, the class vs. function states can be merged # In the start of the module when we're expecting possibly a string that gets marked as a docstring STATE_EXPECT_MODULE_DOCSTRING = 0 # After seeing the class keyword, we...
0.397938
0.634034
import os import pdb import sys from astropy.table import Table import numpy as np from drizzlepac import hapsequencer from drizzlepac.haputils import hla_flag_filter from drizzlepac.devutils.comparison_tools import compare_sourcelists from drizzlepac.devutils.comparison_tools.read_hla import read_hla_catalog from stsc...
drizzlepac/devutils/comparison_tools/integrate_read_hla_catalog.py
import os import pdb import sys from astropy.table import Table import numpy as np from drizzlepac import hapsequencer from drizzlepac.haputils import hla_flag_filter from drizzlepac.devutils.comparison_tools import compare_sourcelists from drizzlepac.devutils.comparison_tools.read_hla import read_hla_catalog from stsc...
0.41941
0.28704
import codecs import os import math import operator from functools import reduce def fetch_data(cand, ref): """ Store each reference and candidate sentences as a list """ references = [] if '.txt' in ref: reference_file = codecs.open(ref, 'r', 'utf-8') references.append(reference_file.read...
example/nmt/code/calculatebleu.py
import codecs import os import math import operator from functools import reduce def fetch_data(cand, ref): """ Store each reference and candidate sentences as a list """ references = [] if '.txt' in ref: reference_file = codecs.open(ref, 'r', 'utf-8') references.append(reference_file.read...
0.378689
0.282233
import unittest from flattery import flatten, unflatten class FunctionTestCase(unittest.TestCase): def __init__(self, **keywords): unittest.TestCase.__init__(self) self.args = [] self.kwargs = {} for k, v in keywords.items(): setattr(self, k, v) def runTest(self): self.assertEqual( s...
test.py
import unittest from flattery import flatten, unflatten class FunctionTestCase(unittest.TestCase): def __init__(self, **keywords): unittest.TestCase.__init__(self) self.args = [] self.kwargs = {} for k, v in keywords.items(): setattr(self, k, v) def runTest(self): self.assertEqual( s...
0.326164
0.501038
from osgeo import gdal import os import numpy as np src_dataset = gdal.Open("D:/10_Article/08_MonthlyRaster/IDW_REM/200702.tif") geotransform = (-180.0, 0.25, 0.0, -90.0, 0.0, 0.25) spatialreference = src_dataset.GetProjection() ncol = 1440 nrow = 720 nband = 1 ## List input raster files os.chdir('D:/10_Article/09_Te...
01_PythonCode/13_DW_AerosolOpticalDepth_v1.py
from osgeo import gdal import os import numpy as np src_dataset = gdal.Open("D:/10_Article/08_MonthlyRaster/IDW_REM/200702.tif") geotransform = (-180.0, 0.25, 0.0, -90.0, 0.0, 0.25) spatialreference = src_dataset.GetProjection() ncol = 1440 nrow = 720 nband = 1 ## List input raster files os.chdir('D:/10_Article/09_Te...
0.173078
0.185966
import os import json import time from digestparser import medium_post from provider.article_processing import download_jats from provider import digest_provider, email_provider, utils from activity.objects import Activity class activity_CreateDigestMediumPost(Activity): def __init__(self, settings, logger, conn=...
activity/activity_CreateDigestMediumPost.py
import os import json import time from digestparser import medium_post from provider.article_processing import download_jats from provider import digest_provider, email_provider, utils from activity.objects import Activity class activity_CreateDigestMediumPost(Activity): def __init__(self, settings, logger, conn=...
0.556159
0.077308
import os import sys import time import glob import numpy as np import torch import logging import argparse import torch.nn as nn import torch.utils import torch.backends.cudnn as cudnn import joint_network as models from dataset import OneHopDataset from torch.utils.data import Dataset, DataLoader import shutil mode...
train.py
import os import sys import time import glob import numpy as np import torch import logging import argparse import torch.nn as nn import torch.utils import torch.backends.cudnn as cudnn import joint_network as models from dataset import OneHopDataset from torch.utils.data import Dataset, DataLoader import shutil mode...
0.45302
0.076822
import abc from event.timeout import BuffTimeOut class Buff: def __init__(self, name, cd): self.name = name self.next_available = 0 self.cd = cd self.on_going = False def equip(self, engine, char_state): current = engine.current_priority() if self.next_availab...
buff/__init__.py
import abc from event.timeout import BuffTimeOut class Buff: def __init__(self, name, cd): self.name = name self.next_available = 0 self.cd = cd self.on_going = False def equip(self, engine, char_state): current = engine.current_priority() if self.next_availab...
0.398641
0.160628
import rospy import tf import sys import math import numpy from geometry_msgs.msg import PointStamped from deictic_gestures.srv import LookAt, CanLookAt from deictic_gestures.msg import LookAtStatus from pepper_resources_synchronizer_msgs.srv import MetaStateMachineRegister, MetaStateMachineRegisterRequest from pepper...
scripts/look_at_srv_node.py
import rospy import tf import sys import math import numpy from geometry_msgs.msg import PointStamped from deictic_gestures.srv import LookAt, CanLookAt from deictic_gestures.msg import LookAtStatus from pepper_resources_synchronizer_msgs.srv import MetaStateMachineRegister, MetaStateMachineRegisterRequest from pepper...
0.38445
0.169681
import argparse import array import asyncio from collections import namedtuple from configparser import ConfigParser import logging import math from pathlib import Path import sys from urllib.parse import urlparse import streams from utils import DotDict import vm Log = logging.getLogger(__name__) AnalogParametersP...
scope.py
import argparse import array import asyncio from collections import namedtuple from configparser import ConfigParser import logging import math from pathlib import Path import sys from urllib.parse import urlparse import streams from utils import DotDict import vm Log = logging.getLogger(__name__) AnalogParametersP...
0.500977
0.12075
import os import shutil import luigi import rasterio as rio from qgreenland.constants import CONFIG, TaskType from qgreenland.util.luigi import LayerTask from qgreenland.util.misc import find_single_file_by_ext, temporary_path_dir from qgreenland.util.raster import gdal_calc_raster, warp_raster class BuildRasterOve...
qgreenland/tasks/common/raster.py
import os import shutil import luigi import rasterio as rio from qgreenland.constants import CONFIG, TaskType from qgreenland.util.luigi import LayerTask from qgreenland.util.misc import find_single_file_by_ext, temporary_path_dir from qgreenland.util.raster import gdal_calc_raster, warp_raster class BuildRasterOve...
0.262936
0.153676
class ScAddr: def IsValid(self, other): pass def ToInt(self, other): pass def __eq__(self, other): pass def __ne__(self, other): pass def __rshift__(self, other): pass def rshift(self, other): pass class ScType: def __eq__(self, other): ...
sc-kpm/python/_definitions/sc.py
class ScAddr: def IsValid(self, other): pass def ToInt(self, other): pass def __eq__(self, other): pass def __ne__(self, other): pass def __rshift__(self, other): pass def rshift(self, other): pass class ScType: def __eq__(self, other): ...
0.61832
0.420005
from sudoku_solver import Sudoku, solve_sudoku, SudokuNotValidError from unittest import TestCase class SudokuTestsNoError(TestCase): def setUp(self) -> None: field = [ [-1, 3, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, 1, 9, 5, -1, -1, -1], [-1, -1, 8, -1, -1, -1, -1, 6...
tests/test_sudoku_solver.py
from sudoku_solver import Sudoku, solve_sudoku, SudokuNotValidError from unittest import TestCase class SudokuTestsNoError(TestCase): def setUp(self) -> None: field = [ [-1, 3, -1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, 1, 9, 5, -1, -1, -1], [-1, -1, 8, -1, -1, -1, -1, 6...
0.360939
0.355048
from honeybee_energy.simulation.parameter import SimulationParameter from honeybee_energy.simulation.output import SimulationOutput from honeybee_energy.simulation.runperiod import RunPeriod from honeybee_energy.simulation.daylightsaving import DaylightSavingTime from honeybee_energy.simulation.control import Simulatio...
scripts/sample_simulation.py
from honeybee_energy.simulation.parameter import SimulationParameter from honeybee_energy.simulation.output import SimulationOutput from honeybee_energy.simulation.runperiod import RunPeriod from honeybee_energy.simulation.daylightsaving import DaylightSavingTime from honeybee_energy.simulation.control import Simulatio...
0.550124
0.515376
from tkinter import * import bookstore_back def get_selected_row(event): try: global selected index=list1.curselection()[0] selected = list1.get(index) e1.delete(0, END) e1.insert(END, selected[1]) e2.delete(0, END) e2.insert(END, selected[2]) e3.dele...
Book_ISBN_Databse/bookstore_front.py
from tkinter import * import bookstore_back def get_selected_row(event): try: global selected index=list1.curselection()[0] selected = list1.get(index) e1.delete(0, END) e1.insert(END, selected[1]) e2.delete(0, END) e2.insert(END, selected[2]) e3.dele...
0.116953
0.113334
from __future__ import absolute_import, division, print_function import six import logging import os import json import numpy as np import torch from madminer.utils.ml import ratio_losses, flow_losses from madminer.utils.ml.models.maf import ConditionalMaskedAutoregressiveFlow from madminer.utils.ml.models.maf_mog im...
madminer/ml.py
from __future__ import absolute_import, division, print_function import six import logging import os import json import numpy as np import torch from madminer.utils.ml import ratio_losses, flow_losses from madminer.utils.ml.models.maf import ConditionalMaskedAutoregressiveFlow from madminer.utils.ml.models.maf_mog im...
0.900256
0.415877
import pytest @pytest.fixture def HeaderFooterItem(): from .. header_footer import HeaderFooterItem return HeaderFooterItem @pytest.fixture def HeaderFooter(): from .. header_footer import HeaderFooter return HeaderFooter def test_ctor_item(HeaderFooterItem): hf = HeaderFooterItem("L") as...
SprityBird/spritybird/python3.5/lib/python3.5/site-packages/openpyxl/worksheet/tests/test_header.py
import pytest @pytest.fixture def HeaderFooterItem(): from .. header_footer import HeaderFooterItem return HeaderFooterItem @pytest.fixture def HeaderFooter(): from .. header_footer import HeaderFooter return HeaderFooter def test_ctor_item(HeaderFooterItem): hf = HeaderFooterItem("L") as...
0.556761
0.381536
from functools import reduce from bruhat import element from bruhat.vec import Space, Hom, Map from bruhat.action import mulclose, mulclose_hom, Perm, Group from bruhat.argv import argv from bruhat.util import factorial, partitions from bruhat.rep import get_perms, Young class Specht(object): def __init__(self...
bruhat/qu.py
from functools import reduce from bruhat import element from bruhat.vec import Space, Hom, Map from bruhat.action import mulclose, mulclose_hom, Perm, Group from bruhat.argv import argv from bruhat.util import factorial, partitions from bruhat.rep import get_perms, Young class Specht(object): def __init__(self...
0.295535
0.462959
from loguru import logger from tqdm import tqdm from os import path as osp import pytorch_lightning as pl from torch import distributed as dist from torch.utils.data import DataLoader, ConcatDataset, DistributedSampler from src.utils.augment import build_augmentor from src.utils.dataloader import get_local_split from...
src/lightning/data.py
from loguru import logger from tqdm import tqdm from os import path as osp import pytorch_lightning as pl from torch import distributed as dist from torch.utils.data import DataLoader, ConcatDataset, DistributedSampler from src.utils.augment import build_augmentor from src.utils.dataloader import get_local_split from...
0.697815
0.318472
import os import typing from typing import Iterator, Optional, Callable, Set def is_proper_file(path: str) -> bool: name = os.path.split(path)[1] return len(name) > 0 and name[0] not in {'.', '~', '_'} def scantree(path: str, follow_symlinks: bool=False) -> Iterator[str]: """List the full path of every file not ...
klgists/files/scantree.py
import os import typing from typing import Iterator, Optional, Callable, Set def is_proper_file(path: str) -> bool: name = os.path.split(path)[1] return len(name) > 0 and name[0] not in {'.', '~', '_'} def scantree(path: str, follow_symlinks: bool=False) -> Iterator[str]: """List the full path of every file not ...
0.674372
0.292861
from flask import request, render_template, g, abort, json, redirect, jsonify, flash from app.models.user import User from app.models.term import Term from app.models.course import Course from app.models.courseStatus import CourseStatus from app.models.courseInstructor import CourseInstructor from app.models.courseQue...
app/controllers/serviceLearning/routes.py
from flask import request, render_template, g, abort, json, redirect, jsonify, flash from app.models.user import User from app.models.term import Term from app.models.course import Course from app.models.courseStatus import CourseStatus from app.models.courseInstructor import CourseInstructor from app.models.courseQue...
0.262842
0.189896
import datetime, random, math class ProductModel: def __init__(self, product_id, product_type, product_name, img_url=None): self.id = product_id if (product_type == 1): self.type = '농산물' elif(product_type == 2): self.type = '수산물' elif(product_type == 3): self.type = '축산물' else: self.type='' ...
models.py
import datetime, random, math class ProductModel: def __init__(self, product_id, product_type, product_name, img_url=None): self.id = product_id if (product_type == 1): self.type = '농산물' elif(product_type == 2): self.type = '수산물' elif(product_type == 3): self.type = '축산물' else: self.type='' ...
0.190347
0.19923
import torch from pytorch3d.structures import Meshes from pytorch3d.renderer import look_at_view_transform, FoVPerspectiveCameras, RasterizationSettings, PointLights, \ MeshRenderer, MeshRasterizer, SoftPhongShader, TexturesVertex from vedo.mesh import Mesh from vedo.io import screenshot from vedo.plotter import sh...
Utils/mesh_visualization.py
import torch from pytorch3d.structures import Meshes from pytorch3d.renderer import look_at_view_transform, FoVPerspectiveCameras, RasterizationSettings, PointLights, \ MeshRenderer, MeshRasterizer, SoftPhongShader, TexturesVertex from vedo.mesh import Mesh from vedo.io import screenshot from vedo.plotter import sh...
0.591723
0.658363
from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\32") buf.write("\u0082\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7") buf.write("\4\b\t\b\4\t\...
script/DOTParser.py
from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\32") buf.write("\u0082\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7") buf.write("\4\b\t\b\4\t\...
0.270191
0.295245
from datetime import datetime import os import re import tempfile from urllib.parse import urlparse, urlencode import zipfile class UserMistake(Exception): """Raised when something went wrong due to user input""" pass def get_id(doi): """Parses Zenodo DOI to isolate record id Parameters ------...
jupyterlab_zenodo/utils.py
from datetime import datetime import os import re import tempfile from urllib.parse import urlparse, urlencode import zipfile class UserMistake(Exception): """Raised when something went wrong due to user input""" pass def get_id(doi): """Parses Zenodo DOI to isolate record id Parameters ------...
0.637482
0.28169
import numpy as np import string import copy from six.moves import xrange from shapeglot.simple_utils import iterate_in_chunks def _all_tensors_have_same_rows(tensor_list): n = tensor_list[0].shape[0] for i in xrange(1, len(tensor_list)): if n != tensor_list[i].shape[0]: return False ...
shapeglot/in_out/numpy_dataset.py
import numpy as np import string import copy from six.moves import xrange from shapeglot.simple_utils import iterate_in_chunks def _all_tensors_have_same_rows(tensor_list): n = tensor_list[0].shape[0] for i in xrange(1, len(tensor_list)): if n != tensor_list[i].shape[0]: return False ...
0.613005
0.32134
from pprint import pformat from six import iteritems class BatchEntityReport(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name ...
kensu/client/models/batch_entity_report.py
from pprint import pformat from six import iteritems class BatchEntityReport(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name ...
0.373419
0.126515
from run_pplm import run_pplm_example import time import os def output_file_path(task, bow, seed, total_samples, m, step_size): dst_file_name = '{},PPLM-BoW,BoW={},seed={},n={},m={},step_size={}'.format( task, bow, seed, total_samples, m, step_size) return 'automated_evaluation/generated_samples/{}/{}...
inference/PPLM-BoW.py
from run_pplm import run_pplm_example import time import os def output_file_path(task, bow, seed, total_samples, m, step_size): dst_file_name = '{},PPLM-BoW,BoW={},seed={},n={},m={},step_size={}'.format( task, bow, seed, total_samples, m, step_size) return 'automated_evaluation/generated_samples/{}/{}...
0.540196
0.301279
""" Collection of Request utility functions """ import hashlib import time import subprocess import sys import ast import uuid import types from engine.errors import ResponseParsingException from engine.errors import TransportLayerException from restler_settings import Settings import engine.primitives as primitives ...
restler/engine/core/request_utilities.py
""" Collection of Request utility functions """ import hashlib import time import subprocess import sys import ast import uuid import types from engine.errors import ResponseParsingException from engine.errors import TransportLayerException from restler_settings import Settings import engine.primitives as primitives ...
0.559531
0.145783
from __future__ import absolute_import, print_function, unicode_literals import re import uuid import logbook import six import validate_email import stethoscope.exceptions logger = logbook.Logger(__name__) MACADDR_PATTERN = re.compile(r'^' + r'\:?'.join([r'([0-9A-F]{1,2})'] * 6) + r'$', re.IGNORECASE) def _is_...
stethoscope/validation.py
from __future__ import absolute_import, print_function, unicode_literals import re import uuid import logbook import six import validate_email import stethoscope.exceptions logger = logbook.Logger(__name__) MACADDR_PATTERN = re.compile(r'^' + r'\:?'.join([r'([0-9A-F]{1,2})'] * 6) + r'$', re.IGNORECASE) def _is_...
0.770076
0.17139
import pandas as pd from splinter import Browser from bs4 import BeautifulSoup from webdriver_manager.chrome import ChromeDriverManager data = {} def scrape_all(): #setup path & initialize browser executable_path = {'executable_path': ChromeDriverManager().install()} browser = Browser('chrome', **executable...
scrape_mars.py
import pandas as pd from splinter import Browser from bs4 import BeautifulSoup from webdriver_manager.chrome import ChromeDriverManager data = {} def scrape_all(): #setup path & initialize browser executable_path = {'executable_path': ChromeDriverManager().install()} browser = Browser('chrome', **executable...
0.328422
0.138928
import os.path #!/usr/bin/python # -*- coding: utf-8 -*- # We need this for gui controls import gui3d import os import humanmodifier import events3d class AssymSlider(gui3d.Slider): def __init__(self, bodypart, label): gui3d.Slider.__init__(self, value=0.0, min=-1.0, max=1.0, label=label...
plugins/0_modeling_7_asymm.py
import os.path #!/usr/bin/python # -*- coding: utf-8 -*- # We need this for gui controls import gui3d import os import humanmodifier import events3d class AssymSlider(gui3d.Slider): def __init__(self, bodypart, label): gui3d.Slider.__init__(self, value=0.0, min=-1.0, max=1.0, label=label...
0.359252
0.195959
import os, string from xml.dom import Node from Ft.Lib import Uri, UriException def Test(tester): base_uri = Uri.OsPathToUri(__file__, attemptAbsolute=True) tester.startTest('Creating test environment') from Ft.Xml import XPointer from Ft.Xml import Domlette r = Domlette.NonvalidatingReader doc...
dependencies/src/4Suite-XML-1.0.2/test/Xml/XPointer/basic_test.py
import os, string from xml.dom import Node from Ft.Lib import Uri, UriException def Test(tester): base_uri = Uri.OsPathToUri(__file__, attemptAbsolute=True) tester.startTest('Creating test environment') from Ft.Xml import XPointer from Ft.Xml import Domlette r = Domlette.NonvalidatingReader doc...
0.201499
0.187504
from pyasn1.type.namedtype import NamedType, NamedTypes, OptionalNamedType, DefaultedNamedType from pyasn1.type.namedval import NamedValues from asn1PERser.classes.data.builtin import * from asn1PERser.classes.types.type import AdditiveNamedTypes from asn1PERser.classes.types.constraint import MIN, MAX, NoConstraint, E...
asn1PERser/test/parsing/asn1_python_code/Types_containing_constrained_types.py
from pyasn1.type.namedtype import NamedType, NamedTypes, OptionalNamedType, DefaultedNamedType from pyasn1.type.namedval import NamedValues from asn1PERser.classes.data.builtin import * from asn1PERser.classes.types.type import AdditiveNamedTypes from asn1PERser.classes.types.constraint import MIN, MAX, NoConstraint, E...
0.7181
0.42185
import re import abc import nltk import typing import collections import numpy as np match_punc = re.compile('[^\w\s]') class ProcessorUnit(metaclass=abc.ABCMeta): """Process unit do not persive state (i.e. do not need fit).""" @abc.abstractmethod def transform(self, input: typing.Any): """Abs...
matchzoo/preprocessor/process_units.py
import re import abc import nltk import typing import collections import numpy as np match_punc = re.compile('[^\w\s]') class ProcessorUnit(metaclass=abc.ABCMeta): """Process unit do not persive state (i.e. do not need fit).""" @abc.abstractmethod def transform(self, input: typing.Any): """Abs...
0.830697
0.478407
DESC = "mps-2019-06-12" INFO = { "CreateSnapshotByTimeOffsetTemplate": { "params": [ { "name": "Name", "desc": "Name of a time point screencapturing template. Length limit: 64 characters." }, { "name": "Width", "desc": "Image width in px. Value range: [128, 4,096]...
tccli/services/mps/v20190612/help.py
DESC = "mps-2019-06-12" INFO = { "CreateSnapshotByTimeOffsetTemplate": { "params": [ { "name": "Name", "desc": "Name of a time point screencapturing template. Length limit: 64 characters." }, { "name": "Width", "desc": "Image width in px. Value range: [128, 4,096]...
0.904982
0.497192
from __future__ import annotations from typing import Iterable, Iterator from .instruction import Instruction, Operation class ReverseMonad: @staticmethod def from_str(lines: Iterator[str]) -> ReverseMonad: instructions = [Instruction.from_str(line) for line in lines] return ReverseMonad(ins...
advent/days/day24/reverse_monad.py
from __future__ import annotations from typing import Iterable, Iterator from .instruction import Instruction, Operation class ReverseMonad: @staticmethod def from_str(lines: Iterator[str]) -> ReverseMonad: instructions = [Instruction.from_str(line) for line in lines] return ReverseMonad(ins...
0.837321
0.273162
import numpy as np from astropy.table import Column, Table from gammapy.maps import Map from gammapy.modeling.models import PowerLawSpectralModel, SkyModel from gammapy.stats import WStatCountsStatistic from ..core import Estimator __all__ = ["SensitivityEstimator"] class SensitivityEstimator(Estimator): """Esti...
gammapy/estimators/points/sensitivity.py
import numpy as np from astropy.table import Column, Table from gammapy.maps import Map from gammapy.modeling.models import PowerLawSpectralModel, SkyModel from gammapy.stats import WStatCountsStatistic from ..core import Estimator __all__ = ["SensitivityEstimator"] class SensitivityEstimator(Estimator): """Esti...
0.931704
0.59928
import numpy as np import numpy.ma as ma import warnings import numba try: import scipy.sparse as sp SCIPY_INSTALLED = True except ImportError: SCIPY_INSTALLED = False class InvalidValuesWarning(UserWarning): pass def _pad_list(x, padding_val=-999): if not isinstance(x, list): raise Typ...
rankereval/data.py
import numpy as np import numpy.ma as ma import warnings import numba try: import scipy.sparse as sp SCIPY_INSTALLED = True except ImportError: SCIPY_INSTALLED = False class InvalidValuesWarning(UserWarning): pass def _pad_list(x, padding_val=-999): if not isinstance(x, list): raise Typ...
0.682468
0.375964
from imutils.video import VideoStream from imutils.video import FPS import numpy as np import argparse import imutils import time import cv2 ap = argparse.ArgumentParser() ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file") ap.add_argument("-m", "--model", required=True, ...
REALTIME_OPENCV_DEEP_LEARNING/real_time_object_detection.py
from imutils.video import VideoStream from imutils.video import FPS import numpy as np import argparse import imutils import time import cv2 ap = argparse.ArgumentParser() ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file") ap.add_argument("-m", "--model", required=True, ...
0.339828
0.232299
import argparse import logging from typing import List, Optional, Dict, Union import tornado.ioloop import tornado.web import tornado.httpserver import tornado.log import asyncio from tornado import concurrent from .utils import utils import kserve.handlers as handlers from kserve import Model from kserve.model_repo...
python/kserve/kserve/model_server.py
import argparse import logging from typing import List, Optional, Dict, Union import tornado.ioloop import tornado.web import tornado.httpserver import tornado.log import asyncio from tornado import concurrent from .utils import utils import kserve.handlers as handlers from kserve import Model from kserve.model_repo...
0.791821
0.076649
import abc from oslo_config import cfg from oslo_db import api as db_api import six _BACKEND_MAPPING = {'sqlalchemy': 'cyborg.db.sqlalchemy.api'} IMPL = db_api.DBAPI.from_config(cfg.CONF, backend_mapping=_BACKEND_MAPPING, lazy=True) def get_instance()...
cyborg/db/api.py
import abc from oslo_config import cfg from oslo_db import api as db_api import six _BACKEND_MAPPING = {'sqlalchemy': 'cyborg.db.sqlalchemy.api'} IMPL = db_api.DBAPI.from_config(cfg.CONF, backend_mapping=_BACKEND_MAPPING, lazy=True) def get_instance()...
0.79999
0.088505
import dash import numpy as np from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_bootstrap_components as dbc import dash_html_components as html import dash_daq as daq from app import app import plotly.graph_objs as go import json, codecs from scipy.integrate import simps...
callbacks/resultsappendagesplots.py
import dash import numpy as np from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_bootstrap_components as dbc import dash_html_components as html import dash_daq as daq from app import app import plotly.graph_objs as go import json, codecs from scipy.integrate import simps...
0.392337
0.180612