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 django import forms from django.core.exceptions import ValidationError from apps.web.forms.bootstrap import BootStrapForm from apps.web.models import Issues, ProjectUser, IssuesType, Module, IssuesReply, ProjectInvite class IssuesModelForm(BootStrapForm, forms.ModelForm): """问题表单验证""" class Meta: ...
apps/web/forms/issues.py
from django import forms from django.core.exceptions import ValidationError from apps.web.forms.bootstrap import BootStrapForm from apps.web.models import Issues, ProjectUser, IssuesType, Module, IssuesReply, ProjectInvite class IssuesModelForm(BootStrapForm, forms.ModelForm): """问题表单验证""" class Meta: ...
0.488527
0.085786
from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Tuple from EtlPipeline.course_stats import get_earnings_unavail_text from EtlPipeline.mappings.base import BaseMappings from EtlPipeline.utils import get_earnings_agg_unavail_messages class LeoInstit...
EtlPipeline/mappings/leo/institution.py
from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Tuple from EtlPipeline.course_stats import get_earnings_unavail_text from EtlPipeline.mappings.base import BaseMappings from EtlPipeline.utils import get_earnings_agg_unavail_messages class LeoInstit...
0.817028
0.171616
import unittest from fftoptionlib.characteristic_funs import ( black_schole_log_st_chf, merton_jump_log_st_chf, poisson_log_st_chf, diffusion_chf, cpp_normal_chf, kou_jump_log_st_chf, double_exponential_chf, poisson_chf, vg_log_st_chf, nig_log_st_chf, ) from fftoptionlib.moment_...
tests/test_moment_generating_funs.py
import unittest from fftoptionlib.characteristic_funs import ( black_schole_log_st_chf, merton_jump_log_st_chf, poisson_log_st_chf, diffusion_chf, cpp_normal_chf, kou_jump_log_st_chf, double_exponential_chf, poisson_chf, vg_log_st_chf, nig_log_st_chf, ) from fftoptionlib.moment_...
0.602179
0.502808
import numpy as np import pandas as pd from tqdm import tqdm import torch from torch import nn from torch.autograd import Variable from torch.nn.utils.clip_grad import clip_grad_norm_ import training.ln_lstm as lstm from captum.attr import LayerIntegratedGradients class SeqLSTM(nn.Module): """ Hi...
src/training/model.py
import numpy as np import pandas as pd from tqdm import tqdm import torch from torch import nn from torch.autograd import Variable from torch.nn.utils.clip_grad import clip_grad_norm_ import training.ln_lstm as lstm from captum.attr import LayerIntegratedGradients class SeqLSTM(nn.Module): """ Hi...
0.912913
0.285914
import copy import os import time import logging import wget from mmdet.apis import init_detector, inference_detector import cv2 as cv from teacher_meta_arch import TeacherMetaArch import torch import numpy as np class IterDet(TeacherMetaArch): """ IterDet object detection model""" def __init__(self, config)...
applications/adaptive-learning/teachers/iterdet.py
import copy import os import time import logging import wget from mmdet.apis import init_detector, inference_detector import cv2 as cv from teacher_meta_arch import TeacherMetaArch import torch import numpy as np class IterDet(TeacherMetaArch): """ IterDet object detection model""" def __init__(self, config)...
0.734881
0.234089
from django.test import TestCase from django.test.client import RequestFactory from django.test import Client from django.urls import reverse from tests.factories.gbe_factories import ( ClassFactory, ConferenceFactory, ConferenceDayFactory, ProfileFactory, RoomFactory, ) from scheduler.models import...
tests/gbe/scheduling/test_copy_staff_area_view.py
from django.test import TestCase from django.test.client import RequestFactory from django.test import Client from django.urls import reverse from tests.factories.gbe_factories import ( ClassFactory, ConferenceFactory, ConferenceDayFactory, ProfileFactory, RoomFactory, ) from scheduler.models import...
0.461745
0.226784
import os import sys from distutils.version import StrictVersion import click from .config import DEFAULT_VERSIONS, SERVICES def _set_default_env(services_version, default_version): """Set environmental variable value if it does not exist.""" os.environ[services_version] = os.environ.get( services_v...
docker_services_cli/env.py
import os import sys from distutils.version import StrictVersion import click from .config import DEFAULT_VERSIONS, SERVICES def _set_default_env(services_version, default_version): """Set environmental variable value if it does not exist.""" os.environ[services_version] = os.environ.get( services_v...
0.377311
0.130507
import pandas as pd import numpy as np class Indicators: def __init__(self): self._moving_average_table = {'ma': self._ma, 'ema': self._ema} # add to the list if a new moving average is programmed def _ema(self, inp, length): assert isinstance(inp, list) or isinstance(inp, np.ndarray) ...
rltbt/indicators.py
import pandas as pd import numpy as np class Indicators: def __init__(self): self._moving_average_table = {'ma': self._ma, 'ema': self._ema} # add to the list if a new moving average is programmed def _ema(self, inp, length): assert isinstance(inp, list) or isinstance(inp, np.ndarray) ...
0.385953
0.400573
import threading import queue import time import logging from lora_multihop import variables __author__ = "<NAME>" ser = None logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s', ) BUF_SIZE = 100 writing_q = queue.Queue(BUF_SIZE) BUF_SIZE = 1000 response_q = queue.Queue(BUF_SIZE) BUF_S...
src/lora_multihop/serial_connection.py
import threading import queue import time import logging from lora_multihop import variables __author__ = "<NAME>" ser = None logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s', ) BUF_SIZE = 100 writing_q = queue.Queue(BUF_SIZE) BUF_SIZE = 1000 response_q = queue.Queue(BUF_SIZE) BUF_S...
0.53777
0.144813
import inspect from abc import abstractmethod from copy import deepcopy from typing import Optional, List, Union import numpy as np import tensorflow as tf from keras import backend as K from deeppavlov.core.models.nn_model import NNModel from deeppavlov.core.common.log import get_logger from deeppavlov.core.models....
deeppavlov/core/models/keras_model.py
import inspect from abc import abstractmethod from copy import deepcopy from typing import Optional, List, Union import numpy as np import tensorflow as tf from keras import backend as K from deeppavlov.core.models.nn_model import NNModel from deeppavlov.core.common.log import get_logger from deeppavlov.core.models....
0.929376
0.258139
import math from typing import Dict import numpy as np import matplotlib.pyplot as plt from pedrec.configs.dataset_configs import get_pedrec_dataset_cfg_default from pedrec.configs.pedrec_net_config import PedRecNet50Config from pedrec.datasets.pedrec_dataset import PedRecDataset from pedrec.models.constants.dataset_...
pedrec/tools/debugging/debug_orientation_issues.py
import math from typing import Dict import numpy as np import matplotlib.pyplot as plt from pedrec.configs.dataset_configs import get_pedrec_dataset_cfg_default from pedrec.configs.pedrec_net_config import PedRecNet50Config from pedrec.datasets.pedrec_dataset import PedRecDataset from pedrec.models.constants.dataset_...
0.788176
0.424949
import numpy as np from falass import readwrite, dataformat import os class Job(): """The catch all. This class is used for setting up the falass job -- and is generally a catch all for inputs that do not fit into other parts. Parameters ---------- files: falass.readwrite.Files A Fil...
falass/job.py
import numpy as np from falass import readwrite, dataformat import os class Job(): """The catch all. This class is used for setting up the falass job -- and is generally a catch all for inputs that do not fit into other parts. Parameters ---------- files: falass.readwrite.Files A Fil...
0.656768
0.500244
import Standard import Utils import pandas import math import FAIRNessInfo import Config import imgkit import os class StandardsUtils: UTILS = Utils.Utils() def __init__(self, input_file): self.INPUT_FILE = input_file def generate_standards_images(self): standards = [] excel_data...
main.py
import Standard import Utils import pandas import math import FAIRNessInfo import Config import imgkit import os class StandardsUtils: UTILS = Utils.Utils() def __init__(self, input_file): self.INPUT_FILE = input_file def generate_standards_images(self): standards = [] excel_data...
0.232223
0.10316
def save_ngram_index(ngram_index_file, hash2id, result_tf, result_df, result_rtf, result_rdf, seen_rev, hash2rev, ngram2kmerann): ''' Write ngram index. Format: id, rev_id, hash, rev_hash, tf, df, etf, edf. etf and edf are tf and df taking into account...
trseeker/seqio/ngram_file.py
def save_ngram_index(ngram_index_file, hash2id, result_tf, result_df, result_rtf, result_rdf, seen_rev, hash2rev, ngram2kmerann): ''' Write ngram index. Format: id, rev_id, hash, rev_hash, tf, df, etf, edf. etf and edf are tf and df taking into account...
0.197599
0.245424
import shutil import pandas as pd import pytest from ramp_utils import read_config from ramp_utils.testing import database_config_template from ramp_utils.testing import ramp_config_template from ramp_database.utils import check_password from ramp_database.utils import setup_db from ramp_database.utils import sessio...
ramp-database/ramp_database/tools/tests/test_user.py
import shutil import pandas as pd import pytest from ramp_utils import read_config from ramp_utils.testing import database_config_template from ramp_utils.testing import ramp_config_template from ramp_database.utils import check_password from ramp_database.utils import setup_db from ramp_database.utils import sessio...
0.408395
0.209046
import inspect import functools import asyncio import typing as t import contextlib import types from .module import Module from .util import isasync FuncType = t.Callable[..., t.Any] Decorator = t.Callable[[FuncType], FuncType] UNSET = inspect.Parameter.empty class NoProvider(RuntimeError): pass class Inje...
diana/injector.py
import inspect import functools import asyncio import typing as t import contextlib import types from .module import Module from .util import isasync FuncType = t.Callable[..., t.Any] Decorator = t.Callable[[FuncType], FuncType] UNSET = inspect.Parameter.empty class NoProvider(RuntimeError): pass class Inje...
0.692226
0.265863
import sys import json import os if len(sys.argv) < 3: printf("Usage: {} <output.cpp> <a.json> [b.json] [...]") sys.exit(1) READER_VERSION = 1 languages = {} for i in sys.argv[2:]: with open(i) as f: d = json.load(f) if d["version"] != READER_VERSION: printf("Version ({}) doe...
src/info/language/language.py
import sys import json import os if len(sys.argv) < 3: printf("Usage: {} <output.cpp> <a.json> [b.json] [...]") sys.exit(1) READER_VERSION = 1 languages = {} for i in sys.argv[2:]: with open(i) as f: d = json.load(f) if d["version"] != READER_VERSION: printf("Version ({}) doe...
0.21215
0.099252
import numpy as np import pytest from scipy import sparse from qutip import data def test_init_empty_data(): shape = (3, 3) base_data = data.Data(shape) assert base_data.shape[0] == shape[0] assert base_data.shape[1] == shape[1] @pytest.mark.parametrize(['base', 'dtype'], [ pytest.param(data.den...
qutip/tests/core/data/test_convert.py
import numpy as np import pytest from scipy import sparse from qutip import data def test_init_empty_data(): shape = (3, 3) base_data = data.Data(shape) assert base_data.shape[0] == shape[0] assert base_data.shape[1] == shape[1] @pytest.mark.parametrize(['base', 'dtype'], [ pytest.param(data.den...
0.674479
0.806738
import sys import argparse arg_no = len(sys.argv) tool_parser = argparse.ArgumentParser(add_help=False) tool_subparsers = tool_parser.add_subparsers(help='commands', dest='command') # The edit command. edit_parser = tool_subparsers.add_parser('edit', help='edit a POSIX group') group0_parser = edit_parser.add_argume...
cog/cli/group_argparser.py
import sys import argparse arg_no = len(sys.argv) tool_parser = argparse.ArgumentParser(add_help=False) tool_subparsers = tool_parser.add_subparsers(help='commands', dest='command') # The edit command. edit_parser = tool_subparsers.add_parser('edit', help='edit a POSIX group') group0_parser = edit_parser.add_argume...
0.313105
0.048003
import os import tempfile import re import shutil import requests import io import urllib from mitmproxy.net import tcp from mitmproxy.test import tutils from pathod import language from pathod import pathoc from pathod import pathod from pathod import test from pathod.pathod import CA_CERT_NAME def treader(bytes)...
test/pathod/tservers.py
import os import tempfile import re import shutil import requests import io import urllib from mitmproxy.net import tcp from mitmproxy.test import tutils from pathod import language from pathod import pathoc from pathod import pathod from pathod import test from pathod.pathod import CA_CERT_NAME def treader(bytes)...
0.369656
0.066085
try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages import {{ cookiecutter.project_slug }} with open("README.md") as readme_file: readme = readme_file.read() with open("CHANGELOG.md") as changelog_file: changelog = changelog_file.read(...
{{cookiecutter.project_name}}/setup.py
try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages import {{ cookiecutter.project_slug }} with open("README.md") as readme_file: readme = readme_file.read() with open("CHANGELOG.md") as changelog_file: changelog = changelog_file.read(...
0.575827
0.234648
import pandas as pd import rpy2.robjects as robjects from rpy2.robjects import pandas2ri, Formula, conversion pandas2ri.activate() from rpy2.robjects.packages import importr import numpy as np deseq = importr('DESeq2') ''' Adopted from: https://stackoverflow.com/questions/41821100/running-deseq2-through-rpy2 ''' to_da...
neals_python_functions/analysis/deseq2.py
import pandas as pd import rpy2.robjects as robjects from rpy2.robjects import pandas2ri, Formula, conversion pandas2ri.activate() from rpy2.robjects.packages import importr import numpy as np deseq = importr('DESeq2') ''' Adopted from: https://stackoverflow.com/questions/41821100/running-deseq2-through-rpy2 ''' to_da...
0.530236
0.541833
import polars as pl import functools as ft from .utils import _as_list, _col_expr __all__ = [ "paste", "paste0", "str_c", "str_detect", "str_extract", "str_length", "str_remove_all", "str_remove", "str_replace_all", "str_replace", "str_ends", "str_starts", "str_s...
tidypolars/stringr.py
import polars as pl import functools as ft from .utils import _as_list, _col_expr __all__ = [ "paste", "paste0", "str_c", "str_detect", "str_extract", "str_length", "str_remove_all", "str_remove", "str_replace_all", "str_replace", "str_ends", "str_starts", "str_s...
0.775095
0.418608
def no_args(): pass no_args() try: no_args('one_arg') except TypeError: pass else: assert False, 'no TypeError raised: 1 arg to no_args' try: no_args(kw='should fail') except TypeError: pass else: assert False, 'no TypeError raised: kwarg to no_args' def one_arg(arg): return arg on...
tests/snippets/func_defaults.py
def no_args(): pass no_args() try: no_args('one_arg') except TypeError: pass else: assert False, 'no TypeError raised: 1 arg to no_args' try: no_args(kw='should fail') except TypeError: pass else: assert False, 'no TypeError raised: kwarg to no_args' def one_arg(arg): return arg on...
0.277375
0.431345
from db import get_db def get_status(): food_data = get_db().execute( 'SELECT id, timestamp, type, quantity' ' FROM food' ' ORDER BY timestamp DESC' ).fetchone() aquarium_data = get_db().execute( 'SELECT id, timestamp, default_mode, total_food_quantity' ' FROM aqua...
flaskr/status.py
from db import get_db def get_status(): food_data = get_db().execute( 'SELECT id, timestamp, type, quantity' ' FROM food' ' ORDER BY timestamp DESC' ).fetchone() aquarium_data = get_db().execute( 'SELECT id, timestamp, default_mode, total_food_quantity' ' FROM aqua...
0.402392
0.101056
import unittest from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.tests.base import test_lots, test_author from openprocurement.tender.belowthreshold.tests.chronograph_blanks import ( # TenderSwitch0BidResourceTest switch_to_unsuccessful, # TenderSwitch1BidResour...
src/openprocurement/tender/openuadefense/tests/chronograph.py
import unittest from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.tests.base import test_lots, test_author from openprocurement.tender.belowthreshold.tests.chronograph_blanks import ( # TenderSwitch0BidResourceTest switch_to_unsuccessful, # TenderSwitch1BidResour...
0.359364
0.512266
import os import pathlib import click from nilearn.image import resample_to_img from nilearn.masking import apply_mask from ..base import MetaResult from ..meta.ibma import rfx_glm from ..meta.cbma import Peaks2MapsKernel from ..io import convert_sleuth_to_dataset n_iters_default = 10000 @click.command(name='peaks2...
nimare/workflows/peaks2maps.py
import os import pathlib import click from nilearn.image import resample_to_img from nilearn.masking import apply_mask from ..base import MetaResult from ..meta.ibma import rfx_glm from ..meta.cbma import Peaks2MapsKernel from ..io import convert_sleuth_to_dataset n_iters_default = 10000 @click.command(name='peaks2...
0.401688
0.211865
# 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 applicable law or agreed to in writing, software # distributed under the ...
SalishSeaTools/salishsea_tools/visualisations.py
# 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 applicable law or agreed to in writing, software # distributed under the ...
0.914479
0.565479
import unittest import subprocess from . import server class ClientHelperMixin(object): """ Helper methods involving the client for server tests """ def runClientCmd(self, client, command, arguments=""): try: client.runCommand(command, arguments) except subprocess.CalledPr...
tests/end_to_end/server_test.py
import unittest import subprocess from . import server class ClientHelperMixin(object): """ Helper methods involving the client for server tests """ def runClientCmd(self, client, command, arguments=""): try: client.runCommand(command, arguments) except subprocess.CalledPr...
0.487063
0.274048
import datetime from sqlalchemy import or_ from lib.util_sqlalchemy import ResourceMixin from coder.extensions import db from coder.blueprints.billing.models.credit_card import CreditCard from coder.blueprints.billing.models.coupon import Coupon from coder.blueprints.billing.gateways.stripecom import ( Customer a...
coder/blueprints/billing/models/invoice.py
import datetime from sqlalchemy import or_ from lib.util_sqlalchemy import ResourceMixin from coder.extensions import db from coder.blueprints.billing.models.credit_card import CreditCard from coder.blueprints.billing.models.coupon import Coupon from coder.blueprints.billing.gateways.stripecom import ( Customer a...
0.725746
0.140956
import sys from pathlib import Path import numpy as np import matplotlib.pyplot as plt from diffpy.utils.parsers.loaddata import loadData DPI = 300 FIGSIZE = (8,4) FONTSIZE = 12 LINEWIDTH = 1 COLORS = dict(bg_blue='#0B3C5D', bg_red='#B82601', bg_green='#1c6b0a', bg_lightblue='#328CC1', bg_darkblue='#062F...
iq_sq_fq_gr_plot/iq_sq_fq_gr_plot.py
import sys from pathlib import Path import numpy as np import matplotlib.pyplot as plt from diffpy.utils.parsers.loaddata import loadData DPI = 300 FIGSIZE = (8,4) FONTSIZE = 12 LINEWIDTH = 1 COLORS = dict(bg_blue='#0B3C5D', bg_red='#B82601', bg_green='#1c6b0a', bg_lightblue='#328CC1', bg_darkblue='#062F...
0.213459
0.379781
"""Client and server classes corresponding to protobuf-defined services.""" import grpc from ydb.public.api.protos import ydb_table_pb2 as ydb_dot_public_dot_api_dot_protos_dot_ydb__table__pb2 class TableServiceStub(object): """Missing associated documentation comment in .proto file.""" def __init__(self, c...
ydb/public/api/grpc/ydb_table_v1_pb2_grpc.py
"""Client and server classes corresponding to protobuf-defined services.""" import grpc from ydb.public.api.protos import ydb_table_pb2 as ydb_dot_public_dot_api_dot_protos_dot_ydb__table__pb2 class TableServiceStub(object): """Missing associated documentation comment in .proto file.""" def __init__(self, c...
0.763043
0.079961
terminalcolors = {"OKGREEN": '\033[92m', "WARNING": '\033[93m', "FAIL": '\033[91m', "ENDC": '\033[0m'} version = "0.1" cmdList = { "fr": {"args": ["ni", "nt", "theta_i"], "types": ["float", "float", "float"], "desc": "Find fresnal coef and return refractive ang...
color.py
terminalcolors = {"OKGREEN": '\033[92m', "WARNING": '\033[93m', "FAIL": '\033[91m', "ENDC": '\033[0m'} version = "0.1" cmdList = { "fr": {"args": ["ni", "nt", "theta_i"], "types": ["float", "float", "float"], "desc": "Find fresnal coef and return refractive ang...
0.125802
0.273753
import os from unittest.case import TestCase from PIL import Image from raytracer.Camera import Camera from raytracer.Lights import Sun, Ambient, Point from raytracer.Materials import BLUE_GLOSSY, ORANGE_GLOSSY, GRAY_MATTE, GRAY_GLOSSY, ORANGE_MATTE, MIRROR_GLOSSY, \ BLUE_MATTE from raytracer.Objects import Spher...
tests/tests.py
import os from unittest.case import TestCase from PIL import Image from raytracer.Camera import Camera from raytracer.Lights import Sun, Ambient, Point from raytracer.Materials import BLUE_GLOSSY, ORANGE_GLOSSY, GRAY_MATTE, GRAY_GLOSSY, ORANGE_MATTE, MIRROR_GLOSSY, \ BLUE_MATTE from raytracer.Objects import Spher...
0.453988
0.416263
import torch import torch.nn as nn import torch.nn.functional as F __all__ = [ "PPLCNet_x0_25", "PPLCNet_x0_35", "PPLCNet_x0_5", "PPLCNet_x0_75", "PPLCNet_x1_0", "PPLCNet_x1_5", "PPLCNet_x2_0", "PPLCNet_x2_5" ] ''' NET_CONFIG = { "blocks2": #k, in_c, out_c, s, use_se [[3, 16, 32, 1, False]], "...
isegm/model/modeling/ppclnet/backbone.py
import torch import torch.nn as nn import torch.nn.functional as F __all__ = [ "PPLCNet_x0_25", "PPLCNet_x0_35", "PPLCNet_x0_5", "PPLCNet_x0_75", "PPLCNet_x1_0", "PPLCNet_x1_5", "PPLCNet_x2_0", "PPLCNet_x2_5" ] ''' NET_CONFIG = { "blocks2": #k, in_c, out_c, s, use_se [[3, 16, 32, 1, False]], "...
0.895697
0.362969
from functools import reduce import logging from operator import mul from os.path import join as pjoin import numpy as np from africanus.rime.predict import (PREDICT_DOCS, predict_checks) from africanus.util.code import format_code, memoize_on_key from africanus.util.cuda import cuda_type, grids from africanus.util...
africanus/rime/cuda/predict.py
from functools import reduce import logging from operator import mul from os.path import join as pjoin import numpy as np from africanus.rime.predict import (PREDICT_DOCS, predict_checks) from africanus.util.code import format_code, memoize_on_key from africanus.util.cuda import cuda_type, grids from africanus.util...
0.620737
0.227158
def isEnglish(s): try: s.encode(encoding='utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True def isUppercase(s): return s.isupper() def isNumberConstraints(n): if 0 <= n <= 2147483647: return True else : return False def ch...
Question04.py
def isEnglish(s): try: s.encode(encoding='utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True def isUppercase(s): return s.isupper() def isNumberConstraints(n): if 0 <= n <= 2147483647: return True else : return False def ch...
0.194942
0.307176
from typing import Optional from numpy import dtype, ndarray, array, vstack class Report: """Report class. Stores user-defined information for print to ``sys.stdout``. Parameters ---------- name Name of the instance. sep Separation between printed columns. The default is 2...
araucaria/main/report.py
from typing import Optional from numpy import dtype, ndarray, array, vstack class Report: """Report class. Stores user-defined information for print to ``sys.stdout``. Parameters ---------- name Name of the instance. sep Separation between printed columns. The default is 2...
0.932875
0.324878
import filecmp import os, sys, traceback import json import uuid import urlparse from nose.tools import assert_raises import tempfile import shutil from synapseclient.exceptions import * import synapseclient import synapseclient.utils as utils from synapseclient.utils import MB, GB from synapseclient import Activity,...
tests/integration/test_sftp_upload.py
import filecmp import os, sys, traceback import json import uuid import urlparse from nose.tools import assert_raises import tempfile import shutil from synapseclient.exceptions import * import synapseclient import synapseclient.utils as utils from synapseclient.utils import MB, GB from synapseclient import Activity,...
0.107461
0.116186
import json import os import os.path import re import shutil import stat import urllib.parse #@<> INCLUDE dump_utils.inc #@<> deploy sandbox testutil.deploy_raw_sandbox(__mysql_sandbox_port1, "root") shell.connect(__sandbox_uri1) dumpdir = os.path.join(__tmp_dir, "dumptests") shutil.rmtree(dumpdir, True) os.makedir...
unittest/scripts/auto/py_shell/scripts/util_dump_instance_corners_norecord.py
import json import os import os.path import re import shutil import stat import urllib.parse #@<> INCLUDE dump_utils.inc #@<> deploy sandbox testutil.deploy_raw_sandbox(__mysql_sandbox_port1, "root") shell.connect(__sandbox_uri1) dumpdir = os.path.join(__tmp_dir, "dumptests") shutil.rmtree(dumpdir, True) os.makedir...
0.197793
0.18628
import io import os import re import tarfile import tempfile from .fnmatch import fnmatch from ..constants import IS_WINDOWS_PLATFORM _SEP = re.compile('/|\\\\') if IS_WINDOWS_PLATFORM else re.compile('/') def tar(path, exclude=None, dockerfile=None, fileobj=None, gzip=False): root = os.path.abspath(path) ...
docker/utils/build.py
import io import os import re import tarfile import tempfile from .fnmatch import fnmatch from ..constants import IS_WINDOWS_PLATFORM _SEP = re.compile('/|\\\\') if IS_WINDOWS_PLATFORM else re.compile('/') def tar(path, exclude=None, dockerfile=None, fileobj=None, gzip=False): root = os.path.abspath(path) ...
0.424173
0.13733
import yaml import subprocess import sys import getopt import json help_message = """access-control.py -k <apiKey> -f <access-bindings-file> -k, --apiKey apikey from the IBM Cloud IAM -b, --access-bindings access binding file which contains the users and the access controls(groups)...
scripts/access-control/access-control.py
import yaml import subprocess import sys import getopt import json help_message = """access-control.py -k <apiKey> -f <access-bindings-file> -k, --apiKey apikey from the IBM Cloud IAM -b, --access-bindings access binding file which contains the users and the access controls(groups)...
0.203035
0.07024
import micropsi_core.tools __author__ = 'joscha' __date__ = '09.05.12' class NetEntity(object): """The basic building blocks of node nets. Attributes: uid: the unique identifier of the net entity index: an attempt at creating an ordering criterion for net entities name: a human reada...
micropsi_core/nodenet/dict_engine/dict_netentity.py
import micropsi_core.tools __author__ = 'joscha' __date__ = '09.05.12' class NetEntity(object): """The basic building blocks of node nets. Attributes: uid: the unique identifier of the net entity index: an attempt at creating an ordering criterion for net entities name: a human reada...
0.848188
0.327265
import time import json class Head: def __init__(self): self._next = self class Entry: def __init__(self, cache, stringified, value): self._cache = cache self._stringified = stringified self.when = time.time() self._next = cache._head._next self._previous = cach...
python/cache.py
import time import json class Head: def __init__(self): self._next = self class Entry: def __init__(self, cache, stringified, value): self._cache = cache self._stringified = stringified self.when = time.time() self._next = cache._head._next self._previous = cach...
0.573798
0.082475
import click import json from pathlib import Path import os import requests from datetime import datetime import boto3 from urllib.parse import unquote_plus from coach import * __API__ = 'https://9fqai4xymb.execute-api.us-east-1.amazonaws.com/latest' class CoachApi: def __init__(self, api, key, s...
main.py
import click import json from pathlib import Path import os import requests from datetime import datetime import boto3 from urllib.parse import unquote_plus from coach import * __API__ = 'https://9fqai4xymb.execute-api.us-east-1.amazonaws.com/latest' class CoachApi: def __init__(self, api, key, s...
0.343342
0.083106
import math from ..annotationsexc import SmallSizeInputError # ---------------------------------------------------------------------------- BIG_NUMBER = 32764 # ---------------------------------------------------------------------------- def octave(value): return math.log(value) / math.log(2) # --------------...
sppas/sppas/src/annotations/Intsint/intsint.py
import math from ..annotationsexc import SmallSizeInputError # ---------------------------------------------------------------------------- BIG_NUMBER = 32764 # ---------------------------------------------------------------------------- def octave(value): return math.log(value) / math.log(2) # --------------...
0.790247
0.36977
import urllib3 from html.parser import HTMLParser from datetime import datetime import pandas as pd import os import time import sys import traceback class ETFParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.was_row = False self.was_label = False self.was_labe...
etf_scrapper.py
import urllib3 from html.parser import HTMLParser from datetime import datetime import pandas as pd import os import time import sys import traceback class ETFParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.was_row = False self.was_label = False self.was_labe...
0.079268
0.05549
from __future__ import absolute_import, division, print_function __metaclass__ = type import socket from ansible.module_utils.six import StringIO from ansible.module_utils.six.moves.http_cookiejar import Cookie from ansible.module_utils.six.moves.http_client import HTTPMessage from ansible.module_utils.urls import f...
test/units/module_utils/urls/test_fetch_url.py
from __future__ import absolute_import, division, print_function __metaclass__ = type import socket from ansible.module_utils.six import StringIO from ansible.module_utils.six.moves.http_cookiejar import Cookie from ansible.module_utils.six.moves.http_client import HTTPMessage from ansible.module_utils.urls import f...
0.751557
0.175044
import sys import logging import socket import json APP_LOGGER_NAME = 'avio' DEFAULT_LOGGER_LEVEL = 'INFO' app_logger = logging.getLogger(APP_LOGGER_NAME) def configure_app_logger(logger_config: dict = None) -> logging.Logger: """ :param logger_config: { 'level': 'INFO', 'use_json_formatter...
avio/log.py
import sys import logging import socket import json APP_LOGGER_NAME = 'avio' DEFAULT_LOGGER_LEVEL = 'INFO' app_logger = logging.getLogger(APP_LOGGER_NAME) def configure_app_logger(logger_config: dict = None) -> logging.Logger: """ :param logger_config: { 'level': 'INFO', 'use_json_formatter...
0.54359
0.100128
from tkinter import * import main_v201 from tkinter import messagebox root01 = Tk() #root01.title(main_v201.t00) root01.geometry("500x300") root01.resizable(0, 0) f00 = Frame(root01, bg='gray54', width=500, height=300) f1 = Frame(root01, bg='gray54', width=500, height=300) f2 = Frame(root01, bg='gray54', width=500, h...
GUI.py
from tkinter import * import main_v201 from tkinter import messagebox root01 = Tk() #root01.title(main_v201.t00) root01.geometry("500x300") root01.resizable(0, 0) f00 = Frame(root01, bg='gray54', width=500, height=300) f1 = Frame(root01, bg='gray54', width=500, height=300) f2 = Frame(root01, bg='gray54', width=500, h...
0.335895
0.158369
__author__ = "<NAME> <<EMAIL>>" # Standard library import httplib import json import os import urllib from collections import Counter # Module specific import ads # Couple of mutable variables for the reader author_query = "^Casey, <NAME>." records_filename = "citations.json" papers = ads.search(author_query) # H...
examples/beers-for-cites.py
__author__ = "<NAME> <<EMAIL>>" # Standard library import httplib import json import os import urllib from collections import Counter # Module specific import ads # Couple of mutable variables for the reader author_query = "^Casey, <NAME>." records_filename = "citations.json" papers = ads.search(author_query) # H...
0.311532
0.162912
import inspect import os import platform import requests from requests import Response from konduto import VERSION from konduto.api.clients import KondutoHttpClient from konduto.api.clients.v1.order import KondutoOrderClient from konduto.api.clients.v1.restrict_list import KondutoRestrictClient from konduto.infrastru...
konduto/api/__init__.py
import inspect import os import platform import requests from requests import Response from konduto import VERSION from konduto.api.clients import KondutoHttpClient from konduto.api.clients.v1.order import KondutoOrderClient from konduto.api.clients.v1.restrict_list import KondutoRestrictClient from konduto.infrastru...
0.631935
0.080719
from __future__ import absolute_import import abc import collections import six import time from elementium.exc import TimeOutError from elementium.util import ( DEFAULT_TTL, ignored ) from elementium.waiters import ConditionElementsWaiter __author__ = "<NAME>" __email__ = "<EMAIL>" @six.add_metaclass(abc...
elementium/elements.py
from __future__ import absolute_import import abc import collections import six import time from elementium.exc import TimeOutError from elementium.util import ( DEFAULT_TTL, ignored ) from elementium.waiters import ConditionElementsWaiter __author__ = "<NAME>" __email__ = "<EMAIL>" @six.add_metaclass(abc...
0.875853
0.268051
import numpy from discrete_fuzzy_operators.base.operators.binary_operators.suboperators.fuzzy_aggregation_operator import \ DiscreteFuzzyAggregationBinaryOperator from typing import Callable, List class Copula(DiscreteFuzzyAggregationBinaryOperator): def __init__(self, n: int, operator_matr...
discrete_fuzzy_operators/base/operators/binary_operators/suboperators/fuzzy_aggregation_suboperators/copula.py
import numpy from discrete_fuzzy_operators.base.operators.binary_operators.suboperators.fuzzy_aggregation_operator import \ DiscreteFuzzyAggregationBinaryOperator from typing import Callable, List class Copula(DiscreteFuzzyAggregationBinaryOperator): def __init__(self, n: int, operator_matr...
0.93459
0.677877
import numpy as np import matplotlib.pyplot as plt from math import cos, sin, tan, pi import math import time class DHparam: """DHパラメータ""" def __init__(self, alpha, a, d, theta): self.alpha = alpha self.a = a self.d = d self.theta = theta class Homogeneous...
misc/old_hurui.py
import numpy as np import matplotlib.pyplot as plt from math import cos, sin, tan, pi import math import time class DHparam: """DHパラメータ""" def __init__(self, alpha, a, d, theta): self.alpha = alpha self.a = a self.d = d self.theta = theta class Homogeneous...
0.237841
0.479686
import json, os, gspread from flask import Flask, render_template, redirect, url_for from google.oauth2 import service_account from dotenv import load_dotenv import pandas as pd def get_credential(): '''Reads environment vars, builds and returns scoped Google credential object''' # Build credential dict ...
app.py
import json, os, gspread from flask import Flask, render_template, redirect, url_for from google.oauth2 import service_account from dotenv import load_dotenv import pandas as pd def get_credential(): '''Reads environment vars, builds and returns scoped Google credential object''' # Build credential dict ...
0.249447
0.285453
import sys import numpy as np from rnn_portfolio import rnn from rnn_portfolio.preprocessing import split_val_tr from rnn_portfolio.preprocessing import get_n_batch def make_empty_datadict(markets, max_time=10000): """ Make a dictionary containing placeholders for OPEN, CLOSE, HIGH, LOW and DATE data that will...
rnn_portfolio/training.py
import sys import numpy as np from rnn_portfolio import rnn from rnn_portfolio.preprocessing import split_val_tr from rnn_portfolio.preprocessing import get_n_batch def make_empty_datadict(markets, max_time=10000): """ Make a dictionary containing placeholders for OPEN, CLOSE, HIGH, LOW and DATE data that will...
0.748904
0.471467
import os import argparse import random import yaml from jinja2 import Template BASE_DIR = os.path.dirname(os.path.abspath(__file__)) def gen_mac(): ''' Generate a random MAC address based on the LAA (locally Administered Addresses) range. x2-xx-xx-xx-xx-xx --> Only currently supported range. x6-xx-x...
gen-vmx-conf.py
import os import argparse import random import yaml from jinja2 import Template BASE_DIR = os.path.dirname(os.path.abspath(__file__)) def gen_mac(): ''' Generate a random MAC address based on the LAA (locally Administered Addresses) range. x2-xx-xx-xx-xx-xx --> Only currently supported range. x6-xx-x...
0.276202
0.050776
from concurrent.futures import ProcessPoolExecutor from functools import partial import numpy as np import os from util import audio from text.pinyinconvert import sentence_to_pinyin from text.symbols import pinyin_dict # 声母韵母化bznsyp中的拼音 对一些做特殊处理 def _format_pinyin(value): if len(value) == 1: return value...
datasets/bznsyp.py
from concurrent.futures import ProcessPoolExecutor from functools import partial import numpy as np import os from util import audio from text.pinyinconvert import sentence_to_pinyin from text.symbols import pinyin_dict # 声母韵母化bznsyp中的拼音 对一些做特殊处理 def _format_pinyin(value): if len(value) == 1: return value...
0.164852
0.158304
import numpy as np import tensorflow as tf from gen_cap import gen_captcha_text_and_image from gen_cap import chars text, image = gen_captcha_text_and_image() print("Image channel: ", image.shape) IMAGE_HEIGHT = 80 IMAGE_WIDTH = 350 MAX_CAPTCHA = 8 print("Length: ", MAX_CAPTCHA) char_set = [] for i...
task1/train.py
import numpy as np import tensorflow as tf from gen_cap import gen_captcha_text_and_image from gen_cap import chars text, image = gen_captcha_text_and_image() print("Image channel: ", image.shape) IMAGE_HEIGHT = 80 IMAGE_WIDTH = 350 MAX_CAPTCHA = 8 print("Length: ", MAX_CAPTCHA) char_set = [] for i...
0.375134
0.17259
import sys import json import xml.etree.ElementTree as ET # Использовать словарь, содержащий следующие ключи: фамилия, имя; номер телефона; # дата рождения (список из трех чисел). Написать программу, выполняющую следующие # действия: ввод с клавиатуры данных в список, состоящий из словарей заданной структуры; # запис...
ind_task_3.py
import sys import json import xml.etree.ElementTree as ET # Использовать словарь, содержащий следующие ключи: фамилия, имя; номер телефона; # дата рождения (список из трех чисел). Написать программу, выполняющую следующие # действия: ввод с клавиатуры данных в список, состоящий из словарей заданной структуры; # запис...
0.113126
0.277173
from ..models import Quotes from flask import render_template, request, redirect, url_for, flash from ..models import User, Blogs, Comment, Subscriber from flask_login import login_required, current_user from . import main from ..request import get_quotes from .forms import BlogForm, CommentForm from .. import db @ma...
app/main/views.py
from ..models import Quotes from flask import render_template, request, redirect, url_for, flash from ..models import User, Blogs, Comment, Subscriber from flask_login import login_required, current_user from . import main from ..request import get_quotes from .forms import BlogForm, CommentForm from .. import db @ma...
0.410756
0.076822
import argparse from pathlib import Path from sys import argv import numpy as np from matplotlib import pyplot as plt import dns def main(): parser = argparse.ArgumentParser(description="Produce plots of time series.") parser.add_argument("runDir", type=str, help="path to the run folder.") parser.add_ar...
python/dnsstats.py
import argparse from pathlib import Path from sys import argv import numpy as np from matplotlib import pyplot as plt import dns def main(): parser = argparse.ArgumentParser(description="Produce plots of time series.") parser.add_argument("runDir", type=str, help="path to the run folder.") parser.add_ar...
0.418103
0.458409
from enum import Enum, IntEnum, unique, EnumMeta from typing import Union from werkzeug.utils import cached_property class _IndexEnumMeta(EnumMeta): def __getitem__(cls, item: int): return list(cls)[item] @unique class Suit(Enum, metaclass=_IndexEnumMeta): diamonds = '♢' spades = '♠' hearts...
jass/logic/card.py
from enum import Enum, IntEnum, unique, EnumMeta from typing import Union from werkzeug.utils import cached_property class _IndexEnumMeta(EnumMeta): def __getitem__(cls, item: int): return list(cls)[item] @unique class Suit(Enum, metaclass=_IndexEnumMeta): diamonds = '♢' spades = '♠' hearts...
0.857186
0.139572
from django.shortcuts import render, redirect from .models import TodoList, Category from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from Project.todo.serializers import UserSerializer, GroupSerializer, TodoSerializer def index(request): ...
Python/Project/Project/todo/views.py
from django.shortcuts import render, redirect from .models import TodoList, Category from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from Project.todo.serializers import UserSerializer, GroupSerializer, TodoSerializer def index(request): ...
0.332961
0.109087
import os import json import time import socket from threading import Thread IPS = [] def trata_cliente(conexao, endereco): requisicao = conexao.recv(1024) print requisicao if requisicao == 'LIST': arqs = os.listdir('/etc/black/garagem/arquivos/') conexao.send(json.dumps(arqs)) elif re...
computacao_movel/DTN/server.py
import os import json import time import socket from threading import Thread IPS = [] def trata_cliente(conexao, endereco): requisicao = conexao.recv(1024) print requisicao if requisicao == 'LIST': arqs = os.listdir('/etc/black/garagem/arquivos/') conexao.send(json.dumps(arqs)) elif re...
0.109921
0.079353
import torch import tqdm class Model(torch.nn.Module): def __init__(self, cfg): super(Model, self).__init__() self.cfg = cfg self.nb_classes = cfg.nb_classes self.linear = torch.nn.Linear(in_features = cfg.embedding_size, out_features ...
classifiers/MLP_ExactSolution.py
import torch import tqdm class Model(torch.nn.Module): def __init__(self, cfg): super(Model, self).__init__() self.cfg = cfg self.nb_classes = cfg.nb_classes self.linear = torch.nn.Linear(in_features = cfg.embedding_size, out_features ...
0.884514
0.292043
from process_utils import * import json import pickle save_common_path = "../processed_data/WNUT_2017/vocab_and_embd.pkl" save_inter_train_path = "../processed_data/WNUT_2017/train_data_intermediate.json" save_inter_train_mixed_case_path = "../processed_data/WNUT_2017/train_mixed_data_intermediate.json" save_inter_de...
process_tools/process_WNUT_phase2.py
from process_utils import * import json import pickle save_common_path = "../processed_data/WNUT_2017/vocab_and_embd.pkl" save_inter_train_path = "../processed_data/WNUT_2017/train_data_intermediate.json" save_inter_train_mixed_case_path = "../processed_data/WNUT_2017/train_mixed_data_intermediate.json" save_inter_de...
0.315736
0.361644
import oqs import platform # to learn the OS we're on import random # KEMs for which unit testing is disabled disabled_KEM_patterns = [] if platform.system() == "Windows": disabled_KEM_patterns = ["Classic-McEliece"] def test_correctness(): for alg_name in oqs.get_enabled_KEM_mechanisms(): if any(i...
tests/test_kem.py
import oqs import platform # to learn the OS we're on import random # KEMs for which unit testing is disabled disabled_KEM_patterns = [] if platform.system() == "Windows": disabled_KEM_patterns = ["Classic-McEliece"] def test_correctness(): for alg_name in oqs.get_enabled_KEM_mechanisms(): if any(i...
0.227641
0.209753
import cv2 import numpy as np # Load face, eye, and nose cascade files face_cascade = cv2.CascadeClassifier(r"C:\Users\sandhyao\code\Section_10_code\haarcascade_frontalface_alt.xml") eye_cascade = cv2.CascadeClassifier(r"C:\Users\sandhyao\code\Section_10_code\haarcascade_eye.xml") nose_cascade = cv2.CascadeClassifier(...
Section_10_code/eye_nose_detector.py
import cv2 import numpy as np # Load face, eye, and nose cascade files face_cascade = cv2.CascadeClassifier(r"C:\Users\sandhyao\code\Section_10_code\haarcascade_frontalface_alt.xml") eye_cascade = cv2.CascadeClassifier(r"C:\Users\sandhyao\code\Section_10_code\haarcascade_eye.xml") nose_cascade = cv2.CascadeClassifier(...
0.599602
0.175839
from docutils.transforms import Transformer from docutils.io import StringOutput from .settings import SettingsSpec from .docstring.writer import TextWriter class DocstringStyle(SettingsSpec): """This class represents docstring style. It converts document tree to text representation and also transforms ...
src/autodoc/style.py
from docutils.transforms import Transformer from docutils.io import StringOutput from .settings import SettingsSpec from .docstring.writer import TextWriter class DocstringStyle(SettingsSpec): """This class represents docstring style. It converts document tree to text representation and also transforms ...
0.929556
0.437944
# ----------------------------------------------------------------------------- # crc32 forge by StalkR # cmdline wrapper by hellman # specific HaloMD modifications by nil # original from comments in http://blog.stalkr.net/2011/03/crc-32-forging.html # ----------------------------------------------------------------...
vendor/crc32forge.py
# ----------------------------------------------------------------------------- # crc32 forge by StalkR # cmdline wrapper by hellman # specific HaloMD modifications by nil # original from comments in http://blog.stalkr.net/2011/03/crc-32-forging.html # ----------------------------------------------------------------...
0.41739
0.148294
from WeOptPy.algorithms import AdaptiveBatAlgorithm from WeOptPy.tests.test_algorithm import ( AlgorithmTestCase, Sphere ) class ABATestCase(AlgorithmTestCase): r"""Test case for AdaptiveBatAlgorithm algorithm. Date: April 2019 Author: <NAME> See Also: * :class:`WeOptPy.algorithms.AdaptiveBatAlgorithm`...
WeOptPy/tests/test_aba.py
from WeOptPy.algorithms import AdaptiveBatAlgorithm from WeOptPy.tests.test_algorithm import ( AlgorithmTestCase, Sphere ) class ABATestCase(AlgorithmTestCase): r"""Test case for AdaptiveBatAlgorithm algorithm. Date: April 2019 Author: <NAME> See Also: * :class:`WeOptPy.algorithms.AdaptiveBatAlgorithm`...
0.791861
0.802788
from bedlam import Game from bedlam import GameObject from bedlam import Scene from bedlam import Sprite # __pragma__('skip') document = window = Math = Date = console = 0 # Prevent complaints by optional static checker # __pragma__('noskip') # __pragma__('noalias', 'clear') BOARD_SIZE = 16 CELL_SIZE = 28 BOARD_MAR...
snake.py
from bedlam import Game from bedlam import GameObject from bedlam import Scene from bedlam import Sprite # __pragma__('skip') document = window = Math = Date = console = 0 # Prevent complaints by optional static checker # __pragma__('noskip') # __pragma__('noalias', 'clear') BOARD_SIZE = 16 CELL_SIZE = 28 BOARD_MAR...
0.441673
0.142202
import pytest import json from pricemonitor.config import Coin from pricemonitor.producing.feed_prices import BtcFeed, BtcFeedError from util.network import DataFormat, NetworkError WBTC_COIN = Coin(symbol="WBTC", address="0x000", name="WrappedBitcoin", volatility=0.05) ETH_COIN = Coin(symbol="ETH", address="0x001",...
tests/test_btc_feed.py
import pytest import json from pricemonitor.config import Coin from pricemonitor.producing.feed_prices import BtcFeed, BtcFeedError from util.network import DataFormat, NetworkError WBTC_COIN = Coin(symbol="WBTC", address="0x000", name="WrappedBitcoin", volatility=0.05) ETH_COIN = Coin(symbol="ETH", address="0x001",...
0.628863
0.313394
import logging import logging.handlers import threading import pynmea2 import serial import aprs import aprstracker __author__ = '<NAME> W2GMD <<EMAIL>>' __copyright__ = 'Copyright 2017 <NAME>' __license__ = 'Apache License, Version 2.0' class SerialGPSPoller(threading.Thread): """Threadable Object for pollin...
aprstracker/classes.py
import logging import logging.handlers import threading import pynmea2 import serial import aprs import aprstracker __author__ = '<NAME> W2GMD <<EMAIL>>' __copyright__ = 'Copyright 2017 <NAME>' __license__ = 'Apache License, Version 2.0' class SerialGPSPoller(threading.Thread): """Threadable Object for pollin...
0.560614
0.073663
def cleaning_func_0(data): # core cleaning code import pandas as pd # data = pd.read_csv('../input/loan.csv', low_memory=False) data.earliest_cr_line = pd.to_datetime(data.earliest_cr_line) return data #============= # Function 1 def cleaning_func_1(data): # core cleaning code import pandas as pd # data = pd.r...
analysis-results/executability-results/loan_data/source_code.py
def cleaning_func_0(data): # core cleaning code import pandas as pd # data = pd.read_csv('../input/loan.csv', low_memory=False) data.earliest_cr_line = pd.to_datetime(data.earliest_cr_line) return data #============= # Function 1 def cleaning_func_1(data): # core cleaning code import pandas as pd # data = pd.r...
0.278747
0.424531
import argparse import logging import os import re from matplotlib import pylab as plt import numpy as np import trace_utils def _SummarizeStatsForAllocators(result_for_pid: dict, allocators: dict): """We compute the wasted memory here by taking the difference of 'allocated_objects_size' and 'size'. See Memor...
tools/memory/partition_allocator/compute_external_fragmentation.py
import argparse import logging import os import re from matplotlib import pylab as plt import numpy as np import trace_utils def _SummarizeStatsForAllocators(result_for_pid: dict, allocators: dict): """We compute the wasted memory here by taking the difference of 'allocated_objects_size' and 'size'. See Memor...
0.489015
0.337995
import datetime import json import logging import requests from core.analytics import OneShotAnalytics from core.errors import ObservableValidationError from core.observables import Hostname, Email, Ip, Hash class ThreatCrowdAPI(object): """Base class for querying the ThreatCrowd API.""" @staticmethod ...
plugins/analytics/public/threatcrowd.py
import datetime import json import logging import requests from core.analytics import OneShotAnalytics from core.errors import ObservableValidationError from core.observables import Hostname, Email, Ip, Hash class ThreatCrowdAPI(object): """Base class for querying the ThreatCrowd API.""" @staticmethod ...
0.601711
0.092565
from django.contrib.auth.decorators import login_required from django.core.exceptions import BadRequest from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from .models import FirstLogin from .forms import * def register(request): """ The view for the register ...
users/views.py
from django.contrib.auth.decorators import login_required from django.core.exceptions import BadRequest from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from .models import FirstLogin from .forms import * def register(request): """ The view for the register ...
0.658308
0.107907
# third party import GPy import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsRegressor # ite absolute from ite.utils.metrics import HistoricMetrics from ite.utils.metrics import Metrics class CMGP: """ An implementation of various Gaussian models for Causal inference building on G...
src/ite/algs/causal_multitask_gaussian_processes/model.py
# third party import GPy import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsRegressor # ite absolute from ite.utils.metrics import HistoricMetrics from ite.utils.metrics import Metrics class CMGP: """ An implementation of various Gaussian models for Causal inference building on G...
0.82251
0.645651
from rest_framework import status from django.shortcuts import reverse from rest_framework.test import APIRequestFactory from dj_tahweela.currencies.views import ExchangeRateView, ExchangeRateTimeSeriesView from dj_tahweela.users.tests.factories import UserFactory from rest_framework.test import APITestCase, force_auth...
dj_tahweela/currencies/tests/test_views.py
from rest_framework import status from django.shortcuts import reverse from rest_framework.test import APIRequestFactory from dj_tahweela.currencies.views import ExchangeRateView, ExchangeRateTimeSeriesView from dj_tahweela.users.tests.factories import UserFactory from rest_framework.test import APITestCase, force_auth...
0.59972
0.239238
import argparse import json import os import time from tweepy import OAuthHandler, API, NotFound ssm = None def get_secret_from_ssm() -> list[str]: import boto3 global ssm if not ssm: ssm = boto3.client('ssm') ssm_key_consumer_key = os.environ['SSM_KEY_CONSUMER_KEY'] ssm_key_consumer_s...
lambda/main.py
import argparse import json import os import time from tweepy import OAuthHandler, API, NotFound ssm = None def get_secret_from_ssm() -> list[str]: import boto3 global ssm if not ssm: ssm = boto3.client('ssm') ssm_key_consumer_key = os.environ['SSM_KEY_CONSUMER_KEY'] ssm_key_consumer_s...
0.275325
0.057071
"""The artifact class and builder.""" from __future__ import unicode_literals from . import utils from .name import Name from .name import SubPart class Artifact: """Represents a design object which can be linked to other design objects. See #SPC-design.artifact """ # pylint: disable=too-many-argum...
artifact_py/artifact.py
"""The artifact class and builder.""" from __future__ import unicode_literals from . import utils from .name import Name from .name import SubPart class Artifact: """Represents a design object which can be linked to other design objects. See #SPC-design.artifact """ # pylint: disable=too-many-argum...
0.906944
0.208642
import requests import nose.tools from mock import patch from videolectures.util import ( VideoInfoExtractor, VideoDownloader, DownloadError, ExtractionError) def _build_response_object(fixture_path): r = requests.Response() r.status_code = 200 r._content = _get_fixture(fixture_path) ...
tests/videolectures/util_test.py
import requests import nose.tools from mock import patch from videolectures.util import ( VideoInfoExtractor, VideoDownloader, DownloadError, ExtractionError) def _build_response_object(fixture_path): r = requests.Response() r.status_code = 200 r._content = _get_fixture(fixture_path) ...
0.558809
0.242323
import datetime import numpy as np class synthetic_data(): # Note: "features" = "exogenous variables" # "labels" = "endogenous variables" def __init__(self, N=100000, num_features=8, true_betas=None, distribution='Poisson', ...
mirabolic/neural_glm/generate_synthetic_data.py
import datetime import numpy as np class synthetic_data(): # Note: "features" = "exogenous variables" # "labels" = "endogenous variables" def __init__(self, N=100000, num_features=8, true_betas=None, distribution='Poisson', ...
0.593609
0.360968
import json import random from datetime import datetime import numpy as np import torch.nn as nn import torch.utils.data import evaluation.evaluators as evaluators import evaluation.metrics as metrics import examples.run_classifier_dataset_utils as classifier_utils import train.callbacks as callbacks import train.tra...
configurable_trainers/dse_configurable_trainer.py
import json import random from datetime import datetime import numpy as np import torch.nn as nn import torch.utils.data import evaluation.evaluators as evaluators import evaluation.metrics as metrics import examples.run_classifier_dataset_utils as classifier_utils import train.callbacks as callbacks import train.tra...
0.651909
0.282852
import os import sys """ Checks the plaidml parameter and sets the plaidml keras backend if needed. """ use_plaidml_keras_backend = False parameter_plaidml_keras_backend = '--plaidml-keras-backend' if parameter_plaidml_keras_backend in sys.argv: use_plaidml_keras_backend = True if use_plaidml_ker...
mlks/main.py
import os import sys """ Checks the plaidml parameter and sets the plaidml keras backend if needed. """ use_plaidml_keras_backend = False parameter_plaidml_keras_backend = '--plaidml-keras-backend' if parameter_plaidml_keras_backend in sys.argv: use_plaidml_keras_backend = True if use_plaidml_ker...
0.379263
0.092074
from oslo_log import log from oslo_utils import importutils from oslo_utils import units import six from manila import exception from manila.i18n import _, _LI, _LW hp3parclient = importutils.try_import("hp3parclient") if hp3parclient: from hp3parclient import file_client LOG = log.getLogger(__name__) MIN_CLIEN...
manila/share/drivers/hp/hp_3par_mediator.py
from oslo_log import log from oslo_utils import importutils from oslo_utils import units import six from manila import exception from manila.i18n import _, _LI, _LW hp3parclient = importutils.try_import("hp3parclient") if hp3parclient: from hp3parclient import file_client LOG = log.getLogger(__name__) MIN_CLIEN...
0.494385
0.061003
import pytest from croo.croo import Croo @pytest.mark.parametrize( 'croo_out_def_json, expected_relpaths', [ ( {"main.t_main_1": {"out": {"path": "main.t_main_1/${i}/${basename}"}}}, ['main.t_main_1/1/t_main_1.1.out', 'main.t_main_1/0/t_main_1.0.out'], ), ( ...
tests/test_subworkflow.py
import pytest from croo.croo import Croo @pytest.mark.parametrize( 'croo_out_def_json, expected_relpaths', [ ( {"main.t_main_1": {"out": {"path": "main.t_main_1/${i}/${basename}"}}}, ['main.t_main_1/1/t_main_1.1.out', 'main.t_main_1/0/t_main_1.0.out'], ), ( ...
0.295433
0.247785
from typing import List from operator import add, mul from util.helpers import solution_timer from util.input_helper import read_entire_input data = read_entire_input(2020,18) def parse(data) -> List[List[str]]: return [tokenise(element) for element in data] def tokenise(exp: str) -> List[str]: exp = exp.rep...
year_2020/day_18_2020.py
from typing import List from operator import add, mul from util.helpers import solution_timer from util.input_helper import read_entire_input data = read_entire_input(2020,18) def parse(data) -> List[List[str]]: return [tokenise(element) for element in data] def tokenise(exp: str) -> List[str]: exp = exp.rep...
0.53048
0.424173
import discord from discord.ext import commands import sqlite3 class Info(commands.Cog): def __init__(self, bot): self.bot = bot # A list of commands @commands.command(aliases=["h","commands"]) async def help(self, ctx): embed = discord.Embed(title="Commands:", color=0xFFFA9E) embed.add_field(name=":mag_r...
cogs/info.py
import discord from discord.ext import commands import sqlite3 class Info(commands.Cog): def __init__(self, bot): self.bot = bot # A list of commands @commands.command(aliases=["h","commands"]) async def help(self, ctx): embed = discord.Embed(title="Commands:", color=0xFFFA9E) embed.add_field(name=":mag_r...
0.151372
0.199639
import os try: import urlparse as url_parser except ImportError: import urllib.parse as url_parser import m3u8 import pytest import playlists def test_loads_should_create_object_from_string(): obj = m3u8.loads(playlists.SIMPLE_PLAYLIST) assert isinstance(obj, m3u8.M3U8) assert 5220 == obj.target_d...
tests/test_loader.py
import os try: import urlparse as url_parser except ImportError: import urllib.parse as url_parser import m3u8 import pytest import playlists def test_loads_should_create_object_from_string(): obj = m3u8.loads(playlists.SIMPLE_PLAYLIST) assert isinstance(obj, m3u8.M3U8) assert 5220 == obj.target_d...
0.456894
0.397646
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import argparse __author__ = '<NAME>' __email__ = '<EMAIL>' ON = 255 OFF = 0 vals = [ON, OFF] def add_glider(i, j, grid): """ add a glider with top left cell at (i, j)""" glider = np.array([[0, 0, 255], ...
cell_life.py
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import argparse __author__ = '<NAME>' __email__ = '<EMAIL>' ON = 255 OFF = 0 vals = [ON, OFF] def add_glider(i, j, grid): """ add a glider with top left cell at (i, j)""" glider = np.array([[0, 0, 255], ...
0.599602
0.335732
import bpy import os import mathutils import math def write_rigid_bodies(f, rigid_bodies, worldQuat, worldScale): f.write("rigid_bodies:\n") for rigid_body in rigid_bodies: is_foot = "foot" in rigid_body.keys() and rigid_body["foot"] > 0.0 location = worldScale * (worldQuat * rigid_body...
Creatures/export_model.py
import bpy import os import mathutils import math def write_rigid_bodies(f, rigid_bodies, worldQuat, worldScale): f.write("rigid_bodies:\n") for rigid_body in rigid_bodies: is_foot = "foot" in rigid_body.keys() and rigid_body["foot"] > 0.0 location = worldScale * (worldQuat * rigid_body...
0.374791
0.28283
from pandas.io.sql import read_sql import pandas as pd import geopandas as gpd import requests from pyiem.util import get_dbconn from pyiem.box_utils import sendfiles2box LOOKUP = { "10240003": "East Nishnabotna River", "07080205": "Middle Cedar River", "07100006": "North Raccoon River", "07060002": "...
scripts/hud/deliver_reports.py
from pandas.io.sql import read_sql import pandas as pd import geopandas as gpd import requests from pyiem.util import get_dbconn from pyiem.box_utils import sendfiles2box LOOKUP = { "10240003": "East Nishnabotna River", "07080205": "Middle Cedar River", "07100006": "North Raccoon River", "07060002": "...
0.440469
0.285397
import tarfile import re from zipfile import ZipFile str = open("metadata.json", "r").read() match = re.search(r'"version":\s"(.*)",', str) metadata_ver = match.group(1) enrich_str = open("source/greynoise_anomali_enrichment.py", "r").read() enrich_match = re.search(r"VERSION\s=\s\S(.*)\S", enrich_str) enrich_ver = e...
greynoise-enrichment/build-bundle.py
import tarfile import re from zipfile import ZipFile str = open("metadata.json", "r").read() match = re.search(r'"version":\s"(.*)",', str) metadata_ver = match.group(1) enrich_str = open("source/greynoise_anomali_enrichment.py", "r").read() enrich_match = re.search(r"VERSION\s=\s\S(.*)\S", enrich_str) enrich_ver = e...
0.19031
0.111967
import os import pandas as pd import threading import time import ujson from tornado_sqlalchemy_login.utils import safe_get, safe_post_cookies, construct_path from traitlets import HasTraits from .samples_mixin import SamplesMixin from ..types.competition import CompetitionSpec from ..types.submission import Submission...
crowdsource/client/client.py
import os import pandas as pd import threading import time import ujson from tornado_sqlalchemy_login.utils import safe_get, safe_post_cookies, construct_path from traitlets import HasTraits from .samples_mixin import SamplesMixin from ..types.competition import CompetitionSpec from ..types.submission import Submission...
0.4917
0.114097
import pytest from prettyqt import core import prettyqt.qt from prettyqt.utils import InvalidParamError location = pytest.importorskip("prettyqt.location") QtLocation = pytest.importorskip("prettyqt.qt.QtLocation") def test_geocodingmanager(qtlog): with qtlog.disabled(): provider = location.GeoService...
tests/test_location.py
import pytest from prettyqt import core import prettyqt.qt from prettyqt.utils import InvalidParamError location = pytest.importorskip("prettyqt.location") QtLocation = pytest.importorskip("prettyqt.qt.QtLocation") def test_geocodingmanager(qtlog): with qtlog.disabled(): provider = location.GeoService...
0.54819
0.409634
import logging from django.db.models import Q from nltk.sentiment import SentimentIntensityAnalyzer from delab.models import Tweet, LANGUAGE from delab.sentiment.sentiment_analysis_ger import classify_german_sentiments def update_tweet_sentiments(simple_request_id=-1, language=LANGUAGE.ENGLISH): if simple_reque...
delab/sentiment/sentiment_classification.py
import logging from django.db.models import Q from nltk.sentiment import SentimentIntensityAnalyzer from delab.models import Tweet, LANGUAGE from delab.sentiment.sentiment_analysis_ger import classify_german_sentiments def update_tweet_sentiments(simple_request_id=-1, language=LANGUAGE.ENGLISH): if simple_reque...
0.286369
0.292908