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 os import pathlib import numpy as np import pandas as pd import torch from torch.utils.data import TensorDataset, DataLoader, BatchSampler from torch.utils.data import WeightedRandomSampler import scipy.sparse as ssp import sklearn.preprocessing as prep import sklearn.pipeline as ppln from sklearn.utils import c...
dataset.py
import os import pathlib import numpy as np import pandas as pd import torch from torch.utils.data import TensorDataset, DataLoader, BatchSampler from torch.utils.data import WeightedRandomSampler import scipy.sparse as ssp import sklearn.preprocessing as prep import sklearn.pipeline as ppln from sklearn.utils import c...
0.873336
0.560493
import numpy as np from gensim import corpora from keras.preprocessing import sequence from nltk.tokenize import TreebankWordTokenizer from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_is_fitted, column_or_1d __author__ = "<NAME>" __credits__ = "https://github.com/octo...
dsbox/ml/neural_networks/processing/text_classification.py
import numpy as np from gensim import corpora from keras.preprocessing import sequence from nltk.tokenize import TreebankWordTokenizer from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_is_fitted, column_or_1d __author__ = "<NAME>" __credits__ = "https://github.com/octo...
0.858303
0.404684
from .parser import TokenGroup, TokenElement, TokenAttribute, is_quote, is_bracket from .tokenizer import tokens from .stringify import stringify class ConvertState: __slots__ = ('inserted', 'text', 'repeat_guard', 'repeaters', 'variables', '_text_inserted') def __init__(self, text: str = No...
emmet/abbreviation/convert.py
from .parser import TokenGroup, TokenElement, TokenAttribute, is_quote, is_bracket from .tokenizer import tokens from .stringify import stringify class ConvertState: __slots__ = ('inserted', 'text', 'repeat_guard', 'repeaters', 'variables', '_text_inserted') def __init__(self, text: str = No...
0.674908
0.231386
from rdkit import Chem import numpy as np class SmilesVectorizer(object): """SMILES vectorizer and devectorizer, with support for SMILES enumeration (atom order randomization) as data augmentation :parameter charset: string containing the characters for the vectorization can also be generat...
ddc_pub/vectorizers.py
from rdkit import Chem import numpy as np class SmilesVectorizer(object): """SMILES vectorizer and devectorizer, with support for SMILES enumeration (atom order randomization) as data augmentation :parameter charset: string containing the characters for the vectorization can also be generat...
0.71602
0.571049
import re from os import path from setuptools import setup from codecs import open here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() def read(*parts): return open(path.join(...
setup.py
import re from os import path from setuptools import setup from codecs import open here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() def read(*parts): return open(path.join(...
0.47025
0.160562
from __future__ import unicode_literals from .imapclient_test import IMAPClientTest from .util import Mock class TestFolderStatus(IMAPClientTest): def test_basic(self): self.client._imap.status.return_value = ( "OK", [b"foo (MESSAGES 3 RECENT 0 UIDNEXT 4 UIDVALIDITY 1435636895 UN...
tests/test_folder_status.py
from __future__ import unicode_literals from .imapclient_test import IMAPClientTest from .util import Mock class TestFolderStatus(IMAPClientTest): def test_basic(self): self.client._imap.status.return_value = ( "OK", [b"foo (MESSAGES 3 RECENT 0 UIDNEXT 4 UIDVALIDITY 1435636895 UN...
0.670177
0.291428
from datetime import datetime from math import floor import requests from requests.exceptions import HTTPError import json import schedule # https://schedule.readthedocs.io/en/stable/ import time def stahniOdjezdy(limit=1000): # https://golemioapi.docs.apiary.io/#reference/public-transport/departure-boards/g...
PyPragueDepartures.py
from datetime import datetime from math import floor import requests from requests.exceptions import HTTPError import json import schedule # https://schedule.readthedocs.io/en/stable/ import time def stahniOdjezdy(limit=1000): # https://golemioapi.docs.apiary.io/#reference/public-transport/departure-boards/g...
0.200362
0.207938
from finviz.async_connector import Connector from lxml import html from lxml import etree import requests import urllib3 import os urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) TABLE = { 'Overview': '110', 'Valuation': '120', 'Ownership': '130', 'Performance': '140', 'Custom'...
finviz/screener.py
from finviz.async_connector import Connector from lxml import html from lxml import etree import requests import urllib3 import os urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) TABLE = { 'Overview': '110', 'Valuation': '120', 'Ownership': '130', 'Performance': '140', 'Custom'...
0.394784
0.089455
from django.utils.translation import ugettext_noop as _ from api import status from api.api_views import APIView from api.exceptions import ObjectNotFound, PreconditionRequired, ObjectAlreadyExists from api.task.response import SuccessTaskResponse from api.utils.db import get_object from api.dc.storage.serializers imp...
api/dc/storage/api_views.py
from django.utils.translation import ugettext_noop as _ from api import status from api.api_views import APIView from api.exceptions import ObjectNotFound, PreconditionRequired, ObjectAlreadyExists from api.task.response import SuccessTaskResponse from api.utils.db import get_object from api.dc.storage.serializers imp...
0.390243
0.096025
from astropy import units as u, constants as const import numpy as np from ..nuclear import nuclear_binding_energy, nuclear_reaction_energy, mass_energy from plasmapy.utils.pytest_helpers import run_test, run_test_equivalent_calls from plasmapy.atomic.exceptions import AtomicError, InvalidParticleError import pytest ...
plasmapy/atomic/tests/test_nuclear.py
from astropy import units as u, constants as const import numpy as np from ..nuclear import nuclear_binding_energy, nuclear_reaction_energy, mass_energy from plasmapy.utils.pytest_helpers import run_test, run_test_equivalent_calls from plasmapy.atomic.exceptions import AtomicError, InvalidParticleError import pytest ...
0.846483
0.585012
import os # Third party imports from fastapi import Depends, APIRouter, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from dotenv import load_dotenv # Local imports from .auth_db import get_user from .encryption import encrypt_text, decrypt_token, encrypt_token fro...
api/auth/authenticate.py
import os # Third party imports from fastapi import Depends, APIRouter, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from dotenv import load_dotenv # Local imports from .auth_db import get_user from .encryption import encrypt_text, decrypt_token, encrypt_token fro...
0.695441
0.096663
import math import matplotlib.pyplot as plt import numpy as np import gtsam import gtsam.utils.plot as gtsam_plot def report_on_progress(graph: gtsam.NonlinearFactorGraph, current_estimate: gtsam.Values, key: int): """Print and plot incremental progress of the robot for 2D Pose SLAM using...
python/gtsam/examples/Pose2ISAM2Example.py
import math import matplotlib.pyplot as plt import numpy as np import gtsam import gtsam.utils.plot as gtsam_plot def report_on_progress(graph: gtsam.NonlinearFactorGraph, current_estimate: gtsam.Values, key: int): """Print and plot incremental progress of the robot for 2D Pose SLAM using...
0.869977
0.750256
from modules.extractors.doc import DocExtractor from modules.metadata import Metadata import rtf2xml.ParseRtf class RtfExtractor(DocExtractor): """Class for handling RTF file data extraction. We will mostly be using the same logic as for MSDoc files, but we need another way to extract metadata, as ...
modules/extractors/rtf.py
from modules.extractors.doc import DocExtractor from modules.metadata import Metadata import rtf2xml.ParseRtf class RtfExtractor(DocExtractor): """Class for handling RTF file data extraction. We will mostly be using the same logic as for MSDoc files, but we need another way to extract metadata, as ...
0.555918
0.302404
__author__ = '<NAME>' import argparse from RouToolPa.Routines import MatplotlibRoutines parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", action="store", dest="input", required=True, type=lambda s : s.split(","), help="Comma separated list of two input f...
scripts/draw/draw_tetra_histogram_with_two_logscaled.py
__author__ = '<NAME>' import argparse from RouToolPa.Routines import MatplotlibRoutines parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", action="store", dest="input", required=True, type=lambda s : s.split(","), help="Comma separated list of two input f...
0.328206
0.171755
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from de...
pybind/slxos/v16r_1_00b/isis_state/router_isis_config/reverse_metric/__init__.py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from de...
0.680348
0.066448
from typing import Dict, List, Optional, Tuple, Union import re SYNTAX_ERROR = "SyntaxError" RUNTIME_ERROR = "RuntimeError" class Number: def __init__(self, value: int) -> None: self.value = value def run(self, variables: Dict[str, int]) -> int: return self.value class Operator: def...
rec.py
from typing import Dict, List, Optional, Tuple, Union import re SYNTAX_ERROR = "SyntaxError" RUNTIME_ERROR = "RuntimeError" class Number: def __init__(self, value: int) -> None: self.value = value def run(self, variables: Dict[str, int]) -> int: return self.value class Operator: def...
0.84916
0.419172
import numpy as np from atom.api import (Enum, Str, set_default) from exopy.tasks.api import SimpleTask, validators ARR_VAL = validators.Feval(types=np.ndarray) class ArrayExtremaTask(SimpleTask): """ Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before ex...
exopy_hqc_legacy/tasks/tasks/util/array_tasks.py
import numpy as np from atom.api import (Enum, Str, set_default) from exopy.tasks.api import SimpleTask, validators ARR_VAL = validators.Feval(types=np.ndarray) class ArrayExtremaTask(SimpleTask): """ Store the pair(s) of index/value for the extrema(s) of an array. Wait for any parallel operation before ex...
0.589598
0.442335
from dataclasses import dataclass, field from typing import List import pandas as pd import xlwings as xw import datetime class PyMoiReader: def read(self) -> pd.DataFrame: pass class CsvReader(PyMoiReader): def __init__(self, fullname, delimiter=',', quotechar='"'): self.fullname = fullname...
pymoi/reader.py
from dataclasses import dataclass, field from typing import List import pandas as pd import xlwings as xw import datetime class PyMoiReader: def read(self) -> pd.DataFrame: pass class CsvReader(PyMoiReader): def __init__(self, fullname, delimiter=',', quotechar='"'): self.fullname = fullname...
0.591841
0.226891
import datajoint as dj schema = dj.Schema() def activate(schema_name, create_schema=True, create_tables=True): """ activate(schema_name, create_schema=True, create_tables=True) :param schema_name: schema name on the database server to activate the `lab` element :param create_schema: when True...
element_lab/lab.py
import datajoint as dj schema = dj.Schema() def activate(schema_name, create_schema=True, create_tables=True): """ activate(schema_name, create_schema=True, create_tables=True) :param schema_name: schema name on the database server to activate the `lab` element :param create_schema: when True...
0.552057
0.365174
from flask import Flask, request, render_template import pandas as pd import pickle import numpy as np from sklearn.externals import joblib from sklearn.preprocessing import StandardScaler import re app = Flask(__name__, template_folder="templates") # Load the model model = joblib.load('./models/model.p') scaler = jo...
Deploying your ML Model/WebProject1/website.py
from flask import Flask, request, render_template import pandas as pd import pickle import numpy as np from sklearn.externals import joblib from sklearn.preprocessing import StandardScaler import re app = Flask(__name__, template_folder="templates") # Load the model model = joblib.load('./models/model.p') scaler = jo...
0.491212
0.075892
import pytz from custom_components.hass_opensprinkler import CONF_CONFIG, CONF_STATIONS, DOMAIN from datetime import datetime, timedelta from homeassistant.util import Throttle from homeassistant.helpers.entity import Entity SCAN_INTERVAL = timedelta(seconds=5) utc_tz = pytz.timezone('UTC') def setup_platf...
hass_opensprinkler/sensor.py
import pytz from custom_components.hass_opensprinkler import CONF_CONFIG, CONF_STATIONS, DOMAIN from datetime import datetime, timedelta from homeassistant.util import Throttle from homeassistant.helpers.entity import Entity SCAN_INTERVAL = timedelta(seconds=5) utc_tz = pytz.timezone('UTC') def setup_platf...
0.722723
0.144149
import dao.PersonDAO as PersonDAO import manager.PermissionManager as PermissionManager def get_all(): get_first_name_last_name(None, None) def get_first_name(first_name): get_first_name_last_name(first_name, None) def get_last_name(last_name): get_first_name_last_name(None, last_name) def get_fir...
manager/PersonManager.py
import dao.PersonDAO as PersonDAO import manager.PermissionManager as PermissionManager def get_all(): get_first_name_last_name(None, None) def get_first_name(first_name): get_first_name_last_name(first_name, None) def get_last_name(last_name): get_first_name_last_name(None, last_name) def get_fir...
0.265024
0.105487
from abc import abstractmethod from typing import ( List, Union, Dict, Tuple ) from mockintosh.constants import PYBARS, JINJA from mockintosh.performance import PerformanceProfile from mockintosh.exceptions import ( CommaInTagIsForbidden ) from mockintosh.templating import TemplateRenderer class ...
mockintosh/config.py
from abc import abstractmethod from typing import ( List, Union, Dict, Tuple ) from mockintosh.constants import PYBARS, JINJA from mockintosh.performance import PerformanceProfile from mockintosh.exceptions import ( CommaInTagIsForbidden ) from mockintosh.templating import TemplateRenderer class ...
0.7773
0.134236
from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'dataproc' class AcceleratorConfig(_messages.Message): r"""Specifies the type and number of accelerator cards attached to the instances of an instance group (see...
lib/googlecloudsdk/third_party/apis/dataproc/v1beta2/dataproc_v1beta2_messages.py
from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'dataproc' class AcceleratorConfig(_messages.Message): r"""Specifies the type and number of accelerator cards attached to the instances of an instance group (see...
0.912602
0.257859
import models import util.validation from database import db_txn from linkr import db from util.exception import * @db_txn def add_link(alias, outgoing_url, password=<PASSWORD>, user_id=None, require_recaptcha=False): """ Add a new link to the database after performing necessary input validation. :param ...
database/link.py
import models import util.validation from database import db_txn from linkr import db from util.exception import * @db_txn def add_link(alias, outgoing_url, password=<PASSWORD>, user_id=None, require_recaptcha=False): """ Add a new link to the database after performing necessary input validation. :param ...
0.75401
0.15704
import os from tqdm import tqdm import torch import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn class PairFM(nn.Module): def __init__(self, user_num, item_num, factors=84, epochs=20, lr=0....
daisy/model/pair/FMRecommender.py
import os from tqdm import tqdm import torch import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn class PairFM(nn.Module): def __init__(self, user_num, item_num, factors=84, epochs=20, lr=0....
0.908193
0.314051
import os import unittest from armi.nuclearDataIO.cccc import isotxs from armi.utils import plotting from armi.reactor.tests import test_reactors from armi.tests import ISOAA_PATH, TEST_ROOT from armi.reactor.flags import Flags from armi.utils.directoryChangers import TemporaryDirectoryChanger class TestPlotting(uni...
armi/utils/tests/test_plotting.py
import os import unittest from armi.nuclearDataIO.cccc import isotxs from armi.utils import plotting from armi.reactor.tests import test_reactors from armi.tests import ISOAA_PATH, TEST_ROOT from armi.reactor.flags import Flags from armi.utils.directoryChangers import TemporaryDirectoryChanger class TestPlotting(uni...
0.626696
0.48621
import os import shutil import unittest import tempfile from telemetry.core import util from telemetry.internal.backends.chrome import crx_id class CrxIdUnittest(unittest.TestCase): CRX_ID_DIR = util.GetUnittestDataDir() PACKED_CRX = os.path.join(CRX_ID_DIR, 'jebgalgnebhfojomionfpkfel...
telemetry/telemetry/internal/backends/chrome/crx_id_unittest.py
import os import shutil import unittest import tempfile from telemetry.core import util from telemetry.internal.backends.chrome import crx_id class CrxIdUnittest(unittest.TestCase): CRX_ID_DIR = util.GetUnittestDataDir() PACKED_CRX = os.path.join(CRX_ID_DIR, 'jebgalgnebhfojomionfpkfel...
0.255715
0.243238
import base64 import json import random from pathlib import Path import imagehash import numpy as np from raymon.profiling.extractors import SimpleExtractor class FixedSubpatchSimilarity(SimpleExtractor): _attrs = ["patch", "refs"] _patch_keys = ["x0", "y0", "<KEY>"] def __init__(self, patch, refs=None...
raymon/profiling/extractors/vision/similarity.py
import base64 import json import random from pathlib import Path import imagehash import numpy as np from raymon.profiling.extractors import SimpleExtractor class FixedSubpatchSimilarity(SimpleExtractor): _attrs = ["patch", "refs"] _patch_keys = ["x0", "y0", "<KEY>"] def __init__(self, patch, refs=None...
0.737158
0.224491
from dataclasses import dataclass from datetime import date, timedelta, datetime from typing import Iterable, Union, List import pandas as pd import numpy as np @dataclass class DateRange: start_date: date end_date: date def __init__(self, start_date, end_date): self.start_date = safe_convert_to_...
pvoutput/daterange.py
from dataclasses import dataclass from datetime import date, timedelta, datetime from typing import Iterable, Union, List import pandas as pd import numpy as np @dataclass class DateRange: start_date: date end_date: date def __init__(self, start_date, end_date): self.start_date = safe_convert_to_...
0.844537
0.314656
import os import mock from oslo_serialization import jsonutils from watcher.common import context from watcher.common import exception from watcher.common import nova_helper from watcher.common import service as watcher_service from watcher.decision_engine.model import element from watcher.decision_engine.model.noti...
python-watcher-2.0.0/watcher/tests/decision_engine/model/notification/test_nova_notifications.py
import os import mock from oslo_serialization import jsonutils from watcher.common import context from watcher.common import exception from watcher.common import nova_helper from watcher.common import service as watcher_service from watcher.decision_engine.model import element from watcher.decision_engine.model.noti...
0.496338
0.096748
import pandas as pd import numpy as np from sklearn.linear_model import RidgeCV from sklearn import metrics from utils.constants import Maps # Pandas options for better printing pd.set_option('display.max_columns', 500) pd.set_option('display.max_rows', 1000) pd.set_option('display.width', 1000) # Read in our scored...
player_rating.py
import pandas as pd import numpy as np from sklearn.linear_model import RidgeCV from sklearn import metrics from utils.constants import Maps # Pandas options for better printing pd.set_option('display.max_columns', 500) pd.set_option('display.max_rows', 1000) pd.set_option('display.width', 1000) # Read in our scored...
0.804291
0.371906
import sqlite3 from models.sl_logger import SlLogger logger = SlLogger.get_logger(__name__) class UserModel: def __init__(self, _id, username, password, pswd_hint): self.id = _id self.username = username self.password = password self.pswd_hint = pswd_hint @classmethod def...
models/user.py
import sqlite3 from models.sl_logger import SlLogger logger = SlLogger.get_logger(__name__) class UserModel: def __init__(self, _id, username, password, pswd_hint): self.id = _id self.username = username self.password = password self.pswd_hint = pswd_hint @classmethod def...
0.376623
0.063628
import psycopg2 def read_db(product_id, track_order): try: connection = psycopg2.connect(database = 'tracklist', user = 'allex', password = '', host = '172.16.17.32', port = '5432') except psycopg2.Error as err: print(...
read_db.py
import psycopg2 def read_db(product_id, track_order): try: connection = psycopg2.connect(database = 'tracklist', user = 'allex', password = '', host = '172.16.17.32', port = '5432') except psycopg2.Error as err: print(...
0.244183
0.094093
from __future__ import print_function, division from warnings import warn import pandas as pd import numpy as np import pickle import copy from nilmtk.utils import find_nearest from nilmtk.feature_detectors import cluster from nilmtk.disaggregate import Disaggregator from nilmtk.datastore import HDFDataStore # Fix t...
nilmtk/disaggregate/combinatorial_optimisation.py
from __future__ import print_function, division from warnings import warn import pandas as pd import numpy as np import pickle import copy from nilmtk.utils import find_nearest from nilmtk.feature_detectors import cluster from nilmtk.disaggregate import Disaggregator from nilmtk.datastore import HDFDataStore # Fix t...
0.739705
0.482307
import contextlib import tensorflow as tf import tensorflow_gan as tfgan sn_gettr = tfgan.features.spectral_normalization_custom_getter def snconv2d(input_, output_dim, k_h=3, k_w=3, d_h=2, d_w=2, training=True, name='snconv2d'): """Creates a 2d conv-layer with Spectral Norm applied to the weights. ...
galaxy2galaxy/layers/spectral_ops.py
import contextlib import tensorflow as tf import tensorflow_gan as tfgan sn_gettr = tfgan.features.spectral_normalization_custom_getter def snconv2d(input_, output_dim, k_h=3, k_w=3, d_h=2, d_w=2, training=True, name='snconv2d'): """Creates a 2d conv-layer with Spectral Norm applied to the weights. ...
0.917342
0.671982
from __future__ import annotations import json import os import re from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Any, Collection, Optional from dotenv import load_dotenv from .logger import set_log from .util import datetime_parser, open_query, postgres_date...
src/duneapi/types.py
from __future__ import annotations import json import os import re from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Any, Collection, Optional from dotenv import load_dotenv from .logger import set_log from .util import datetime_parser, open_query, postgres_date...
0.654122
0.265577
import asyncio from FIREX.utils import admin_cmd, edit_or_reply, sudo_cmd from userbot import * from userbot.cmdhelp import CmdHelp DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "ν2.ο" @bot.on(admin_cmd(pattern="think$")) @bot.on(sudo_cmd(pattern="think$", allow_sudo=True)) async def _(event): if event.fwd_f...
userbot/plugins/Xtra_Plugin/animations.py
import asyncio from FIREX.utils import admin_cmd, edit_or_reply, sudo_cmd from userbot import * from userbot.cmdhelp import CmdHelp DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "ν2.ο" @bot.on(admin_cmd(pattern="think$")) @bot.on(sudo_cmd(pattern="think$", allow_sudo=True)) async def _(event): if event.fwd_f...
0.17774
0.065276
import unittest from domain_scoring.domain_value_transformer import NaiveTransformer, SMALLER from util.lists import all_pairs class NaiveDomainValueTransformerTest(unittest.TestCase): def setUp(self): self.transformer = NaiveTransformer() self.oracle = self._create_oracle(range(6)) def test...
tests/domain_scoring/domain_value_transformer_test.py
import unittest from domain_scoring.domain_value_transformer import NaiveTransformer, SMALLER from util.lists import all_pairs class NaiveDomainValueTransformerTest(unittest.TestCase): def setUp(self): self.transformer = NaiveTransformer() self.oracle = self._create_oracle(range(6)) def test...
0.582135
0.645092
__all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"CheckpointingNotSupported": "00_callbacks.ipynb", "GradientCheckpointing": "00_callbacks.ipynb", "Singleton": "00_utils.ipynb", "str_to_type": "00_utils.ipynb", "print_versions": "00_utils.ipynb", "set...
blurr/_nbdev.py
__all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"CheckpointingNotSupported": "00_callbacks.ipynb", "GradientCheckpointing": "00_callbacks.ipynb", "Singleton": "00_utils.ipynb", "str_to_type": "00_utils.ipynb", "print_versions": "00_utils.ipynb", "set...
0.547948
0.411702
import math import pandas as pd import os class BaseGeoCalculations(): @staticmethod def __getLength(lon_max, lon_min): return lon_max - lon_min @staticmethod def __getWidth(lat_max, lat_min): return lat_max - lat_min @staticmethod # Returns a tuple with the side length and ...
AcridotheresCristatellusExpansion/ACExpansion/utils/utils_get_map_parameters.py
import math import pandas as pd import os class BaseGeoCalculations(): @staticmethod def __getLength(lon_max, lon_min): return lon_max - lon_min @staticmethod def __getWidth(lat_max, lat_min): return lat_max - lat_min @staticmethod # Returns a tuple with the side length and ...
0.72952
0.193471
import sys import importlib def _get_deps_info(): """Overview of the installed version of main dependencies Returns ------- deps_info: dict version information on relevant Python libraries """ deps = [ "pip", "setuptools", "imblearn", "sklearn", ...
imblearn/utils/_show_versions.py
import sys import importlib def _get_deps_info(): """Overview of the installed version of main dependencies Returns ------- deps_info: dict version information on relevant Python libraries """ deps = [ "pip", "setuptools", "imblearn", "sklearn", ...
0.437583
0.208139
import os import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder import keras from framesandoflow import files2frames, images_normalize class FramesGenerator(keras.utils.Sequence): """ Read and yields video frames/optical flow for Keras.model.fit_generator """ def __ini...
datagenerator.py
import os import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder import keras from framesandoflow import files2frames, images_normalize class FramesGenerator(keras.utils.Sequence): """ Read and yields video frames/optical flow for Keras.model.fit_generator """ def __ini...
0.735262
0.29726
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'GeoLocation.lat' db.alter_column(u'faver_geolocation', 'lat', self.gf('django....
trolly/faver/migrations/0007_auto__chg_field_geolocation_lat__chg_field_geolocation_long.py
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'GeoLocation.lat' db.alter_column(u'faver_geolocation', 'lat', self.gf('django....
0.502686
0.090574
import base64 import json from typing import Any, Dict, List from google.protobuf.json_format import Parse, ParseDict from cosmpy.common.rest_client import RestClient from cosmpy.protos.cosmos.crypto.secp256k1.keys_pb2 import ( # noqa: F401 # pylint: disable=unused-import PubKey as ProtoPubKey, ) from cosmpy.pr...
cosmpy/tx/rest_client.py
import base64 import json from typing import Any, Dict, List from google.protobuf.json_format import Parse, ParseDict from cosmpy.common.rest_client import RestClient from cosmpy.protos.cosmos.crypto.secp256k1.keys_pb2 import ( # noqa: F401 # pylint: disable=unused-import PubKey as ProtoPubKey, ) from cosmpy.pr...
0.782579
0.077204
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.hvac_design_objects import SizingSystem log = logging.getLogger(__name__) class TestSizingSystem(unittest.TestCase): def setUp(self): self.fd, self.path = tempfile....
tests/test_sizingsystem.py
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.hvac_design_objects import SizingSystem log = logging.getLogger(__name__) class TestSizingSystem(unittest.TestCase): def setUp(self): self.fd, self.path = tempfile....
0.355663
0.141281
from typing import Optional from torch import nn from torch.nn import functional as F from ..ff import FF class SpeechLSTM(nn.Module): """A bidirectional LSTM encoder with subsampling for speech features. The number of LSTM layers is defined by the `layers` argument, i.e. `1_1_2_2_1_1` denotes 6 LSTM l...
pysimt/layers/encoders/speech_lstm.py
from typing import Optional from torch import nn from torch.nn import functional as F from ..ff import FF class SpeechLSTM(nn.Module): """A bidirectional LSTM encoder with subsampling for speech features. The number of LSTM layers is defined by the `layers` argument, i.e. `1_1_2_2_1_1` denotes 6 LSTM l...
0.962205
0.671773
from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import * import numpy as np from scipy import interpolate, linalg, signal class FirstOrder(signal.TransferFunction): """First order heat capacity differential equation model. The...
heatcapacity/fit.py
from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import * import numpy as np from scipy import interpolate, linalg, signal class FirstOrder(signal.TransferFunction): """First order heat capacity differential equation model. The...
0.928975
0.52476
from sage.structure.sage_object import SageObject from sage.rings.all import Integer, infinity, ZZ, QQ, CC from sage.modules.free_module import span from sage.modular.modform.constructor import Newform, CuspForms from sage.modular.arithgroup.congroup_gamma0 import is_Gamma0 from sage.misc.misc_c import prod class Ls...
src/sage/modular/abvar/lseries.py
from sage.structure.sage_object import SageObject from sage.rings.all import Integer, infinity, ZZ, QQ, CC from sage.modules.free_module import span from sage.modular.modform.constructor import Newform, CuspForms from sage.modular.arithgroup.congroup_gamma0 import is_Gamma0 from sage.misc.misc_c import prod class Ls...
0.875946
0.510558
import json import time, datetime import os import shutil class V2XDataCollector: def __init__(self, environment:str): self.environment = environment self.loggingDirectory = None self.initializationTimestamp = None self.hostBsmLogfile = None self.remoteBsmLogfile = None ...
src/common/v2x-data-collector/V2XDataCollector.py
import json import time, datetime import os import shutil class V2XDataCollector: def __init__(self, environment:str): self.environment = environment self.loggingDirectory = None self.initializationTimestamp = None self.hostBsmLogfile = None self.remoteBsmLogfile = None ...
0.116337
0.107204
SC ={ 'DRV_ERROR_CODES': 20001, 'DRV_SUCCESS': 20002, 'DRV_VXDNOTINSTALLED' : 20003, 'DRV_ERROR_SCAN' : 20004, 'DRV_ERROR_CHECK_SUM' : 20005, 'DRV_ERROR_FILELOAD' : 20006, 'DRV_UNKNOWN_FUNCTION' : 20007, 'DRV_ERROR_VXD_INIT' : 20008, 'DRV_ERROR_ADDRESS'...
labscript_devices/AndorSolis/andor_sdk/status_codes.py
SC ={ 'DRV_ERROR_CODES': 20001, 'DRV_SUCCESS': 20002, 'DRV_VXDNOTINSTALLED' : 20003, 'DRV_ERROR_SCAN' : 20004, 'DRV_ERROR_CHECK_SUM' : 20005, 'DRV_ERROR_FILELOAD' : 20006, 'DRV_UNKNOWN_FUNCTION' : 20007, 'DRV_ERROR_VXD_INIT' : 20008, 'DRV_ERROR_ADDRESS'...
0.159021
0.058319
import serial import struct import time import sys from numpy import * class sutterMP285 : 'Class which allows interaction with the Sutter Manipulator 285' def __init__(self): self.verbose = 1. # level of messages self.timeOut = 30 # timeout in sec # initialize serial connection to controlle...
sutterMP285.py
import serial import struct import time import sys from numpy import * class sutterMP285 : 'Class which allows interaction with the Sutter Manipulator 285' def __init__(self): self.verbose = 1. # level of messages self.timeOut = 30 # timeout in sec # initialize serial connection to controlle...
0.182244
0.151749
import sys import copy import tempfile import pytest import torch import numpy as np import nibabel as nib import torchio as tio from ..utils import TorchioTestCase class TestImage(TorchioTestCase): """Tests for `Image`.""" def test_image_not_found(self): with self.assertRaises(FileNotFoundError): ...
tests/data/test_image.py
import sys import copy import tempfile import pytest import torch import numpy as np import nibabel as nib import torchio as tio from ..utils import TorchioTestCase class TestImage(TorchioTestCase): """Tests for `Image`.""" def test_image_not_found(self): with self.assertRaises(FileNotFoundError): ...
0.615203
0.583619
from __future__ import absolute_import, division, print_function import logging from collections import defaultdict, namedtuple import pytest import torch import pyro import pyro.distributions as dist import pyro.optim as optim from pyro.contrib.gp.kernels import Cosine, Matern32, RBF, WhiteNoise from pyro.contrib.g...
tests/contrib/gp/test_models.py
from __future__ import absolute_import, division, print_function import logging from collections import defaultdict, namedtuple import pytest import torch import pyro import pyro.distributions as dist import pyro.optim as optim from pyro.contrib.gp.kernels import Cosine, Matern32, RBF, WhiteNoise from pyro.contrib.g...
0.836921
0.504516
from numpy import random import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation def adjust_spines(ax, spines): """ removing the spines from a matplotlib graphics. taken from matplotlib gallery anonymous author. parameters ---------- ax: a matplolib ax...
inkdrops.py
from numpy import random import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation def adjust_spines(ax, spines): """ removing the spines from a matplotlib graphics. taken from matplotlib gallery anonymous author. parameters ---------- ax: a matplolib ax...
0.388618
0.59408
from vmaf.config import VmafConfig dataset_name = 'test_image' yuv_fmt = 'yuv444p' ref_videos = [ {'content_id': 0, 'content_name': '100007', 'height': 321, 'path': VmafConfig.test_resource_path('test_image_yuv', '100007.yuv'), 'width': 481}, {'content_id': 1, 'content_name': '100039', 'height': 321, ...
python/test/resource/test_image_dataset_noisy.py
from vmaf.config import VmafConfig dataset_name = 'test_image' yuv_fmt = 'yuv444p' ref_videos = [ {'content_id': 0, 'content_name': '100007', 'height': 321, 'path': VmafConfig.test_resource_path('test_image_yuv', '100007.yuv'), 'width': 481}, {'content_id': 1, 'content_name': '100039', 'height': 321, ...
0.433742
0.159479
"""MySQL prerequisite.""" import logging import os from spet.lib.utilities import download from spet.lib.utilities import execute from spet.lib.utilities import extract from spet.lib.utilities import prettify class MySQL: """MySQL prerequisite. Args: mysql_ver (str): Version number for MySQL ...
spet/lib/prerequisites/mysql.py
"""MySQL prerequisite.""" import logging import os from spet.lib.utilities import download from spet.lib.utilities import execute from spet.lib.utilities import extract from spet.lib.utilities import prettify class MySQL: """MySQL prerequisite. Args: mysql_ver (str): Version number for MySQL ...
0.753829
0.098209
from django.db import migrations, models import django.db.models.deletion import martor.models class Migration(migrations.Migration): initial = True dependencies = [ ('tag', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ...
django/codentino/apps/blog/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion import martor.models class Migration(migrations.Migration): initial = True dependencies = [ ('tag', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ...
0.60743
0.191365
import numpy from io_funcs.binary_io import BinaryIOCollection import logging class MinMaxNormalisation(object): def __init__(self, feature_dimension, min_value = 0.01, max_value = 0.99, min_vector = 0.0, max_vector = 0.0, exclude_columns=[]): # this is the wrong name for this logger because we can also...
src/frontend/min_max_norm.py
import numpy from io_funcs.binary_io import BinaryIOCollection import logging class MinMaxNormalisation(object): def __init__(self, feature_dimension, min_value = 0.01, max_value = 0.99, min_vector = 0.0, max_vector = 0.0, exclude_columns=[]): # this is the wrong name for this logger because we can also...
0.454956
0.386127
from functools import partial import glob import os import shutil import threading import unittest from absl.testing import absltest import jax import jax.numpy as jnp import jax.profiler from jax.config import config import jax.test_util as jtu try: import portpicker except ImportError: portpicker = None try: ...
tests/profiler_test.py
from functools import partial import glob import os import shutil import threading import unittest from absl.testing import absltest import jax import jax.numpy as jnp import jax.profiler from jax.config import config import jax.test_util as jtu try: import portpicker except ImportError: portpicker = None try: ...
0.498535
0.193776
from __future__ import absolute_import, print_function, unicode_literals import re import debug # pyflakes:ignore from ietf.submit.parsers.base import FileParser class PlainParser(FileParser): ext = 'txt' mimetypes = ['text/plain', ] def __init__(self, fd): super(P...
ietf/submit/parsers/plain_parser.py
from __future__ import absolute_import, print_function, unicode_literals import re import debug # pyflakes:ignore from ietf.submit.parsers.base import FileParser class PlainParser(FileParser): ext = 'txt' mimetypes = ['text/plain', ] def __init__(self, fd): super(P...
0.4917
0.100481
import six as _six from flytekit.common import sdk_bases as _sdk_bases from flytekit.common.exceptions import user as _user_exceptions from flytekit.models.core import identifier as _core_identifier class Identifier(_core_identifier.Identifier, metaclass=_sdk_bases.ExtendedSdkType): _STRING_TO_TYPE_MAP = { ...
flytekit/common/core/identifier.py
import six as _six from flytekit.common import sdk_bases as _sdk_bases from flytekit.common.exceptions import user as _user_exceptions from flytekit.models.core import identifier as _core_identifier class Identifier(_core_identifier.Identifier, metaclass=_sdk_bases.ExtendedSdkType): _STRING_TO_TYPE_MAP = { ...
0.677794
0.108378
MV_OK = 0x00000000 # < 成功,无错误 | en:Successed, no error MV_E_HANDLE = 0x80000000 # < 错误或无效的句柄 | en:Error or invalid handle MV_E_SUPPORT = 0x80000001 # < 不支持的功能 | en:Not supported function MV_E_BUFOVER ...
hik-driver/MVS/Samples/Python/MvImport/MvErrorDefine_const.py
MV_OK = 0x00000000 # < 成功,无错误 | en:Successed, no error MV_E_HANDLE = 0x80000000 # < 错误或无效的句柄 | en:Error or invalid handle MV_E_SUPPORT = 0x80000001 # < 不支持的功能 | en:Not supported function MV_E_BUFOVER ...
0.300746
0.07843
import os import re from time import time from pygaggle.rerank.base import Query, Text from pygaggle.rerank.transformer import MonoT5 def main(): DATA_DIR = "/home/l224016/projects/ia376_projeto_final/data/robust04/" RUNS_DIR = "/home/l224016/projects/ia376_projeto_final/data/robust04/runs" SEGMENTS_DIR =...
codigos/t5_reranker_robust04.py
import os import re from time import time from pygaggle.rerank.base import Query, Text from pygaggle.rerank.transformer import MonoT5 def main(): DATA_DIR = "/home/l224016/projects/ia376_projeto_final/data/robust04/" RUNS_DIR = "/home/l224016/projects/ia376_projeto_final/data/robust04/runs" SEGMENTS_DIR =...
0.331552
0.138958
from PySide2.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QFileDialog from PySide2.QtCore import Qt # parent UI from ui_node_manager_mainwindow import Ui_MainWindow # custom content from Node import Node from Node_ListWidget import Node_ListWidget from NodeContentWidget import NodeContentWidget from SaveDialog i...
pyScript_NodeManager/MainWindow.py
from PySide2.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QFileDialog from PySide2.QtCore import Qt # parent UI from ui_node_manager_mainwindow import Ui_MainWindow # custom content from Node import Node from Node_ListWidget import Node_ListWidget from NodeContentWidget import NodeContentWidget from SaveDialog i...
0.211906
0.053874
from scipy.interpolate import InterpolatedUnivariateSpline as _spline import numpy as np import scipy.integrate as intg class NaNException(Exception): pass def hmf_integral_gtm(M, dndm, mass_density=False): """ Cumulatively integrate dn/dm. Parameters ---------- M : array_like Array o...
hmf/integrate_hmf.py
from scipy.interpolate import InterpolatedUnivariateSpline as _spline import numpy as np import scipy.integrate as intg class NaNException(Exception): pass def hmf_integral_gtm(M, dndm, mass_density=False): """ Cumulatively integrate dn/dm. Parameters ---------- M : array_like Array o...
0.890491
0.524273
import numpy as np from optuna import Trial from sklearn.decomposition import PCA import mutation_prediction.data as data import mutation_prediction.embeddings.aaindex as aaindex from mutation_prediction.data import Dataset from mutation_prediction.embeddings import Embedding, EmbeddingMatrix class AcidsOneHot(Embed...
mutation_prediction/embeddings/acids.py
import numpy as np from optuna import Trial from sklearn.decomposition import PCA import mutation_prediction.data as data import mutation_prediction.embeddings.aaindex as aaindex from mutation_prediction.data import Dataset from mutation_prediction.embeddings import Embedding, EmbeddingMatrix class AcidsOneHot(Embed...
0.691602
0.439807
from typing import Optional import torch import torch.nn as nn from torch import Tensor, LongTensor from torch_geometric.typing import OptTensor from tsl.nn.functional import reverse_tensor from tsl.nn.layers.graph_convs.grin_cell import GRIL from tsl.utils.parser_utils import str_to_bool from ...base.embedding impor...
tsl/nn/models/imputation/grin_model.py
from typing import Optional import torch import torch.nn as nn from torch import Tensor, LongTensor from torch_geometric.typing import OptTensor from tsl.nn.functional import reverse_tensor from tsl.nn.layers.graph_convs.grin_cell import GRIL from tsl.utils.parser_utils import str_to_bool from ...base.embedding impor...
0.963057
0.582135
import datetime, copy, os import matchesDealEngine class CBaseStrategy(object): def __init__(self, stockCode): super(CBaseStrategy, self).__init__() self.stockCode = stockCode self.customInit() self.initCashe() #最新数据 self.currentData = {} #连接池,用于发送信号 self.requesHandlerObjList = [] #数据缓存 #当前时间,最近的一...
baseStrategy.py
import datetime, copy, os import matchesDealEngine class CBaseStrategy(object): def __init__(self, stockCode): super(CBaseStrategy, self).__init__() self.stockCode = stockCode self.customInit() self.initCashe() #最新数据 self.currentData = {} #连接池,用于发送信号 self.requesHandlerObjList = [] #数据缓存 #当前时间,最近的一...
0.081695
0.124665
from bresenham import bresenham from scipy.spatial import Voronoi import numpy as np from queue import PriorityQueue import networkx as nx def closest_node(graph, current_position): ''' Compute the closest node in the graph to the current position ''' closest_node = None dist = 100000 xy_posit...
lib/voronoi_utils.py
from bresenham import bresenham from scipy.spatial import Voronoi import numpy as np from queue import PriorityQueue import networkx as nx def closest_node(graph, current_position): ''' Compute the closest node in the graph to the current position ''' closest_node = None dist = 100000 xy_posit...
0.729905
0.574275
from cStringIO import StringIO from zope.interface import implements from zope.interface.verify import verifyObject from twisted.trial import unittest from twisted.internet import reactor from twisted.internet.address import IPv4Address from twisted.internet.defer import Deferred from twisted.web import server, resou...
twisted/web/test/test_web.py
from cStringIO import StringIO from zope.interface import implements from zope.interface.verify import verifyObject from twisted.trial import unittest from twisted.internet import reactor from twisted.internet.address import IPv4Address from twisted.internet.defer import Deferred from twisted.web import server, resou...
0.437583
0.188884
import logging from threading import Thread, Lock from impacket.structure import Structure lock = Lock() class RemComMessage(Structure): structure = ( ('Command','4096s=""'), ('WorkingDir','260s=""'), ('Priority','<L=0x20'), ('ProcessID','<L=0x01'), ('Machine','260s=""')...
lib/psexec.py
import logging from threading import Thread, Lock from impacket.structure import Structure lock = Lock() class RemComMessage(Structure): structure = ( ('Command','4096s=""'), ('WorkingDir','260s=""'), ('Priority','<L=0x20'), ('ProcessID','<L=0x01'), ('Machine','260s=""')...
0.361616
0.039862
import torch import math import numpy as np class LabelGuessor(object): def __init__(self, thresh): self.thresh = thresh def __call__(self, model, ims, balance, delT): org_state = { k: v.clone().detach() for k, v in model.state_dict().items() } is_train...
PT-BOSS/label_guessor.py
import torch import math import numpy as np class LabelGuessor(object): def __init__(self, thresh): self.thresh = thresh def __call__(self, model, ims, balance, delT): org_state = { k: v.clone().detach() for k, v in model.state_dict().items() } is_train...
0.247714
0.384768
import matplotlib.pyplot import seaborn import pandas import numpy class TfidfPlotter: color = seaborn.color_palette() def plot( self, dataset, tfidf_mat, tfidf_features, labels, top_n=10, ): print('calculating top tfidf scores per label') m...
plotting_utils/plot_tfidf.py
import matplotlib.pyplot import seaborn import pandas import numpy class TfidfPlotter: color = seaborn.color_palette() def plot( self, dataset, tfidf_mat, tfidf_features, labels, top_n=10, ): print('calculating top tfidf scores per label') m...
0.385375
0.333273
import json from Utils import RAR from Utils import Download from rarfile import RarFile from Utils import Json import os class ModelMan : def __init__(self ,googleDriveId:str , name:str , fileName:str): self.name = name self.fileName = fileName self.googleDriveId = googleDriveId def D...
Src/ModelM.py
import json from Utils import RAR from Utils import Download from rarfile import RarFile from Utils import Json import os class ModelMan : def __init__(self ,googleDriveId:str , name:str , fileName:str): self.name = name self.fileName = fileName self.googleDriveId = googleDriveId def D...
0.103942
0.078395
import os import sys import time import text_utils as tu from rfid_mifare_cloner import ( is_tag_reader_connected, create_dump_tag, write_new_tag, check_dependencies_installled, ) from exceptions import TagNotFoundException, NotClassifMifareTagException def welcome_screen(): """ Only shown when t...
RFID_mifare_cloner/cli.py
import os import sys import time import text_utils as tu from rfid_mifare_cloner import ( is_tag_reader_connected, create_dump_tag, write_new_tag, check_dependencies_installled, ) from exceptions import TagNotFoundException, NotClassifMifareTagException def welcome_screen(): """ Only shown when t...
0.268174
0.074703
from __future__ import unicode_literals import core.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('proposals', '0020_auto_20160202_1048'), ] operations = [ migrations.AlterField( model_name='talkproposal', name='...
src/proposals/migrations/0021_auto_20160222_0709.py
from __future__ import unicode_literals import core.models from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('proposals', '0020_auto_20160202_1048'), ] operations = [ migrations.AlterField( model_name='talkproposal', name='...
0.58522
0.17989
from discord import Guild from discord.errors import NotFound from contextlib import suppress from src.utils import channel_to_dict, member_to_dict, role_to_dict, user_to_dict, guild_to_dict class Pools: def __init__(self, bot): self.nonexistant = [] self.bot = bot async def get_all_emoji(s...
shard/src/api/pools.py
from discord import Guild from discord.errors import NotFound from contextlib import suppress from src.utils import channel_to_dict, member_to_dict, role_to_dict, user_to_dict, guild_to_dict class Pools: def __init__(self, bot): self.nonexistant = [] self.bot = bot async def get_all_emoji(s...
0.494629
0.097262
import sys import pandas as pd from sqlalchemy import create_engine def transform_categories(categories_df): """ Makes transformations in the categories data. Arguments: categories_df: the categories dataframe Output: categories_df_trans: the transformed categories dataframe ""...
data/process_data.py
import sys import pandas as pd from sqlalchemy import create_engine def transform_categories(categories_df): """ Makes transformations in the categories data. Arguments: categories_df: the categories dataframe Output: categories_df_trans: the transformed categories dataframe ""...
0.639624
0.51251
class Entry: def __init__(self, tagged, untagged): self.tagged = tagged self.untagged = untagged def get_tagged(self): return self.tagged def get_untagged(self): return self.untagged @staticmethod def decode(data): f_tagged = None if "tagged" in data: f_tagged = data["tagged"...
it/interfaces/structures/default/python/test.py
class Entry: def __init__(self, tagged, untagged): self.tagged = tagged self.untagged = untagged def get_tagged(self): return self.tagged def get_untagged(self): return self.untagged @staticmethod def decode(data): f_tagged = None if "tagged" in data: f_tagged = data["tagged"...
0.781247
0.221793
__author__ = '<NAME>' __date__ = '2019-11-17' __copyright__ = '(C) 2019, <NAME>' from PyQt5.QtCore import QCoreApplication, QVariant from qgis.core import (QgsProcessing, QgsFeatureSink, QgsProcessingException, QgsProcessingAlgorithm, ...
processing_provider/Survey_traverseAdjustment.py
__author__ = '<NAME>' __date__ = '2019-11-17' __copyright__ = '(C) 2019, <NAME>' from PyQt5.QtCore import QCoreApplication, QVariant from qgis.core import (QgsProcessing, QgsFeatureSink, QgsProcessingException, QgsProcessingAlgorithm, ...
0.623721
0.207757
import unittest import jinja2 import app class OSTemplateViewTestCase(unittest.TestCase): def setUp(self): config = app.ConfigWrapper() self.app = app.app(config).test_client() def test_latest_defaults(self): obs = self.app.get('/') exp = jinja2.Template(TEMPLATE).render(tag...
tests.py
import unittest import jinja2 import app class OSTemplateViewTestCase(unittest.TestCase): def setUp(self): config = app.ConfigWrapper() self.app = app.app(config).test_client() def test_latest_defaults(self): obs = self.app.get('/') exp = jinja2.Template(TEMPLATE).render(tag...
0.54819
0.271783
from unittest import TestCase from unittest.mock import MagicMock, patch, Mock from samcli.lib.sync.sync_flow_factory import SyncFlowFactory from samcli.lib.utils.cloudformation import CloudFormationResourceSummary class TestSyncFlowFactory(TestCase): def create_factory(self, auto_dependency_layer: bool = False)...
tests/unit/lib/sync/test_sync_flow_factory.py
from unittest import TestCase from unittest.mock import MagicMock, patch, Mock from samcli.lib.sync.sync_flow_factory import SyncFlowFactory from samcli.lib.utils.cloudformation import CloudFormationResourceSummary class TestSyncFlowFactory(TestCase): def create_factory(self, auto_dependency_layer: bool = False)...
0.693992
0.308737
from __future__ import print_function import itertools from PhysicsTools.Heppy.analyzers.core.VertexHistograms import VertexHistograms from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle from PhysicsTools.HeppyCore.statistics.average impor...
PhysicsTools/Heppy/python/analyzers/objects/VertexAnalyzer.py
from __future__ import print_function import itertools from PhysicsTools.Heppy.analyzers.core.VertexHistograms import VertexHistograms from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle from PhysicsTools.HeppyCore.statistics.average impor...
0.658198
0.219923
# <codecell> from pandas import read_csv import os, os.path import csv import matplotlib.pyplot as plt import re import dateutil.parser os.chdir('/home/will/HIVReportGen/') # <codecell> def extract_YOB(inp): try: return float(inp.split('-')[0]) except AttributeError: return float(inp) e...
DemoGraphs.py
# <codecell> from pandas import read_csv import os, os.path import csv import matplotlib.pyplot as plt import re import dateutil.parser os.chdir('/home/will/HIVReportGen/') # <codecell> def extract_YOB(inp): try: return float(inp.split('-')[0]) except AttributeError: return float(inp) e...
0.248717
0.211702
import atexit import builtins import os import tempfile import webbrowser from types import TracebackType from typing import Any, Dict, Iterator, Optional, Union from urllib import parse import certifi import lomond import requests import simplejson import determined_common.requests from determined_common.api import ...
common/determined_common/api/request.py
import atexit import builtins import os import tempfile import webbrowser from types import TracebackType from typing import Any, Dict, Iterator, Optional, Union from urllib import parse import certifi import lomond import requests import simplejson import determined_common.requests from determined_common.api import ...
0.68342
0.24979
import importlib import os from pathlib import Path from typing import Any import pytest from pydolphinscheduler.core import configuration from pydolphinscheduler.core.configuration import ( BUILD_IN_CONFIG_PATH, config_path, get_single_config, set_single_config, ) from pydolphinscheduler.exceptions i...
dolphinscheduler-python/pydolphinscheduler/tests/core/test_configuration.py
import importlib import os from pathlib import Path from typing import Any import pytest from pydolphinscheduler.core import configuration from pydolphinscheduler.core.configuration import ( BUILD_IN_CONFIG_PATH, config_path, get_single_config, set_single_config, ) from pydolphinscheduler.exceptions i...
0.615435
0.322993
from __future__ import with_statement from pybench import Test class WithFinally(Test): version = 2.0 operations = 20 rounds = 80000 class ContextManager(object): def __enter__(self): pass def __exit__(self, exc, val, tb): pass def test(self): cm ...
tests/benchmarks/pybench/With.py
from __future__ import with_statement from pybench import Test class WithFinally(Test): version = 2.0 operations = 20 rounds = 80000 class ContextManager(object): def __enter__(self): pass def __exit__(self, exc, val, tb): pass def test(self): cm ...
0.493409
0.127979
import os import sys import json from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtGui import * class WindowClassificationTrainUpdateLossParam(QtWidgets.QWidget): forward_train = QtCore.pyqtSignal(); backward_scheduler_param = QtCore.pyqtSignal(); def __init__(self): ...
classification/training/update/WindowClassificationTrainUpdateLossParam.py
import os import sys import json from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtGui import * class WindowClassificationTrainUpdateLossParam(QtWidgets.QWidget): forward_train = QtCore.pyqtSignal(); backward_scheduler_param = QtCore.pyqtSignal(); def __init__(self): ...
0.267217
0.122944
import math from collections import defaultdict import bisect import numpy as np from unittest.mock import MagicMock from mmdet.datasets import (ClassBalancedDataset, ConcatDataset, CustomDataset, MultiImageMixDataset, RepeatDataset) def test_dataset_wrapper(): CustomDataset.load_ann...
tests/test_data/test_datasets/test_dataset_wrapper.py
import math from collections import defaultdict import bisect import numpy as np from unittest.mock import MagicMock from mmdet.datasets import (ClassBalancedDataset, ConcatDataset, CustomDataset, MultiImageMixDataset, RepeatDataset) def test_dataset_wrapper(): CustomDataset.load_ann...
0.612657
0.519034
import logging import os import random import hydra from hydra.utils import instantiate import numpy as np import torch import wandb from allennlp.nn.util import get_text_field_mask from torch.distributions import Categorical from omegaconf import OmegaConf from viraal.config import (flatten_dict, get_key, pass_conf...
viraal/rerank/tag.py
import logging import os import random import hydra from hydra.utils import instantiate import numpy as np import torch import wandb from allennlp.nn.util import get_text_field_mask from torch.distributions import Categorical from omegaconf import OmegaConf from viraal.config import (flatten_dict, get_key, pass_conf...
0.535098
0.112893
import logging from typing import Dict, Optional, Sequence, Type, Union import tensorflow as tf from tensorflow.keras.layers import Layer from ..block.mlp import MLPBlock from ..ranking_metric import AvgPrecisionAt, NDCGAt, RecallAt from .base import PredictionTask def name_fn(name, inp): return "/".join([name,...
transformers4rec/tf/model/prediction_task.py
import logging from typing import Dict, Optional, Sequence, Type, Union import tensorflow as tf from tensorflow.keras.layers import Layer from ..block.mlp import MLPBlock from ..ranking_metric import AvgPrecisionAt, NDCGAt, RecallAt from .base import PredictionTask def name_fn(name, inp): return "/".join([name,...
0.949412
0.297467
import os import sys import inspect import meshlabxml as mlx import platform import glob import shutil import time from threading import Thread ''' Description: It takes via normal script "simplifybulk.py" 17 minutes to Decimate a 3M faces into 7 resolutions [100K, 200K, 300K, 400K, 500K, 600K, 750K]...
simplifybulkthreaded.py
import os import sys import inspect import meshlabxml as mlx import platform import glob import shutil import time from threading import Thread ''' Description: It takes via normal script "simplifybulk.py" 17 minutes to Decimate a 3M faces into 7 resolutions [100K, 200K, 300K, 400K, 500K, 600K, 750K]...
0.108012
0.174164
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from dxm.lib.masking_api.api_client import ApiClient class ReidentificationJobApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the cl...
dxm/lib/masking_api/api/reidentification_job_api.py
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from dxm.lib.masking_api.api_client import ApiClient class ReidentificationJobApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the cl...
0.712932
0.055926
from __future__ import division, unicode_literals, print_function, absolute_import import numpy as np import traitlets as tl from podpac.core.node import NodeException from podpac.core.units import UnitsDataArray from podpac.core.utils import common_doc from podpac.core.compositor.compositor import COMMON_COMPOSITOR_...
podpac/core/compositor/ordered_compositor.py
from __future__ import division, unicode_literals, print_function, absolute_import import numpy as np import traitlets as tl from podpac.core.node import NodeException from podpac.core.units import UnitsDataArray from podpac.core.utils import common_doc from podpac.core.compositor.compositor import COMMON_COMPOSITOR_...
0.82425
0.461623
import os import numpy as np import pandas as pd import time as tm import rpy2.robjects as robjects import tensorflow as tf import math import scipy.io as sio import optunity as opt from tensorflow.contrib.tensor_forest.python import tensor_forest from tensorflow.python.ops import resources import SparseMatrix as sm ...
Scripts/run_LAmbDA.py
import os import numpy as np import pandas as pd import time as tm import rpy2.robjects as robjects import tensorflow as tf import math import scipy.io as sio import optunity as opt from tensorflow.contrib.tensor_forest.python import tensor_forest from tensorflow.python.ops import resources import SparseMatrix as sm ...
0.287368
0.379091
from django.test import TransactionTestCase from django.conf import settings from django.test.client import Client from spotseeker_server.models import Spot, SpotExtendedInfo import simplejson as json import random from django.test.utils import override_settings from mock import patch from django.core import cache from...
test/uw_spot/spot_put.py
from django.test import TransactionTestCase from django.conf import settings from django.test.client import Client from spotseeker_server.models import Spot, SpotExtendedInfo import simplejson as json import random from django.test.utils import override_settings from mock import patch from django.core import cache from...
0.549399
0.089694
u""" Created at 2020.01.02 A python wrapper for running the netprophet to replace snakemake """ import os import sys import json import logging from argparse import ArgumentParser, ArgumentError from multiprocessing import Pool from shutil import rmtree from subprocess import check_call, CalledProcessError from tqdm...
main.py
u""" Created at 2020.01.02 A python wrapper for running the netprophet to replace snakemake """ import os import sys import json import logging from argparse import ArgumentParser, ArgumentError from multiprocessing import Pool from shutil import rmtree from subprocess import check_call, CalledProcessError from tqdm...
0.35209
0.146667
import sys from functools import lru_cache, partial from itertools import combinations import generator_conf import jinja2 def all_combinations(l): return [x for n in range(len(l) + 1) for x in combinations(l, n)] def indent(n, s): return s.replace("\n", "\n" + " " * (n * 4)) def nested_statements(layers...
python/generate_from_jinja.py
import sys from functools import lru_cache, partial from itertools import combinations import generator_conf import jinja2 def all_combinations(l): return [x for n in range(len(l) + 1) for x in combinations(l, n)] def indent(n, s): return s.replace("\n", "\n" + " " * (n * 4)) def nested_statements(layers...
0.279632
0.126785
from RLTest import Env import random def aofTestCommon(env, reloadfn): # TODO: Change this attribute in rmtest env.cmd('ft.create', 'idx', 'schema', 'field1', 'text', 'field2', 'numeric') reloadfn() for x in range(1, 10): env.assertCmdOk('ft.add', 'idx', 'd...
src/pytest/test_aof.py
from RLTest import Env import random def aofTestCommon(env, reloadfn): # TODO: Change this attribute in rmtest env.cmd('ft.create', 'idx', 'schema', 'field1', 'text', 'field2', 'numeric') reloadfn() for x in range(1, 10): env.assertCmdOk('ft.add', 'idx', 'd...
0.303216
0.361446