code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from __future__ import unicode_literals import os import re import getpass import posixpath import logging from subprocess import Popen, PIPE from dvc.config import Config from dvc.scheme import Schemes from dvc.remote.base import RemoteBASE, RemoteCmdError from dvc.utils import fix_env, tmp_fname logger = logging...
dvc/remote/hdfs.py
from __future__ import unicode_literals import os import re import getpass import posixpath import logging from subprocess import Popen, PIPE from dvc.config import Config from dvc.scheme import Schemes from dvc.remote.base import RemoteBASE, RemoteCmdError from dvc.utils import fix_env, tmp_fname logger = logging...
0.391639
0.09426
import adsk.core, adsk.fusion, adsk.cam, traceback import xml.etree.ElementTree as ET import glob import shutil, datetime def serchTargetFile(): # logicoolのプロファイルのファイルパスをリストで取得 logicoolProfileList = glob.glob(r"C:\Users\*\AppData\Local\Logitech\Logitech Gaming Software\profiles\*.xml") targetFile = 0 ...
UpdateFusionPathForLogicool.py
import adsk.core, adsk.fusion, adsk.cam, traceback import xml.etree.ElementTree as ET import glob import shutil, datetime def serchTargetFile(): # logicoolのプロファイルのファイルパスをリストで取得 logicoolProfileList = glob.glob(r"C:\Users\*\AppData\Local\Logitech\Logitech Gaming Software\profiles\*.xml") targetFile = 0 ...
0.107367
0.118054
import sublime import sublime_plugin import json import locale import os import re import subprocess import sys PY3K = sys.version_info >= (3, 0, 0) if PY3K: from .ScalaFormatLib.MergeUtils import merge_code from .ScalaFormatLib import log else: from ScalaFormatLib.MergeUtils import merge_code from ...
ScalaFormat.py
import sublime import sublime_plugin import json import locale import os import re import subprocess import sys PY3K = sys.version_info >= (3, 0, 0) if PY3K: from .ScalaFormatLib.MergeUtils import merge_code from .ScalaFormatLib import log else: from ScalaFormatLib.MergeUtils import merge_code from ...
0.299105
0.053874
from collections import OrderedDict import pymel.core as pm import meta.core attr_rig_components = 'rigComponents' attr_rig = 'rig' attr_rig_group = 'rigGroup' attr_built = 'isBuild' attr_socket = 'socket' attr_component_group = 'componentGroup' attr_controls = 'controls' attr_bind = 'bindJoints' attr_start_joint = ...
meta/examples/rig.py
from collections import OrderedDict import pymel.core as pm import meta.core attr_rig_components = 'rigComponents' attr_rig = 'rig' attr_rig_group = 'rigGroup' attr_built = 'isBuild' attr_socket = 'socket' attr_component_group = 'componentGroup' attr_controls = 'controls' attr_bind = 'bindJoints' attr_start_joint = ...
0.742702
0.291233
from __future__ import print_function from __future__ import unicode_literals from __future__ import division import argparse, nltk from collections import Counter from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer """ Author: <NAME>, U...
bag_of_words/bow/bag_of_words_final.py
from __future__ import print_function from __future__ import unicode_literals from __future__ import division import argparse, nltk from collections import Counter from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer """ Author: <NAME>, U...
0.577376
0.269449
import csv import logging import os import re import sys from urllib2 import urlopen from envparse import env import sql_utils from lisa_parser import config logger = logging.getLogger(__file__.split('/')[-1]) def add_get_function(regex, content): def inner(): try: aux = re.search(regex, co...
HyperV/WS2012R2/lisa/Infrastructure/lisa-parser/lisa_parser/parse_build.py
import csv import logging import os import re import sys from urllib2 import urlopen from envparse import env import sql_utils from lisa_parser import config logger = logging.getLogger(__file__.split('/')[-1]) def add_get_function(regex, content): def inner(): try: aux = re.search(regex, co...
0.189371
0.125065
import os import urllib.request import tarfile import numpy as np import torch import torch.nn import torch.nn.functional import pytorch_lightning as pl from pytorch_lightning import loggers as pl_loggers from math import pi from typing import Sequence, Tuple, Union, Optional, List from torch.utils.data import DataLo...
instance_segmentation.py
import os import urllib.request import tarfile import numpy as np import torch import torch.nn import torch.nn.functional import pytorch_lightning as pl from pytorch_lightning import loggers as pl_loggers from math import pi from typing import Sequence, Tuple, Union, Optional, List from torch.utils.data import DataLo...
0.886724
0.700325
from app import app import json import os from flask import jsonify, request from app.services import user_services, auth_service, faq_services, exame_services from app.util.decorator import requires_authn, requires_authz from app.util.exceptions import AbroadException @app.route('/', methods=['GET']) def home(): ...
app/controllers/default.py
from app import app import json import os from flask import jsonify, request from app.services import user_services, auth_service, faq_services, exame_services from app.util.decorator import requires_authn, requires_authz from app.util.exceptions import AbroadException @app.route('/', methods=['GET']) def home(): ...
0.217421
0.045522
from scriptcore.testing.testcase import TestCase from scriptcore.console.output.output import Output class TestOutput(TestCase): def test_title(self): """ Test title-function :return: void """ text = self.rand_str() text2 = self.rand_str() output = Out...
tests/console/output/testoutput.py
from scriptcore.testing.testcase import TestCase from scriptcore.console.output.output import Output class TestOutput(TestCase): def test_title(self): """ Test title-function :return: void """ text = self.rand_str() text2 = self.rand_str() output = Out...
0.683631
0.5144
from logging import getLogger from datetime import datetime from contextlib import contextmanager import csv import os import io import threading import multiprocessing import warnings import pandas as pd import sqlalchemy logger = getLogger(__name__) class Connector: """ Init Args: connector: an ob...
sqljob/sqljob.py
from logging import getLogger from datetime import datetime from contextlib import contextmanager import csv import os import io import threading import multiprocessing import warnings import pandas as pd import sqlalchemy logger = getLogger(__name__) class Connector: """ Init Args: connector: an ob...
0.526343
0.151686
import hashlib from datetime import datetime, timedelta from typing import Iterable, List, Optional from flask_sqlalchemy import SQLAlchemy from sqlalchemy import func, ForeignKey, DateTime from sqlalchemy.orm.exc import NoResultFound from servicex.mailgun_adaptor import MailgunAdaptor db = SQLAlchemy() max_string_s...
servicex/models.py
import hashlib from datetime import datetime, timedelta from typing import Iterable, List, Optional from flask_sqlalchemy import SQLAlchemy from sqlalchemy import func, ForeignKey, DateTime from sqlalchemy.orm.exc import NoResultFound from servicex.mailgun_adaptor import MailgunAdaptor db = SQLAlchemy() max_string_s...
0.783658
0.107813
from heapq import nlargest from collections import deque try: from accel import longest_common_substring except ImportError: raise RuntimeError("Unable to import the extension") class PyyMatcher(object): """ Class for calculating the similarity of two string objects. Usage: >>> obj = PyyMat...
pyymatcher/matcher.py
from heapq import nlargest from collections import deque try: from accel import longest_common_substring except ImportError: raise RuntimeError("Unable to import the extension") class PyyMatcher(object): """ Class for calculating the similarity of two string objects. Usage: >>> obj = PyyMat...
0.783119
0.268222
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
tests/templates/test_subroutines/test_grover.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
0.953405
0.655047
from unittest.mock import Mock, call import pickle from rnnr.callbacks import checkpoint def test_ok(tmp_path): max_epoch, max_saved = 5, 2 objs_values = { "model": [f"MODEL_{i}" for i in range(max_epoch)], "opt": [f"OPT_{i}" for i in range(max_epoch)], } ckpt_name = "ckpt" callb...
tests/test_checkpointing.py
from unittest.mock import Mock, call import pickle from rnnr.callbacks import checkpoint def test_ok(tmp_path): max_epoch, max_saved = 5, 2 objs_values = { "model": [f"MODEL_{i}" for i in range(max_epoch)], "opt": [f"OPT_{i}" for i in range(max_epoch)], } ckpt_name = "ckpt" callb...
0.593963
0.449211
import librace class RaceRawParam: def __init__(self, data, count): self.data = data self.count = count class RaceParam: def __init__(self, type, delay_time_usec, last_chunk_size): self.type = type self.delay_time_usec = delay_time_usec self.last_chunk_size = last_chu...
bindings/python/race.py
import librace class RaceRawParam: def __init__(self, data, count): self.data = data self.count = count class RaceParam: def __init__(self, type, delay_time_usec, last_chunk_size): self.type = type self.delay_time_usec = delay_time_usec self.last_chunk_size = last_chu...
0.319015
0.226805
from collections import OrderedDict import torch import torch.nn as nn from .base import TorchModel from .utils import get_shape from .layers import ConvBlock, Upsample, Combine from .blocks import DefaultBlock from ..utils import unpack_args class EncoderModule(nn.ModuleDict): """ Encoder: create compressed r...
batchflow/models/torch/encoder_decoder.py
from collections import OrderedDict import torch import torch.nn as nn from .base import TorchModel from .utils import get_shape from .layers import ConvBlock, Upsample, Combine from .blocks import DefaultBlock from ..utils import unpack_args class EncoderModule(nn.ModuleDict): """ Encoder: create compressed r...
0.919367
0.274239
import rospy import actionlib from hanoying_back.msg import GameState, GameMoveAction, GameMoveGoal from hanoying_back.srv import GameSolveList rospy.init_node("ctrl") def on_feedback(feedback): print(str(feedback.percent*100) + "%") def on_result(status, result): # may want to update that if changing game:...
hanoying_front/src/ctrl/ctrl.py
import rospy import actionlib from hanoying_back.msg import GameState, GameMoveAction, GameMoveGoal from hanoying_back.srv import GameSolveList rospy.init_node("ctrl") def on_feedback(feedback): print(str(feedback.percent*100) + "%") def on_result(status, result): # may want to update that if changing game:...
0.227641
0.125253
import os import sys import importlib from collections import deque from werkzeug.utils import cached_property, import_string from jinja2 import Markup from flask import json # Find the stack on which we want to store the database connection. # Starting with Flask 0.9, the _app_ctx_stack is the correct one, # before th...
spotipo_plugins/__init__.py
import os import sys import importlib from collections import deque from werkzeug.utils import cached_property, import_string from jinja2 import Markup from flask import json # Find the stack on which we want to store the database connection. # Starting with Flask 0.9, the _app_ctx_stack is the correct one, # before th...
0.544559
0.134151
import unittest import numpy from cqcpy import test_utils import cqcpy.spin_utils as spin_utils import cqcpy.cc_equations as cc_equations class CCRDMTest(unittest.TestCase): def setUp(self): pass def test_1rdm_opt(self): no = 4 nv = 8 thresh = 1e-12 T1, T2 = test_util...
cqcpy/tests/test_cc_rdm.py
import unittest import numpy from cqcpy import test_utils import cqcpy.spin_utils as spin_utils import cqcpy.cc_equations as cc_equations class CCRDMTest(unittest.TestCase): def setUp(self): pass def test_1rdm_opt(self): no = 4 nv = 8 thresh = 1e-12 T1, T2 = test_util...
0.411347
0.618608
import os import zipfile from datetime import date, timedelta from io import BytesIO, StringIO import httpx import pandas as pd import app from CONSTANTS import * ISO_2_TO_ISO_3_URL = "https://raw.githubusercontent.com/ilyabo/aiddata/master/data/static/data/countries-iso2-iso3.csv" POPULATION_URL = ( "http://api...
data_loader.py
import os import zipfile from datetime import date, timedelta from io import BytesIO, StringIO import httpx import pandas as pd import app from CONSTANTS import * ISO_2_TO_ISO_3_URL = "https://raw.githubusercontent.com/ilyabo/aiddata/master/data/static/data/countries-iso2-iso3.csv" POPULATION_URL = ( "http://api...
0.293101
0.271134
from fastapi import APIRouter, Depends from apps.climsoft.services import obsscheduleclass_service from apps.climsoft.schemas import obsscheduleclass_schema from utils.response import get_success_response, get_error_response from sqlalchemy.orm.session import Session from apps.climsoft.db.engine import SessionLocal fro...
src/apps/climsoft/controllers/obsscheduleclass_controller.py
from fastapi import APIRouter, Depends from apps.climsoft.services import obsscheduleclass_service from apps.climsoft.schemas import obsscheduleclass_schema from utils.response import get_success_response, get_error_response from sqlalchemy.orm.session import Session from apps.climsoft.db.engine import SessionLocal fro...
0.328422
0.096919
from datetime import datetime from course_lib.Base.Evaluation.Evaluator import * from src.data_management.New_DataSplitter_leave_k_out import * from src.data_management.RecSys2019Reader import RecSys2019Reader from src.data_management.data_reader import get_UCM_train_new from src.model import new_best_models from src....
scripts/hp_tuning/run_tuning_weight_UCM.py
from datetime import datetime from course_lib.Base.Evaluation.Evaluator import * from src.data_management.New_DataSplitter_leave_k_out import * from src.data_management.RecSys2019Reader import RecSys2019Reader from src.data_management.data_reader import get_UCM_train_new from src.model import new_best_models from src....
0.404978
0.142918
import gc import glob import json import nltk import os import re import string import sys from collections import OrderedDict from math import log10 from nltk.corpus import stopwords from nltk import word_tokenize from nltk.stem.porter import PorterStemmer from string import translate #Global Constants PATH = sys.a...
ir_project/tokenizer.py
import gc import glob import json import nltk import os import re import string import sys from collections import OrderedDict from math import log10 from nltk.corpus import stopwords from nltk import word_tokenize from nltk.stem.porter import PorterStemmer from string import translate #Global Constants PATH = sys.a...
0.062581
0.145874
from config import Config from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from dataset import connect from pla...
crawlers/src/crawler.py
from config import Config from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from dataset import connect from pla...
0.13788
0.057019
"""Optimizing stack usage (pushes and pops).""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow_probability.python.experimental.auto_batching import instructions as inst def fuse_pop_push(program): """Fuses pop+push s...
tensorflow_probability/python/experimental/auto_batching/stack_optimization.py
"""Optimizing stack usage (pushes and pops).""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow_probability.python.experimental.auto_batching import instructions as inst def fuse_pop_push(program): """Fuses pop+push s...
0.794385
0.467393
import json import os import re import ssl from urllib.request import Request, urlopen import pandas as pd import requests import usaddress from bs4 import BeautifulSoup from . import df_to_tempfile class Scriptor: def __init__(self, **kwargs): self.__dict__.update(kwargs) def get_hnum(self, addres...
library/script/nycdoc_corrections.py
import json import os import re import ssl from urllib.request import Request, urlopen import pandas as pd import requests import usaddress from bs4 import BeautifulSoup from . import df_to_tempfile class Scriptor: def __init__(self, **kwargs): self.__dict__.update(kwargs) def get_hnum(self, addres...
0.379148
0.106551
from __future__ import absolute_import, division, print_function import numpy as np import time import glob import sys from os import makedirs, remove from os.path import exists, join as pjoin, isfile, isdir import nibabel import pickle import amico.scheme from amico.preproc import debiasRician import amico.lut impor...
amico/core.py
from __future__ import absolute_import, division, print_function import numpy as np import time import glob import sys from os import makedirs, remove from os.path import exists, join as pjoin, isfile, isdir import nibabel import pickle import amico.scheme from amico.preproc import debiasRician import amico.lut impor...
0.545286
0.130562
import argparse from io import StringIO import os import shutil import subprocess import sys import tempfile from unittest import mock from unittest.mock import patch from oslo_serialization import jsonutils as json from tempest.cmd import subunit_describe_calls from tempest.tests import base class TestArgumentPar...
tempest/tests/cmd/test_subunit_describe_calls.py
import argparse from io import StringIO import os import shutil import subprocess import sys import tempfile from unittest import mock from unittest.mock import patch from oslo_serialization import jsonutils as json from tempest.cmd import subunit_describe_calls from tempest.tests import base class TestArgumentPar...
0.413477
0.302365
import pandas as pd import numpy as np def get_stock_daily_fundamental(dates: np.array, date_position_dic: dict, code_order_dic: dict, data_path: str) -> dict: """ :param data_path: :param dates: 所以日期的array :param date_position_dic: 日期到位置的字典 :param code_order_dic: 股...
QBG/DataLoader/data_processors/get_stock_daily_fundamental.py
import pandas as pd import numpy as np def get_stock_daily_fundamental(dates: np.array, date_position_dic: dict, code_order_dic: dict, data_path: str) -> dict: """ :param data_path: :param dates: 所以日期的array :param date_position_dic: 日期到位置的字典 :param code_order_dic: 股...
0.24599
0.450359
class QueryOperatorException(Exception): pass class BaseQueryOperator(object): # The symbol that identifies this operator in kwargs # ie: colname__<symbol> symbol = None # The comparator symbol this operator uses in cql cql_symbol = None def __unicode__(self): if self.cql_symbol is N...
cqlengine/operators.py
class QueryOperatorException(Exception): pass class BaseQueryOperator(object): # The symbol that identifies this operator in kwargs # ie: colname__<symbol> symbol = None # The comparator symbol this operator uses in cql cql_symbol = None def __unicode__(self): if self.cql_symbol is N...
0.73431
0.282227
from json import JSONDecodeError from django.db import models from django.utils import timezone from django.core import serializers import uuid, logging, json logger = logging.getLogger(__name__) # Create your models here. class ARSModel(models.Model): class Meta: abstract = True def to_dict(self): ...
tr_sys/tr_ars/models.py
from json import JSONDecodeError from django.db import models from django.utils import timezone from django.core import serializers import uuid, logging, json logger = logging.getLogger(__name__) # Create your models here. class ARSModel(models.Model): class Meta: abstract = True def to_dict(self): ...
0.393618
0.065905
import networkx as nx __author__ = """\n""".join(['<NAME> <<EMAIL>>', '<NAME> (<EMAIL>)', '<NAME> (<EMAIL>)']) __all__ = ['convert_node_labels_to_integers', 'relabel_nodes'] def relabel_nodes(G, mapping, copy=True): """Relabel the nodes of the graph G. Par...
networkx-1.8.1/networkx/relabel.py
import networkx as nx __author__ = """\n""".join(['<NAME> <<EMAIL>>', '<NAME> (<EMAIL>)', '<NAME> (<EMAIL>)']) __all__ = ['convert_node_labels_to_integers', 'relabel_nodes'] def relabel_nodes(G, mapping, copy=True): """Relabel the nodes of the graph G. Par...
0.670608
0.493592
import os import sys import getopt import scipy.stats as stats import pandas as pd import numpy as np import sqlite3 DATA_DIR = os.path.join("..","data") def connect_db(file_path): """ function to connection to aavail database """ try: conn = sqlite3.connect(file_path) print("...succe...
data-vis-mpl/scripts/aavail-data-ingestor.py
import os import sys import getopt import scipy.stats as stats import pandas as pd import numpy as np import sqlite3 DATA_DIR = os.path.join("..","data") def connect_db(file_path): """ function to connection to aavail database """ try: conn = sqlite3.connect(file_path) print("...succe...
0.232659
0.215981
import re REGEX_CLEANER = re.compile(r"[^a-z0-9_@]", re.I) class AliasExpression(object): """ Crea una expresion SQL alias <campo> AS <alias> o simplemente <campo> si no fue provisto un alias """ def __init__(self, field_name, alias=None, *args, **kwargs): super(self.__class__, self).__init__()...
pqb/expressions.py
import re REGEX_CLEANER = re.compile(r"[^a-z0-9_@]", re.I) class AliasExpression(object): """ Crea una expresion SQL alias <campo> AS <alias> o simplemente <campo> si no fue provisto un alias """ def __init__(self, field_name, alias=None, *args, **kwargs): super(self.__class__, self).__init__()...
0.489015
0.137417
from parkour.env import env from parkour.utils import normalize_name, shorten_name import aiotfm import time import re MODIFY_RANK = (4 << 8) + 255 ROOM_PASSWORD = (13 << 8) + 255 class Commands(aiotfm.Client): def __init__(self, *args, **kwargs): self.next_available_restart = time.time() + 600.0 super().__in...
bots/parkour/commands.py
from parkour.env import env from parkour.utils import normalize_name, shorten_name import aiotfm import time import re MODIFY_RANK = (4 << 8) + 255 ROOM_PASSWORD = (13 << 8) + 255 class Commands(aiotfm.Client): def __init__(self, *args, **kwargs): self.next_available_restart = time.time() + 600.0 super().__in...
0.453262
0.159774
'''Runner for flashing with Black Magic Probe.''' # https://github.com/blacksphere/blackmagic/wiki from runners.core import ZephyrBinaryRunner, RunnerCaps class BlackMagicProbeRunner(ZephyrBinaryRunner): '''Runner front-end for Black Magic probe.''' def __init__(self, cfg, gdb_serial): super(BlackMa...
scripts/west_commands/runners/blackmagicprobe.py
'''Runner for flashing with Black Magic Probe.''' # https://github.com/blacksphere/blackmagic/wiki from runners.core import ZephyrBinaryRunner, RunnerCaps class BlackMagicProbeRunner(ZephyrBinaryRunner): '''Runner front-end for Black Magic probe.''' def __init__(self, cfg, gdb_serial): super(BlackMa...
0.598312
0.089256
import os from . import ColumnType def write_for_mysql(tab_info, to_dir): """MySQL向けのCreateTable文を生成 """ os.makedirs(to_dir, exist_ok=True) for t in tab_info: write_for_mysql_tab(t, to_dir) return None def write_for_mysql_tab(tab_info, to_dir, table_sep='_'): """MySQL向けのCreateTable文...
src/table_def/write_for_mysql.py
import os from . import ColumnType def write_for_mysql(tab_info, to_dir): """MySQL向けのCreateTable文を生成 """ os.makedirs(to_dir, exist_ok=True) for t in tab_info: write_for_mysql_tab(t, to_dir) return None def write_for_mysql_tab(tab_info, to_dir, table_sep='_'): """MySQL向けのCreateTable文...
0.136752
0.120957
from typing import Any, List, Literal, TypedDict from .FHIR_canonical import FHIR_canonical from .FHIR_Element import FHIR_Element from .FHIR_markdown import FHIR_markdown from .FHIR_string import FHIR_string # A Capability Statement documents a set of capabilities (behaviors) of a FHIR Server for a particular versio...
src/fhir_types/FHIR_CapabilityStatement_Document.py
from typing import Any, List, Literal, TypedDict from .FHIR_canonical import FHIR_canonical from .FHIR_Element import FHIR_Element from .FHIR_markdown import FHIR_markdown from .FHIR_string import FHIR_string # A Capability Statement documents a set of capabilities (behaviors) of a FHIR Server for a particular versio...
0.792022
0.450057
import time from concurrent import futures from oslo_log import log as logging from ironic_oneviewd.conf import CONF from ironic_oneviewd import utils LOG = logging.getLogger(__name__) ENROLL_PROVISION_STATE = 'enroll' MANAGEABLE_PROVISION_STATE = 'manageable' INSPECTION_FAILED_PROVISION_STATE = 'inspect failed' I...
ironic_oneviewd/node_manager/manage.py
import time from concurrent import futures from oslo_log import log as logging from ironic_oneviewd.conf import CONF from ironic_oneviewd import utils LOG = logging.getLogger(__name__) ENROLL_PROVISION_STATE = 'enroll' MANAGEABLE_PROVISION_STATE = 'manageable' INSPECTION_FAILED_PROVISION_STATE = 'inspect failed' I...
0.27406
0.142649
consonantMap_TwoDCode ={ "b":(1.0,0.5), "p":(1.0,1.5), "g":(7.0,0.5), "k":(7.0,1.5), "h":(7.0,3.0), "f":(7.0,4.0), "d":(12.0,0.5), "t":(12.0,1.5), "n":(22.5,0.5), "l":(22.5,1.5), "r":( 22.5,2.5), "zh":(30,1.7), "z":(30,1.5), "j":(30.0,0.5), ...
dimsim/utils/maps.py
consonantMap_TwoDCode ={ "b":(1.0,0.5), "p":(1.0,1.5), "g":(7.0,0.5), "k":(7.0,1.5), "h":(7.0,3.0), "f":(7.0,4.0), "d":(12.0,0.5), "t":(12.0,1.5), "n":(22.5,0.5), "l":(22.5,1.5), "r":( 22.5,2.5), "zh":(30,1.7), "z":(30,1.5), "j":(30.0,0.5), ...
0.325092
0.538073
from django.conf import settings from django.core.urlresolvers import reverse from django.db import transaction from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.http import Http404 from django.shortcuts import redirect from djan...
entrepreneur/views/manage_job_offers.py
from django.conf import settings from django.core.urlresolvers import reverse from django.db import transaction from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.http import Http404 from django.shortcuts import redirect from djan...
0.489503
0.059949
from dataclasses import dataclass import logging from typing import ClassVar from bitey.cpu.arch import EightBitArch @dataclass class AddressingMode: """ Addressing mode base class """ bytes: int """ The number of bytes an instruction with this addressing mode takes, including the instruc...
bitey/cpu/addressing_mode.py
from dataclasses import dataclass import logging from typing import ClassVar from bitey.cpu.arch import EightBitArch @dataclass class AddressingMode: """ Addressing mode base class """ bytes: int """ The number of bytes an instruction with this addressing mode takes, including the instruc...
0.782579
0.545528
from typing import Any, List, Dict, Callable from functools import wraps from pathlib import PurePath from dataclasses import dataclass, fields from dataclasses_jsonschema import JsonSchemaMixin class Result: code = int @dataclass class Ok(JsonSchemaMixin, Result): ok: bool = True code: int = 200 @dataclass c...
yrest/utils.py
from typing import Any, List, Dict, Callable from functools import wraps from pathlib import PurePath from dataclasses import dataclass, fields from dataclasses_jsonschema import JsonSchemaMixin class Result: code = int @dataclass class Ok(JsonSchemaMixin, Result): ok: bool = True code: int = 200 @dataclass c...
0.772015
0.191895
from django.test import TestCase from collection_json import Collection from testapp.models import Person try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse class DictionaryTest(TestCase): """tests when the response contains a dictionary""" def test_no_serializ...
testapp/tests/test_renderer_infer.py
from django.test import TestCase from collection_json import Collection from testapp.models import Person try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse class DictionaryTest(TestCase): """tests when the response contains a dictionary""" def test_no_serializ...
0.661048
0.465266
import json from typing import Dict, List import numpy from matplotlib import pyplot as plt from GPErks.constants import HEIGHT, WIDTH class TrainStats: def __init__(self, metrics_names): self.current_epoch: int = 0 self.best_epoch: int = 0 self.train_loss: List[float] = [] self....
GPErks/train/train_stats.py
import json from typing import Dict, List import numpy from matplotlib import pyplot as plt from GPErks.constants import HEIGHT, WIDTH class TrainStats: def __init__(self, metrics_names): self.current_epoch: int = 0 self.best_epoch: int = 0 self.train_loss: List[float] = [] self....
0.761184
0.437403
from buzzblog.gen import TAccountService from buzzblog.base_client import BaseClient class Client(BaseClient): def __init__(self, ip_address, port, timeout=30000, logger=None): super().__init__(TAccountService.Client, ip_address, port, timeout, logger) def authenticate_user(self, request_metadata, username,...
app/wordfilter/service/tests/site-packages/buzzblog/account_client.py
from buzzblog.gen import TAccountService from buzzblog.base_client import BaseClient class Client(BaseClient): def __init__(self, ip_address, port, timeout=30000, logger=None): super().__init__(TAccountService.Client, ip_address, port, timeout, logger) def authenticate_user(self, request_metadata, username,...
0.549641
0.057865
import django_filters from django.db.models import Q from rest_framework_gis.filterset import GeoFilterSet from django_filters.rest_framework import FilterSet from rest_framework_gis.filters import GeometryFilter from vocabs.models import SkosConcept from . models import TempSpatial, Source class SourceListFilter(dj...
shps/filters.py
import django_filters from django.db.models import Q from rest_framework_gis.filterset import GeoFilterSet from django_filters.rest_framework import FilterSet from rest_framework_gis.filters import GeometryFilter from vocabs.models import SkosConcept from . models import TempSpatial, Source class SourceListFilter(dj...
0.556641
0.092115
import sys from typing import TypeVar, Generic, List, Any S = TypeVar('S') # Generic Sequence I = TypeVar('I') # Generic Item class SubSeq(Generic[S]): """ Represents a SubSequence """ def __init__(self): pass class CommonSubSeq(Generic[S], SubSeq[S]): """ Represents a sub-seque...
automergetool/amt_lcs.py
import sys from typing import TypeVar, Generic, List, Any S = TypeVar('S') # Generic Sequence I = TypeVar('I') # Generic Item class SubSeq(Generic[S]): """ Represents a SubSequence """ def __init__(self): pass class CommonSubSeq(Generic[S], SubSeq[S]): """ Represents a sub-seque...
0.7237
0.34762
import datetime import os from subprocess import PIPE, run BUILD_SOURCE_DIR = os.path.join( os.path.dirname(__file__), '../../', 'build/bench') builds = ['build_noopt', 'build_mkl', 'build_blas'] def iter_executables(*executables): for build in builds: if not os.path.exists(os.path.join(BUILD_SOUR...
tools/benchmark/benchmark_util.py
import datetime import os from subprocess import PIPE, run BUILD_SOURCE_DIR = os.path.join( os.path.dirname(__file__), '../../', 'build/bench') builds = ['build_noopt', 'build_mkl', 'build_blas'] def iter_executables(*executables): for build in builds: if not os.path.exists(os.path.join(BUILD_SOUR...
0.222278
0.062217
import tensorflow as tf from stagedml.models.transformer.imports import ( LearningRateScheduler, LearningRateFn, BASE_PARAMS, Subtokenizer, train_input_fn, map_data_for_transformer_fn ) from stagedml.models.transformer.model import ( create_train_model, create_eval_model, create_optimizer ) from typing i...
src/stagedml/models/transformer/data.py
import tensorflow as tf from stagedml.models.transformer.imports import ( LearningRateScheduler, LearningRateFn, BASE_PARAMS, Subtokenizer, train_input_fn, map_data_for_transformer_fn ) from stagedml.models.transformer.model import ( create_train_model, create_eval_model, create_optimizer ) from typing i...
0.725746
0.255971
import os from setuptools import find_packages from pkg_resources import parse_version here = os.path.abspath(os.path.dirname(__file__)) about = {} with open(os.path.join(here, 'camelot', '__version__.py'), 'r') as f: exec(f.read(), about) with open('README.md', 'r') as f: readme = f.read() def setup_pack...
setup.py
import os from setuptools import find_packages from pkg_resources import parse_version here = os.path.abspath(os.path.dirname(__file__)) about = {} with open(os.path.join(here, 'camelot', '__version__.py'), 'r') as f: exec(f.read(), about) with open('README.md', 'r') as f: readme = f.read() def setup_pack...
0.322419
0.061227
import sys import os os.environ['TF_CPP_MIN_LOG_LEVEL']='3' from shutil import rmtree import numpy as np import pandas as pd import configargparse from tqdm import tqdm import ast import h5py import cv2 import time from ct_segnet.model_utils.losses import custom_objects_dict from ct_segnet.data_utils import patch_ma...
bin/run_segmenter.py
import sys import os os.environ['TF_CPP_MIN_LOG_LEVEL']='3' from shutil import rmtree import numpy as np import pandas as pd import configargparse from tqdm import tqdm import ast import h5py import cv2 import time from ct_segnet.model_utils.losses import custom_objects_dict from ct_segnet.data_utils import patch_ma...
0.274254
0.133246
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.MultiCurrencyMoneyOpenApi import MultiCurrencyMoneyOpenApi class AlipayBossFncSettleSettlementbillCancelModel(object): def __init__(self): self._cancel_amount = None self._out_biz_no = None self._...
alipay/aop/api/domain/AlipayBossFncSettleSettlementbillCancelModel.py
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.MultiCurrencyMoneyOpenApi import MultiCurrencyMoneyOpenApi class AlipayBossFncSettleSettlementbillCancelModel(object): def __init__(self): self._cancel_amount = None self._out_biz_no = None self._...
0.535341
0.077797
import logging from .exceptions import Cannot_login from .regex import re_show, re_video, re_lenguage, re_csrf_token from chibi_dl.site.base.site import Site as Site_base logger = logging.getLogger( "chibi_dl.sites.crunchyroll" ) class Site( Site_base ): @property def token( self ): if self.parent:...
chibi_dl/site/crunchyroll/site.py
import logging from .exceptions import Cannot_login from .regex import re_show, re_video, re_lenguage, re_csrf_token from chibi_dl.site.base.site import Site as Site_base logger = logging.getLogger( "chibi_dl.sites.crunchyroll" ) class Site( Site_base ): @property def token( self ): if self.parent:...
0.326701
0.134236
import numpy as np import pandas as pd from pandas import DataFrame, Series, date_range, timedelta_range import pandas._testing as tm class TestTimeSeries: def test_contiguous_boolean_preserve_freq(self): rng = date_range("1/1/2000", "3/1/2000", freq="B") mask = np.zeros(len(rng), dtype=bool) ...
pandas/tests/series/test_timeseries.py
import numpy as np import pandas as pd from pandas import DataFrame, Series, date_range, timedelta_range import pandas._testing as tm class TestTimeSeries: def test_contiguous_boolean_preserve_freq(self): rng = date_range("1/1/2000", "3/1/2000", freq="B") mask = np.zeros(len(rng), dtype=bool) ...
0.717903
0.58945
from __future__ import unicode_literals import time from mock import patch, Mock from nose.tools import raises from boto.cloudfront.exception import CloudFrontServerError from tests import TestCase, with_settings from catsnap import Client from catsnap.table.image import Image from catsnap.table.task_transaction impo...
tests/worker/test_invalidate.py
from __future__ import unicode_literals import time from mock import patch, Mock from nose.tools import raises from boto.cloudfront.exception import CloudFrontServerError from tests import TestCase, with_settings from catsnap import Client from catsnap.table.image import Image from catsnap.table.task_transaction impo...
0.578567
0.124027
from langParser import Parser from executor import Executor from langEnums import * # This class is used to store variables and function class SymbolTable: def __init__(self): self.variableTable = {"true":(Types.Boolean, 1), "false":(Types.Boolean, 0)} self.functionTable = {} self.enableFunctionFeature = False ...
lexer.py
from langParser import Parser from executor import Executor from langEnums import * # This class is used to store variables and function class SymbolTable: def __init__(self): self.variableTable = {"true":(Types.Boolean, 1), "false":(Types.Boolean, 0)} self.functionTable = {} self.enableFunctionFeature = False ...
0.260389
0.203569
import re import json import os import sys import redis import logging import numpy as np from flask import Flask, request from flask_cors import CORS, cross_origin from PIL import Image, ImageEnhance from keras.models import model_from_json from keras.optimizers import RMSprop app = Flask(__name__) cors = CORS(app) ...
src/python/project/prediction_app/prediction.py
import re import json import os import sys import redis import logging import numpy as np from flask import Flask, request from flask_cors import CORS, cross_origin from PIL import Image, ImageEnhance from keras.models import model_from_json from keras.optimizers import RMSprop app = Flask(__name__) cors = CORS(app) ...
0.407687
0.177383
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QGroupBox, QFormLayout, QLabel, QComboBox, QCheckBox class SettingsDialog(QDialog): def __init__(self, settings, controller): super(SettingsDialog, self).__init__() self.settings = settings self.controller = controller ...
GUI/Settings.py
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QGroupBox, QFormLayout, QLabel, QComboBox, QCheckBox class SettingsDialog(QDialog): def __init__(self, settings, controller): super(SettingsDialog, self).__init__() self.settings = settings self.controller = controller ...
0.648021
0.086285
from pathlib import Path from typing import Any import numpy as np import pytest from jina import DocumentSet from jina.drivers.cache import BaseCacheDriver from jina.executors.indexers.cache import DocIDCache from jina.proto import jina_pb2 from jina.types.document import uid from tests import random_docs class Mo...
tests/unit/drivers/test_cache_driver.py
from pathlib import Path from typing import Any import numpy as np import pytest from jina import DocumentSet from jina.drivers.cache import BaseCacheDriver from jina.executors.indexers.cache import DocIDCache from jina.proto import jina_pb2 from jina.types.document import uid from tests import random_docs class Mo...
0.592549
0.397237
import pandas as pd import numpy as np from datetime import datetime, timedelta from os.path import isfile # utilities for extracting prior and post on indicators def extract_indicators(wdi_df, indicator_codes): return wdi_df[wdi_df['Indicator Code'].isin(indicator_codes)] def lag_variable_simple(data, col, num_ye...
notebooks/util/explore.py
import pandas as pd import numpy as np from datetime import datetime, timedelta from os.path import isfile # utilities for extracting prior and post on indicators def extract_indicators(wdi_df, indicator_codes): return wdi_df[wdi_df['Indicator Code'].isin(indicator_codes)] def lag_variable_simple(data, col, num_ye...
0.446736
0.411466
from thrift.Thrift import * from ttypes import * from thrift.Thrift import TProcessor from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None class Iface: def recoverBlock(self, datanode, namespaceId, b...
src/contrib/thriftdatanode/gen-py/hadoopdatanode/ThriftHadoopDatanode.py
from thrift.Thrift import * from ttypes import * from thrift.Thrift import TProcessor from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None class Iface: def recoverBlock(self, datanode, namespaceId, b...
0.658747
0.107954
import csv import pickle import nltk from SWIMMRS.src.TweetClassifier import Tokenizer, FeatureExtraction import re # Read the tweets one by one and process it negtn_regex = re.compile( r"""(?:^(?:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|i...
src/TweetClassifier/Classifier.py
import csv import pickle import nltk from SWIMMRS.src.TweetClassifier import Tokenizer, FeatureExtraction import re # Read the tweets one by one and process it negtn_regex = re.compile( r"""(?:^(?:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|i...
0.098577
0.248283
from plum import Dispatcher, clear_all_cache, Referentiable, Self, List from plum.type import subclasscheck_cache from ..util import benchmark def test_cache_function_call_performance_and_correctness(): # Test performance. dispatch = Dispatcher() def f_native(x): pass @dispatch def f(x):...
tests/dispatcher/test_cache.py
from plum import Dispatcher, clear_all_cache, Referentiable, Self, List from plum.type import subclasscheck_cache from ..util import benchmark def test_cache_function_call_performance_and_correctness(): # Test performance. dispatch = Dispatcher() def f_native(x): pass @dispatch def f(x):...
0.844794
0.520923
import re def check_exception(word): # Checa se a palavra corresponde a uma exceção (artigo, preposição ou conjunção) exceptionsPort = ['o', 'os', 'a', 'as', 'um', 'uns', 'uma', 'umas', 'ao', 'aos', 'à', 'às', 'do', 'dos', 'da', 'das', 'dum', 'duns', 'duma', 'dumas', 'no', 'nos', 'na', 'nas', 'num', 'nuns', 'numa', '...
lattes2bib/utils.py
import re def check_exception(word): # Checa se a palavra corresponde a uma exceção (artigo, preposição ou conjunção) exceptionsPort = ['o', 'os', 'a', 'as', 'um', 'uns', 'uma', 'umas', 'ao', 'aos', 'à', 'às', 'do', 'dos', 'da', 'das', 'dum', 'duns', 'duma', 'dumas', 'no', 'nos', 'na', 'nas', 'num', 'nuns', 'numa', '...
0.200401
0.506591
"""GRPC targets.""" from typing import Any, Callable, Iterable, Optional from absl import logging import tensorflow as tf from load_test.targets import target from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2_grpc class TfServingGrpcWorker: """A worker th...
models/experimental/inference/load_test/targets/grpc_target.py
"""GRPC targets.""" from typing import Any, Callable, Iterable, Optional from absl import logging import tensorflow as tf from load_test.targets import target from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2_grpc class TfServingGrpcWorker: """A worker th...
0.944035
0.210259
import numpy as np import time import tqdm import os from photonpy import Context, GaussianPSFMethods, Estimator, Dataset import photonpy.cpp.spotdetect as spotdetect from photonpy.cpp.calib import GainOffset_Calib from photonpy.cpp.calib import GainOffsetImage_Calib from photonpy.cpp.estim_queue import EstimQueue fro...
photonpy/smlm/process_movie.py
import numpy as np import time import tqdm import os from photonpy import Context, GaussianPSFMethods, Estimator, Dataset import photonpy.cpp.spotdetect as spotdetect from photonpy.cpp.calib import GainOffset_Calib from photonpy.cpp.calib import GainOffsetImage_Calib from photonpy.cpp.estim_queue import EstimQueue fro...
0.413122
0.345712
import os import pwd import sys from socket import socketpair student_user = os.getenv("STUDENT_USER", "tester") # UNIX user to run user code as grader_user = os.getenv("GRADER_USER", "root") # UNIX user to run grader as student_path = os.getenv("PWD", "/submission/user") # Submitted files grader_path = os.getenv("...
graderutils/__main__.py
import os import pwd import sys from socket import socketpair student_user = os.getenv("STUDENT_USER", "tester") # UNIX user to run user code as grader_user = os.getenv("GRADER_USER", "root") # UNIX user to run grader as student_path = os.getenv("PWD", "/submission/user") # Submitted files grader_path = os.getenv("...
0.117332
0.115586
class Interaction(object): """The interaction module for inheritance. User interaction with a Markov chain. Functions: getter and setter for the self._data. getter and setter for the self._chain. """ def __init__(self, name=None, **kwargs): """Creates a new in...
chain/interaction.py
class Interaction(object): """The interaction module for inheritance. User interaction with a Markov chain. Functions: getter and setter for the self._data. getter and setter for the self._chain. """ def __init__(self, name=None, **kwargs): """Creates a new in...
0.909281
0.375735
import numpy as np import matplotlib.pyplot as plt from .riemann_solvers import GenericSolver, newton class PSystemSolver(GenericSolver): """ d_t(u1) - d_x(u2) = 0 d_t(u2) - d_x(p(u1)) = 0 with p(x) = - x^(-gamma) """ def _read_particular_parameters(self, parameters): self.gam...
schema/Dimension1/Euler/exact_solvers/p_system_solver.py
import numpy as np import matplotlib.pyplot as plt from .riemann_solvers import GenericSolver, newton class PSystemSolver(GenericSolver): """ d_t(u1) - d_x(u2) = 0 d_t(u2) - d_x(p(u1)) = 0 with p(x) = - x^(-gamma) """ def _read_particular_parameters(self, parameters): self.gam...
0.575827
0.531635
import decimal import json import uuid from django import forms from django.conf import settings from django.core import exceptions, serializers, validators from django.core.management import call_command from django.db import IntegrityError, connection, models from django.test import TestCase, TransactionTestCase, ov...
tests/fields/test_encrypted.py
import decimal import json import uuid from django import forms from django.conf import settings from django.core import exceptions, serializers, validators from django.core.management import call_command from django.db import IntegrityError, connection, models from django.test import TestCase, TransactionTestCase, ov...
0.633183
0.259204
import argparse import torch import numpy as np import matplotlib.pyplot as plt from pybpl.library import Library from pybpl.model import CharacterModel from pybpl.objects import CharacterType def optimize_type(model, c, lr, nb_iter, eps, show_examples=True): """ Take a character type and optimize its param...
examples/optimize_type.py
import argparse import torch import numpy as np import matplotlib.pyplot as plt from pybpl.library import Library from pybpl.model import CharacterModel from pybpl.objects import CharacterType def optimize_type(model, c, lr, nb_iter, eps, show_examples=True): """ Take a character type and optimize its param...
0.679072
0.615492
import pandas as pd import matplotlib.pyplot as plt import numpy as np import skfuzzy CONSENSUS_THRESHOLD = 64 # example of data reading data = pd.read_excel('./Data/secondRound.xlsx', sheet_name='Survey Round 2 Responses') data = data.drop(columns='Experts') data = data.iloc[:, [not 'Experts confidence' ...
traditional_delphi.py
import pandas as pd import matplotlib.pyplot as plt import numpy as np import skfuzzy CONSENSUS_THRESHOLD = 64 # example of data reading data = pd.read_excel('./Data/secondRound.xlsx', sheet_name='Survey Round 2 Responses') data = data.drop(columns='Experts') data = data.iloc[:, [not 'Experts confidence' ...
0.612078
0.578686
import numpy as np import scipy.sparse as sp from sklearn.utils.fixes import loguniform from sklearn.utils.validation import check_random_state import pytest from cca_zoo.data import generate_covariance_data from cca_zoo.model_selection import GridSearchCV, RandomizedSearchCV from cca_zoo.models import ( rCCA, ...
cca_zoo/test/test_models.py
import numpy as np import scipy.sparse as sp from sklearn.utils.fixes import loguniform from sklearn.utils.validation import check_random_state import pytest from cca_zoo.data import generate_covariance_data from cca_zoo.model_selection import GridSearchCV, RandomizedSearchCV from cca_zoo.models import ( rCCA, ...
0.736874
0.606732
from __future__ import unicode_literals from selenium.common.exceptions import NoSuchElementException from .helpers import SeleniumTestCase class PjaxrNoMatchingIDTest(SeleniumTestCase): def test_no_matching_id_pjaxr_request(self): self.browser_get_reverse('index') self.assert_title('index-titl...
test_app/tests/test_no_matching_id.py
from __future__ import unicode_literals from selenium.common.exceptions import NoSuchElementException from .helpers import SeleniumTestCase class PjaxrNoMatchingIDTest(SeleniumTestCase): def test_no_matching_id_pjaxr_request(self): self.browser_get_reverse('index') self.assert_title('index-titl...
0.627951
0.24201
import os import glob import pprint from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt import getopt import sys import csv def remove_characters(value=str, deletechars=str) -> str: """ Removes the given characters from the given string. Parameters: ----------- value: str ...
lyric-analysis.py
import os import glob import pprint from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt import getopt import sys import csv def remove_characters(value=str, deletechars=str) -> str: """ Removes the given characters from the given string. Parameters: ----------- value: str ...
0.301979
0.222637
import tensorflow as tf import numpy as np from ... import is_best_practice from .layers import conv_block from . import TFModel class UNet(TFModel): """ UNet **Configuration** inputs : dict dict with 'images' and 'masks' (see :meth:`._make_inputs`) body : dict num_blocks : int ...
dataset/models/tf/unet.py
import tensorflow as tf import numpy as np from ... import is_best_practice from .layers import conv_block from . import TFModel class UNet(TFModel): """ UNet **Configuration** inputs : dict dict with 'images' and 'masks' (see :meth:`._make_inputs`) body : dict num_blocks : int ...
0.941405
0.3398
#!/usr/bin/python import optparse, os, shutil, sys, tempfile, glob, shlex, vcf, pysam, tarfile from subprocess import * import subprocess CHUNK_SIZE = 2**20 #1mb def cleanup_before_exit( tmp_dir ): if tmp_dir and os.path.exists( tmp_dir ): shutil.rmtree( tmp_dir ) def __main__(): parser = optparse....
tools/trena/makeTRN_wrapper.py
#!/usr/bin/python import optparse, os, shutil, sys, tempfile, glob, shlex, vcf, pysam, tarfile from subprocess import * import subprocess CHUNK_SIZE = 2**20 #1mb def cleanup_before_exit( tmp_dir ): if tmp_dir and os.path.exists( tmp_dir ): shutil.rmtree( tmp_dir ) def __main__(): parser = optparse....
0.111919
0.067948
from sqlalchemy import func from src import constants as const from src.db_connection import Session from src.modules.user.user_model import User logger = const.logger def user_exists(discord_id): """ Checks if a user exists by id :param discord_id: Discord id :return: Boolean """ session = ...
src/modules/user/user_util.py
from sqlalchemy import func from src import constants as const from src.db_connection import Session from src.modules.user.user_model import User logger = const.logger def user_exists(discord_id): """ Checks if a user exists by id :param discord_id: Discord id :return: Boolean """ session = ...
0.671794
0.182134
from homeassistant.const import TEMP_CELSIUS from . import KNOWN_DEVICES, HomeKitEntity DEPENDENCIES = ['homekit_controller'] HUMIDITY_ICON = 'mdi-water-percent' TEMP_C_ICON = "mdi-temperature-celsius" BRIGHTNESS_ICON = "mdi-brightness-6" UNIT_PERCENT = "%" UNIT_LUX = "lux" def setup_platform(hass, config, add_en...
homeassistant/components/homekit_controller/sensor.py
from homeassistant.const import TEMP_CELSIUS from . import KNOWN_DEVICES, HomeKitEntity DEPENDENCIES = ['homekit_controller'] HUMIDITY_ICON = 'mdi-water-percent' TEMP_C_ICON = "mdi-temperature-celsius" BRIGHTNESS_ICON = "mdi-brightness-6" UNIT_PERCENT = "%" UNIT_LUX = "lux" def setup_platform(hass, config, add_en...
0.826187
0.191517
from __future__ import absolute_import, print_function import argparse import csv import codecs import os import requests from .csv import CSVDialect from .files import files_lookup from .digiposte import create_account, upload_diploma, get_student_url DIGIPOSTE_BASE_URL = "https://api.digiposte.fr/api/v3" # No trai...
imt_digiposte_woleet/__main__.py
from __future__ import absolute_import, print_function import argparse import csv import codecs import os import requests from .csv import CSVDialect from .files import files_lookup from .digiposte import create_account, upload_diploma, get_student_url DIGIPOSTE_BASE_URL = "https://api.digiposte.fr/api/v3" # No trai...
0.342352
0.067209
from tqdm import tqdm import nibabel as nib from pathlib import Path from visualize import case_plt from trainer import predict_case, cascade_predict_case, cascade_predict, evaluate_case, \ batch_evaluate, batch_cascade_predict from data import CaseDataset, save_pred, save_case from network import ResUnet3D, ResAtt...
nb_post_iib.py
from tqdm import tqdm import nibabel as nib from pathlib import Path from visualize import case_plt from trainer import predict_case, cascade_predict_case, cascade_predict, evaluate_case, \ batch_evaluate, batch_cascade_predict from data import CaseDataset, save_pred, save_case from network import ResUnet3D, ResAtt...
0.399109
0.201401
import pprint import re # noqa: F401 import six class CharityOrg(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the val...
src/ebay_rest/api/commerce_charity/models/charity_org.py
import pprint import re # noqa: F401 import six class CharityOrg(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the val...
0.541409
0.100348
import os.path from enum import Enum import numpy as np import pytest from numerous.engine.simulation import Simulation from numerous.engine.system import Subsystem, Item from numerous.engine.model import Model from tests.test_equations import TestEq_input, Test_Eq, TestEq_ground class SolverType(Enum): SOLVER_...
tests/test_caching_model.py
import os.path from enum import Enum import numpy as np import pytest from numerous.engine.simulation import Simulation from numerous.engine.system import Subsystem, Item from numerous.engine.model import Model from tests.test_equations import TestEq_input, Test_Eq, TestEq_ground class SolverType(Enum): SOLVER_...
0.466359
0.362602
from manim import * class GraphAreaPlot(Scene): def construct(self): ax = Axes( x_range=[0, 10, 1], y_range=[-1,1,1], y_length = 1, axis_config={"include_tip": False} ) labels = ax.get_axis_labels(x_label="Weight", y_label="") # sel...
rough.py
from manim import * class GraphAreaPlot(Scene): def construct(self): ax = Axes( x_range=[0, 10, 1], y_range=[-1,1,1], y_length = 1, axis_config={"include_tip": False} ) labels = ax.get_axis_labels(x_label="Weight", y_label="") # sel...
0.724675
0.505188
import pytest from conftest import quoted_object, run_setup_sql from pgbedrock import ownerships as own from pgbedrock import attributes, privileges from pgbedrock.context import ObjectInfo Q_CREATE_SEQUENCE = 'SET ROLE {}; CREATE SEQUENCE {}.{}; RESET ROLE;' Q_SCHEMA_EXISTS = "SELECT schema_name FROM information_sch...
tests/test_ownerships.py
import pytest from conftest import quoted_object, run_setup_sql from pgbedrock import ownerships as own from pgbedrock import attributes, privileges from pgbedrock.context import ObjectInfo Q_CREATE_SEQUENCE = 'SET ROLE {}; CREATE SEQUENCE {}.{}; RESET ROLE;' Q_SCHEMA_EXISTS = "SELECT schema_name FROM information_sch...
0.449634
0.302378
import pytest import torch from mmflow.models.decoders.maskflownet_decoder import (BasicDeformWarpBlock, DeformWarpBlock, MaskFlowNetSDecoder, MaskModu...
tests/test_models/test_decoder/test_maskflownets_decoder.py
import pytest import torch from mmflow.models.decoders.maskflownet_decoder import (BasicDeformWarpBlock, DeformWarpBlock, MaskFlowNetSDecoder, MaskModu...
0.838944
0.625753
import os from azlmbr.entity import EntityId from azlmbr.math import Vector3 from editor_python_test_tools.editor_entity_utils import EditorEntity from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import azlmbr.bus as bus import azlmbr.components as comp...
AutomatedTesting/Gem/PythonTests/prefab/Prefab_Test_Utils.py
import os from azlmbr.entity import EntityId from azlmbr.math import Vector3 from editor_python_test_tools.editor_entity_utils import EditorEntity from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import azlmbr.bus as bus import azlmbr.components as comp...
0.466116
0.190573
import tensorflow as tf import numpy as np import math def roi_rotate_quad(featuremap, quadboxes, shape, input_shape): """ :param featuremap: (B, H, W, C) :param quadboxes: (B, N, 8) :param shape: (new_h, new_w) :param input_shape: (B, H, W, C) :return: cropped feature (BN, new_h, new_w, C) ...
roi_rotate.py
import tensorflow as tf import numpy as np import math def roi_rotate_quad(featuremap, quadboxes, shape, input_shape): """ :param featuremap: (B, H, W, C) :param quadboxes: (B, N, 8) :param shape: (new_h, new_w) :param input_shape: (B, H, W, C) :return: cropped feature (BN, new_h, new_w, C) ...
0.779112
0.576959
import numpy as np from pyuvsim import AnalyticBeam from numpy.polynomial.chebyshev import chebval from . import utils def stokes_matrix(pol_index): """ Calculate Pauli matrices for pseudo-Stokes conversion. Source code adapted from `pyuvdata`. Derived from https://arxiv.org/pdf/1401.2095.pdf, the P...
hera_sim/beams.py
import numpy as np from pyuvsim import AnalyticBeam from numpy.polynomial.chebyshev import chebval from . import utils def stokes_matrix(pol_index): """ Calculate Pauli matrices for pseudo-Stokes conversion. Source code adapted from `pyuvdata`. Derived from https://arxiv.org/pdf/1401.2095.pdf, the P...
0.949365
0.923558
from typing import List, Optional, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def beta_bernoulli(length: int, alpha: float, beta: float) -> torch.Tensor: """Compute beta bernoulli distribution. Args: length: K, total length. alpha, beta: beta-b...
tacospawn/taco/misc.py
from typing import List, Optional, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def beta_bernoulli(length: int, alpha: float, beta: float) -> torch.Tensor: """Compute beta bernoulli distribution. Args: length: K, total length. alpha, beta: beta-b...
0.976106
0.698304
from __future__ import absolute_import, division, print_function import argparse import os import glob import numpy as np from fastespy.readpydata import readgraphpy from fastespy.analysis import periodogram, hist_norm from scipy.stats import norm import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt ...
fastespy/scripts/plot_periodogram_histogram.py
from __future__ import absolute_import, division, print_function import argparse import os import glob import numpy as np from fastespy.readpydata import readgraphpy from fastespy.analysis import periodogram, hist_norm from scipy.stats import norm import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt ...
0.608478
0.363958
import numpy as np import wavio import librosa import wave from scipy import signal from scipy import fromstring, int16 from scipy import fftpack from PyEMD import EMD def window_(x_2d, window): """ inputs: x_2d : inputs (2D array) window : string, float, or tuple The t...
prowav/utils.py
import numpy as np import wavio import librosa import wave from scipy import signal from scipy import fromstring, int16 from scipy import fftpack from PyEMD import EMD def window_(x_2d, window): """ inputs: x_2d : inputs (2D array) window : string, float, or tuple The t...
0.672117
0.51812
import argparse # Parameters parser = argparse.ArgumentParser(description='Catcher') parser.add_argument('--grid', dest='grid', type=int, default=11, help='Game grid size.') parser.add_argument('--hidden', dest='hidden', type=int, default=100, help='Number of neuron in the hidden layer.') parser.add_argument('--memory...
examples/catcher.py
import argparse # Parameters parser = argparse.ArgumentParser(description='Catcher') parser.add_argument('--grid', dest='grid', type=int, default=11, help='Game grid size.') parser.add_argument('--hidden', dest='hidden', type=int, default=100, help='Number of neuron in the hidden layer.') parser.add_argument('--memory...
0.794863
0.117016
from tile import Tile class Map(object): def __init__(self, tile_size_x=20, tile_size_y=20): # creates an empty nested list of tiles self.tile_size_x = tile_size_x self.tile_size_y = tile_size_y self.tile_list = ([[Tile(x,y) for x in xrange(tile_size_y)] ...
The Coding Dead/game/map.py
from tile import Tile class Map(object): def __init__(self, tile_size_x=20, tile_size_y=20): # creates an empty nested list of tiles self.tile_size_x = tile_size_x self.tile_size_y = tile_size_y self.tile_list = ([[Tile(x,y) for x in xrange(tile_size_y)] ...
0.399694
0.330471
from marshal import loads, dumps from operator import attrgetter, getitem from typing import Any, Type, List, Dict, Optional, Union, Sequence, Callable from dataclasses import is_dataclass, MISSING from .common import Serializer, T, K, AbstractFactory from .fields import get_dataclass_fields, FieldInfo, get_typeddict...
dataclass_factory/serializers.py
from marshal import loads, dumps from operator import attrgetter, getitem from typing import Any, Type, List, Dict, Optional, Union, Sequence, Callable from dataclasses import is_dataclass, MISSING from .common import Serializer, T, K, AbstractFactory from .fields import get_dataclass_fields, FieldInfo, get_typeddict...
0.752013
0.155046
from time import sleep from errors.codes import ERROR_DESC_T from ccutils.databases.configuration import DBConfigurator from network.manager.networkManager import NetworkManager from clusterServer.callbacks.clusterEndpointCallback import ClusterEndpointCallback from clusterServer.callbacks.imageRepositoryCallback impor...
src/Infraestructura/clusterServer/mainReactor/clusterServerMainReactor.py
from time import sleep from errors.codes import ERROR_DESC_T from ccutils.databases.configuration import DBConfigurator from network.manager.networkManager import NetworkManager from clusterServer.callbacks.clusterEndpointCallback import ClusterEndpointCallback from clusterServer.callbacks.imageRepositoryCallback impor...
0.608245
0.053874
import torch import torch.nn as nn import torchvision.datasets as dsets import torchvision.transforms as transforms # hyper parameters input_size = 784 hidden_size = 500 num_classes = 10 num_epochs = 10 batch_size = 100 lr = 0.001 # MNIST dataset train_dataset = dsets.MNIST(root='./data', ...
mnist_fc.py
import torch import torch.nn as nn import torchvision.datasets as dsets import torchvision.transforms as transforms # hyper parameters input_size = 784 hidden_size = 500 num_classes = 10 num_epochs = 10 batch_size = 100 lr = 0.001 # MNIST dataset train_dataset = dsets.MNIST(root='./data', ...
0.910811
0.658294
"""SQuAD 1.1 BERT data loader.""" import os import pickle import tempfile from typing import Any, Mapping from urllib import request from absl import logging import tensorflow as tf from transformers import BertTokenizer from load_test.data import data_loader from official.nlp.data import squad_lib class SquadBertL...
models/experimental/inference/load_test/data/squad_bert.py
"""SQuAD 1.1 BERT data loader.""" import os import pickle import tempfile from typing import Any, Mapping from urllib import request from absl import logging import tensorflow as tf from transformers import BertTokenizer from load_test.data import data_loader from official.nlp.data import squad_lib class SquadBertL...
0.746509
0.29733
from cros.factory.device import accelerometer from cros.factory.device import device_utils from cros.factory.test.i18n import _ from cros.factory.test import test_case from cros.factory.test import test_ui from cros.factory.utils.arg_utils import Arg from cros.factory.utils import type_utils class AccelerometersCalib...
py/test/pytests/accelerometers_calibration.py
from cros.factory.device import accelerometer from cros.factory.device import device_utils from cros.factory.test.i18n import _ from cros.factory.test import test_case from cros.factory.test import test_ui from cros.factory.utils.arg_utils import Arg from cros.factory.utils import type_utils class AccelerometersCalib...
0.536313
0.333368