code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import sys from pyspark.sql.functions import * from pyspark.sql import Row from pyspark.sql import SparkSession from AQPython.Annotation import * spark = SparkSession.builder.getOrCreate() def FilterProperty(df, name, value="", valueArr=[], valueCompare="=", limit=0, negate=False): """Provide the ability to filter ...
AQPython/Query.py
import sys from pyspark.sql.functions import * from pyspark.sql import Row from pyspark.sql import SparkSession from AQPython.Annotation import * spark = SparkSession.builder.getOrCreate() def FilterProperty(df, name, value="", valueArr=[], valueCompare="=", limit=0, negate=False): """Provide the ability to filter ...
0.749546
0.642517
from pathlib import Path from bokeh.palettes import diverging_palette import geopandas as gpd import numpy as np import pandas as pd import pandas_bokeh data_dir = Path("../data") html_dir = Path("../html") pandas_bokeh.output_notebook() # %% esbmap_stations = ( gpd.read_file( data_dir / "heatmap_statio...
notebooks/plot_clustered_esbmap_stations.py
from pathlib import Path from bokeh.palettes import diverging_palette import geopandas as gpd import numpy as np import pandas as pd import pandas_bokeh data_dir = Path("../data") html_dir = Path("../html") pandas_bokeh.output_notebook() # %% esbmap_stations = ( gpd.read_file( data_dir / "heatmap_statio...
0.669313
0.302423
import pygame class Window: """ The Window class is a wrapper around a pygame window. It provides very basic rendering functionallity. Attributes: ----------------- background_colour : list(int, int, int) The background colour provided to the constructor. ...
provided_code/window.py
import pygame class Window: """ The Window class is a wrapper around a pygame window. It provides very basic rendering functionallity. Attributes: ----------------- background_colour : list(int, int, int) The background colour provided to the constructor. ...
0.883053
0.462412
class RecognitionConfig(object): class AudioEncoding(object): """ Audio encoding of the data sent in the audio message. All encodings support only 1 channel (mono) audio. Only ``FLAC`` includes a header that describes the bytes of audio that follow the header. The other encodings are...
generated/python/gapic-google-cloud-speech-v1beta1/google/cloud/gapic/speech/v1beta1/enums.py
class RecognitionConfig(object): class AudioEncoding(object): """ Audio encoding of the data sent in the audio message. All encodings support only 1 channel (mono) audio. Only ``FLAC`` includes a header that describes the bytes of audio that follow the header. The other encodings are...
0.901324
0.655198
import copy import glob import jinja2 import jinja2.ext import os import shutil import subprocess import sys import yaml # For list.append in Jinja templates Jinja2 = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="."),extensions=['jinja2.ext.do']) def file_get_contents(filename, encoding=None): wi...
openssh/oqs-template/generate.py
import copy import glob import jinja2 import jinja2.ext import os import shutil import subprocess import sys import yaml # For list.append in Jinja templates Jinja2 = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="."),extensions=['jinja2.ext.do']) def file_get_contents(filename, encoding=None): wi...
0.203708
0.057467
import traceback from flask import Flask, Response, request, jsonify from flask.ext.cors import CORS, cross_origin from TermSuggestionsAggregator import TermSuggestionsAggregator, Aggregation from elsearch import ELSearch from wnsearch import WNSearch from word2vec import Word2VecSuggester from precomputed import Preco...
webserver/webTermSuggester.py
import traceback from flask import Flask, Response, request, jsonify from flask.ext.cors import CORS, cross_origin from TermSuggestionsAggregator import TermSuggestionsAggregator, Aggregation from elsearch import ELSearch from wnsearch import WNSearch from word2vec import Word2VecSuggester from precomputed import Preco...
0.32338
0.106877
import os import json from pysls.src.events.generate_event import generete_event event_sam_file_base = 'event_sam' event_pysls_file_base = 'event_pysls' def compare(event_sam_file, event_pysls_file): with open(event_sam_file, 'r') as event_sam: event_sam_content = json.load(event_sam) with open(event_...
pysls/tests/generate_event_test.py
import os import json from pysls.src.events.generate_event import generete_event event_sam_file_base = 'event_sam' event_pysls_file_base = 'event_pysls' def compare(event_sam_file, event_pysls_file): with open(event_sam_file, 'r') as event_sam: event_sam_content = json.load(event_sam) with open(event_...
0.222362
0.138724
import subprocess from pathlib import Path # configs samples = [ "mada_1-19", "mada_1-8", "mada_1-6", "mada_103", "mada_1-1", "mada_130", "mada_132", "mada_128", "mada_2-1", "mada_1-51", "mada_1-20", "mada_2-31", "mada_109", "mada_112", "mada_1-5", "mada_...
pipelines/snakemake/scripts/compare_kept_reads.py
import subprocess from pathlib import Path # configs samples = [ "mada_1-19", "mada_1-8", "mada_1-6", "mada_103", "mada_1-1", "mada_130", "mada_132", "mada_128", "mada_2-1", "mada_1-51", "mada_1-20", "mada_2-31", "mada_109", "mada_112", "mada_1-5", "mada_...
0.264263
0.305011
import dash import dash_html_components as html import dash_bootstrap_components as dbc import base64 # Author parameters bg_color="#506784", font_color="#F3F6FA" author = "<NAME>" emailAuthor = "<EMAIL>" supervisor = "Prof. <NAME>" emailSupervisor = "<EMAIL>" logo1path = "./pictures/1200px-Louvain_School_of_Managemen...
appHeader.py
import dash import dash_html_components as html import dash_bootstrap_components as dbc import base64 # Author parameters bg_color="#506784", font_color="#F3F6FA" author = "<NAME>" emailAuthor = "<EMAIL>" supervisor = "Prof. <NAME>" emailSupervisor = "<EMAIL>" logo1path = "./pictures/1200px-Louvain_School_of_Managemen...
0.376623
0.156846
import json import os import shutil import sys from argparse import ArgumentParser from pathlib import Path from catalyst.utils import load_ordered_yaml from jinja2 import Environment, FileSystemLoader sys.path.insert(0, str(Path(__file__).absolute().parent.parent / "src")) from data.data_info import TargetMapInfo fr...
data_preparation/make_config.py
import json import os import shutil import sys from argparse import ArgumentParser from pathlib import Path from catalyst.utils import load_ordered_yaml from jinja2 import Environment, FileSystemLoader sys.path.insert(0, str(Path(__file__).absolute().parent.parent / "src")) from data.data_info import TargetMapInfo fr...
0.391755
0.119974
import unittest from numpy import array, linspace, ones from numpy.testing import assert_array_equal from chaco.api import DataRange1D from chaco.function_data_source import FunctionDataSource from traits.testing.unittest_tools import UnittestTools class FunctionDataSourceTestCase(UnittestTools, unittest....
chaco/tests/function_data_source_test_case.py
import unittest from numpy import array, linspace, ones from numpy.testing import assert_array_equal from chaco.api import DataRange1D from chaco.function_data_source import FunctionDataSource from traits.testing.unittest_tools import UnittestTools class FunctionDataSourceTestCase(UnittestTools, unittest....
0.587943
0.695648
from rdkit import Chem from rdkit.Chem import AllChem from rdkit import RDLogger RDLogger.DisableLog('rdApp.*') import logging import numpy as np import os.path as osp import pandas as pd from torch_geometric.data import Data from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, m...
src/baseline/train_ap.py
from rdkit import Chem from rdkit.Chem import AllChem from rdkit import RDLogger RDLogger.DisableLog('rdApp.*') import logging import numpy as np import os.path as osp import pandas as pd from torch_geometric.data import Data from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, m...
0.879574
0.528229
import os import os.path import pickle import traceback from collections import deque, Counter import numpy as np import pandas as pd from state import Molecule, Atom, Bond, length, distance from util import mp_map_parititons def main(): mp_map_parititons(process_partition) def process_partition(index): t...
compute_features.py
import os import os.path import pickle import traceback from collections import deque, Counter import numpy as np import pandas as pd from state import Molecule, Atom, Bond, length, distance from util import mp_map_parititons def main(): mp_map_parititons(process_partition) def process_partition(index): t...
0.390592
0.242873
from __future__ import unicode_literals import flask from flask import Blueprint, request import flask_restplus as restplus # Add a dummy Resource to verify that the app is properly set. class HelloWorld(restplus.Resource): def get(self): return {} class GoodbyeWorld(restplus.Resource): def __ini...
tests/legacy/test_api_with_blueprint.py
from __future__ import unicode_literals import flask from flask import Blueprint, request import flask_restplus as restplus # Add a dummy Resource to verify that the app is properly set. class HelloWorld(restplus.Resource): def get(self): return {} class GoodbyeWorld(restplus.Resource): def __ini...
0.568775
0.126353
from esper.prelude import * from .queries import query @query("Conversations") def conversations_for_display(): from query.models import FaceCharacterActor, Shot from rekall.video_interval_collection import VideoIntervalCollection from rekall.parsers import in_array, bbox_payload_parser, merge_dict_parsers...
app/esper/queries/conversations.py
from esper.prelude import * from .queries import query @query("Conversations") def conversations_for_display(): from query.models import FaceCharacterActor, Shot from rekall.video_interval_collection import VideoIntervalCollection from rekall.parsers import in_array, bbox_payload_parser, merge_dict_parsers...
0.228845
0.185394
from datetime import datetime from typing import Callable, List, Optional, Union import pandas as pd import pyarrow import pytz from pydantic.typing import Literal from feast import FileSource, OnDemandFeatureView from feast.data_source import DataSource from feast.errors import FeastJoinKeysDuringMaterialization fro...
sdk/python/feast/infra/offline_stores/file.py
from datetime import datetime from typing import Callable, List, Optional, Union import pandas as pd import pyarrow import pytz from pydantic.typing import Literal from feast import FileSource, OnDemandFeatureView from feast.data_source import DataSource from feast.errors import FeastJoinKeysDuringMaterialization fro...
0.887935
0.32748
from aioclustermanager.k8s.caller import K8SCaller from base64 import b64decode import aiohttp import asyncio import logging import os import ssl import tempfile logger = logging.getLogger('aioclustermanager') SERVICE_HOST_ENV_NAME = "KUBERNETES_SERVICE_HOST" SERVICE_PORT_ENV_NAME = "KUBERNETES_SERVICE_PORT" SERVICE...
aioclustermanager/k8s/__init__.py
from aioclustermanager.k8s.caller import K8SCaller from base64 import b64decode import aiohttp import asyncio import logging import os import ssl import tempfile logger = logging.getLogger('aioclustermanager') SERVICE_HOST_ENV_NAME = "KUBERNETES_SERVICE_HOST" SERVICE_PORT_ENV_NAME = "KUBERNETES_SERVICE_PORT" SERVICE...
0.385722
0.059456
# Function to find the lowest common ancestor in a BST. from collections import deque def LCA(root, n1, n2): # code here. if min(n1, n2) <= root.data <= max(n1, n2): return root else: l = r = 0 if root.left != None: l = LCA(root.left, n1, n2) if root.right != ...
Competitive Programming/Binary Search Trees/Lowest Common Ancestor in a BST.py
# Function to find the lowest common ancestor in a BST. from collections import deque def LCA(root, n1, n2): # code here. if min(n1, n2) <= root.data <= max(n1, n2): return root else: l = r = 0 if root.left != None: l = LCA(root.left, n1, n2) if root.right != ...
0.750918
0.643525
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from .registry import register_model from .helpers import load_pretrained from .adaptive_avgmax_pool import SelectAdaptivePool2d from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD __all__ = ['Xceptio...
deeptensor/model/timm/gluon_xception.py
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict from .registry import register_model from .helpers import load_pretrained from .adaptive_avgmax_pool import SelectAdaptivePool2d from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD __all__ = ['Xceptio...
0.736495
0.385057
import argparse import os import random from glob import glob from pathlib import Path import click import numpy as np import tifffile from PIL import Image from tqdm import tqdm def img_loader(fp): if Path(fp).suffix.lower() in [".jpg", ".jpeg", ".png"]: arr = np.array(Image.open(fp)) else: ...
torchsat_imc/cli/calcuate_mean_std.py
import argparse import os import random from glob import glob from pathlib import Path import click import numpy as np import tifffile from PIL import Image from tqdm import tqdm def img_loader(fp): if Path(fp).suffix.lower() in [".jpg", ".jpeg", ".png"]: arr = np.array(Image.open(fp)) else: ...
0.478773
0.222964
import numpy as np from .. import ccllib as lib from ..core import check from ..pk2d import Pk2D from ..power import linear_matter_power, nonlin_matter_power from ..background import growth_factor from .tracers import PTTracer try: import fastpt as fpt HAVE_FASTPT = True except ImportError: HAVE_FASTPT = F...
pyccl/nl_pt/power.py
import numpy as np from .. import ccllib as lib from ..core import check from ..pk2d import Pk2D from ..power import linear_matter_power, nonlin_matter_power from ..background import growth_factor from .tracers import PTTracer try: import fastpt as fpt HAVE_FASTPT = True except ImportError: HAVE_FASTPT = F...
0.836888
0.509154
import os from collections import namedtuple from subprocess import check_output import numpy as np import psycopg2 def establish_connection(): """Connect to an existing database """ conn = psycopg2.connect("dbname=vagrant user=vagrant") return conn def parse_season_day_period(time_id): """Return...
models/energy_supply/utilities.py
import os from collections import namedtuple from subprocess import check_output import numpy as np import psycopg2 def establish_connection(): """Connect to an existing database """ conn = psycopg2.connect("dbname=vagrant user=vagrant") return conn def parse_season_day_period(time_id): """Return...
0.612078
0.52476
from __future__ import print_function import argparse import pandas as pd TAXLEVELS = {'k': 'kingdom', 'p': 'phylum', 'c': 'class', 'o': 'order', 'f': 'family', 'g': 'genus', 's': 'species', 't': 'subtype'} def main(): '...
scripts/metaphlan2_taxprofile2csv.py
from __future__ import print_function import argparse import pandas as pd TAXLEVELS = {'k': 'kingdom', 'p': 'phylum', 'c': 'class', 'o': 'order', 'f': 'family', 'g': 'genus', 's': 'species', 't': 'subtype'} def main(): '...
0.660391
0.206214
import jpype import common class MyImpl(object): def blah(self): pass class ClassProxy: def __init__(self, proxy): self.proxy = proxy class ArrayProxy: def __init__(self, proxy): self.proxy = proxy class StringProxy: def __init__(self, proxy): self.proxy = proxy ...
test/jpypetest/test_classhints.py
import jpype import common class MyImpl(object): def blah(self): pass class ClassProxy: def __init__(self, proxy): self.proxy = proxy class ArrayProxy: def __init__(self, proxy): self.proxy = proxy class StringProxy: def __init__(self, proxy): self.proxy = proxy ...
0.63624
0.340102
from lib import route, response, request, static_file, getSys, getMem, getHtop, abort, return_Json, getPath, login_required, getUser, Login, Logout, addAdmin, delAdmin, getAdminList import os # 首页403 @route('/', method=['GET','POST','PUT','DELETE','OPTIONS']) def index(): return abort(403) # 防止爬虫 @route('/robots.tx...
router.py
from lib import route, response, request, static_file, getSys, getMem, getHtop, abort, return_Json, getPath, login_required, getUser, Login, Logout, addAdmin, delAdmin, getAdminList import os # 首页403 @route('/', method=['GET','POST','PUT','DELETE','OPTIONS']) def index(): return abort(403) # 防止爬虫 @route('/robots.tx...
0.189334
0.036494
import unittest from touchdown.core import errors from touchdown.core.workspace import Workspace from touchdown.tests.aws import StubberTestCase from touchdown.tests.fixtures.aws import VpcFixture from touchdown.tests.stubs.aws import NetworkAclStubber class TestNetworkAclCreation(StubberTestCase): def test_cre...
touchdown/tests/test_aws_vpc_network_acl.py
import unittest from touchdown.core import errors from touchdown.core.workspace import Workspace from touchdown.tests.aws import StubberTestCase from touchdown.tests.fixtures.aws import VpcFixture from touchdown.tests.stubs.aws import NetworkAclStubber class TestNetworkAclCreation(StubberTestCase): def test_cre...
0.530236
0.331012
from oneflow.compatible.single_client.experimental.load_mnist import load_mnist from oneflow.compatible.single_client.ops.data_ops import ( BlobConf, ImageCodec, ImagePreprocessor, ImageResizePreprocessor, NormByChannelPreprocessor, RawCodec, decode_ofrecord, decode_random, ) from oneflo...
python/oneflow/compatible/single_client/data.py
from oneflow.compatible.single_client.experimental.load_mnist import load_mnist from oneflow.compatible.single_client.ops.data_ops import ( BlobConf, ImageCodec, ImagePreprocessor, ImageResizePreprocessor, NormByChannelPreprocessor, RawCodec, decode_ofrecord, decode_random, ) from oneflo...
0.387343
0.169028
from django.utils import timezone from rest_framework import serializers from core.models import User from cases.models import ( Case, CaseType, CaseWorkflow, ) from cases.models import ( Product, ExportSource, Sector, ) from organisations.models import Organisation from security.constants ...
trade_remedies_api/api_test/serializers.py
from django.utils import timezone from rest_framework import serializers from core.models import User from cases.models import ( Case, CaseType, CaseWorkflow, ) from cases.models import ( Product, ExportSource, Sector, ) from organisations.models import Organisation from security.constants ...
0.553988
0.262266
from lazy_property import LazyProperty from datetime import datetime import re as regex import json import requests from urllib.parse import urlparse, parse_qs from bs4 import BeautifulSoup, Tag from markdownify import markdownify class Notice: ''' Notice of KNU CSE official notice post example: https://compu...
src/comp_crawling/notice.py
from lazy_property import LazyProperty from datetime import datetime import re as regex import json import requests from urllib.parse import urlparse, parse_qs from bs4 import BeautifulSoup, Tag from markdownify import markdownify class Notice: ''' Notice of KNU CSE official notice post example: https://compu...
0.500977
0.123709
from itertools import product from typing import List, Optional, Dict, Tuple from matplotlib.axes import Axes from mpl_format.axes.axes_formatter import AxesFormatter from mpl_format.text.text_utils import map_text, wrap_text from pandas import Series, isnull, DataFrame, pivot_table, notnull from probability.distribut...
survey/questions/ranked_choice_question.py
from itertools import product from typing import List, Optional, Dict, Tuple from matplotlib.axes import Axes from mpl_format.axes.axes_formatter import AxesFormatter from mpl_format.text.text_utils import map_text, wrap_text from pandas import Series, isnull, DataFrame, pivot_table, notnull from probability.distribut...
0.907929
0.429071
import numpy as np from dissimilarity import compute_dissimilarity, dissimilarity from dipy.tracking.distances import bundles_distances_mam from sklearn.neighbors import KDTree from nibabel import trackvis from dipy.tracking.utils import length from dipy.viz import fvtk import os import vtk.util.colors as colors try: ...
segmentation_as_NN_and_lap.py
import numpy as np from dissimilarity import compute_dissimilarity, dissimilarity from dipy.tracking.distances import bundles_distances_mam from sklearn.neighbors import KDTree from nibabel import trackvis from dipy.tracking.utils import length from dipy.viz import fvtk import os import vtk.util.colors as colors try: ...
0.52074
0.361897
import unittest import jax.numpy as np from jax import random from jax.experimental import stax import flows def is_bijective( test, init_fun, inputs=random.uniform(random.PRNGKey(0), (20, 4), minval=-10.0, maxval=10.0), tol=1e-3 ): input_dim = inputs.shape[1] params, direct_fun, inverse_fun = init_fun(...
tests/test_bijections.py
import unittest import jax.numpy as np from jax import random from jax.experimental import stax import flows def is_bijective( test, init_fun, inputs=random.uniform(random.PRNGKey(0), (20, 4), minval=-10.0, maxval=10.0), tol=1e-3 ): input_dim = inputs.shape[1] params, direct_fun, inverse_fun = init_fun(...
0.674694
0.721375
import requests import json import os import time import sys from util import * def get_accesstoken(tenantid, client_id, client_secret): '''GET access token for Authorization''' endpoint = "https://login.microsoftonline.com/{}/oauth2/token".format(tenantid) resource ="https://management.azure.com/" gr...
Content/Backup/Azure Backup Service/WorkloadManager/src/azurebackupservice/azure_backup.py
import requests import json import os import time import sys from util import * def get_accesstoken(tenantid, client_id, client_secret): '''GET access token for Authorization''' endpoint = "https://login.microsoftonline.com/{}/oauth2/token".format(tenantid) resource ="https://management.azure.com/" gr...
0.147095
0.054626
from __future__ import division, absolute_import, print_function import json import os.path import unittest from test._common import RSRC from beetsplug.acousticbrainz import AcousticPlugin, ABSCHEME class MapDataToSchemeTest(unittest.TestCase): def test_basic(self): ab = AcousticPlugin() data ...
test/test_acousticbrainz.py
from __future__ import division, absolute_import, print_function import json import os.path import unittest from test._common import RSRC from beetsplug.acousticbrainz import AcousticPlugin, ABSCHEME class MapDataToSchemeTest(unittest.TestCase): def test_basic(self): ab = AcousticPlugin() data ...
0.662687
0.291687
import requests import datetime from requests import ConnectionError from ..exceptions import ( APIError, InvalidResponse, ) from ..utils import check_status_code from ..compat import json # monkeypatching requests # https://github.com/kennethreitz/requests/issues/1595 requests.models.json = json class Base...
betfairlightweight/endpoints/baseendpoint.py
import requests import datetime from requests import ConnectionError from ..exceptions import ( APIError, InvalidResponse, ) from ..utils import check_status_code from ..compat import json # monkeypatching requests # https://github.com/kennethreitz/requests/issues/1595 requests.models.json = json class Base...
0.488771
0.088347
import argparse import datetime import json import os import platform import subprocess import sys import types import semver def log(message, command=False): prefix = "$" if command else "#" print(f"{prefix} {message}", file=sys.stderr) def run_command(description, args, capture_output=True, shell=True): ...
tools/release_tool.py
import argparse import datetime import json import os import platform import subprocess import sys import types import semver def log(message, command=False): prefix = "$" if command else "#" print(f"{prefix} {message}", file=sys.stderr) def run_command(description, args, capture_output=True, shell=True): ...
0.352202
0.144783
def romanToDecimal(roman_number): roman_list = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} result = 0 for index,current_number in enumerate(roman_number): if (index+1) == len(roman_number) or roman_list[current_number] >= roman_list[roman_number[index+1]]: result+=roman_li...
ancestral_names/sortRoman.py
def romanToDecimal(roman_number): roman_list = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} result = 0 for index,current_number in enumerate(roman_number): if (index+1) == len(roman_number) or roman_list[current_number] >= roman_list[roman_number[index+1]]: result+=roman_li...
0.138899
0.213213
__author__ = 'rayleigh' from wiking.models import Article, ArticleVersion import os class ArticleService: ROOT_PATH = '/wiki' PATH_NOT_FIND = 1 NO_ERRORS = 0 def __init__(self): pass @staticmethod def get_absolute_url(article, articles=[]): return os.path.join(ArticleService....
wiking/services/articles.py
__author__ = 'rayleigh' from wiking.models import Article, ArticleVersion import os class ArticleService: ROOT_PATH = '/wiki' PATH_NOT_FIND = 1 NO_ERRORS = 0 def __init__(self): pass @staticmethod def get_absolute_url(article, articles=[]): return os.path.join(ArticleService....
0.389314
0.101634
import copy from typing import Dict, List from polyaxon import types from polyaxon.exceptions import PolyaxonfileError, PolyaxonSchemaError from polyaxon.polyaxonfile.specs import BaseSpecification, kinds from polyaxon.polyaxonfile.specs.libs.parser import Parser from polyaxon.polyflow import ( ParamSpec, V1C...
core/polyaxon/polyaxonfile/specs/compiled_operation.py
import copy from typing import Dict, List from polyaxon import types from polyaxon.exceptions import PolyaxonfileError, PolyaxonSchemaError from polyaxon.polyaxonfile.specs import BaseSpecification, kinds from polyaxon.polyaxonfile.specs.libs.parser import Parser from polyaxon.polyflow import ( ParamSpec, V1C...
0.78436
0.20199
import math import numpy import statsmodels.api as sm lowess= sm.nonparametric.lowess import esutil from galpy.util import bovy_coords, bovy_plot from scipy.interpolate import interp1d,UnivariateSpline import apogee.tools.read as apread import isodist import numpy as np import matplotlib.pyplot as plt import os import ...
py/define_rgbsample.py
import math import numpy import statsmodels.api as sm lowess= sm.nonparametric.lowess import esutil from galpy.util import bovy_coords, bovy_plot from scipy.interpolate import interp1d,UnivariateSpline import apogee.tools.read as apread import isodist import numpy as np import matplotlib.pyplot as plt import os import ...
0.280814
0.216094
from errno import ESRCH import yaml import re import subprocess import os from datetime import datetime from time import time, sleep from subprocess import Popen from subprocess import PIPE from subprocess import CalledProcessError from subprocess import TimeoutExpired from argparse import ArgumentParser from qcloud...
tests/perfs/perfs.py
from errno import ESRCH import yaml import re import subprocess import os from datetime import datetime from time import time, sleep from subprocess import Popen from subprocess import PIPE from subprocess import CalledProcessError from subprocess import TimeoutExpired from argparse import ArgumentParser from qcloud...
0.238728
0.061059
import os import click from ggdtrack.duke_dataset import Duke, DukeMini from ggdtrack.visdrone_dataset import VisDrone from ggdtrack.mot16_dataset import Mot16 from ggdtrack.eval import prep_eval_graphs, prep_eval_tracks, eval_prepped_tracks, eval_prepped_tracks_joined from ggdtrack.graph_diff import prep_minimal_gra...
ablation.py
import os import click from ggdtrack.duke_dataset import Duke, DukeMini from ggdtrack.visdrone_dataset import VisDrone from ggdtrack.mot16_dataset import Mot16 from ggdtrack.eval import prep_eval_graphs, prep_eval_tracks, eval_prepped_tracks, eval_prepped_tracks_joined from ggdtrack.graph_diff import prep_minimal_gra...
0.317744
0.136839
import logging from typing import Union from easydict import EasyDict as edict from xviz.message import XVIZMessage from xviz.v2.session_pb2 import Metadata, StreamMetadata from xviz.v2.style_pb2 import StyleStreamValue ANNOTATION_TYPES = StreamMetadata.AnnotationType CATEGORY = StreamMetadata.Category COORDINATE_TYP...
python/xviz/builder/base_builder.py
import logging from typing import Union from easydict import EasyDict as edict from xviz.message import XVIZMessage from xviz.v2.session_pb2 import Metadata, StreamMetadata from xviz.v2.style_pb2 import StyleStreamValue ANNOTATION_TYPES = StreamMetadata.AnnotationType CATEGORY = StreamMetadata.Category COORDINATE_TYP...
0.613352
0.258642
Langs = {'en': u'Английский', 'ja': u'Японский', 'ru': u'Русский', 'auto': u'Авто', 'sq': u'Албанский', # 'ar': u'Арабский', 'af': u'Африкаанс', 'be': u'Белорусский', 'bg': u'Болгарский', 'cy': u'Валлийский', 'hu': u'Венгерский', 'vi': u'Вьетнамский', 'gl': u'Галисийский', 'nl': u...
extensions/trans.py
Langs = {'en': u'Английский', 'ja': u'Японский', 'ru': u'Русский', 'auto': u'Авто', 'sq': u'Албанский', # 'ar': u'Арабский', 'af': u'Африкаанс', 'be': u'Белорусский', 'bg': u'Болгарский', 'cy': u'Валлийский', 'hu': u'Венгерский', 'vi': u'Вьетнамский', 'gl': u'Галисийский', 'nl': u...
0.121009
0.133726
from mitmproxy import contentviews from mitmproxy.test import tflow from mitmproxy.test import tutils from mitmproxy.test import taddons from mitmproxy.net.http import Headers from ..mitmproxy import tservers example_dir = tutils.test_data.push("../examples") class TestScripts(tservers.MasterTest): def test_add...
test/examples/test_examples.py
from mitmproxy import contentviews from mitmproxy.test import tflow from mitmproxy.test import tutils from mitmproxy.test import taddons from mitmproxy.net.http import Headers from ..mitmproxy import tservers example_dir = tutils.test_data.push("../examples") class TestScripts(tservers.MasterTest): def test_add...
0.451085
0.339937
import logging import tornado.web from sqlalchemy.orm import scoped_session import bbtornado.models from bbtornado.handlers import ThreadRequestContext log = logging.getLogger('bbtornado.web') from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class Application(tornado.web.Application)...
bbtornado/web.py
import logging import tornado.web from sqlalchemy.orm import scoped_session import bbtornado.models from bbtornado.handlers import ThreadRequestContext log = logging.getLogger('bbtornado.web') from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class Application(tornado.web.Application)...
0.539226
0.054299
from odoo import fields, models from odoo.tools import float_compare class PurchaseOrderLine(models.Model): _inherit = 'purchase.order.line' qty_received = fields.Float(compute='_compute_qty_received', string="Received Qty", store=True) def _compute_qty_received(self): super(PurchaseOrderLine, ...
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/purchase_mrp/models/purchase_mrp.py
from odoo import fields, models from odoo.tools import float_compare class PurchaseOrderLine(models.Model): _inherit = 'purchase.order.line' qty_received = fields.Float(compute='_compute_qty_received', string="Received Qty", store=True) def _compute_qty_received(self): super(PurchaseOrderLine, ...
0.364891
0.243744
import itertools as it def run_opcode(code_list): """Run the opcode as determined by the values in code_list Before you enter the next loop, check to see if the opcode (the first number in the sequence of 4) is 99. If it is, then you can stop and return the code as it stands. Parameters ----...
day02/day02_puz2.py
import itertools as it def run_opcode(code_list): """Run the opcode as determined by the values in code_list Before you enter the next loop, check to see if the opcode (the first number in the sequence of 4) is 99. If it is, then you can stop and return the code as it stands. Parameters ----...
0.665737
0.609001
import os import random import string from typing import Optional from idact.core.auth import KeyType from idact.detail.auth.get_public_key_location import get_public_key_location from idact.detail.log.get_logger import get_logger KEY_NAME_PREFIX = {KeyType.RSA: 'id_rsa_'} KEY_NAME_SUFFIX_LENGTH = 2 KEY_NAME_SUFFIX_...
idact/detail/auth/get_free_private_key_location.py
import os import random import string from typing import Optional from idact.core.auth import KeyType from idact.detail.auth.get_public_key_location import get_public_key_location from idact.detail.log.get_logger import get_logger KEY_NAME_PREFIX = {KeyType.RSA: 'id_rsa_'} KEY_NAME_SUFFIX_LENGTH = 2 KEY_NAME_SUFFIX_...
0.842734
0.109801
from __future__ import annotations import requests from pydantic import BaseModel # , validator class OlId(BaseModel): key: str class OlType(BaseModel): type: str value: str class Identifier(BaseModel): goodreads: list[str] librarything: list[str] class Work(BaseModel): authors: list[O...
src/Books/work.py
from __future__ import annotations import requests from pydantic import BaseModel # , validator class OlId(BaseModel): key: str class OlType(BaseModel): type: str value: str class Identifier(BaseModel): goodreads: list[str] librarything: list[str] class Work(BaseModel): authors: list[O...
0.53437
0.19789
import logging import sys class Error(Exception): """Base class for Telemetry exceptions.""" def __init__(self, msg=''): super(Error, self).__init__(msg) self._debugging_messages = [] def AddDebuggingMessage(self, msg): """Adds a message to the description of the exception. Many Telemetry exc...
third_party/catapult/telemetry/telemetry/core/exceptions.py
import logging import sys class Error(Exception): """Base class for Telemetry exceptions.""" def __init__(self, msg=''): super(Error, self).__init__(msg) self._debugging_messages = [] def AddDebuggingMessage(self, msg): """Adds a message to the description of the exception. Many Telemetry exc...
0.538741
0.112747
from charms.reactive import is_state, remove_state, set_state, when, when_any, when_none, when_not from charmhelpers.core import hookenv from charms.layer.apache_bigtop_base import Bigtop, get_hadoop_version @when('hadoop-plugin.joined') @when_not('namenode.joined') def blocked(principal): hookenv.status_set('bl...
bigtop-packages/src/charm/hadoop/layer-hadoop-plugin/reactive/apache_bigtop_plugin.py
from charms.reactive import is_state, remove_state, set_state, when, when_any, when_none, when_not from charmhelpers.core import hookenv from charms.layer.apache_bigtop_base import Bigtop, get_hadoop_version @when('hadoop-plugin.joined') @when_not('namenode.joined') def blocked(principal): hookenv.status_set('bl...
0.51562
0.113236
import gym import numpy as np import cv2 from gym import spaces class MLToGymEnv(gym.Env): def __init__(self, env, train_mode, reward_range=(-np.inf, np.inf)): """Wraps UnityEnvironment of ML-Agents to be used by baselines algorithms """ gym.Env.__init__(self) self.unityEnv = env ...
run/baselines_wrapper.py
import gym import numpy as np import cv2 from gym import spaces class MLToGymEnv(gym.Env): def __init__(self, env, train_mode, reward_range=(-np.inf, np.inf)): """Wraps UnityEnvironment of ML-Agents to be used by baselines algorithms """ gym.Env.__init__(self) self.unityEnv = env ...
0.380414
0.445952
from pathlib import Path import argparse import pickle import pandas as pd import numpy as np def softmax(x): """ >>> res = softmax(np.array([0, 200, 10])) >>> np.sum(res) 1.0 >>> np.all(np.abs(res - np.array([0, 1, 0])) < 0.0001) True >>> res = softmax(np.array([[0, 200, 10], [0, 10, 200...
fuse_results_epic.py
from pathlib import Path import argparse import pickle import pandas as pd import numpy as np def softmax(x): """ >>> res = softmax(np.array([0, 200, 10])) >>> np.sum(res) 1.0 >>> np.all(np.abs(res - np.array([0, 1, 0])) < 0.0001) True >>> res = softmax(np.array([[0, 200, 10], [0, 10, 200...
0.777553
0.360517
import os, sys from pathlib import Path import configparser from .Logger import LOGGER import uuid import base64 #just for test current_dir = os.getcwd() sys.path.append(current_dir) #just for test try: from Fcp.Node import Node except ModuleNotFoundError: raise ModuleNotFoundError('Fcp module is required') ...
Fsite/Base/Core.py
import os, sys from pathlib import Path import configparser from .Logger import LOGGER import uuid import base64 #just for test current_dir = os.getcwd() sys.path.append(current_dir) #just for test try: from Fcp.Node import Node except ModuleNotFoundError: raise ModuleNotFoundError('Fcp module is required') ...
0.197135
0.049154
from Tea.core import TeaCore from alibabacloud_tea_openapi.client import Client as OpenApiClient from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_tea_util.client import Client as UtilClient from alibabacloud_dingtalk.yida_1_0 import models as dingtalkyida__1__0_models from alibabacloud_...
dingtalk/python/alibabacloud_dingtalk/yida_1_0/client.py
from Tea.core import TeaCore from alibabacloud_tea_openapi.client import Client as OpenApiClient from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_tea_util.client import Client as UtilClient from alibabacloud_dingtalk.yida_1_0 import models as dingtalkyida__1__0_models from alibabacloud_...
0.503418
0.043773
from __future__ import annotations import inspect import os import re import shlex from enum import Enum from typing import Iterable, Pattern, Sequence from pants.option.errors import ParseError from pants.util.eval import parse_expression from pants.util.memo import memoized_method class UnsetBool: """A type ...
src/python/pants/option/custom_types.py
from __future__ import annotations import inspect import os import re import shlex from enum import Enum from typing import Iterable, Pattern, Sequence from pants.option.errors import ParseError from pants.util.eval import parse_expression from pants.util.memo import memoized_method class UnsetBool: """A type ...
0.843573
0.477554
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats from math import e def plotData( fileTypePlots, transformedData, verbose): """Plot query data using matplotlib""" # making functions more explicit transformedData = transformedDa...
valkyrie_pkg/plot_data.py
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats from math import e def plotData( fileTypePlots, transformedData, verbose): """Plot query data using matplotlib""" # making functions more explicit transformedData = transformedDa...
0.737442
0.61878
"""find_similar_issues tests.""" import mock import unittest import webapp2 import webtest from datastore import data_types from handlers.testcase_detail import find_similar_issues from issue_management.monorail import issue from tests.test_libs import helpers as test_helpers from tests.test_libs import test_utils @...
src/python/tests/appengine/handlers/testcase_detail/find_similar_issues_test.py
"""find_similar_issues tests.""" import mock import unittest import webapp2 import webtest from datastore import data_types from handlers.testcase_detail import find_similar_issues from issue_management.monorail import issue from tests.test_libs import helpers as test_helpers from tests.test_libs import test_utils @...
0.645902
0.307345
import hashlib import urllib import typing import re from mitmproxy import ctx from mitmproxy import flow from mitmproxy import exceptions from mitmproxy import io from mitmproxy import command import mitmproxy.types class ServerPlayback: def __init__(self): self.flowmap = {} self.stop = False ...
mitmproxy/addons/serverplayback.py
import hashlib import urllib import typing import re from mitmproxy import ctx from mitmproxy import flow from mitmproxy import exceptions from mitmproxy import io from mitmproxy import command import mitmproxy.types class ServerPlayback: def __init__(self): self.flowmap = {} self.stop = False ...
0.476092
0.160135
from __future__ import (division, absolute_import, print_function, unicode_literals) import os import threading import subprocess import tempfile import shlex from string import Template from beets import ui, util, plugins, config from beets.plugins import BeetsPlugin from beets.util.confit im...
beetsplug/convert.py
from __future__ import (division, absolute_import, print_function, unicode_literals) import os import threading import subprocess import tempfile import shlex from string import Template from beets import ui, util, plugins, config from beets.plugins import BeetsPlugin from beets.util.confit im...
0.654453
0.108189
import sys import unittest from conduit import Node import numpy as np class Test_Conduit_Node(unittest.TestCase): def test_simple(self): a_val = np.uint32(10) b_val = np.uint32(20) c_val = np.float64(30.0) n = Node() n['a'] = a_val n['b'] = b_val n['c'] =...
src/tests/conduit/python/t_python_conduit_node.py
import sys import unittest from conduit import Node import numpy as np class Test_Conduit_Node(unittest.TestCase): def test_simple(self): a_val = np.uint32(10) b_val = np.uint32(20) c_val = np.float64(30.0) n = Node() n['a'] = a_val n['b'] = b_val n['c'] =...
0.189484
0.517022
from __future__ import print_function import re from functools import partial from mapproxy.compat import iteritems, itervalues, iterkeys from mapproxy.request.wmts import ( wmts_request, make_wmts_rest_request_parser, URLTemplateConverter, FeatureInfoURLTemplateConverter, ) from mapproxy.layer import In...
mapproxy/service/wmts.py
from __future__ import print_function import re from functools import partial from mapproxy.compat import iteritems, itervalues, iterkeys from mapproxy.request.wmts import ( wmts_request, make_wmts_rest_request_parser, URLTemplateConverter, FeatureInfoURLTemplateConverter, ) from mapproxy.layer import In...
0.318379
0.161982
import torch def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False): """Calculate overlap between two set of bboxes. If ``is_aligned`` is ``False``, then calculate the ious between each bbox of bboxes1 and bboxes2, otherwise the ious between each aligned pair of bboxes1 and bboxes2. A...
mmdet/core/bbox/geometry.py
import torch def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False): """Calculate overlap between two set of bboxes. If ``is_aligned`` is ``False``, then calculate the ious between each bbox of bboxes1 and bboxes2, otherwise the ious between each aligned pair of bboxes1 and bboxes2. A...
0.887583
0.747432
import random import json import logging import copy from camera_trap_classifier.data.utils import ( randomly_split_dataset, map_label_list_to_numeric_dict, export_dict_to_json, _balanced_sampling) from camera_trap_classifier.data.importer import DatasetImporter logger = logging.getLogger(__name__) class ...
camera_trap_classifier/data/inventory.py
import random import json import logging import copy from camera_trap_classifier.data.utils import ( randomly_split_dataset, map_label_list_to_numeric_dict, export_dict_to_json, _balanced_sampling) from camera_trap_classifier.data.importer import DatasetImporter logger = logging.getLogger(__name__) class ...
0.663451
0.295807
from __future__ import absolute_import, unicode_literals from optimove.constants import AUTHORIZED_DELIMITERS, UNAUTHORIZED_DELIMITERS class Customers(object): client = None def __init__(self, client): self.client = client def get_customers_by_action(self, recipient_group_id, action_id, date, a...
optimove/customers.py
from __future__ import absolute_import, unicode_literals from optimove.constants import AUTHORIZED_DELIMITERS, UNAUTHORIZED_DELIMITERS class Customers(object): client = None def __init__(self, client): self.client = client def get_customers_by_action(self, recipient_group_id, action_id, date, a...
0.757974
0.154695
import re class Checker: def __init__(self): pass @staticmethod def isLevelUp(page_source): return 'Level Up' in page_source @staticmethod def isBotDetected(page_source): return 'captcha' in page_source class Url: def __init__(self): pass root = ...
util.py
import re class Checker: def __init__(self): pass @staticmethod def isLevelUp(page_source): return 'Level Up' in page_source @staticmethod def isBotDetected(page_source): return 'captcha' in page_source class Url: def __init__(self): pass root = ...
0.382487
0.105119
import argparse import logging from multiprocessing import Event, Process from pathlib import Path import time import derp.util import derp.brain import derp.camera import derp.imu import derp.joystick import derp.servo import derp.writer def all_running(processes): """ Returns whether all processes are currently...
bin/drive.py
import argparse import logging from multiprocessing import Event, Process from pathlib import Path import time import derp.util import derp.brain import derp.camera import derp.imu import derp.joystick import derp.servo import derp.writer def all_running(processes): """ Returns whether all processes are currently...
0.338186
0.096535
from typing import Dict, Optional, Union, cast import numpy as np import pandas as pd from scipy import sparse from autosklearn.constants import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, MULTILABEL_CLASSIFICATION, MULTIOUTPUT_REGRESSION, REGRESSION, ) from autosklearn.data.abstract_dat...
autosklearn/data/xy_data_manager.py
from typing import Dict, Optional, Union, cast import numpy as np import pandas as pd from scipy import sparse from autosklearn.constants import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, MULTILABEL_CLASSIFICATION, MULTIOUTPUT_REGRESSION, REGRESSION, ) from autosklearn.data.abstract_dat...
0.695958
0.239816
import os import shutil import argparse import tarfile from encoding.utils import download, mkdir _TARGET_DIR = os.path.expanduser('../dataset/') def parse_args(): parser = argparse.ArgumentParser( description='Initialize PASCAL VOC dataset.', epilog='Example: python prepare_pascal.py', f...
scripts/prepare_pascal.py
import os import shutil import argparse import tarfile from encoding.utils import download, mkdir _TARGET_DIR = os.path.expanduser('../dataset/') def parse_args(): parser = argparse.ArgumentParser( description='Initialize PASCAL VOC dataset.', epilog='Example: python prepare_pascal.py', f...
0.278551
0.108001
from selenium import webdriver from time import sleep class ChromeAuto: def __init__(self): self.driver_path = 'chromedriver' self.options = webdriver.ChromeOptions() self.options.add_argument('user-data-dir=Perfil') self.chrome = webdriver.Chrome( self.driver_path, ...
Curso_Python/Secao5-modulos-uteis/134_selenium_automatizando_tarefas_navegador/main.py
from selenium import webdriver from time import sleep class ChromeAuto: def __init__(self): self.driver_path = 'chromedriver' self.options = webdriver.ChromeOptions() self.options.add_argument('user-data-dir=Perfil') self.chrome = webdriver.Chrome( self.driver_path, ...
0.332202
0.054601
import logging from ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER from ryu.controller.handler import CONFIG_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_0 from ryu.ofproto import ofpro...
ryu/app/aa.py
import logging from ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER from ryu.controller.handler import CONFIG_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_0 from ryu.ofproto import ofpro...
0.182316
0.090053
import collections from io import StringIO import os import time import requests from ns_stitchclient.transit.writer import Writer DEFAULT_MAX_BATCH_SIZE_BYTES = 4194304 DEFAULT_BATCH_DELAY_SECONDS = 60.0 MAX_MESSAGES_PER_BATCH = 20000 DEFAULT_STITCH_URL = 'https://api.stitchdata.com/v2/import/push' class MessageToo...
ns_stitchclient/client.py
import collections from io import StringIO import os import time import requests from ns_stitchclient.transit.writer import Writer DEFAULT_MAX_BATCH_SIZE_BYTES = 4194304 DEFAULT_BATCH_DELAY_SECONDS = 60.0 MAX_MESSAGES_PER_BATCH = 20000 DEFAULT_STITCH_URL = 'https://api.stitchdata.com/v2/import/push' class MessageToo...
0.536556
0.242262
import json import time from typing import Any import nonebot from apscheduler.schedulers.asyncio import AsyncIOScheduler from nonebot.adapters import Bot from nonebot.log import logger from .config import Config _cooldown_events = {} driver = nonebot.get_driver() config = Config(**driver.config.dict()) BACKUP_FI...
nonebot_plugin_cooldown/cooldown.py
import json import time from typing import Any import nonebot from apscheduler.schedulers.asyncio import AsyncIOScheduler from nonebot.adapters import Bot from nonebot.log import logger from .config import Config _cooldown_events = {} driver = nonebot.get_driver() config = Config(**driver.config.dict()) BACKUP_FI...
0.530723
0.138928
from datetime import timedelta from django.utils.translation import ugettext_lazy as _ from mayan.apps.common.queues import queue_tools from mayan.apps.task_manager.classes import CeleryQueue from mayan.apps.task_manager.workers import worker_fast, worker_medium from celery.schedules import crontab from .literals i...
mayan/apps/documents/queues.py
from datetime import timedelta from django.utils.translation import ugettext_lazy as _ from mayan.apps.common.queues import queue_tools from mayan.apps.task_manager.classes import CeleryQueue from mayan.apps.task_manager.workers import worker_fast, worker_medium from celery.schedules import crontab from .literals i...
0.430626
0.089335
from django.contrib import admin from django.urls import path, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from mainPage.views import * from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path...
SACWebApp/SACWebApp/urls.py
from django.contrib import admin from django.urls import path, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from mainPage.views import * from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path...
0.251372
0.052328
""" Test for projectq.backends._awsbraket._awsbraket_boto3_client.py """ import pytest from unittest.mock import patch from ._awsbraket_boto3_client_test_fixtures import * # noqa: F401,F403 # ============================================================================== _has_boto3 = True try: import botocore ...
projectq/backends/_awsbraket/_awsbraket_boto3_client_test.py
""" Test for projectq.backends._awsbraket._awsbraket_boto3_client.py """ import pytest from unittest.mock import patch from ._awsbraket_boto3_client_test_fixtures import * # noqa: F401,F403 # ============================================================================== _has_boto3 = True try: import botocore ...
0.509276
0.335596
import re from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import View from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .models import Posts, Like...
core/views.py
import re from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import View from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .models import Posts, Like...
0.449876
0.082328
from logging import fatal import os from pathlib import Path import shutil import zipfile import re from mirdata import download_utils, core import pytest @pytest.fixture def mock_download_from_remote(mocker): return mocker.patch.object(download_utils, "download_from_remote") @pytest.fixture def mock_download...
tests/test_download_utils.py
from logging import fatal import os from pathlib import Path import shutil import zipfile import re from mirdata import download_utils, core import pytest @pytest.fixture def mock_download_from_remote(mocker): return mocker.patch.object(download_utils, "download_from_remote") @pytest.fixture def mock_download...
0.424173
0.316396
import argparse import logging import operator import os import re import six import subprocess import sys import yaml this_dir = os.path.realpath(os.path.dirname(__file__)) sys.path.append(os.path.realpath(os.path.join(os.pardir, os.pardir))) from geodata.address_formatting.formatter import AddressFormatter from geo...
scripts/geodata/neighborhoods/reverse_geocode.py
import argparse import logging import operator import os import re import six import subprocess import sys import yaml this_dir = os.path.realpath(os.path.dirname(__file__)) sys.path.append(os.path.realpath(os.path.join(os.pardir, os.pardir))) from geodata.address_formatting.formatter import AddressFormatter from geo...
0.396769
0.147617
import os from scielo_v3_manager.v3_gen import generates def add_pids_to_xml(xml_sps, document, xml_file_path, pid_v2, v3_manager): """ Garante que o PID v3 esteja no XML e que ele esteja registrado no SPF, seja no Article ou no v3_manager """ # add scielo_pid_v2, se aplicável _add_scielo_pid...
dsm/extdeps/doc_ids_manager.py
import os from scielo_v3_manager.v3_gen import generates def add_pids_to_xml(xml_sps, document, xml_file_path, pid_v2, v3_manager): """ Garante que o PID v3 esteja no XML e que ele esteja registrado no SPF, seja no Article ou no v3_manager """ # add scielo_pid_v2, se aplicável _add_scielo_pid...
0.518302
0.183887
import csv import json import os import click from os.path import isfile, isdir from pathlib import Path from policy_sentry.util.actions import get_service_from_action from policy_sentry.analysis.analyze import analyze_by_access_level from policy_sentry.shared.constants import DATABASE_FILE_PATH from policy_sentry.shar...
analyze_public_instances_results.py
import csv import json import os import click from os.path import isfile, isdir from pathlib import Path from policy_sentry.util.actions import get_service_from_action from policy_sentry.analysis.analyze import analyze_by_access_level from policy_sentry.shared.constants import DATABASE_FILE_PATH from policy_sentry.shar...
0.194597
0.067547
import json import requests from Logs.log_configuration import configure_logger from api_client.url_helpers.organization_group_url import get_organization_group_children_url, \ get_parent_organization_group_url, get_organization_group_details_url from models.api_header_model import RequestHeader log = configure_...
UEM-Samples/ProductProvisioning/product_app_deployment_automation/api_client/organization_group.py
import json import requests from Logs.log_configuration import configure_logger from api_client.url_helpers.organization_group_url import get_organization_group_children_url, \ get_parent_organization_group_url, get_organization_group_details_url from models.api_header_model import RequestHeader log = configure_...
0.363873
0.066478
import json from pprint import pformat from celery import states from celery.result import AsyncResult from flask import abort import config from gcpdac.application_ci import create_application, delete_application from gcpdac.celery_tasks import deploy_application_task, destroy_application_task logger = config.logge...
gcpdac/application.py
import json from pprint import pformat from celery import states from celery.result import AsyncResult from flask import abort import config from gcpdac.application_ci import create_application, delete_application from gcpdac.celery_tasks import deploy_application_task, destroy_application_task logger = config.logge...
0.113211
0.143668
from decimal import Decimal from django.conf import settings from products.models import Products class Favorite(object): def __init__(self, request): """ Initialize the favorite """ self.session = request.session favorite = self.session.get(settings.FAVORITE_SESSION_ID) ...
favorite/favorite.py
from decimal import Decimal from django.conf import settings from products.models import Products class Favorite(object): def __init__(self, request): """ Initialize the favorite """ self.session = request.session favorite = self.session.get(settings.FAVORITE_SESSION_ID) ...
0.557604
0.131312
from socket import socket, AF_INET, SOCK_STREAM from threading import Thread import time from person import Person # GLOBAL CONSTANTS (Sabitler) HOST = "localhost" PORT = 5500 ADDR = (HOST, PORT) MAX_CONNECTIONS = 10 BUFSIZE = 512 # aktarılan data'nın byte sayısı TIME = time.ctime(t...
server/server.py
from socket import socket, AF_INET, SOCK_STREAM from threading import Thread import time from person import Person # GLOBAL CONSTANTS (Sabitler) HOST = "localhost" PORT = 5500 ADDR = (HOST, PORT) MAX_CONNECTIONS = 10 BUFSIZE = 512 # aktarılan data'nın byte sayısı TIME = time.ctime(t...
0.203668
0.088347
from cfnlint import CloudFormationLintRule from cfnlint import RuleMatch class AvailabilityZone(CloudFormationLintRule): """Check Availibility Zone parameter checks """ id = 'W2508' shortdesc = 'Availability Zone Parameters are of correct type AWS::EC2::AvailabilityZone::Name' description = 'Check if ...
src/cfnlint/rules/parameters/AvailabilityZone.py
from cfnlint import CloudFormationLintRule from cfnlint import RuleMatch class AvailabilityZone(CloudFormationLintRule): """Check Availibility Zone parameter checks """ id = 'W2508' shortdesc = 'Availability Zone Parameters are of correct type AWS::EC2::AvailabilityZone::Name' description = 'Check if ...
0.734881
0.141193
import logging import torch import argparse import os from sklearn import metrics from timeit import default_timer as timer from utils import getModel, resumeFromPath from data.ImagenetDataset import get_zipped_dataloaders, REDUCED_SET_PATH, FULL_SET_PATH from data.utils import getLabelToClassMapping from typing import...
benchmarkMSD.py
import logging import torch import argparse import os from sklearn import metrics from timeit import default_timer as timer from utils import getModel, resumeFromPath from data.ImagenetDataset import get_zipped_dataloaders, REDUCED_SET_PATH, FULL_SET_PATH from data.utils import getLabelToClassMapping from typing import...
0.695545
0.19758
CREATE_TABLES = """ DROP TABLE IF EXISTS staging_yellow_trips; CREATE TABLE IF NOT EXISTS staging_yellow_trips ( VendorID INT, tpep_pickup_datetime TIMESTAMP, tpep_dropoff_datetime TIMESTAMP, passenger_count INT, trip_distance FLOAT, RatecodeID INT, store_and_fwd_flag TEXT, PULocationID INT, DOLocationID I...
scripts/sql_queries.py
CREATE_TABLES = """ DROP TABLE IF EXISTS staging_yellow_trips; CREATE TABLE IF NOT EXISTS staging_yellow_trips ( VendorID INT, tpep_pickup_datetime TIMESTAMP, tpep_dropoff_datetime TIMESTAMP, passenger_count INT, trip_distance FLOAT, RatecodeID INT, store_and_fwd_flag TEXT, PULocationID INT, DOLocationID I...
0.1139
0.0566
import time from prometheus_client import CONTENT_TYPE_LATEST, Summary, Counter, generate_latest from werkzeug.routing import Map, Rule from werkzeug.serving import run_simple from werkzeug.wrappers import Request, Response from werkzeug.exceptions import InternalServerError from app.collector import collect_sensors c...
airfilter-exporter/app/http.py
import time from prometheus_client import CONTENT_TYPE_LATEST, Summary, Counter, generate_latest from werkzeug.routing import Map, Rule from werkzeug.serving import run_simple from werkzeug.wrappers import Request, Response from werkzeug.exceptions import InternalServerError from app.collector import collect_sensors c...
0.621656
0.121555
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from django.contrib import admin from account.views import * from community.views import * from base.views import * from django.conf.urls.static import static from django.conf import settings from rest_framework import route...
work/urls.py
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from django.contrib import admin from account.views import * from community.views import * from base.views import * from django.conf.urls.static import static from django.conf import settings from rest_framework import route...
0.281603
0.065785
import torch import torch.nn as nn import torch.nn.functional as F from neurolab import params as P from neurolab import utils from neurolab.model import Model class Net(Model): # Layer names CONV1 = 'conv1' RELU1 = 'relu1' POOL1 = 'pool1' BN1 = 'bn1' CONV2 = 'conv2' RELU2 = 'relu2' BN2 = 'bn2' CONV3 = 'con...
models/gdes/vae_6l.py
import torch import torch.nn as nn import torch.nn.functional as F from neurolab import params as P from neurolab import utils from neurolab.model import Model class Net(Model): # Layer names CONV1 = 'conv1' RELU1 = 'relu1' POOL1 = 'pool1' BN1 = 'bn1' CONV2 = 'conv2' RELU2 = 'relu2' BN2 = 'bn2' CONV3 = 'con...
0.791297
0.372391
import requests from threading import * import sys import getopt '''requests用于请求目标站点; threading用于启用多线程; sys用于解析命令行参数; getopt用于处理命令行参数;''' # 程序标识 def banner(): print("\n********************") name = ''' .__ .__ ___. .__ __ .__ | |__ |__| \_ |__ |__| | | __ |__| | | \ | | ...
hibiki.py
import requests from threading import * import sys import getopt '''requests用于请求目标站点; threading用于启用多线程; sys用于解析命令行参数; getopt用于处理命令行参数;''' # 程序标识 def banner(): print("\n********************") name = ''' .__ .__ ___. .__ __ .__ | |__ |__| \_ |__ |__| | | __ |__| | | \ | | ...
0.09123
0.090534
from __future__ import annotations from asyncio import Future, get_event_loop, wait_for from re import search from typing import TYPE_CHECKING, Any, Callable, Dict, Literal, Optional, Union import aiohttp # Internal imports from .internals import CacheHandler, HTTPHandler, WebSocketHandler if TYPE_CHECKING: fro...
voltage/client.py
from __future__ import annotations from asyncio import Future, get_event_loop, wait_for from re import search from typing import TYPE_CHECKING, Any, Callable, Dict, Literal, Optional, Union import aiohttp # Internal imports from .internals import CacheHandler, HTTPHandler, WebSocketHandler if TYPE_CHECKING: fro...
0.948882
0.19521
import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import hawtorch import hawtorch.io as io from hawtorch import Trainer import models from torchvision import datasets, transforms args = io.load_json("mnist_config.json") logger = io.logger(args["workspace_path"]) d...
mnist/train.py
import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import hawtorch import hawtorch.io as io from hawtorch import Trainer import models from torchvision import datasets, transforms args = io.load_json("mnist_config.json") logger = io.logger(args["workspace_path"]) d...
0.758868
0.394026
import warnings import numpy as np import pandas as pd from .base import BaseExtensionTests class BaseDtypeTests(BaseExtensionTests): """Base class for ExtensionDtype classes""" def test_name(self, dtype): assert isinstance(dtype.name, str) def test_kind(self, dtype): valid = set('biuf...
pandas/tests/extension/base/dtype.py
import warnings import numpy as np import pandas as pd from .base import BaseExtensionTests class BaseDtypeTests(BaseExtensionTests): """Base class for ExtensionDtype classes""" def test_name(self, dtype): assert isinstance(dtype.name, str) def test_kind(self, dtype): valid = set('biuf...
0.532911
0.492249
import argparse class SDParser: """Class for handling CLI interaction.""" def __init__(self) -> None: """See class docstring.""" self.parser = argparse.ArgumentParser() self._add_optionals(self.parser) self.subparsers = self._add_subparser(self.parser) self.gen_pars...
schemadown/parser.py
import argparse class SDParser: """Class for handling CLI interaction.""" def __init__(self) -> None: """See class docstring.""" self.parser = argparse.ArgumentParser() self._add_optionals(self.parser) self.subparsers = self._add_subparser(self.parser) self.gen_pars...
0.7237
0.152568
import json import random import re import sys import threading import time from azure.iot.device import IoTHubDeviceClient, Message AUX_CONNECTION_STRING = sys.argv[1] AUX_BASE_HEART_RATE = 65 AUX_BASE_BODY_TEMPERATURE = 37.0 AUX_MAXIMUM_BODY_TEMPERATURE = 40.0 #SENSOR DATA WILL HOST SENSOR METRICS ...
iot-client/iot-hub-client-message.py
import json import random import re import sys import threading import time from azure.iot.device import IoTHubDeviceClient, Message AUX_CONNECTION_STRING = sys.argv[1] AUX_BASE_HEART_RATE = 65 AUX_BASE_BODY_TEMPERATURE = 37.0 AUX_MAXIMUM_BODY_TEMPERATURE = 40.0 #SENSOR DATA WILL HOST SENSOR METRICS ...
0.1495
0.03394
from __future__ import unicode_literals from django.db import transaction, IntegrityError from django.test import TestCase from .models import (Place, Restaurant, Waiter, ManualPrimaryKey, RelatedModel, MultiModel) class OneToOneTests(TestCase): def setUp(self): self.p1 = Place(name='<NAME>', addre...
tests/one_to_one/tests.py
from __future__ import unicode_literals from django.db import transaction, IntegrityError from django.test import TestCase from .models import (Place, Restaurant, Waiter, ManualPrimaryKey, RelatedModel, MultiModel) class OneToOneTests(TestCase): def setUp(self): self.p1 = Place(name='<NAME>', addre...
0.711932
0.434461
import math import numpy as np import torch from torch.nn import init np.random.seed(4) # to compare with pytorch, we use the same init function as pytoch uses def reset_paramters(weight_shape, bias_shape): weight = torch.rand(weight_shape) bias = torch.rand(bias_shape) init.kaiming_uniform_(weight, a=...
vanilia_convolution/neural_layer.py
import math import numpy as np import torch from torch.nn import init np.random.seed(4) # to compare with pytorch, we use the same init function as pytoch uses def reset_paramters(weight_shape, bias_shape): weight = torch.rand(weight_shape) bias = torch.rand(bias_shape) init.kaiming_uniform_(weight, a=...
0.863938
0.601184