content
stringlengths
0
991k
tokens
int64
0
655k
from _TFL.pyk import pyk from rsclib.HTML_Parse import tag, Page_Tree from rsclib.autosuper import autosuper from spider.common import Interface, Inet4, Inet6, unroutable from spider.common import WLAN_Config from spider.luci import Version_Mixin class Status (Page_Tree, Versio...
1,478
from PIL import Image import cv2 import imagehash import math import numpy as np DIFF_THRES = 20 LIMIT = 2 RESIZE = 1000 def calc_hash(img): """ Calculate the wavelet hash of the image img: (ndarray) image file """ img = resize(img) return imagehash.whash(Image.fromarray(img)) def compare(ha...
406
from .cli.cli import main if __name__ == '__main__': main()
18
import time from PyQt5 import QtGui, QtCore from ui.room_item import Ui_Form from PyQt5.QtWidgets import QWidget class Room_Item(QWidget,Ui_Form): def __init__(self,parent=None,room_data=None): super(Room_Item,self).__init__(parent) self.setupUi(self) self.data = room_data self.setRo...
218
import asyncio import re import sys import traceback import toga from toga import Key from .keys import toga_to_winforms_key from .libs import Threading, WinForms, shcore, user32, win_version from .libs.proactor import WinformsProactorEventLoop from .window import Window class MainWindow(Window): def winforms_FormC...
1,680
""" /*************************************************************************** SimplePhotogrammetryRoutePlanner A QGIS plugin A imple photogrammetry route planner. Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ ------------...
275
""" Created on Tue Jul 24 14:38:20 2018 dimension reduction with VarianceThreshold using sklearn. Feature selector that removes all low-variance features. @author: lenovo """ from sklearn.feature_selection import VarianceThreshold import numpy as np np.random.seed(1) X = np.random.randn(100, 10) X = np.hstack([X, np.ze...
189
from my_multi_main3 import main import numpy as np import argparse import time parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--test-...
812
"""HDF5 related files. This file contains a set of functions that related to read and write HDF5 files. Author: Yuhuang Hu Email : duguyue100@gmail.com """ from __future__ import print_function, absolute_import import h5py from spiker import log logger = log.get_logger("data-hdf5", log.DEBUG) def init_hdf5(file_path, m...
265
import flatbuffers class FloatingPoint(object): __slots__ = ['_tab'] @classmethod def GetRootAsFloatingPoint(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = FloatingPoint() x.Init(buf, n + offset) return x def Init(self, buf, pos...
198
"""[Scynced Lights] Class attributes are "shared" Instance attributes are not shared. """ def sub(x, y): f class Light: pass a = Light() b = Ligth()
44
from __future__ import unicode_literals, division, absolute_import import time import logging from collections import deque try: from UserDict import DictMixin except ImportError: from collections import Mapping as DictMixin import six from six import iteritems from six.moves import cPickle class BaseCounter(ob...
2,007
"""Feature extractor class for ViT.""" from typing import List, Optional, Union import numpy as np from PIL import Image from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...file_utils import TensorType from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ImageFeatur...
1,406
UNKNOWN = -1 def read_val(): return int(input()) def read_row(): return list(map(int, input().split())) def read_grid(): return [read_row() for _ in range(read_val())] def make_blank_row(i): return [UNKNOWN] * i def make_blank_grid(n): return [make_blank_row(i) for i in range(1, n + 1)] def compute_...
198
import platform operating_system = platform.system().lower() if operating_system == 'darwin': from .blender_utils_macos import get_installed_blender_versions operating_system_name = 'macos' elif operating_system == 'linux': from .blender_utils_linux import get_installed_blender_versions operating_system...
368
import functools import random from math import cos, pi import cv2 import kornia import numpy as np import torch from kornia.augmentation import ColorJitter from data.util import read_img from PIL import Image from io import BytesIO from utils.util import opt_get ''' if __name__ == '__main__': import numpy as np ...
1,744
print(b"%%" % ()) print(b"=%d=" % 1) print(b"=%d=%d=" % (1, 2)) print(b"=%s=" % b"str") print(b"=%r=" % b"str") print("PASS")
58
import pytest import albumentations as A from .context import TfDataAugmentation as Tfda from . import test_utils from .test_utils import TestResult @pytest.mark.parametrize( "quality_lower, quality_upper, expected, message", [ (-1, 100, TestResult.Error, "quality_lower < min => Error"), (0...
489
import os from torch.utils.data import DataLoader from continuum.datasets import CIFAR10, InMemoryDataset from continuum.datasets import MNIST import torchvision from continuum.scenarios import TransformationIncremental import pytest import numpy as np from continuum.transforms.bg_swap import BackgroundSwap DATA_PATH =...
646
import os JQUERY_VERSION = "1.6.2" JQUERY_UI_VERSION = "1.8.16" DATE_TEXT_SIZE = 25 TEXT_SIZE = 85 TEXTAREA_COLS = 85 TEXTAREA_ROWS_SHORT = 2 TEXTAREA_ROWS_LONG = 4 TEXTAREA_ROWS_XLONG = 10 MAX_LENGTH_CHECKLIST_NOTES = 255 EMAIL_LENGTH = 60 _app_path = None _config_file = None _app_name = None session_lock_dir = None p...
284
from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy from .._version import VERSION if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential class WebSiteMana...
563
import django.http import unittest.mock from .. import middleware def get_response(req): return django.http.HttpResponse() def test_leaves_remote_addr_alone_if_no_real_ip(): remote_addr = object() request = unittest.mock.MagicMock() request.META = {"REMOTE_ADDR": remote_addr} middleware.XRealIPMiddl...
184
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) GPIO.output(21, GPIO.LOW) time.sleep(3.00) GPIO.output(21, GPIO.HIGH) GPIO.cleanup()
53
from direct.directnotify.DirectNotifyGlobal import directNotify class Notifier: def __init__(self, name): """ @param name: The name of the notifier. Be sure to add it to your config/Config.prc! @type name: str """ self.notify = directNotify.newCategory(name)
69
import numpy as np def train_ml_squarer() -> None: print("Training!") def square() -> int: """Square a number...maybe""" return np.random.randint(1, 100) if __name__ == '__main__': train_ml_squarer()
60
""" Platformer Game """ import arcade SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 650 SCREEN_TITLE = "Platformer" CHARACTER_SCALING = 1 TILE_SCALING = 0.5 COIN_SCALING = 0.5 SPRITE_PIXEL_SIZE = 128 GRID_PIXEL_SIZE = SPRITE_PIXEL_SIZE * TILE_SCALING PLAYER_MOVEMENT_SPEED = 10 GRAVITY = 1 PLAYER_JUMP_SPEED = 20 class MyGame(arca...
968
''' lib/ycmd/start.py Server bootstrap logic. Includes a utility class for normalizing parameters and calculating default ones. Also includes a helper to set up the temporary options file. ''' import logging import os import tempfile from ..process import ( FileHandles, Process, ) from ..util.fs import ( de...
4,053
import serial import sys import struct import pprint import argparse import code pp = pprint.PrettyPrinter() class ConsoleUI: def opStart(self, name): sys.stdout.write(name.ljust(40)) def opProgress(self, progress, total=-1): if (total >= 0): prstr = "0x%04x / 0x%04x" % (progress, to...
1,265
from CIM16.IEC61968.Common.ActivityRecord import ActivityRecord class ComplianceEvent(ActivityRecord): """Compliance events are used for reporting regulatory or contract compliance issues and/or variances. These might be created as a consequence of local business processes and associated rules. It is anticipated th...
270
import logging from django.db.models.query_utils import Q from django.shortcuts import get_object_or_404 from django.utils.decorators import method_decorator from django_filters.rest_framework import DjangoFilterBackend from drf_yasg import openapi from drf_yasg.openapi import Parameter from drf_yasg.utils import no_bo...
8,973
"""Mypy style test cases for SQLAlchemy stubs and plugin.""" import os import os.path import sys import pytest from mypy.test.config import test_temp_dir from mypy.test.data import DataDrivenTestCase, DataSuite from mypy.test.helpers import assert_string_arrays_equal from mypy.util import try_find_python2_interpreter...
534
from __future__ import print_function import argparse import hashlib import os import sys from gnupg import GPG from jinja2 import Template class Version: def __init__(self, version): self.version = version parts = version.split('.') if len(parts) > 2: self.major = ".".join(parts...
687
from flask import Flask, jsonify, request, make_response, redirect, url_for import jwt import datetime import os from functools import wraps from flask_sqlalchemy import SQLAlchemy import uuid from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.utils import secure_filename from sqlal...
4,310
""" An API to insert and retrieve metadata on cloud artifacts. No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1alpha1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six ...
1,416
from __future__ import absolute_import, division, unicode_literals, print_function import re import os import tempfile import six from .. import environment from ..console import log from .. import util WIN = (os.name == "nt") def _find_conda(): """Find the conda executable robustly across conda versions. Retur...
1,228
""" Function objects. In PyPy there is no difference between built-in and user-defined function objects; the difference lies in the code object found in their func_code attribute. """ from pypy.rlib.unroll import unrolling_iterable from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace imp...
5,286
"""Timer class based on the timeit.Timer class, but torch aware.""" import enum import timeit import textwrap from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union import numpy as np import torch from torch.utils.benchmark.utils import common, cpp_jit from torch.utils.benchmark.utils._stubs impo...
3,522
from Ranger.src.Range.Cut import Cut class Range(object): """ Class used to represent a range along some 1-D domain. The range is represented by 2 cutpoints can can be unbounded by specifying an aboveAll or belowAll Cut. """ def __init__(self, lowerCut, upperCut): """ Instantiates a Rang...
4,066
from pyrelational.data.data_manager import GenericDataManager
11
from selfdrive.car import dbc_dict from cereal import car Ecu = car.CarParams.Ecu class CarControllerParams: ANGLE_DELTA_BP = [0., 5., 15.] ANGLE_DELTA_V = [5., .8, .15] ANGLE_DELTA_VU = [5., 3.5, 0.4] LKAS_MAX_TORQUE = 1 STEER_THRESHOLD = 1.0 class CAR: XTRAIL = "NISSAN X-TRAIL 2017"...
4,750
from .core import Core, Settings class Download(Core): host = 'https://artifacts.elastic.co/downloads/beats/elastic-agent/{endpoint}' endpoint = Settings.download_endpoint kwargs = { 'stream': True } def parse_response(self, response): self.__logger.debug('Saving file to download pat...
124
from .single_stage import SingleStageDetector from ..registry import DETECTORS from mmdet.core import bbox2result import torch.nn as nn import torch from .. import builder import numpy as np import cv2 from mmdet.core import bbox2roi, bbox2result, build_assigner, build_sampler @DETECTORS.register_module class CSP(Singl...
3,715
import board import busio import digitalio import adafruit_rfm9x RADIO_FREQ_MHZ = 915.0 CS = digitalio.DigitalInOut(board.D5) RESET = digitalio.DigitalInOut(board.D6) LED = digitalio.DigitalInOut(board.D13) LED.direction = digitalio.Direction.OUTPUT spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) rfm9x =...
276
""" Class to hold clinical outcome model. Predicts probability of good outcome of patient(s) or group(s) of patients. Call `calculate_outcome_for_all(args)` from outside of the object Inputs ====== All inputs take np arrays (for multiple groups of patients). mimic: proportion of patients with stroke mimic ich: proporti...
2,717
from django.conf.urls.defaults import patterns, url from djangopypi.feeds import ReleaseFeed urlpatterns = patterns("djangopypi.views", url(r'^$', "root", name="djangopypi-root"), url(r'^packages/$','packages.index', name='djangopypi-package-index'), url(r'^simple/$','packages.simple_index', name='djangopyp...
689
import pandas as pd from pandas.compat import StringIO import numpy numpy.set_printoptions(threshold=numpy.nan) def main(): df = pd.read_csv(StringIO(earnings), sep=",", header=None, names=['symbol', 'exchange', 'eps_pct_diff_surp', 'asof_date']) df = df.sort_values(by=['asof_date']) pr...
77,644
import mock from oslo_config import cfg from oslo_utils import fixture as utils_fixture from oslo_utils import timeutils from oslo_utils import uuidutils from neutron.conf.services import metering_agent as metering_agent_config from neutron.services.metering.agents import metering_agent from neutron.tests import base f...
2,177
from PIL import ImageChops, Image as PILImage from http.client import HTTPConnection from time import sleep from traceback import format_stack, print_exc def Tint(image, color): return ImageChops.blend(image, PILImage.new('RGB', image.size, color), 0.36) def GetStatusCode(host, path="/"): """ This function retr...
187
from abc import ( ABCMeta, abstractmethod, abstractproperty, ) from numpy import concatenate from lru import LRU from pandas import isnull from pandas.tslib import normalize_date from toolz import sliding_window from six import with_metaclass from zipline.assets import Equity, Future from zipline.assets.con...
4,448
import requests API_URL = 'https://secure.techfortesco.com/tescolabsapi/restservice.aspx' class TescoLabsApi(object): def __init__(self, url, developerkey, applicationkey): self.url = url self.developerkey = developerkey self.applicationkey = applicationkey res = requests.get(self.ur...
273
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0002_tag'), ] operations = [ migrations.AddField( model_name='item', name='tags', field=models.ManyToManyField(related_name='items', to='catalog.T...
78
"""Base task runner""" import os import subprocess import threading from pwd import getpwnam from tempfile import NamedTemporaryFile from typing import Optional, Union from airflow.configuration import conf from airflow.exceptions import AirflowConfigException from airflow.models.taskinstance import load_error_file fro...
1,119
import unittest """ Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string. end_other('Hiabc', 'abc') → True end...
498
"""Document formats. :since: pyglet 1.1 """
15
import os from dotenv import load_dotenv load_dotenv() class Config: SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://fidel:fidel@localhost/blog' UPLOADED_PHOTOS_DEST = 'app/static/photos' QUOTES_URL = 'http://quotes.stormconsultancy.co.uk/random.json' MAIL_...
178
_TF_INCLUDE_PATH = "TF_INCLUDE_PATH" _TF_LIB_PATH = "TF_LIB_PATH" def _get_env_var_with_default(repository_ctx, env_var): """Returns evironment variable value.""" if env_var in repository_ctx.os.environ: value = repository_ctx.os.environ[env_var] return value else: fail("Environment variable '%s' was ...
322
import yaml from os import path from netmiko import ConnectHandler home_dir = path.expanduser("~") filename = path.join(home_dir, ".netmiko.yml") with open(filename) as f: yaml_out = yaml.safe_load(f) cisco3 = yaml_out["cisco3"] net_connect = ConnectHandler(**cisco3) print() print(net_connect.find_prompt()) print()
85
0
from QcloudApi.modules import base class Trade(base.Base): requestHost = 'trade.api.qcloud.com'
24
"""Support for ICS Calendar.""" import copy import logging from datetime import datetime, timedelta from urllib.error import ContentTooShortError, HTTPError, URLError from urllib.request import ( HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, HTTPDigestAuthHandler, build_opener, install_open...
1,822
"""SSD dataset""" from __future__ import division import os import json import xml.etree.ElementTree as et import numpy as np import cv2 import mindspore.dataset as de import mindspore.dataset.vision.c_transforms as C from mindspore.mindrecord import FileWriter from .config import config from .box_utils import jaccard_...
4,002
from ccxt.base.exchange import Exchange import json from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from ccxt.base.errors import PermissionDenied from ccxt.base.errors import AccountSuspended from ccxt.base.errors import ArgumentsRequired from ccxt.base.errors import BadReque...
30,258
from arm.logicnode.arm_nodes import * class SetTransformNode(ArmLogicTreeNode): """Use to set the transform of an object.""" bl_idname = 'LNSetTransformNode' bl_label = 'Set Object Transform' arm_version = 1 def init(self, context): super(SetTransformNode, self).init(context) self.ad...
138
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, "README.rst"), encodin...
343
from ssmpfwd.helpers import verify_plugin_version, verbose_debug_quiet, time_decorator from unittest.mock import MagicMock, patch import unittest class TestVerifyPluginVersion(unittest.TestCase): @patch("ssmpfwd.helpers.subprocess") def test_verify_plugin_version_success(self, mock_subprocess): re...
585
import numpy as np import matplotlib.pyplot as plt import pint from main import ureg ureg.setup_matplotlib(True) from uncertainties import ufloat, umath, unumpy import pandas as pd from scipy.signal import find_peaks from scipy.integrate import simpson from scipy.optimize import curve_fit plt.rcParams['text.usetex'] = ...
1,290
from flask import Flask, request, redirect from twilio.twiml.messaging_response import MessagingResponse from get_secrets import * def main(): resp = MessagingResponse() resp.message ("You have reached the DogBot. Thanks for contacting us :)") return str(resp) if __name__ == "__main__": main()
69
from __future__ import annotations from enum import IntEnum class Algorithm(IntEnum): """ https://developers.yubico.com/YubiHSM2/Concepts/Algorithms.html """ RSA_PKCS1_SHA1 = 1 RSA_PKCS1_SHA256 = 2 RSA_PKCS1_SHA384 = 3 RSA_PKCS1_SHA512 = 4 RSA_PSS_SHA1 = 5 RSA_PSS_SHA256 = 6 RSA_...
1,831
import unittest.mock from functools import partial import bokeh.core.properties as bp import param import pytest from bokeh.document import Document from bokeh.io.doc import patch_curdoc from bokeh.models import Div from panel.layout import Tabs, WidgetBox from panel.reactive import Reactive, ReactiveHTML from panel.vi...
3,203
"""This module holds data for ppr queue event tracking.""" from __future__ import annotations from mhr_api.models import utils as model_utils from mhr_api.utils.base import BaseEnum from .db import db class EventTracking(db.Model): """This class manages all of the event tracking information.""" class EventTra...
825
import unittest from hydrus.core import HydrusConstants as HC from hydrus.core import HydrusData from hydrus.core import HydrusSerialisable from hydrus.client import ClientApplicationCommand as CAC from hydrus.client import ClientConstants as CC from hydrus.client import ClientData from hydrus.client import ClientDefau...
7,971
import requests import json import time import random from . import conf, data, lang from inukit.timestamp import natural_date, natural_time, timestamp_now def is_same_day(ts1, ts2) -> bool: def d(ts): return natural_date(ts, '%Y-%m-%d') return d(ts1) == d(ts2) def handle_morning(qq): last_morning =...
430
""" Django settings for app project. Generated by 'django-admin startproject' using Django 2.1.15. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os BASE_DIR ...
608
'''Test config updates ''' import subprocess import os import json import time import datetime import requests import pytest G_TEST_HOST = 'http://127.0.0.1:12345' def run_command(command): p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate()...
4,413
"""The setup script.""" from setuptools import find_packages, setup test_requirements = [ "black>=19.10b0", "flake8>=3.8.3", "flake8-debugger>=3.2.1", ] dev_requirements = [ *test_requirements, "wheel>=0.34.2", ] requirements = [ "cdp-backend[pipeline]==3.0.2", "cdp-scrapers[king_county]>=0....
348
from scrapy.spider import BaseSpider from scrapy.http import Request from scrapy.selector import XmlXPathSelector from openrecipes.spiders.elanaspantry_spider import ElanaspantryMixin class ElanaspantryfeedSpider(BaseSpider, ElanaspantryMixin): name = "elanaspantry.feed" allowed_domains = [ "www.elanasp...
171
from django.db import models from AlyMoly.mantenedor.models import Producto, Promocion, Trabajador class Turno(models.Model): """ estado: 1 --> abierto 2 --> cerrado """ fecha_apertura_sistema = models.DateTimeField() fecha_cierre_sistema = models.DateTimeField(null=True,...
743
"""Train (basic) densely-connected oracle.""" import os import time import multiprocessing as mp import pandas as pd import torch from torch import optim from torch.utils.data import DataLoader, Subset, TensorDataset, WeightedRandomSampler from profit.dataset.splitters import split_method_dict from profit.models.torch ...
1,108
import os import mock import grpc from grpc.experimental import aio import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core imp...
35,846
import numpy as np from skimage.morphology import max_tree, area_closing, area_opening from skimage.morphology import max_tree_local_maxima, diameter_opening from skimage.morphology import diameter_closing from skimage.util import invert from skimage._shared.testing import assert_array_equal, TestCase eps = 1e-12 def _...
8,835
import logging import os from pathlib import Path from typing import Any, Callable, Optional from torch.utils.data import Dataset from torchvision import transforms from PIL import Image import cv2 import numpy as np class URISC(Dataset): def __init__( self, dir: str, mode: str = 'train', ...
479
import torch.nn as nn class FeatureMatchingLoss(nn.Module): r"""Compute feature matching loss""" def __init__(self, criterion='l1'): super(FeatureMatchingLoss, self).__init__() if criterion == 'l1': self.criterion = nn.L1Loss() elif criterion == 'l2' or criterion == 'mse': ...
265
import time import uuid from eventlet.green import threading from oslo_config import cfg from oslo_log import log as logging import six from cinder import exception from cinder.i18n import _ from cinder import utils from cinder.volume import configuration from cinder.volume.drivers.san import san import cinder.volume.d...
3,540
""" Author: Alexander David Leech Date: 30/09/2015 Rev: 2 Lang: Python 2.7 Deps: Pyserial, Pymodbus, logging """ import time import logging from pymodbus.client.sync import ModbusSerialClient \ as ModbusClient ...
231
import os import subprocess from unittest import mock import pytest from pre_commit.constants import VERSION as PRE_COMMIT_VERSION import testing.git from all_repos import autofix_lib from all_repos import clone from all_repos import git from all_repos.config import load_config @pytest.mark.parametrize( ('cli_repos...
3,043
""" Generate random usernames in """ import random from .names import names as default_names class NameGenerator(object): def __init__(self, names=None): self.names = names or default_names def __call__(self): return self.names.pop(random.randrange(len(self.names))) def __iter__(self): ...
78
from django.utils import timezone from rest_framework.authtoken.models import Token class AuthTokenHandler: """ Handles variations in auth token """ @staticmethod def expired_token(auth_token): """ Checks expiry of auth token """ utc_now = timezone.now() expir...
139
from .useful_functions import get_ngrams, words_to_ngrams_list, remove_hook_words, remove_words from .transformers import phrases_transform, phrases2lower, phrases_without_excess_symbols from .tokenizers import text2sentences, split_by_words, sentence_split from .stemlem_operators import create_stemmer_lemmer, create_s...
123
import dependency_checker import dependency_installer import dependency_updater import logger from rendering import VortexWindow import pyglet import sys if sys.version_info < (3, 6): logger.critical( "Vortex", "Python version is too old. Please use python 3.6 or higher.") sys.exit(1) if not dependenc...
154
""" Intergation of the pytorch_transformers openai and gpt2 modules. Note that these objects are only to be used to load pretrained models. The pytorch-transformers library wasn't designed to train these models from scratch. """ import pytorch_transformers as pt from flambe.nlp.transformers.utils import TransformerText...
302
from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, LSTM, Dense import tensorflow.keras as keras from zoo.automl.model.abstract import BaseModel from zoo.automl.common.util import * from zoo.automl.common.metrics import Evaluator class LSTMSeq2Seq(BaseModel): def __init__(self, chec...
2,457
from src.layers.LayerHelper import * from settings import LayerSettings as layerSettings import tensorflow as tf import os CUDA_VISIBLE_DEVICES=0 os.environ["CUDA_VISIBLE_DEVICES"] = "0" def LSTM(name_, inputTensor_, numberOfOutputs_, isTraining_, dropoutProb_=None): with tf.name_scope(name_): cell = tf.nn.rnn_cell...
373
import wx import re import string help_pat = re.compile( r'(.*){(.*)}(.*)' ) options_pat = re.compile( r'(.*)\[(.*)\](.*)' ) key_map = { 'F1': wx.WXK_F1, 'F2': wx.WXK_F2, 'F3': wx.WXK_F3, 'F4': wx.WXK_F4, 'F5': wx.WXK_F5, 'F6': wx.WXK_F6, 'F7': wx.WXK_F7, 'F8': wx.WXK_F8, ...
1,666
"""LCM type definitions This file automatically generated by lcm. DO NOT MODIFY BY HAND!!!! """ import cStringIO as StringIO import struct class request_t(object): __slots__ = ["utime"] def __init__(self): self.utime = 0 def encode(self): buf = StringIO.StringIO() buf.write(request_t...
416
from conans import ConanFile, CMake import os channel = os.getenv("CONAN_CHANNEL", "testing") username = os.getenv("CONAN_USERNAME", "memsharded") class EasyLoggingTestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "easyloggingpp/9.94.1@%s/%s" % (username, channel) generators...
190
"""Interaction Transformation expression's **Inspector** Sub-module containing three classes to help inspect and explain the results obtained with the itea. - ``ITExpr_explainer``: Implementations of feature importances methods specific to the Interaction-Transformation representation, and several visualization ...
415
import unittest from ovos_plugin_manager.skills import find_skill_plugins class TestPlugin(unittest.TestCase): @classmethod def setUpClass(self): self.skill_id = "ovos-skill-timer.OpenVoiceOS" def test_find_plugin(self): plugins = find_skill_plugins() self.assertIn(self.skill_id, lis...
73
from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Convolution2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU from keras.optimizers import Adam from sklearn.model_selection import train_test_split from keras.mo...
1,453
import pytest from brownie import interface def test_uniswap_add_two_tokens( admin, alice, chain, bank, werc20, ufactory, urouter, simple_oracle, oracle, celo, cusd, ceur, UniswapV2SpellV1, UniswapV2Oracle, core_oracle ): spell = UniswapV2SpellV1.deploy(bank, werc20, urouter, celo, {'from': admin}) cusd.min...
872
""" This module patches a few core functions to add compression capabilities, since gevent-websocket does not appear to be maintained anymore. """ from socket import error from zlib import ( decompressobj, MAX_WBITS, Z_FULL_FLUSH, ) from geventwebsocket.exceptions import ( ProtocolError, WebSocketEr...
607