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 io from future.utils import itervalues from mock import patch from snips_nlu.constants import ( RES_ENTITY, RES_INTENT, RES_INTENT_NAME, RES_SLOTS, RES_VALUE, RANDOM_STATE) from snips_nlu.dataset import Dataset from snips_nlu.exceptions import IntentNotFoundErro...
snips_nlu/tests/test_probabilistic_intent_parser.py
from __future__ import unicode_literals import io from future.utils import itervalues from mock import patch from snips_nlu.constants import ( RES_ENTITY, RES_INTENT, RES_INTENT_NAME, RES_SLOTS, RES_VALUE, RANDOM_STATE) from snips_nlu.dataset import Dataset from snips_nlu.exceptions import IntentNotFoundErro...
0.631481
0.352536
# using unfinished example classes # pylint: disable=too-few-public-methods import copy import pickle # category: copy def copy_method(): """copy.copy(obj): Copy the content of an item.""" class _Copyable: def __init__(self, value): self.value = value def __copy__(self): ...
pyhow/samples/impl/serializables.py
# using unfinished example classes # pylint: disable=too-few-public-methods import copy import pickle # category: copy def copy_method(): """copy.copy(obj): Copy the content of an item.""" class _Copyable: def __init__(self, value): self.value = value def __copy__(self): ...
0.789234
0.308047
import os from mkultra.soft_prompt import SoftPrompt import torch import json def test_json(inference_resources): model, tokenizer = inference_resources # Arrange sp_a = SoftPrompt.from_string(" a b c d e f g", model=model, tokenizer=tokenizer) # Act sp_str = sp_a.to_json() sp_b = SoftPrompt....
mkultra/tests/io_test.py
import os from mkultra.soft_prompt import SoftPrompt import torch import json def test_json(inference_resources): model, tokenizer = inference_resources # Arrange sp_a = SoftPrompt.from_string(" a b c d e f g", model=model, tokenizer=tokenizer) # Act sp_str = sp_a.to_json() sp_b = SoftPrompt....
0.64969
0.345078
import pickle import cv2 as cv from mine_topological_map.graph import Graph, Node import numpy as np import networkx import math from torch import save import os # mouse callback function cv.destroyAllWindows() COLORS = {"none": (100, 85, 82), "background": (143, 130, 116), "base_node_color": (20...
mine_topological_map/mine_topological_map/drawing.py
import pickle import cv2 as cv from mine_topological_map.graph import Graph, Node import numpy as np import networkx import math from torch import save import os # mouse callback function cv.destroyAllWindows() COLORS = {"none": (100, 85, 82), "background": (143, 130, 116), "base_node_color": (20...
0.452536
0.203075
import json from alipay.aop.api.constant.ParamConstants import * class GfacConsolidationEntryLineDTO(object): def __init__(self): self._biz_bill_nos_map = None self._biz_elements = None self._direction = None self._is_fa_entry = None self._is_ma_entry = None self....
alipay/aop/api/domain/GfacConsolidationEntryLineDTO.py
import json from alipay.aop.api.constant.ParamConstants import * class GfacConsolidationEntryLineDTO(object): def __init__(self): self._biz_bill_nos_map = None self._biz_elements = None self._direction = None self._is_fa_entry = None self._is_ma_entry = None self....
0.454109
0.13612
__requires__ = ['SQLAlchemy >= 0.7'] import pkg_resources import unittest import subprocess import sys import os sys.path.insert(0, os.path.join(os.path.dirname( os.path.abspath(__file__)), '..')) import mirrormanager2.lib import tests FOLDER = os.path.dirname(os.path.abspath(__file__)) CONFIG = """ DB_URL =...
tests/test_umdl.py
__requires__ = ['SQLAlchemy >= 0.7'] import pkg_resources import unittest import subprocess import sys import os sys.path.insert(0, os.path.join(os.path.dirname( os.path.abspath(__file__)), '..')) import mirrormanager2.lib import tests FOLDER = os.path.dirname(os.path.abspath(__file__)) CONFIG = """ DB_URL =...
0.345768
0.232267
from pypal import private_globals as _pal import ctypes as c import weakref from bodybase import BodyBase class Body(BodyBase): def set_position(self, pos, rot=(0, 0, 0)): """ Sets the position of the body and its orientation. Parameters: pos: ``float[3]`` The x, y, z, position of...
pypal/body/body.py
from pypal import private_globals as _pal import ctypes as c import weakref from bodybase import BodyBase class Body(BodyBase): def set_position(self, pos, rot=(0, 0, 0)): """ Sets the position of the body and its orientation. Parameters: pos: ``float[3]`` The x, y, z, position of...
0.87035
0.609495
import base64 import logging import pickle import psycopg2.extensions import select import time from django import db from django.db import connection from django.db import models from satori.core.dbev.events import registry from satori.events import Event from satori.core.models import Entity def row_to_dict(cursor,...
satori.core/satori/core/dbev/notifier.py
import base64 import logging import pickle import psycopg2.extensions import select import time from django import db from django.db import connection from django.db import models from satori.core.dbev.events import registry from satori.events import Event from satori.core.models import Entity def row_to_dict(cursor,...
0.233095
0.088544
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- # TEST ...
sdk/attestation/azure-security-attestation/tests/test_policy_getset_async.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- # TEST ...
0.855429
0.254519
import datetime import time from urllib import urlencode from django.core.cache import cache from django.db.models import Count, Q from django.shortcuts import render_to_response from django.template import RequestContext from thing.models import ServerStatus def render_page(template, data, request, character_ids=...
thing/stuff.py
import datetime import time from urllib import urlencode from django.core.cache import cache from django.db.models import Count, Q from django.shortcuts import render_to_response from django.template import RequestContext from thing.models import ServerStatus def render_page(template, data, request, character_ids=...
0.416203
0.127761
import warnings from collections.abc import Iterable from itertools import chain import torch from torch.utils.data import DataLoader, Dataset def parse_init_arg(arg): if isinstance(arg, Dataset): data, labels = next(iter(DataLoader(arg, batch_size=len(arg)))) # data = data.view(len(arg), -1) # ...
prototorch/components/initializers.py
import warnings from collections.abc import Iterable from itertools import chain import torch from torch.utils.data import DataLoader, Dataset def parse_init_arg(arg): if isinstance(arg, Dataset): data, labels = next(iter(DataLoader(arg, batch_size=len(arg)))) # data = data.view(len(arg), -1) # ...
0.825308
0.407982
# Standard library import sys import json # 3rd party packages # Local source from parametrization_clean.infrastructure.config.default import DefaultSettings from parametrization_clean.infrastructure.exception.exception import ConfigurationError # Note: the following imports are required so that python can use the re...
parametrization_clean/infrastructure/config/local.py
# Standard library import sys import json # 3rd party packages # Local source from parametrization_clean.infrastructure.config.default import DefaultSettings from parametrization_clean.infrastructure.exception.exception import ConfigurationError # Note: the following imports are required so that python can use the re...
0.370567
0.117826
import asyncio import serial from . import AbstractAsyncWrapper class Serial(AbstractAsyncWrapper): """ asyncserial is a simple wrapper for the pyserial library to provide async functionality. It is transparent to the pyserial interface and supports all parameters. You can e.g. create a connection b...
asyncserial/async_serial_wrapper.py
import asyncio import serial from . import AbstractAsyncWrapper class Serial(AbstractAsyncWrapper): """ asyncserial is a simple wrapper for the pyserial library to provide async functionality. It is transparent to the pyserial interface and supports all parameters. You can e.g. create a connection b...
0.704668
0.173393
import sys import logging import os import cv2 from utils import write_image, key_action, init_cam from models.transferred_model import predict_class from datetime import datetime if __name__ == "__main__": # folder to write images to out_folder = sys.argv[1] # maybe you need this os.environ['KMP_D...
imageclassifier/capture.py
import sys import logging import os import cv2 from utils import write_image, key_action, init_cam from models.transferred_model import predict_class from datetime import datetime if __name__ == "__main__": # folder to write images to out_folder = sys.argv[1] # maybe you need this os.environ['KMP_D...
0.231701
0.138113
from userbot import bot from sys import argv import sys from telethon.errors.rpcerrorlist import PhoneNumberInvalidError import os from telethon import TelegramClient from var import Var from userbot.Config import Config from telethon.tl.functions.channels import InviteToChannelRequest, JoinChannelRequest from userbot....
Pythonbot/__main__.py
from userbot import bot from sys import argv import sys from telethon.errors.rpcerrorlist import PhoneNumberInvalidError import os from telethon import TelegramClient from var import Var from userbot.Config import Config from telethon.tl.functions.channels import InviteToChannelRequest, JoinChannelRequest from userbot....
0.192577
0.075414
import numpy as np import cv2 import matplotlib.pyplot as plt def of_tracing(video_filename, pts, frame_range=(0,10000), displaying=False, out_folder=None): result = list() result.append(pts) cap = cv2.VideoCapture(video_filename) # params for ShiTomasi corner detection feature_params = dict(maxC...
optical_flow_tracing.py
import numpy as np import cv2 import matplotlib.pyplot as plt def of_tracing(video_filename, pts, frame_range=(0,10000), displaying=False, out_folder=None): result = list() result.append(pts) cap = cv2.VideoCapture(video_filename) # params for ShiTomasi corner detection feature_params = dict(maxC...
0.445047
0.367327
import os import sys from bin.color import bcolor class CommandLine: def __init__(self, option_info_list): """Configure and parse the command line options. Args: option_info_list (list): A list of parameters to configure. option_info_list.item (String): An information stri...
bin/commandline.py
import os import sys from bin.color import bcolor class CommandLine: def __init__(self, option_info_list): """Configure and parse the command line options. Args: option_info_list (list): A list of parameters to configure. option_info_list.item (String): An information stri...
0.533154
0.166641
import traceback from datetime import datetime, date from time import mktime from struct import unpack as unpack, error as unpack_error import ctypes """ Issues: 1. Too many files opened. Variable contract is equal to message sequence #. In this case we have got an error "Too many files opened" because Exchange open a...
batsmc/parser.py
import traceback from datetime import datetime, date from time import mktime from struct import unpack as unpack, error as unpack_error import ctypes """ Issues: 1. Too many files opened. Variable contract is equal to message sequence #. In this case we have got an error "Too many files opened" because Exchange open a...
0.31258
0.234982
from openpyxl import Workbook, load_workbook from halo import Halo import time from datetime import date, timedelta, datetime from copy import copy class XCel: def __init__(self, config): p1 = time.time() self.config = config spin = Halo(text="Opening template file: {0}".format(self.config['...
xcel.py
from openpyxl import Workbook, load_workbook from halo import Halo import time from datetime import date, timedelta, datetime from copy import copy class XCel: def __init__(self, config): p1 = time.time() self.config = config spin = Halo(text="Opening template file: {0}".format(self.config['...
0.335133
0.205974
from ctypes import * import os import sys import platform import inspect import subprocess import ctypes import ctypes.util def UNCHECKED(type): if (hasattr(type, "_type_") and isinstance(type._type_, str) and type._type_ != "P"): return type else: return c_void_p def is_os_64bit...
cryptlex/lexfloatclient/lexfloatclient_native.py
from ctypes import * import os import sys import platform import inspect import subprocess import ctypes import ctypes.util def UNCHECKED(type): if (hasattr(type, "_type_") and isinstance(type._type_, str) and type._type_ != "P"): return type else: return c_void_p def is_os_64bit...
0.209227
0.072407
from __future__ import print_function from __future__ import absolute_import from __future__ import division import Eto.Drawing as drawing import Eto.Forms as forms import Rhino.UI import json import os import importlib import sys HERE = os.path.dirname(__file__) UI_FOLDER = os.path.join(HERE, "..", "..", "ui/Rhino...
src/compas_rv2/rhino/forms/menu.py
from __future__ import print_function from __future__ import absolute_import from __future__ import division import Eto.Drawing as drawing import Eto.Forms as forms import Rhino.UI import json import os import importlib import sys HERE = os.path.dirname(__file__) UI_FOLDER = os.path.join(HERE, "..", "..", "ui/Rhino...
0.320502
0.04653
from django import template from django.template import Library, Node, Variable, loader from django_recurly.utils import recurly from django_recurly.models import Account from django_recurly.helpers.recurlyjs import get_config, get_subscription_form, get_billing_info_update_form register = template.Library() @regi...
django_recurly/templatetags/recurly_js.py
from django import template from django.template import Library, Node, Variable, loader from django_recurly.utils import recurly from django_recurly.models import Account from django_recurly.helpers.recurlyjs import get_config, get_subscription_form, get_billing_info_update_form register = template.Library() @regi...
0.264643
0.129871
import os, glob import pandas as pd ########### READ IN DATA ########### filesFolder = outputPath = features2removeFile = classifierName = filesFound = glob.glob(filesFolder + '/*.csv') counter = 0 concatDf = pd.DataFrame() features2remove = pd.read_csv(features2removeFile) features2removeList = list(f...
misc/1_UMAP_create_data_set_collapsed_091020.py
import os, glob import pandas as pd ########### READ IN DATA ########### filesFolder = outputPath = features2removeFile = classifierName = filesFound = glob.glob(filesFolder + '/*.csv') counter = 0 concatDf = pd.DataFrame() features2remove = pd.read_csv(features2removeFile) features2removeList = list(f...
0.08388
0.124213
import platform import sys import time from pyhutool.gui.Const import _const if sys.platform == 'darwin': from . import Osx as _platformModule elif sys.platform == 'win32': from . import Win as _platformModule elif platform.system() == 'Linux': from . import X11 as _platformModule else: raise NotImplem...
pyhutool/gui/Mouse.py
import platform import sys import time from pyhutool.gui.Const import _const if sys.platform == 'darwin': from . import Osx as _platformModule elif sys.platform == 'win32': from . import Win as _platformModule elif platform.system() == 'Linux': from . import X11 as _platformModule else: raise NotImplem...
0.339171
0.222489
from par import * import matplotlib.pyplot as plt for dset in ['W','C']: D = read2Ddataset(nrad, N2, lambda i,j: fn(i,j) + dset + '.txt') plt.figure(figsize = (12,8)) plt.subplot(231) plt.title(u'$\\tau_{\\rm es}$ of the corona') plt.pcolor(radii, etas, DPA(D,'taues_tmin').transpose(), cmap = 'CM...
sketches/maps2d-1/plot.py
from par import * import matplotlib.pyplot as plt for dset in ['W','C']: D = read2Ddataset(nrad, N2, lambda i,j: fn(i,j) + dset + '.txt') plt.figure(figsize = (12,8)) plt.subplot(231) plt.title(u'$\\tau_{\\rm es}$ of the corona') plt.pcolor(radii, etas, DPA(D,'taues_tmin').transpose(), cmap = 'CM...
0.542621
0.673306
import abc import time from time import sleep from threading import Thread, Condition, Lock import thread from Queue import Queue, Empty import zmq from quantity.digger.util import mlogger as log from quantity.digger.event import Event class Timer(object): """ 定时器,会定时往事件队列中发送定时事件。 """ def __init__(self, e...
quantity/digger/event/eventengine.py
import abc import time from time import sleep from threading import Thread, Condition, Lock import thread from Queue import Queue, Empty import zmq from quantity.digger.util import mlogger as log from quantity.digger.event import Event class Timer(object): """ 定时器,会定时往事件队列中发送定时事件。 """ def __init__(self, e...
0.238816
0.069007
from control import * import numpy as np from lmfit import Model import inspect def convert_magnitude_phase_to_complex (mag, phase_deg): """ Parameters ---------- mag: numpy array or object convertable using numpy.array(object) Contains gain magnitude data corresponding to a specific frequency...
bode_fit.py
from control import * import numpy as np from lmfit import Model import inspect def convert_magnitude_phase_to_complex (mag, phase_deg): """ Parameters ---------- mag: numpy array or object convertable using numpy.array(object) Contains gain magnitude data corresponding to a specific frequency...
0.918813
0.667588
import json as json import logging import xbmc import xbmcaddon import xbmcgui # read settings ADDON = xbmcaddon.Addon() logger = logging.getLogger(__name__) ADDON_ID = ADDON.getAddonInfo("id") MEDIA_URI = "special://home/addons/{}/resources/media/".format(ADDON_ID) def art(image): return { "thumb": i...
resources/lib/kodiutils.py
import json as json import logging import xbmc import xbmcaddon import xbmcgui # read settings ADDON = xbmcaddon.Addon() logger = logging.getLogger(__name__) ADDON_ID = ADDON.getAddonInfo("id") MEDIA_URI = "special://home/addons/{}/resources/media/".format(ADDON_ID) def art(image): return { "thumb": i...
0.399226
0.076996
import functools import string import typing as t from mypy.errorcodes import ErrorCode from mypy.nodes import ( Expression, FuncDef, LambdaExpr, NameExpr, RefExpr, StrExpr, ) from mypy.options import Options from mypy.plugin import ( MethodContext, Plugin, ) from mypy.types import ( ...
loguru_mypy/__init__.py
import functools import string import typing as t from mypy.errorcodes import ErrorCode from mypy.nodes import ( Expression, FuncDef, LambdaExpr, NameExpr, RefExpr, StrExpr, ) from mypy.options import Options from mypy.plugin import ( MethodContext, Plugin, ) from mypy.types import ( ...
0.473901
0.126461
import numpy as np from typing import Optional, Callable import pandas as pd from statsmodels.stats.weightstats import DescrStatsW from fastcore.all import store_attr from ...utils.statistics import bootstrap_stats from .eval_metric import EvalMetric, OldEvalMetric from ..data.fold_yielder import FoldYielder __all__ ...
lumin/nn/metrics/reg_eval.py
import numpy as np from typing import Optional, Callable import pandas as pd from statsmodels.stats.weightstats import DescrStatsW from fastcore.all import store_attr from ...utils.statistics import bootstrap_stats from .eval_metric import EvalMetric, OldEvalMetric from ..data.fold_yielder import FoldYielder __all__ ...
0.835349
0.423935
import os import json def store_h2o_frame(data, directory, filename, force=False, parts=1): """ Export a given H2OFrame to a path on the machine this python session is currently connected to. :param data: the Frame to save to disk. :param directory: the directory to the save point on disk. :param ...
mercury_ml/common/providers/artifact_storage/local.py
import os import json def store_h2o_frame(data, directory, filename, force=False, parts=1): """ Export a given H2OFrame to a path on the machine this python session is currently connected to. :param data: the Frame to save to disk. :param directory: the directory to the save point on disk. :param ...
0.693161
0.61607
import os from ament_index_python.packages import get_package_prefix from ament_index_python.packages import get_package_share_directory from launch.conditions import IfCondition import launch.actions import launch_ros.actions from nav2_common.launch import RewrittenYaml def generate_launch_description(): # G...
launch/nav2_bringup_launch.py
import os from ament_index_python.packages import get_package_prefix from ament_index_python.packages import get_package_share_directory from launch.conditions import IfCondition import launch.actions import launch_ros.actions from nav2_common.launch import RewrittenYaml def generate_launch_description(): # G...
0.465387
0.176885
import time import logging import adjtimex # freq is ppm (parts per million) with a 16-bit fractional part (2^-16 ppm) SEC_TO_FREQ = 65536000000 # Max offset in seconds before making a step. MAX_OFFSET = 0.5 # Maximum offset to enter sync state SYNC_OFFSET = 0.005 class PyPLL(object): """ PyPLL T...
pypll.py
import time import logging import adjtimex # freq is ppm (parts per million) with a 16-bit fractional part (2^-16 ppm) SEC_TO_FREQ = 65536000000 # Max offset in seconds before making a step. MAX_OFFSET = 0.5 # Maximum offset to enter sync state SYNC_OFFSET = 0.005 class PyPLL(object): """ PyPLL T...
0.741861
0.481941
from . import number_patterns as npa from . import tuple_rules as tp ordinal_big_tuples = [(npa.ones_ptrn_no11 + "1\.000\.0([01][1-9]|10)\.$", '.*', 'millions', ' einmilljónasta og'), ("^1\.000\.0([01][1-9]|10)\.$", '.*', 'millions',' milljónasta og'), (npa.ones_ptrn_no11 + "1\.000\.000\.$", '.*', 'millions', ...
regina_normalizer/ordinal_big_tuples.py
from . import number_patterns as npa from . import tuple_rules as tp ordinal_big_tuples = [(npa.ones_ptrn_no11 + "1\.000\.0([01][1-9]|10)\.$", '.*', 'millions', ' einmilljónasta og'), ("^1\.000\.0([01][1-9]|10)\.$", '.*', 'millions',' milljónasta og'), (npa.ones_ptrn_no11 + "1\.000\.000\.$", '.*', 'millions', ...
0.141905
0.246874
import cv2 from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console # DANGER! This is insecure. See http://twil.io/secure account_sid = 'AC9ff3f227c0a9de0606351f3656ee2274' auth_token = '<PASSWORD>' client = Client(account_sid, auth_token) face_cascade=cv2.CascadeClassifier("haarcasca...
camera.py
import cv2 from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console # DANGER! This is insecure. See http://twil.io/secure account_sid = 'AC9ff3f227c0a9de0606351f3656ee2274' auth_token = '<PASSWORD>' client = Client(account_sid, auth_token) face_cascade=cv2.CascadeClassifier("haarcasca...
0.358353
0.148541
import ure as re import ujson as json import usocket as socket from ucollections import namedtuple from .protocol import * from .transport import SocketIO URL_RE = re.compile(r'http://([A-Za-z0-9\-\.]+)(?:\:([0-9]+))?(/.+)?') URI = namedtuple('URI', ('hostname', 'port', 'path')) def urlparse(uri): """Parse ht...
nodemcu/usocketio/client.py
import ure as re import ujson as json import usocket as socket from ucollections import namedtuple from .protocol import * from .transport import SocketIO URL_RE = re.compile(r'http://([A-Za-z0-9\-\.]+)(?:\:([0-9]+))?(/.+)?') URI = namedtuple('URI', ('hostname', 'port', 'path')) def urlparse(uri): """Parse ht...
0.356335
0.192312
from tg.request_local import Request, Response import logging log = logging.getLogger(__name__) class SeekableRequestBodyMiddleware(object): def __init__(self, app): self.app = app def _stream_response(self, data): try: for chunk in data: yield chunk final...
tg/support/middlewares.py
from tg.request_local import Request, Response import logging log = logging.getLogger(__name__) class SeekableRequestBodyMiddleware(object): def __init__(self, app): self.app = app def _stream_response(self, data): try: for chunk in data: yield chunk final...
0.446012
0.081119
from base.exchange import exchange import time class binance(exchange): """description of class""" # user can be subscribe one or more market(symbol). F.e: suscriber_trade = ['BTCTRY', 'BTCUSDT'] # also user can be subscribe all markets(symbols). F.e: suscriber_trade = ['all'] def __init__(self, sub...
CWS/binance.py
from base.exchange import exchange import time class binance(exchange): """description of class""" # user can be subscribe one or more market(symbol). F.e: suscriber_trade = ['BTCTRY', 'BTCUSDT'] # also user can be subscribe all markets(symbols). F.e: suscriber_trade = ['all'] def __init__(self, sub...
0.501709
0.287949
import unittest import os import run_chained class RunChainedTests(unittest.TestCase): def test_root_nodes(self): root_node = '1' first_stage = 1 n_nodes = 4 root_nodes = run_chained.compute_parent_nodes(root_node, first_stage, n_nodes) self.assertEqual(['1'], root_nodes...
workflows/cp-leaveout/py/tests/test_run_chained.py
import unittest import os import run_chained class RunChainedTests(unittest.TestCase): def test_root_nodes(self): root_node = '1' first_stage = 1 n_nodes = 4 root_nodes = run_chained.compute_parent_nodes(root_node, first_stage, n_nodes) self.assertEqual(['1'], root_nodes...
0.354433
0.421969
from .detail.const_dict import ConstDict from .detail.common import timestamp_now, _to_float from datetime import datetime import pandas as pd class QuoteBase(ConstDict): def __init__(self, quote, time=None): quote['time'] = time if time else timestamp_now() ConstDict.__init__(self, quote) def _get(self, key)...
robinhood/quote.py
from .detail.const_dict import ConstDict from .detail.common import timestamp_now, _to_float from datetime import datetime import pandas as pd class QuoteBase(ConstDict): def __init__(self, quote, time=None): quote['time'] = time if time else timestamp_now() ConstDict.__init__(self, quote) def _get(self, key)...
0.785802
0.243333
from .statistics import Ranking from .character import Character from .cover import Cover from .date import Date from .next_airing import NextAiring from .title import Title from .trailer import Trailer from .score import Score from .season import Season from typing import Callable, Dict, List class Anime: """An...
anilist/types/anime.py
from .statistics import Ranking from .character import Character from .cover import Cover from .date import Date from .next_airing import NextAiring from .title import Title from .trailer import Trailer from .score import Score from .season import Season from typing import Callable, Dict, List class Anime: """An...
0.795539
0.141311
import yaml from optparse import OptionParser import os.path known_dirs = {} includes = [] opts = set() def process(options): yaml_fname = options.yaml_filename prefix = os.path.realpath(options.top_directory) with open(yaml_fname, 'r') as f: y = yaml.load(f, Loader=yaml.CLoader) for el in ...
bear2cmake.py
import yaml from optparse import OptionParser import os.path known_dirs = {} includes = [] opts = set() def process(options): yaml_fname = options.yaml_filename prefix = os.path.realpath(options.top_directory) with open(yaml_fname, 'r') as f: y = yaml.load(f, Loader=yaml.CLoader) for el in ...
0.124572
0.0809
from __future__ import annotations from typing import Iterable import re from pathlib import Path from pdtable.store import BlockIterator from pdtable.table_origin import ( NullInputIssueTracker, InputIssueTracker, InputError, LoadItem, ) from ._protocol import ( Loader, ) from ._loaders import mak...
pdtable/io/load/_orchestrators.py
from __future__ import annotations from typing import Iterable import re from pathlib import Path from pdtable.store import BlockIterator from pdtable.table_origin import ( NullInputIssueTracker, InputIssueTracker, InputError, LoadItem, ) from ._protocol import ( Loader, ) from ._loaders import mak...
0.900034
0.207435
from s5v2 import * from prettytable import PrettyTable def my_table(): # no arguments are passed in, which seems a bit weird. We're hard-coding a function that only does one thing. x = PrettyTable(['Style', 'Average Price']) # setup a new pretty table list and give and give it two list items x.add_row(['Print', pret...
resources/ds_basics/s5v3.py
from s5v2 import * from prettytable import PrettyTable def my_table(): # no arguments are passed in, which seems a bit weird. We're hard-coding a function that only does one thing. x = PrettyTable(['Style', 'Average Price']) # setup a new pretty table list and give and give it two list items x.add_row(['Print', pret...
0.334155
0.630941
line0.timing_system.channels.hsc.delay = 4.97e-06 line0.Phase [s] = 5.4527e-06 line0.ChopX = 33.79 line0.ChopY = 30.17 line0.description = 'S-1t' line0.updated = '17 Oct 15:03' line1.timing_system.channels.hsc.delay = 0.0 line1.ChopX = 37.28 line1.ChopY = 30.925 line1.description = 'S-1' line1.updated = '17 Oct 15:05' ...
settings/high_speed_chopper_modes_settings.py
line0.timing_system.channels.hsc.delay = 4.97e-06 line0.Phase [s] = 5.4527e-06 line0.ChopX = 33.79 line0.ChopY = 30.17 line0.description = 'S-1t' line0.updated = '17 Oct 15:03' line1.timing_system.channels.hsc.delay = 0.0 line1.ChopX = 37.28 line1.ChopY = 30.925 line1.description = 'S-1' line1.updated = '17 Oct 15:05' ...
0.459319
0.191592
import scrapy from scrapy_news.items import SoccerNewsItem import scrapy_news.url_selector as url_selector #to run #scrapy crawl zerozero class ZeroZeroSpider(scrapy.Spider): name = 'zerozero' allowed_domains = ['zerozero.pt'] start_urls = [ #'http://www.zerozero.pt/news.php?id=224561', #'...
scrapy_news/scrapy_news/spiders/zerozero.py
import scrapy from scrapy_news.items import SoccerNewsItem import scrapy_news.url_selector as url_selector #to run #scrapy crawl zerozero class ZeroZeroSpider(scrapy.Spider): name = 'zerozero' allowed_domains = ['zerozero.pt'] start_urls = [ #'http://www.zerozero.pt/news.php?id=224561', #'...
0.190272
0.273362
import numpy as np from PIL import Image from matplotlib import pyplot as plt # %% Q6_1_4 alpha-trimmed mean filter Q6_1_4 = np.asarray(Image.open("Q6_1_4.tiff")) plt.show() def alpha_filter(img_raw, n: int = 3, d=0.1): m = (n - 1) // 2 trimmed = max(int(d * n ** 2), 1) row, col = img_raw.shape img_...
lab6/Q6_1_4.py
import numpy as np from PIL import Image from matplotlib import pyplot as plt # %% Q6_1_4 alpha-trimmed mean filter Q6_1_4 = np.asarray(Image.open("Q6_1_4.tiff")) plt.show() def alpha_filter(img_raw, n: int = 3, d=0.1): m = (n - 1) // 2 trimmed = max(int(d * n ** 2), 1) row, col = img_raw.shape img_...
0.686475
0.65557
from bs4 import BeautifulSoup import os import csv import time import datetime #returns list of files in the directory def getAllFiles(dir): files = [] listing = os.listdir(dir) for fileName in listing: files.append(fileName) return files #format and get output folder name def getOutputFolder(folder, files): #...
source/parser.py
from bs4 import BeautifulSoup import os import csv import time import datetime #returns list of files in the directory def getAllFiles(dir): files = [] listing = os.listdir(dir) for fileName in listing: files.append(fileName) return files #format and get output folder name def getOutputFolder(folder, files): #...
0.07228
0.205755
import pickle import os import numpy as np from scipy import sparse def load_ft_vec(dpath): '''load fasttext with vec file''' wv = dict() with open(dpath) as dfile: dfile.readline() for line in dfile: line = line.split() wv[line[0]] = [float(item) for item in line[1...
dia_wt/build_dia.py
import pickle import os import numpy as np from scipy import sparse def load_ft_vec(dpath): '''load fasttext with vec file''' wv = dict() with open(dpath) as dfile: dfile.readline() for line in dfile: line = line.split() wv[line[0]] = [float(item) for item in line[1...
0.37777
0.171581
import numpy as np from collections import deque import rospy NORMAL_MAXIMUM = 16384 BUFFER_NP_TYPE = '<i2' # little endian, signed short def normalize(snd_data): """Average the volume out """ r = snd_data * (NORMAL_MAXIMUM * 1. / max(1, np.abs(snd_data).max())) return r.astype(snd_data.dtype) ...
src/ros_speech2text/s2t/speech_detection.py
import numpy as np from collections import deque import rospy NORMAL_MAXIMUM = 16384 BUFFER_NP_TYPE = '<i2' # little endian, signed short def normalize(snd_data): """Average the volume out """ r = snd_data * (NORMAL_MAXIMUM * 1. / max(1, np.abs(snd_data).max())) return r.astype(snd_data.dtype) ...
0.739328
0.37912
import pytest from deprecate.utils import no_warning_call from tests.collection_deprecate import ( depr_accuracy_extra, depr_accuracy_map, depr_accuracy_skip, depr_pow_args, depr_pow_mix, depr_pow_self, depr_pow_self_double, depr_pow_self_twice, depr_pow_skip_if_false_true, depr...
tests/test_functions.py
import pytest from deprecate.utils import no_warning_call from tests.collection_deprecate import ( depr_accuracy_extra, depr_accuracy_map, depr_accuracy_skip, depr_pow_args, depr_pow_mix, depr_pow_self, depr_pow_self_double, depr_pow_self_twice, depr_pow_skip_if_false_true, depr...
0.674479
0.437763
import re, pywikibot, requests import toolforge from datetime import datetime site = pywikibot.Site('et', "wikipedia") conn = toolforge.connect('etwiki_p') def encode_if_necessary(b): if type(b) is bytes: return b.decode('utf8') return b def run_query(sqlquery): #query = query.encode('utf-8') #pr...
disambigReps-et.py
import re, pywikibot, requests import toolforge from datetime import datetime site = pywikibot.Site('et', "wikipedia") conn = toolforge.connect('etwiki_p') def encode_if_necessary(b): if type(b) is bytes: return b.decode('utf8') return b def run_query(sqlquery): #query = query.encode('utf-8') #pr...
0.079596
0.071267
import glob from jinja2 import Template import random import argparse import os parser = argparse.ArgumentParser() parser.add_argument('name', nargs='*', default='.') parser.add_argument('--step', type=int, default=50, help='Pixels between each visualized pixel.') args = parser.parse_args() dirs = [name for name ...
tools/vis_saliency.py
import glob from jinja2 import Template import random import argparse import os parser = argparse.ArgumentParser() parser.add_argument('name', nargs='*', default='.') parser.add_argument('--step', type=int, default=50, help='Pixels between each visualized pixel.') args = parser.parse_args() dirs = [name for name ...
0.276202
0.067608
import argparse import numpy as np import pandas as pd from settings import experiments, lambdas, functions, TRANSIENT_VALUE, RESULT_DIR from statistics import response_time_blockchain, number_users_system, calculate_transient, mean_error, \ bar_plot_metrics, bar_plot_one_metric, plot_transient, new_plot, new_plo...
statistics-web3py/main.py
import argparse import numpy as np import pandas as pd from settings import experiments, lambdas, functions, TRANSIENT_VALUE, RESULT_DIR from statistics import response_time_blockchain, number_users_system, calculate_transient, mean_error, \ bar_plot_metrics, bar_plot_one_metric, plot_transient, new_plot, new_plo...
0.445047
0.451629
import warnings import pandas as pd import pymssa # https://github.com/kieferk/pymssa from autoscalingsim.scaling.policiesbuilder.metric.forecasting.forecasting_model import ForecastingModel from autoscalingsim.utils.error_check import ErrorChecker @ForecastingModel.register('ssa') class SingularSpectrumAnalysis(Fore...
autoscalingsim/scaling/policiesbuilder/metric/forecasting/models/ssa.py
import warnings import pandas as pd import pymssa # https://github.com/kieferk/pymssa from autoscalingsim.scaling.policiesbuilder.metric.forecasting.forecasting_model import ForecastingModel from autoscalingsim.utils.error_check import ErrorChecker @ForecastingModel.register('ssa') class SingularSpectrumAnalysis(Fore...
0.758868
0.254127
from django.db import models, IntegrityError from django.contrib.auth import get_user_model class BranchManager(models.Manager): """ This will have methods to easily help us interact with the Branch object. We override the default Django Manager. """ def get_agent_branch(self, agent=None): ""...
cargotracker/branches/models.py
from django.db import models, IntegrityError from django.contrib.auth import get_user_model class BranchManager(models.Manager): """ This will have methods to easily help us interact with the Branch object. We override the default Django Manager. """ def get_agent_branch(self, agent=None): ""...
0.704567
0.246341
"""Module providing reading time adapter""" from babel.dates import format_datetime from Acquisition import aq_inner from plone import api from plone.dexterity.utils import safe_utf8 from plone.event.utils import pydt from zope.interface import implementer from ade25.base.interfaces import IContentInfoProvider @impl...
ade25/base/content_info.py
"""Module providing reading time adapter""" from babel.dates import format_datetime from Acquisition import aq_inner from plone import api from plone.dexterity.utils import safe_utf8 from plone.event.utils import pydt from zope.interface import implementer from ade25.base.interfaces import IContentInfoProvider @impl...
0.795698
0.218649
from __future__ import annotations import random from enum import Enum import attrs import structlog @attrs.define class Code: a: int b: int c: int d: int @classmethod def from_number(cls, n: int) -> Code: return cls( a=(n // 1000) % 10, b=(n // 100) % 10, ...
py/vault/vault.py
from __future__ import annotations import random from enum import Enum import attrs import structlog @attrs.define class Code: a: int b: int c: int d: int @classmethod def from_number(cls, n: int) -> Code: return cls( a=(n // 1000) % 10, b=(n // 100) % 10, ...
0.580471
0.291472
from datetime import datetime from pathlib import Path import pytest from PIL import Image from pytest_toolbox import gettree, mktree from pytest_toolbox.comparison import RegexStr from harrier.build import FileData from harrier.config import Mode from harrier.main import build from harrier.render import json_filter,...
tests/test_render.py
from datetime import datetime from pathlib import Path import pytest from PIL import Image from pytest_toolbox import gettree, mktree from pytest_toolbox.comparison import RegexStr from harrier.build import FileData from harrier.config import Mode from harrier.main import build from harrier.render import json_filter,...
0.348978
0.134122
import unittest from datetime import datetime from mongoengine import connect from mongoengine import Document from mongoengine.fields import ListField, DateTimeField from twitter_watcher.db.models import Listener from twitter_watcher.observers import ObserverTwitter class ListernerModel(unittest.TestCase): @...
tests/test_models.py
import unittest from datetime import datetime from mongoengine import connect from mongoengine import Document from mongoengine.fields import ListField, DateTimeField from twitter_watcher.db.models import Listener from twitter_watcher.observers import ObserverTwitter class ListernerModel(unittest.TestCase): @...
0.696578
0.37981
import string, random from django.db import models from django.contrib.auth.models import User class base_element(models.Model): """ Base element, abstract class """ name = models.CharField(max_length=128) short_description = models.CharField(max_length=256) description = models.TextFie...
greenknight/models.py
import string, random from django.db import models from django.contrib.auth.models import User class base_element(models.Model): """ Base element, abstract class """ name = models.CharField(max_length=128) short_description = models.CharField(max_length=256) description = models.TextFie...
0.553747
0.229956
from flask import jsonify, send_from_directory from sqlalchemy import or_ from main.db_utils import create_new_specimen, \ create_request, notify_requests_pending from main.model import db, TolidSpecies, TolidSpecimen, \ TolidUser, TolidRole, TolidRequest from main.excel_utils import validate_excel import conn...
tolid-api/app/main/controllers/creators_controller.py
from flask import jsonify, send_from_directory from sqlalchemy import or_ from main.db_utils import create_new_specimen, \ create_request, notify_requests_pending from main.model import db, TolidSpecies, TolidSpecimen, \ TolidUser, TolidRole, TolidRequest from main.excel_utils import validate_excel import conn...
0.541894
0.2334
import numpy as np import sys import os import multiprocessing from astropy.stats import RipleysKEstimator # astropy's ripley's K import pandas as pd import glob import datetime sys.path.append("..") from stationsim_model import Model #python version of stationsim import matplotlib.pyplot as plt from seaborn import k...
Projects/ABM_DA/stationsim/stationsim_validation/stationsim_validation.py
import numpy as np import sys import os import multiprocessing from astropy.stats import RipleysKEstimator # astropy's ripley's K import pandas as pd import glob import datetime sys.path.append("..") from stationsim_model import Model #python version of stationsim import matplotlib.pyplot as plt from seaborn import k...
0.672762
0.348119
import pymysql import time import bs4 import requests import re import json import datetime from multiprocessing import Pool with open('config.json', 'r') as f: config = json.load(f) database = config['database connection'] with open(config['track user path'], 'r') as f: baseusers = [i.strip('\n') fo...
mysqldataupdater.py
import pymysql import time import bs4 import requests import re import json import datetime from multiprocessing import Pool with open('config.json', 'r') as f: config = json.load(f) database = config['database connection'] with open(config['track user path'], 'r') as f: baseusers = [i.strip('\n') fo...
0.155303
0.075312
from UniqueConfiguration import UniqueConfiguration from command_args import get_args, get_optional_arg, get_mandatory_arg, get_mandatory_arg_no_print, is_true, get_mandatory_arg_validated, get_optional_arg_validated class AwsUniqueConfiguration(UniqueConfiguration): def __init__(self, args, suffix): super...
orchestration/run/AwsUniqueConfiguration.py
from UniqueConfiguration import UniqueConfiguration from command_args import get_args, get_optional_arg, get_mandatory_arg, get_mandatory_arg_no_print, is_true, get_mandatory_arg_validated, get_optional_arg_validated class AwsUniqueConfiguration(UniqueConfiguration): def __init__(self, args, suffix): super...
0.416915
0.124266
import re import spacy from geopy.geocoders import Nominatim ''' More info: https://geopy.readthedocs.io/en/stable/#geopy.location.Location.address ''' class TweetUserLocatorUtils(): def __init__(self, locator_user_agent='random_user') -> None: self.locator = Nominatim(user_agent=locator_user_agent) ...
twyloc/locator_utils.py
import re import spacy from geopy.geocoders import Nominatim ''' More info: https://geopy.readthedocs.io/en/stable/#geopy.location.Location.address ''' class TweetUserLocatorUtils(): def __init__(self, locator_user_agent='random_user') -> None: self.locator = Nominatim(user_agent=locator_user_agent) ...
0.784319
0.248283
import math from pypy.lang.js.jsparser import parse, ParseError from pypy.lang.js.astbuilder import ASTBuilder from pypy.lang.js.operations import * from pypy.lang.js.jsobj import ThrowException from pypy.rlib.objectmodel import we_are_translated from pypy.rlib.streamio import open_file_as_stream ASTBUILDER = ASTBuild...
pypy/lang/js/interpreter.py
import math from pypy.lang.js.jsparser import parse, ParseError from pypy.lang.js.astbuilder import ASTBuilder from pypy.lang.js.operations import * from pypy.lang.js.jsobj import ThrowException from pypy.rlib.objectmodel import we_are_translated from pypy.rlib.streamio import open_file_as_stream ASTBUILDER = ASTBuild...
0.29798
0.214239
import logging import re from austlang import constants logging.basicConfig(level=logging.DEBUG) class SilRcemAdapter(object): """SIL Retired Core Element Mappings""" SOURCE_NAME = constants.SIL_RCEM_SOURCE_ABBREV # Mappings defined the in schema RETIREMENT_TYPE_CHANGE = "C" RETIREMENT_TYPE_DUPLI...
language_explorer/language_sources/sil_rcem.py
import logging import re from austlang import constants logging.basicConfig(level=logging.DEBUG) class SilRcemAdapter(object): """SIL Retired Core Element Mappings""" SOURCE_NAME = constants.SIL_RCEM_SOURCE_ABBREV # Mappings defined the in schema RETIREMENT_TYPE_CHANGE = "C" RETIREMENT_TYPE_DUPLI...
0.50952
0.070176
import albumentations import streamlit as st from elements import ( checkbox, element_description, min_max, num_interval, radio, rgb, several_nums, text_input, ) def select_next_aug(augmentations): """ Returns last selected transformation. Parameters: augmentation...
augbuilder/augmentation.py
import albumentations import streamlit as st from elements import ( checkbox, element_description, min_max, num_interval, radio, rgb, several_nums, text_input, ) def select_next_aug(augmentations): """ Returns last selected transformation. Parameters: augmentation...
0.791378
0.309024
import random, ecdsa, hashlib, base58, binascii, requests, time ##--------------BECH32------------------------------------------------- CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" def bech32_polymod(values): """Internal function that computes the Bech32 checksum.""" generator = [0x3b6a57b2, 0x26508e6d, 0x1e...
Zderzacz_btc.py
import random, ecdsa, hashlib, base58, binascii, requests, time ##--------------BECH32------------------------------------------------- CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" def bech32_polymod(values): """Internal function that computes the Bech32 checksum.""" generator = [0x3b6a57b2, 0x26508e6d, 0x1e...
0.608943
0.460532
from .autodiff import Variable from .tensor_data import TensorData from . import operators class Tensor(Variable): """ Tensor is a generalization of Scalar in that it is a Variable that handles multidimensional arrays. Attributes: _tensor (:class:`TensorData`) : the tensor data storage ...
Module-2/minitorch/tensor.py
from .autodiff import Variable from .tensor_data import TensorData from . import operators class Tensor(Variable): """ Tensor is a generalization of Scalar in that it is a Variable that handles multidimensional arrays. Attributes: _tensor (:class:`TensorData`) : the tensor data storage ...
0.949342
0.606877
import argparse import os import bz2 import yaml import json from glob import glob from tqdm import tqdm import xml.etree.ElementTree as ET def parse_file(file_path): with bz2.open(file_path, 'r') as f: root = ET.fromstring(f.read()) tool = root.attrib['tool'] for result in...
scripts/parse_svcomp_results.py
import argparse import os import bz2 import yaml import json from glob import glob from tqdm import tqdm import xml.etree.ElementTree as ET def parse_file(file_path): with bz2.open(file_path, 'r') as f: root = ET.fromstring(f.read()) tool = root.attrib['tool'] for result in...
0.219505
0.113383
from typing import Callable, Final, Tuple, TypeVar WORD_SIZE: Final[int] = 32 REGISTER_BITS: Final[int] = 3 MEM_ADDR_BITS: Final[int] = 10 OPCODE_BITS: Final[int] = 6 # Binary values are either str "0b0" or int Binary = TypeVar("Binary", str, int) def _split_args(args: str, pos: int, second_bits: int = -1) -> Tuple...
toymachine/machine.py
from typing import Callable, Final, Tuple, TypeVar WORD_SIZE: Final[int] = 32 REGISTER_BITS: Final[int] = 3 MEM_ADDR_BITS: Final[int] = 10 OPCODE_BITS: Final[int] = 6 # Binary values are either str "0b0" or int Binary = TypeVar("Binary", str, int) def _split_args(args: str, pos: int, second_bits: int = -1) -> Tuple...
0.901769
0.400749
from parsing.grammar import * def get_sample_1(): # From http://web.cs.dal.ca/~sjackson/lalr1.html return Grammar([ NonTerminal('N', [ "V '=' E", "E" ]), NonTerminal('E', [ "V" ]), NonTerminal('V', [ "'x'", "'*' E" ...
samples.py
from parsing.grammar import * def get_sample_1(): # From http://web.cs.dal.ca/~sjackson/lalr1.html return Grammar([ NonTerminal('N', [ "V '=' E", "E" ]), NonTerminal('E', [ "V" ]), NonTerminal('V', [ "'x'", "'*' E" ...
0.520496
0.244769
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed from wtforms import StringField, EmailField, PasswordField, SubmitField, TextAreaField from wtforms.validators import DataRequired, Email, EqualTo, ValidationError, Length from .models import model from flask_login import current_user Us...
app/forms.py
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed from wtforms import StringField, EmailField, PasswordField, SubmitField, TextAreaField from wtforms.validators import DataRequired, Email, EqualTo, ValidationError, Length from .models import model from flask_login import current_user Us...
0.441914
0.173708
import json import os import numpy as np import tensorflow as tf import encoder import model def top_k_logits(logits, k): if k == 0: # no truncation return logits def _top_k(): values, _ = tf.nn.top_k(logits, k=k) min_values = values[:, -1, tf.newaxis] return tf.comp...
ai.py
import json import os import numpy as np import tensorflow as tf import encoder import model def top_k_logits(logits, k): if k == 0: # no truncation return logits def _top_k(): values, _ = tf.nn.top_k(logits, k=k) min_values = values[:, -1, tf.newaxis] return tf.comp...
0.673299
0.356111
from enum import Enum class UnrootedConflictStatus(Enum): EQUIVALENT = 0 INCOMPATIBLE = 1 RESOLVES = 2 # compatible with "other" tree, and split is not in that tree TRIVIAL = 3 # will be compatible with any taxonomy NOT_COMPARABLE = 4 # e.g. lacking an OTT ID in a comparison to taxonomy class...
peyotl/phylo/compat.py
from enum import Enum class UnrootedConflictStatus(Enum): EQUIVALENT = 0 INCOMPATIBLE = 1 RESOLVES = 2 # compatible with "other" tree, and split is not in that tree TRIVIAL = 3 # will be compatible with any taxonomy NOT_COMPARABLE = 4 # e.g. lacking an OTT ID in a comparison to taxonomy class...
0.706292
0.327265
from __future__ import annotations from datetime import datetime from typing import Optional from marshmallow.fields import Integer, String from numpy import sqrt, log, rad2deg, void from astropy.wcs import WCS from ..schemas import AfterglowSchema, DateTime, Float __all__ = [ 'IAstrometry', 'IFwhm', 'ISourceI...
afterglow_core/models/source_extraction.py
from __future__ import annotations from datetime import datetime from typing import Optional from marshmallow.fields import Integer, String from numpy import sqrt, log, rad2deg, void from astropy.wcs import WCS from ..schemas import AfterglowSchema, DateTime, Float __all__ = [ 'IAstrometry', 'IFwhm', 'ISourceI...
0.947563
0.367611
__all__ = ['read_wininfo'] import sys import pathlib import numpy as np import h5py def read_wininfo(filename): """Read the window information from an EIS HDF5 header file Parameters ---------- filename : str or pathlib.Path object Name of either the data or head HDF5 file for a single EIS ob...
eispac/core/read_wininfo.py
__all__ = ['read_wininfo'] import sys import pathlib import numpy as np import h5py def read_wininfo(filename): """Read the window information from an EIS HDF5 header file Parameters ---------- filename : str or pathlib.Path object Name of either the data or head HDF5 file for a single EIS ob...
0.534855
0.269614
from Spot import * from bosdyn.api import image_pb2 import time import numpy as np import imutils import cv2 import OpenGL import bosdyn.api import bosdyn.client.util import io import os import sys from OpenGL.GL import * from OpenGL.GL import shaders, GL_VERTEX_SHADER from OpenGL.GLU import * from OpenGL.GLUT impo...
edj/Spot_image_capture.py
from Spot import * from bosdyn.api import image_pb2 import time import numpy as np import imutils import cv2 import OpenGL import bosdyn.api import bosdyn.client.util import io import os import sys from OpenGL.GL import * from OpenGL.GL import shaders, GL_VERTEX_SHADER from OpenGL.GLU import * from OpenGL.GLUT impo...
0.697609
0.256238
from __future__ import print_function import os.path as osp import subprocess import shutil import shlex import sys import os from importlib import import_module sys.path.append('support') d=osp.abspath(osp.dirname(__file__)) sys.path.append(d) print(d) from opts import * import pcgtests as test with open(osp.join...
python/build.py
from __future__ import print_function import os.path as osp import subprocess import shutil import shlex import sys import os from importlib import import_module sys.path.append('support') d=osp.abspath(osp.dirname(__file__)) sys.path.append(d) print(d) from opts import * import pcgtests as test with open(osp.join...
0.163279
0.067301
import sys, os, math import os.path as path import numpy as np def circle(allParms): localInputFolder = allParms["Interface"]["localInputFolder"] centerX = float(allParms["Minor"]["photometryCurXvolts"]) centerY = float(allParms["Minor"]["photometryCurYvolts"]) sweepDurMs = float(allParms["Minor"]["pho...
src/Toronado/Imaging/Helper/Scans/createPhotometryScans.py
import sys, os, math import os.path as path import numpy as np def circle(allParms): localInputFolder = allParms["Interface"]["localInputFolder"] centerX = float(allParms["Minor"]["photometryCurXvolts"]) centerY = float(allParms["Minor"]["photometryCurYvolts"]) sweepDurMs = float(allParms["Minor"]["pho...
0.260954
0.196788
import re import textfsm import pathlib from pprint import pprint as pp from pyEXOS import EXOS from napalm.base import NetworkDriver from napalm.base.exceptions import ( ConnectionException, MergeConfigException, ReplaceConfigException, ) class ExosDriver(NetworkDriver): """Napalm driver fo...
napalm_exos/exos.py
import re import textfsm import pathlib from pprint import pprint as pp from pyEXOS import EXOS from napalm.base import NetworkDriver from napalm.base.exceptions import ( ConnectionException, MergeConfigException, ReplaceConfigException, ) class ExosDriver(NetworkDriver): """Napalm driver fo...
0.338186
0.090454
import os, sys import time import subprocess, psutil, tempfile, portalocker import socket import uuid import logging from tinydb import TinyDB, Query from datetime import datetime import json from ..util import util def start(): logger = util.logger(__name__) sys.stdout.write('Starting broadcast service.') curren...
gesso/gesso/service/announce.py
import os, sys import time import subprocess, psutil, tempfile, portalocker import socket import uuid import logging from tinydb import TinyDB, Query from datetime import datetime import json from ..util import util def start(): logger = util.logger(__name__) sys.stdout.write('Starting broadcast service.') curren...
0.056275
0.053849
import numpy as np import scipy import warnings def norms_init(B=None, Binv=None): """ Initialize norms to use. The primal space is the space of variables, the dual space is the space of the gradients. Operator B transforms the primal space to the dual. l2_norm_sqr(x) := ||x||^2...
utils.py
import numpy as np import scipy import warnings def norms_init(B=None, Binv=None): """ Initialize norms to use. The primal space is the space of variables, the dual space is the space of the gradients. Operator B transforms the primal space to the dual. l2_norm_sqr(x) := ||x||^2...
0.712632
0.502563
import gc import os import cv2 import keras import matplotlib.pyplot as plt import numpy as np import pandas as pd import tifffile as tiff from keras import backend as K from keras.backend import binary_crossentropy from keras.layers import concatenate, Conv2D, Input, MaxPooling2D, UpSampling2D, Cropping2D from keras....
create_model/generate_pic.py
import gc import os import cv2 import keras import matplotlib.pyplot as plt import numpy as np import pandas as pd import tifffile as tiff from keras import backend as K from keras.backend import binary_crossentropy from keras.layers import concatenate, Conv2D, Input, MaxPooling2D, UpSampling2D, Cropping2D from keras....
0.758332
0.477128
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobsapp', '0017_auto_20200221_1034'), ] operations = [ migrations.RemoveField( model_name='applicant1', name='category', ), migrations.RemoveField( ...
jobsapp/migrations/0018_auto_20200222_1831.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobsapp', '0017_auto_20200221_1034'), ] operations = [ migrations.RemoveField( model_name='applicant1', name='category', ), migrations.RemoveField( ...
0.624637
0.131034
"""Script for quick-and-dirty time dilation calculations""" from argparse import ArgumentParser from decimal import Decimal, getcontext def time_breakdown(time_in_years): """Function for formatting time nicely""" light_seconds = time_in_years * 31556926 years, year_rem = divmod(light_seconds, 31556926) ...
timedil.py
"""Script for quick-and-dirty time dilation calculations""" from argparse import ArgumentParser from decimal import Decimal, getcontext def time_breakdown(time_in_years): """Function for formatting time nicely""" light_seconds = time_in_years * 31556926 years, year_rem = divmod(light_seconds, 31556926) ...
0.799677
0.320901
import logging LOG = logging.getLogger(__name__) class QuickCLIContextConfig(object): ''' Application Context Config ''' PARAMS = { 'allow_unset': (bool, True), 'unset_value': (str, '') } def __init__(self, context, **kwargs): ''' Constructor ''' self.context = conte...
src/quick_cli/context.py
import logging LOG = logging.getLogger(__name__) class QuickCLIContextConfig(object): ''' Application Context Config ''' PARAMS = { 'allow_unset': (bool, True), 'unset_value': (str, '') } def __init__(self, context, **kwargs): ''' Constructor ''' self.context = conte...
0.660282
0.062303
from __future__ import absolute_import from __future__ import print_function import os import sys from dxlbootstrap.util import MessageUtils from dxlclient.client_config import DxlClientConfig from dxlclient.client import DxlClient root_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(root_dir + "/../...
sample/basic/basic_update_event_example.py
from __future__ import absolute_import from __future__ import print_function import os import sys from dxlbootstrap.util import MessageUtils from dxlclient.client_config import DxlClientConfig from dxlclient.client import DxlClient root_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(root_dir + "/../...
0.408041
0.074736
begin_unit comment|'# Copyright (c) 2014 Red Hat, Inc.' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comme...
nova/scheduler/client/query.py
begin_unit comment|'# Copyright (c) 2014 Red Hat, Inc.' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comme...
0.771026
0.072341
import numpy as np import random def lsi(x, y, params=None): """ An implementation of the local synthetic instances (LSI) method for over-sampling a dataset. Arguments: x - An N by M numpy array containing N samples of M dimensions (i.e. features) y - An N by D numpy array containing N labels of D...
lsi-oversampling/lsi.py
import numpy as np import random def lsi(x, y, params=None): """ An implementation of the local synthetic instances (LSI) method for over-sampling a dataset. Arguments: x - An N by M numpy array containing N samples of M dimensions (i.e. features) y - An N by D numpy array containing N labels of D...
0.76769
0.777046
from typing import Tuple, Optional import torch import torch.nn as nn from torecsys.layers import BiasEncodingLayer from torecsys.models.ctr import CtrBaseModel class DeepSessionInterestNetworkModel(CtrBaseModel): """ # TODO: [in development] Model class of Deep Session Interest Network (DSIN), which i...
torecsys/models/ctr/deep_session_interest_network.py
from typing import Tuple, Optional import torch import torch.nn as nn from torecsys.layers import BiasEncodingLayer from torecsys.models.ctr import CtrBaseModel class DeepSessionInterestNetworkModel(CtrBaseModel): """ # TODO: [in development] Model class of Deep Session Interest Network (DSIN), which i...
0.861276
0.640636
import os import importlib import numpy as np import matplotlib.pyplot as plt import picasso_addon.io as addon_io import spt.immobile_props as improps import spt.analyze as analyze importlib.reload(improps) plt.style.use('~/lbFCS/styles/paper.mplstyle') ############################################# Load raw data dir...
scripts/plotting/immob_props_single.py
import os import importlib import numpy as np import matplotlib.pyplot as plt import picasso_addon.io as addon_io import spt.immobile_props as improps import spt.analyze as analyze importlib.reload(improps) plt.style.use('~/lbFCS/styles/paper.mplstyle') ############################################# Load raw data dir...
0.45302
0.211804
import pprint import re # noqa: F401 import six class SrPathObject(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...
syntropy_sdk/models/sr_path_object.py
import pprint import re # noqa: F401 import six class SrPathObject(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...
0.605916
0.088583
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms import ModelForm from .models import NeighborHood, UserProfile, Business, Post class RegisterForm(UserCreationForm): email = forms.EmailField(required=True, ...
z_neighborhood/forms.py
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms import ModelForm from .models import NeighborHood, UserProfile, Business, Post class RegisterForm(UserCreationForm): email = forms.EmailField(required=True, ...
0.486819
0.089973
import unittest from hypothesis import given import hypothesis.strategies as st import pytest import curver from curver.kernel.decorators import memoize # Special import needed for decorating. TRIANGULATIONS = { (0, 3): '3_p', (0, 4): '6_JDky1', (0, 5): '9_ZFO4OuIV', (0, 6): 'c_ZlgeM906o-354', ...
tests/strategies.py
import unittest from hypothesis import given import hypothesis.strategies as st import pytest import curver from curver.kernel.decorators import memoize # Special import needed for decorating. TRIANGULATIONS = { (0, 3): '3_p', (0, 4): '6_JDky1', (0, 5): '9_ZFO4OuIV', (0, 6): 'c_ZlgeM906o-354', ...
0.474388
0.433382
from ..utils import fromtimestamp from .model import Model class Movie(Model): """Movie Object Attributes ---------- id: :class:`str` | |movie_id| user_id: :class:`str` | |id| title: :class:`str` | Live title subtitle: :class:`str` | Live subtitle (telop) ...
twitcaspy/models/movie.py
from ..utils import fromtimestamp from .model import Model class Movie(Model): """Movie Object Attributes ---------- id: :class:`str` | |movie_id| user_id: :class:`str` | |id| title: :class:`str` | Live title subtitle: :class:`str` | Live subtitle (telop) ...
0.882807
0.512693
# https://www.youtube.com/watch?v=Vq2xt2D3e3E notes = {0:'do',2:'ré',4:'mi',5:'fa',7:'sol',9:'la',11:'si'} ordre_notes = {0:'do',1:'ré',2:'mi',3:'fa',4:'sol',5:'la',6:'si'} notes_ordre = {'do':0,'ré':1,'mi':2,'fa':3,'sol':4,'la':5,'si':6} hauteur_notes = {'do':0,'ré':2,'mi':4,'fa':5,'sol':7,'la':9,'si':11} alt = {-2:...
gammes.py
# https://www.youtube.com/watch?v=Vq2xt2D3e3E notes = {0:'do',2:'ré',4:'mi',5:'fa',7:'sol',9:'la',11:'si'} ordre_notes = {0:'do',1:'ré',2:'mi',3:'fa',4:'sol',5:'la',6:'si'} notes_ordre = {'do':0,'ré':1,'mi':2,'fa':3,'sol':4,'la':5,'si':6} hauteur_notes = {'do':0,'ré':2,'mi':4,'fa':5,'sol':7,'la':9,'si':11} alt = {-2:...
0.281208
0.248905
import pandas as pd import re import requests from datetime import date from flask import request from flask import Flask, render_template, redirect from datetime import datetime from bs4 import BeautifulSoup app = Flask(__name__) @app.route('/') @app.route('/home', methods=['GET','POST']) def scrapping(): global...
Scripts/app.py
import pandas as pd import re import requests from datetime import date from flask import request from flask import Flask, render_template, redirect from datetime import datetime from bs4 import BeautifulSoup app = Flask(__name__) @app.route('/') @app.route('/home', methods=['GET','POST']) def scrapping(): global...
0.194904
0.127625