code stringlengths 1 199k |
|---|
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
'''
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.utils import six
from .common im... |
__author__ = 'Thomas Rueckstiess, ruecksti@in.tum.de'
from environment import Environment
class GraphicalEnvironment(Environment):
""" Special type of environment that has graphical output and therefore needs a renderer.
"""
def __init__(self):
self.renderer = None
def setRenderer(self, renderer... |
from __future__ import print_function, absolute_import, division
import os
from peewee import *
from playhouse.pool import PooledMySQLDatabase
try:
import yaml
except ImportError:
from .yaml import yaml
__all__ = ['get_database']
def get_settings(config_file=None):
""" Parse config file and load settings
... |
"""
continuity
~~~~~~~~~~
Continuity API.
:copyright: 2015 by Jonathan Zempel.
:license: BSD, see LICENSE for more details.
"""
__author__ = "Jonathan Zempel"
__license__ = "BSD"
__version__ = "1.0.1" |
import tornado.web
import tornado.ioloop
import tornado.concurrent
import logging
path_maps = {
}
class get(object):
def __init__(self, path, names=None):
global path_maps
self.path = path
path_maps[path] = self
self.function = None
if names is None:
names = []
... |
"""
cookiecutter.cleanup
--------------------
Functions for cleaning up after Cookiecutter project generation occurs.
"""
from __future__ import unicode_literals
import logging
import os
import shutil
from .exceptions import MissingProjectDir
def remove_repo(repo_dir, generated_project):
"""
Move the generated ... |
"""
Implement go_library, go_binary and go_test
"""
import os
import subprocess
import blade
import build_rules
import configparse
import console
from target import Target
from blade_util import var_to_list
class GoTarget(Target):
"""This class is the base of all go targets. """
_go_os = None
_go_arch = Non... |
from tastypie.resources import ModelResource
from brubeck.blogs.models import Entry,Blog
from tastypie import fields
from brubeck.publishing.api import SectionResource
class BlogResource(ModelResource):
section = fields.ForeignKey(SectionResource, 'blog')
class Meta:
queryset = Blog.objects.all()
resource_name = ... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 30, transform = "RelativeDifference", sigma = 0.0, exog_count = 100, ar_order = 0); |
from nose.tools import eq_
import bot_mock
from pyfibot.modules import module_urltitle
import pytest
from vcr import VCR
my_vcr = VCR(path_transformer=VCR.ensure_suffix('.yaml'),
cassette_library_dir="tests/cassettes/",
record_mode=pytest.config.getoption("--vcrmode"))
@pytest.fixture
def botm... |
import threading
import numpy
import time
import os.path
from ginga.misc import Widgets, CanvasTypes, Bunch
from ginga.util import iqcalc, wcs
from ginga import GingaPlugin
from ginga.util.six.moves import map, zip, filter
try:
from ginga.misc import Plot
have_mpl = True
except ImportError:
have_mpl = False... |
from __future__ import absolute_import
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'i_gng.settings')
from django.conf import settings # noqa
app = Celery('i_gng_cel')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task... |
import os.path
from shipmaster.core.plugins import Plugin
class SSHPlugin(Plugin):
@classmethod
def contribute_to_argparse(cls, parser, commands):
commands['run'].add_argument(
"--debug-ssh-agent",
help="Show some output related to ssh-agent forwarding.",
action="stor... |
"""
>>> from django.core.paginator import Paginator
>>> from linaro_django_pagination.templatetags.pagination_tags import paginate
>>> from django.template import Template, Context
>>> p = Paginator(range(15), 2)
>>> pg = paginate({'paginator': p, 'page_obj': p.page(1)})
>>> pg['pages']
[1, 2, 3, 4, 5, 6, 7, 8]
>>> pg[... |
from traits.api import Code, Button, Int, on_trait_change, Any, HasTraits,List, Str, Enum, Instance, Bool
from traitsui.api import (View, Item, Group, HGroup, CodeEditor,
spring, Handler, EnumEditor)
from cviewer.plugins.cff2.csurface_darray import CSurfaceDarray
class SurfaceParame... |
'''
Tests that normally require you to close the tray icons etc
'''
from __future__ import print_function
from __future__ import absolute_import
import os
import time
import queue
import pytest
from system_tray import SystemTray
import tray
ICON_FILE = os.path.join(os.getcwd(), 'Heineken2.ico')
TOOLTIP = 'testing_toolt... |
from __future__ import unicode_literals, division
from celery.app import app_or_default
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from accio import models
from psutil import Process
@admin.register(models.Job)
class JobAdmin(ModelAdmin):
list_display = ('task', 'args', 'kwargs', '... |
from .PBXItem import *
class PBXTargetDependency(PBXItem):
def __init__(self, identifier, dictionary):
super(self.__class__, self).__init__(identifier, dictionary)
def resolveGraph(self, project):
super(self.__class__, self).resolveGraph(project)
self.resolveGraphNodeForKey(kPBX_TARGETDE... |
"""
Tests for scaling utilities module.
"""
from __future__ import annotations
from math import pi, sqrt
import numpy as np
import pytest
from dxtbx.model import (
Beam,
Crystal,
Experiment,
ExperimentList,
GoniometerFactory,
Scan,
)
from dxtbx.serialize import load
from libtbx import phil
from ... |
from __future__ import absolute_import, unicode_literals
import json
import os
from django.contrib.contenttypes.models import ContentType
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.shortcuts import render
from django.utils.encoding import python_2_unicode_compati... |
""" Set of tools relate to version numbers
"""
import re
def compare(a_str, b_str):
""" Compare two versions
>>> compare("1.2.3", "1.2.3")
0
>>> compare("1.2.3", "1.2.3-rc1")
-1
>>> compare("1.20", "1.3")
1
>>> compare("1.20", "1.3-rc2")
1
"""
v_a = explode_version(a_str)
... |
import os
def get_file_list(path, extension):
"""Get a sorted list of full file names (with path) in a given `path` folder having a given `extension`"""
return sorted([
"{}/{}".format(dir_path, file_name)[2:]
for dir_path, dir_names, file_names in os.walk(path)
for file_name in file_name... |
import unittest
class TelemetryTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass |
from Scenario2 import Constants
__author__ = 'daniel.dinu'
class CipherImplementationStatistics:
def __init__(self, name, block_size, key_size, implementation_version, position=0):
"""
Initialize cipher implementation statistics
:param name: Cipher name
:param block_size: Cipher bloc... |
import numbers
from typing import List, Optional, Tuple, Type
import warnings
import numpy as np
from pandas._libs import lib, missing as libmissing
from pandas._typing import ArrayLike, DtypeObj
from pandas.compat.numpy import function as nv
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.ca... |
"""
Shogun KMM demo based on interactive SVM demo by Christian \
Widmer and Soeren Sonnenburg which itself is based on PyQT Demo by Eli Bendersky
Cameron Lai
License: GPLv3
"""
import numpy
import sys, os, csv
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import matplotlib
from matplotlib.colorbar import make_ax... |
import sys
if sys.platform == 'cli':
import clr
import math
clr.AddReference("NumpyDotNet")
import NumpyDotNet
NumpyDotNet.umath.__init__()
pi = math.pi
e = math.e
from NumpyDotNet.umath import *
def frompyfunc(*args):
raise NotImplementedError() |
import os
import sysconfig
from .query_processor import *
from .tract_label_indices import *
from .shell import *
from . import tractography
def find_queries_path():
possible_paths = []
# Try all possible schemes where python expects data to stay.
for scheme in sysconfig.get_scheme_names():
default_... |
"""
The redundancy measure of Sigtermans based on causal tensors.
"""
import numpy as np
from ...exceptions import ditException
from ..pid import BaseBivariatePID
__all__ = (
'PID_CT',
)
def i_triangle(d, source_0, source_1, target):
"""
Compute the path information, and if it is direct or not.
Paramete... |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'TEST_NAME': ':memory:',
},
}
ALLOWED_HOSTS = []
TIME_ZONE = 'America/Chicago'
LANGUAGE... |
from keras.callbacks import Callback
from keras import backend as K
from kaos.nputils import log_sum_exp
from kaos.utils import tuplify, listify
import numpy as np
import csv
from collections import deque, OrderedDict, Iterable
import sys
import os
def _print(stream, string):
print(string, file = sys.stdout)
if... |
from django.template import loader, RequestContext
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.core.xheaders import populate_xheaders
from django.utils.safestring import mark_safe
from django.v... |
from collections import namedtuple
from checks import AgentCheck
import requests
class PowerDNSRecursorCheck(AgentCheck):
# See https://doc.powerdns.com/md/recursor/stats/ for metrics explanation
GAUGE_METRICS = [
'cache-entries',
'concurrent-queries',
'failed-host-entries',
'neg... |
from django.contrib import admin
from .models import *
from goflow.workflow.models import Transition
from goflow.workflow.admin import TransitionAdmin as TransitionAdminOld
class ImageAdmin(admin.ModelAdmin):
list_display = ('category', 'graphic', 'file', 'url')
list_filter = ('category',)
admin.site.register(I... |
try:
from google.appengine.api import apiproxy_stub_map
except ImportError:
from .boot import setup_env
setup_env()
import os
import sys
from djangoappengine.utils import on_production_server
DEBUG = not on_production_server
TEMPLATE_DEBUG = DEBUG
SITE_ID = 1
if on_production_server:
DATABASES = {
'defau... |
from __future__ import (absolute_import, division, print_function)
def patch_well_known_namespaces(etree_module):
import warnings
from owscapable.namespaces import Namespaces
ns = Namespaces()
"""Monkey patches the etree module to add some well-known namespaces."""
try:
register_namespace = ... |
import os
from unittest import TestCase
from mock import patch, Mock, MagicMock
from purchasing.notifications import Notification
class TestNotification(TestCase):
def setUp(self):
os.environ['CONFIG'] = 'purchasing.settings.TestConfig'
@patch('purchasing.notifications.render_template', return_value='a ... |
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
class Command(BaseCommand):
help = 'Create admin user'
def handle(self, *args, **options):
if options['verbosity'] >= 1... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import copy
import os
import select
import socket
import threading
import time
import uuid
import warnings
from ..extern.six.moves import queue, range
from ..extern.six.moves import xmlrpc_client as xmlrpc
from ... |
"""Interface to `slugs` synthesizer."""
from __future__ import absolute_import
from __future__ import print_function
import datetime
import json
import logging
import os
import pprint
import subprocess32
import sys
import time
import textwrap
import humanize
from omega.symbolic import symbolic as _symbolic
import natso... |
import sys
import unittest
from dbuf import compile
class TestSignature (unittest.TestCase):
def test_signature (self):
checktable = {'org.dbuf.test.Signature.BasicTypes' : '(ybnqiuxtdsogv)',
'org.dbuf.test.Signature.ArrayTypes' : '(yay)',
... |
from . import domainresource
class OrderResponse(domainresource.DomainResource):
""" A response to an order.
"""
resource_name = "OrderResponse"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless ... |
"""
A lexical analyzer class for IMAP responses.
Although Lexer does all the work, TokenSource is the class to use for
external callers.
"""
from __future__ import unicode_literals
import six
__all__ = ["TokenSource"]
CTRL_CHARS = frozenset(c for c in range(32))
ALL_CHARS = frozenset(c for c in range(256))
SPECIALS = f... |
import numpy as np
import scipy as sp
from scipy.linalg import hankel
from scipy.signal import hilbert
import matplotlib.pyplot as plt
from .maths import square, is_power2, prime_factors, compute_n_fft, next_power2
from .viz import compute_vmin_vmax
class Spectrum(object):
"""Spectral estimator following Welch's me... |
"""
Encapsulates task scheduling.
enqueue() submits a task, and tasks are processed sequentially, in the order
in which they are submitted.
The actual task queue implementation is encapsulated (and hidden) in this
module.
Task types are mapped to task implementations by implForName, and those
implementations are execut... |
from __future__ import unicode_literals
import shutil
import tempfile
import warnings
from django.utils import six
class TempDirMixin(object):
tempDirPrefix = None
def setUp(self):
"""
Creates a pristine temp directory.
"""
super(TempDirMixin, self).setUp()
if self.tempDi... |
from sqlalchemy.ext.assignmapper import assign_mapper
from sqlalchemy import *
from paste.util.import_string import eval_import
from authkit.users import *
class UsersFromDatabase(Users):
"""
Database Version
"""
def __init__(self, model, encrypt=None):
if encrypt is None:
def encryp... |
"""
taggerTrainingKeras.py
train Deep Named entities tagger
H. Déjean
copyright Naverlabs 2017
READ project
Developed for the EU project READ. The READ project has received funding
from the European Union's Horizon 2020 research and innovation programme
under grant agreement No 674943.
... |
import os
from typing import Union, Tuple
from torchtext._internal.module_utils import is_module_available
from torchtext.data.datasets_utils import (
_wrap_split_argument,
_create_dataset_directory,
)
if is_module_available("torchdata"):
from torchdata.datapipes.iter import FileOpener, HttpReader, Iterable... |
from .. import FairseqOptimizer
class FairseqLRScheduler(object):
def __init__(self, args, optimizer):
super().__init__()
if not isinstance(optimizer, FairseqOptimizer):
raise ValueError('optimizer must be an instance of FairseqOptimizer')
self.args = args
self.optimizer ... |
from __future__ import absolute_import
import os
from flask import Flask as _Base, abort
from flask.helpers import send_from_directory
class Flask(_Base):
def __init__(self, *args, **kwargs):
kwargs.setdefault('static_url_path', '')
super(Flask, self).__init__(*args, **kwargs)
def send_static_fi... |
"""Contains form class defintions for form for the questions app.
Classes: [
SurveyQuestionForm
]
"""
from django import forms
from django.core.urlresolvers import reverse
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout
from . ... |
import requests
import igraph as ig
OMNIPATH_ROOT='http://omnipathdb.org'
def get_omnipath_ptm_graph():
query = OMNIPATH_ROOT+'/ptms'
response = requests.get(query)
if response.status_code != 200:
print('Error requesting %s ...' % query)
return None
data = response.content.decode('utf-8'... |
"""
stock.py
:copyright: (c) 2015 by Fulfil.IO Inc.
:license: BSD, see LICENSE for more details.
"""
from trytond.pool import PoolMeta, Pool
from trytond.transaction import Transaction
from trytond.model import fields
from trytond.pyson import Eval
__metaclass__ = PoolMeta
__all__ = ['Move']
class Move:
... |
"""
Author: Dr. John T. Hwang <hwangjt@umich.edu>
This package is distributed under New BSD license.
"""
import numpy as np
import scipy.sparse.linalg
import scipy.linalg
import contextlib
from smt.utils.options_dictionary import OptionsDictionary
VALID_SOLVERS = (
"krylov-dense",
"dense-lu",
"dense-chol",
... |
import socket
import urllib2
import time
import csv
import sys
from multiprocessing import Process
from math import sqrt
KNOWN = "123456789"
UNKNOWN = '0'*(9-len(KNOWN))
ON_STRIPE = False
if ON_STRIPE:
PRIMARY_SERVER = "https://level08-1.stripe-ctf.com/user-xgxyqyxucz/"
WEBHOOK = "level02-3.stripe-ctf.com"
... |
"""
interfaces
~~~~~~~~~~
Implements a ``implements()`` function that does interfaces. It's
a very simple implementation and does not handle multiple calls
to implements() properly.
:copyright: (c) Copyright 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import sys... |
"""A data source for reading from pre-recorded OpenXC trace files."""
import logging
import time
from .base import DataSourceError, BytestreamDataSource
from openxc.formats.json import JsonFormatter
LOG = logging.getLogger(__name__)
class TraceDataSource(BytestreamDataSource):
"""A class to replay a previously reco... |
from django.forms import ModelForm
from cyder.cydns.cname.models import CNAME
class CNAMEForm( ModelForm ):
class Meta:
model = CNAME
exclude = ('data_domain', 'fqdn') |
from .textinput import TextInput
class PasswordInput(TextInput):
def __init__(self, initial=None, placeholder=None, readonly=False, on_keyUp=None, on_endEditing=None, on_beginEditing=None, on_textChange=None):
super(PasswordInput, self).__init__(initial, placeholder, readonly, on_keyUp, on_endEditing, on_be... |
import cv2
from numpy import math, hstack
import numpy as np
class FileVideoCapture(object):
def __init__(self, path):
self.path = path
self.frame = 1
def isOpened(self):
im = cv2.imread(self.path.format(self.frame))
return im != None
def read(self):
im = cv2.imread(self.path.format(self.frame))
status =... |
from flask.ext.wtf import Form
from wtforms import TextField, PasswordField,DecimalField
from wtforms.validators import Required, DataRequired
from app import db,models
class LoginForm(Form):
def get_default_money():
cash = models.Info.query.get(1)
if cash is not None:
return int(cash.money)
else:
return 0... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('talks', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='talk',
name='email',
field=models.EmailFie... |
import numpy as np
def im3DNORM(img, normind, varargin=None):
"""
% IMAGE3DNORM computes the desired image norm
% IMAGE3DNORM(IMG,NORMIND) computes the norm of image IMG using the norm
% defined in NORMIND
%
% IMG A 3D image
% NORMIND {non-zero int, inf, -inf, 'fro', 'nuc... |
from typing import Optional, Union, Mapping # Special
from typing import Sequence # ABCs
from typing import Tuple # Classes
import numpy as np
import pandas as pd
from anndata import AnnData
from matplotlib.axes import Axes
from matplotlib import pyplot as pl
from matplotlib.colors import Normalize
from .. import lo... |
"""Presubmit tests for android_webview/support_library/
Runs various style checks before upload.
"""
def CheckChangeOnUpload(input_api, output_api):
results = []
results.extend(_CheckAnnotatedInvocationHandlers(input_api, output_api))
results.extend(_CheckFeatureDevSuffix(input_api, output_api))
return results
... |
from distutils.core import setup, Extension
excmem = Extension('pyasm.excmem',['pyasm/excmem/excmem.c'])
structs = Extension('pyasm.structs',['pyasm/structs/structs.c'])
setup(name='pyasm',
version='0.3',
description='dynamic x86 assembler for python',
author='Grant Olson',
author_email='kgo@gra... |
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise RuntimeError("Python 2.7 or later required")
if __package__ or "." in __name__:
from . import _datacollection
else:
import _datacollection
try:
import builtins as __builtin__
except ImportError:
... |
import requests
import time
from mock import patch, MagicMock, ANY
from datetime import datetime
try:
# Django <= 1.6 backwards compatibility
from django.utils import simplejson as json
except ImportError:
# Django >= 1.7
import json
from django.contrib.auth.models import User
from django.contrib.sites.... |
from flask import Flask, render_template, request
app = Flask(__name__)
app.config['DEBUG'] = True # Enable this only while testing!
@app.route('/')
def hello():
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0') |
import time
from dpl.core.things import Slider, ThingRegistry, ThingFactory, Actuator
from .shift_reg_gpio_buffered import ShiftRegBuffered, ShiftRegGPIOBuffered
def check_shift_reg_type(test_obj):
if not isinstance(test_obj, ShiftRegBuffered):
raise ValueError('type of con_instance value must be a ShiftReg... |
import sys
from os import listdir
from os.path import abspath, join, splitext, isdir
from json import load
from app.plugins.autograder import getTestFileParsers
USAGE = """Usage:
python graderTester <pluginName> <testfolder>
"""
def findTestFile(folderPath, folderName):
for f in listdir(folderPath):
if splitext(f... |
"""
Standardize names of data files on Florida Department of State.
File-name conventions on FL site are very consistent: tab-delimited text files containing county-level results are retrieved by election date:
https://doe.dos.state.fl.us/elections/resultsarchive/ResultsExtract.Asp?ElectionDate=1/26/2010&OfficialRe... |
import cv2
from android import Android
droid = Android()
import numpy as np
def rectify(h):
h = h.reshape((4,2))
hnew = np.zeros((4,2),dtype = np.float32)
add = h.sum(1)
hnew[0] = h[np.argmin(add)]
hnew[2] = h[np.argmax(add)]
diff = np.diff(h,axis = 1)
hnew[1] = h[np.argmin(diff)]
hnew[3... |
import pyb
from pyb import I2C
if not hasattr(pyb, 'Accel'):
print('SKIP')
raise SystemExit
accel_addr = 76
pyb.Accel() # this will init the MMA for us
i2c = I2C(1, I2C.MASTER, baudrate=400000)
print(i2c.scan())
print(i2c.is_ready(accel_addr))
print(i2c.mem_read(1, accel_addr, 7, timeout=500))
i2c.mem_write(0, ... |
from .jobscheduler import JobExistError
from .jobscheduler import JobScheduler
from .jobscheduler import NextFireTimeError
from .jobscheduler import get_next_fire_time
__all__ = [
'JobExistError',
'JobScheduler',
'NextFireTimeError',
'get_next_fire_time',
] |
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.req... |
import ShareYourSystem as SYS
MyNbconverter=SYS.NbconverterClass(
).folder(
SYS.Classor
).scriptbook(
**{
'GuidingBookStr':'Doc'
}
).notebook(
'Presentation.ipynb'
).nbconvert(
'Readme.md'
)
print('MyNbconverter is ')
SYS._print(MyNbconverter) |
from .env import *
from .files import *
from .net import *
from .oss import *
from .system_pm import *
from .win import *
from .pkg_config import *
from .scm import *
from .apple import * |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/armor/mandalorian/shared_armor_mandalorian_gloves.iff"
result.attribute_template_id = 0
result.stfName("wearables_name","armor_mandalorian_gloves")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ... |
"""Objects for encapsulating parameter initialization strategies."""
from abc import ABCMeta, abstractmethod
import numbers
import numpy
import theano
from six import add_metaclass
@add_metaclass(ABCMeta)
class NdarrayInitialization(object):
"""Base class specifying the interface for ndarray initialization."""
... |
"""Support for the Locative platform."""
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS
from homeassistant.components.device_tracker.config_entry import TrackerEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpe... |
import typing
import pint # type: ignore
class QuantityRange:
def __init__(self) -> None:
self._lower: typing.Optional[pint.quantity.Quantity] = None
self._upper: typing.Optional[pint.quantity.Quantity] = None
@classmethod
def from_pair(cls, value1: pint.quantity.Quantity, value2: pint.quan... |
"""
Complement the regions of a bed file. Requires a file that maps source names
to sizes. This should be in the simple LEN file format (each line contains
a source name followed by a size, separated by whitespace).
usage: %prog bed_file chrom_length_file
"""
import sys
from bx.bitset import *
from bx.bitset_builders i... |
import json
import requests
import logging
""" OANDA API wrapper for OANDA's REST API """
""" EndpointsMixin provides a mixin for the API instance
Parameters that need to be embedded in the API url just need to be passed as a keyword argument.
E.g. oandapy_instance.get_instruments(instruments="EUR_USD")
"""
logging.get... |
import os;
import sys;
import fnmatch;
import subprocess;
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__));
def find_files(start_path, file_pattern, max_depth=-1):
matches = []
for root, dirnames, filenames in os.walk(start_path):
for filename in fnmatch.filter(filenames, file_pattern):
depth = len(root... |
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
DATA = "test.txt";
voltage, deflection, uncertainty = np.loadtxt(DATA, skiprows=26 , unpack=True, delimiter=',');
plt.xlabel("Voltage (V)");
plt.ylabel("Deflection (mm)");
plt.title("Voltage vs. Deflection at 435nm");
plt.plot(defle... |
from django.contrib import admin
from chatterbot.ext.django_chatterbot.models import Statement, Response
class StatementAdmin(admin.ModelAdmin):
list_display = ('text', )
list_filter = ('text', )
search_fields = ('text', )
class ResponseAdmin(admin.ModelAdmin):
list_display = ('statement', 'occurrence',... |
from quaternions.quaternion import Quaternion |
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/particle/shared_particle_test_40.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from django.shortcuts import render
from store.models import userDetail
from store.models import authDb
from store.models import logDb
from django import forms
from django.core.mail import send_mail
... |
import pytest
from mitmproxy.utils.spec import parse_spec
def test_parse_spec():
flow_filter, subject, replacement = parse_spec("/foo/bar/voing")
assert flow_filter.pattern == "foo"
assert subject == "bar"
assert replacement == "voing"
flow_filter, subject, replacement = parse_spec("/bar/voing")
... |
from telex.plugin.ConfigurablePluginManager import ConfigurablePluginManager
import configparser
PLUGIN_CONFIG_NAME="plugins.conf"
def __get_section_name(category_name, plugin_name):
if category_name and category_name != "Default":
return "{}: {}".format(category_name, plugin_name)
return plugin_name
de... |
"""
OLASS Client
------------
OneFlorda Linkage Submission System (OLASS) client software
<https://github.com/ufbmi/olass-client> is designed to compute hashes of the
specific patient data elements and submit them to the OLASS server
<https://github.com/ufbmi/olass-server> to achieve de-duplication.
The client authoriz... |
from sklearn.cross_validation import KFold
from sklearn.cross_validation import train_test_split
from sklearn.metrics import mean_squared_error
from math import sqrt
import numpy as np
import pandas as pd
import scipy as sci
from matplotlib import pyplot as plt
from sklearn.metrics import r2_score
def plot_r2(y, y_pred... |
from flask import Blueprint
api = Blueprint('api', __name__)
from . import connect, hd, slow, wv, hk, adu5, mon, history, turf, hk_surf, sshk, g12, cmd |
from typing import Optional
from mitmproxy.contrib.wbxml import ASCommandResponse
from . import base
class ViewWBXML(base.View):
name = "WBXML"
__content_types = (
"application/vnd.wap.wbxml",
"application/vnd.ms-sync.wbxml"
)
def __call__(self, data, **metadata):
try:
... |
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
j = 1
i = 0
nums_len = len(nums)
while j < nums_len:
if nums[j] != nums[i]:
i += 1... |
""" Deployment Settings
@requires: U{B{I{gluon}} <http://web2py.com>}
@copyright: 2009-2014 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in t... |
from handler.base_plugin import CommandPlugin
from utils import upload_photo
from PIL import Image, ImageDraw, ImageFont
import aiohttp, io
class MemeDoerPlugin(CommandPlugin):
__slots__ = ("fonts", "sizes", "allow_photos", "default_photo")
def __init__(self, *commands, prefixes=None, strict=False, font="impact... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.