code stringlengths 1 199k |
|---|
import common
import os
import sys
import uuid
def get_plan_by_name(name):
'''
Get plan info by name
'''
ast = common.acli()
ast.conn()
ast.sendCmd("OutPlanShow")
res = ast.recvArr()
size = len(res)
for i in range(size):
res_dict = common.make_dict(res[i])
if name == ... |
from itertools import izip, cycle, count
from django.core import validators
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from django.forms import fields, widgets
from django.core.exceptions import ValidationError
from django.forms.util import ErrorList
from django.utils.safestr... |
from __future__ import division # 1/2 = 0.5, not 0.
from sackmat_m import *
def test_submx_premul():
A = sackmat([
[1,2,3],
[4,5,6],
[7,8,9]])
Q = sackmat([
[0,1],
[1,0]])
[sr, ar] = [1, 1]
Q.printp("Q")
A.printp("Old A")
A.premultiply_by_submatrix(Q, sr, ar)
A.printp("New A")
def test_tip():
A = sack... |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Face... |
from django.conf import settings
from django.core.mail import get_connection
from celery.task import task
import commands
@task
def pomodoro(sender=None,id=None):
'''
'''
commands.getoutput("open http://www.google.com") |
from sgext.drivers.devices.loadbalancers.amazonelb import * |
from __future__ import (absolute_import, division, print_function)
from .._sympy_Lambdify import _callback_factory
from sympy import symbols, atan
import numpy as np
import pytest
try:
import numba
except ImportError:
numba = None
def test_callback_factory():
args = x, y = symbols('x y')
expr = x + atan... |
from __future__ import generators
import time
import traceback
from UserList import UserList
from Queue import Queue, Empty as QueueEmpty
from celery.utils.compat import OrderedDict
class AttributeDict(dict):
"""Dict subclass with attribute access."""
def __getattr__(self, key):
try:
return ... |
from django.contrib.contenttypes.models import ContentType
from log_register.models import Lot
from log_register.settings import ERROR, DEBUG, SUCCESS, WARNING, INFO
def get_lot_for_objects(obj, force=False):
"""
This method returns (creates id needed) a Lot object for a object in data base.
This is useful ... |
variables = {"schema_name": "NeuroML_v2.2.xsd"} |
import argparse
import sys
from gzip import GzipFile
from lzma import LZMAFile
from tarfile import TarFile
import ujson
def main(path, verify=False, format='json'):
code = 0
try:
if path.endswith('.pkg.tar.gz'):
f = GzipFile(path)
elif path.endswith('.pkg.tar.xz'):
f = LZ... |
import json
import pathlib
from .mimebundle import spec_to_mimebundle
def write_file_or_filename(fp, content, mode="w"):
"""Write content to fp, whether fp is a string, a pathlib Path or a
file-like object"""
if isinstance(fp, str) or isinstance(fp, pathlib.PurePath):
with open(fp, mode) as f:
... |
from __future__ import print_function, division
import sys,os
qspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,qspin_path)
from quspin.basis import spin_basis_general,spin_basis_1d
from quspin.operators import hamiltonian
from quspin.operators._make_hamiltonian import _consolidate_static
import numpy as n... |
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
- Use sentry for error logging
'''
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.u... |
"""Filesystem database for large binary data objects (blobs)
"""
from __future__ import absolute_import
from corehq.blobs.exceptions import NotFound
class MigratingBlobDB(object):
"""Adaptor for migrating from one blob db backend to another"""
def __init__(self, new_db, old_db):
self.new_db = new_db
... |
from . import domainresource
class Observation(domainresource.DomainResource):
""" Measurements and simple assertions.
Measurements and simple assertions made about a patient, device or other
subject.
"""
resource_type = "Observation"
def __init__(self, jsondict=None, strict=True):
""" I... |
"""
WSGI applications that parse the URL and dispatch to on-disk resources
"""
import os
import sys
import imp
import mimetypes
try:
import pkg_resources
except ImportError:
pkg_resources = None
from paste import request
from paste import fileapp
from paste.util import import_string
from paste import httpexcept... |
from __future__ import unicode_literals
import codecs
import gzip
import os
import six
from six.moves import urllib
from .base import EditorIO
__all__ = (
'FileIO',
'GZipFileIO',
'DirectoryIO',
'HttpIO',
)
ENCODINGS = ['utf-8', 'latin-1']
class FileIO(EditorIO):
"""
I/O backend for the native fi... |
"""Tests for :py:mod:`katdal.concatdata`."""
import numpy as np
from nose.tools import assert_equal, assert_in, assert_not_in, assert_raises
from katdal.categorical import CategoricalData
from katdal.concatdata import ConcatenatedSensorCache
from katdal.sensordata import SensorCache, SimpleSensorGetter
class TestConcat... |
from features import abstract_feature as af
class UserMentionsCountFeature(af.AbstractFeature):
def __repr__(self):
return "<UserMentionsCountFeature>"
def __str__(self):
return "User Mentions Count Feature"
def extract(self, tweet):
return "user_mentions_count", len(tweet.entities.u... |
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE']='opentrain.settings'
from reports.models import RawReport
for x in xrange(int(sys.argv[1]),60000,1000):
rrs = list(RawReport.objects.all().order_by('id')[x:x+1000])
for rr in rrs:
t = rr.get_first_item_timestamp()
if t:
... |
from __future__ import absolute_import, print_function, division
import unittest
import numpy
import theano
from theano import function, config
from theano import scalar
import theano.tensor as tensor
from theano.tensor.elemwise import CAReduce, Elemwise
from theano.tests import unittest_tools as utt
class T_max_and_ar... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from rlpy.Representations import IndependentDiscretizationCompactBinary
from rlpy.Domains import Gri... |
import os
from chirp import *
if __name__ == '__main__':
process_parameters, benchmark_parameters, file_parameters = options_parser.parse_args()
if not file_parameters.pre_sorted:
external_sort.batch_sort(process_parameters, file_parameters)
if benchmark_parameters.read_range_width == 1:
ben... |
import string
import numpy as np
import theano
import theano.tensor as T
from theano.sandbox.cuda import cuda_available, GpuOp
from theano.ifelse import ifelse
if cuda_available:
from theano.sandbox.cuda import (basic_ops, CudaNdarrayType,
CudaNdarray)
from theano.misc.pycuda_in... |
import os
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
def get_test_dir():
return os.path.abspath(os.path.join(os.path.dirname(__file__),
'sources.list.d'))
def test_url_constants():
from rosdep2.gbpdistro_support import ... |
from collections import deque
class node(object):
def __init__(self, label, neighbours):
self.label = label
self.neighbours = neighbours
def xfs(node, b=True):
q = deque()
visited = set([])
q.append(node)
visited.add(node)
while (len(q) > 0):
if b:
n = q.pople... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Event.notes'
db.add_column(u'events_event', 'notes',
self.gf('django.db.models.fields.TextField')... |
"""
DBSCAN: Density-Based Spatial Clustering of Applications with Noise
"""
import numpy as np
from ..base import BaseEstimator, ClusterMixin
from ..metrics import pairwise_distances
from ..utils import check_random_state
from ..neighbors import NearestNeighbors
def dbscan(X, eps=0.5, min_samples=5, metric='minkowski',... |
"""Generated message classes for apikeys version v1.
Manages the API keys associated with developer projects.
"""
from googlecloudsdk.third_party.apitools.base.protorpclite import messages as _messages
from googlecloudsdk.third_party.apitools.base.py import encoding
package = 'apikeys'
class AndroidApplication(_message... |
"""
A family of high-level user commands acting on the entire simulation.
Any new commands added to this directory will automatically become
available for any program.
Commands here should be 'bullet-proof' and work 'from scratch'.
That is, they should print warnings if required but should not raise
errors that would i... |
from leonardo.module.web.models import Widget
from leonardo.module.nav.mixins import NavigationWidgetMixin
from feincms.module.page.extensions.navigation import (NavigationExtension,
PagePretender)
from django.utils.translation import ugettext_lazy as _
class Navig... |
"""
Cores are containers for plugins.
The general purpose core is Client, which handles tcp/ip.
TODO:
udp and ssl clients.
""" |
def extractIsekaisummonMe(item):
'''
Parser for 'isekaisummon.me'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Railway Hero', 'The Legend of the Railway Hero', 'trans... |
default_app_config = 'apps.admin.fail_login.apps.FailLoginConfig' |
from __future__ import division, print_function, absolute_import
__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly',
'RegularGridInterpolator', 'interpn']
import itertools
import warnings
import functools
import operator
import numpy as np
from numpy import (array, transpose, searchso... |
import logging
from flask import flash
from flask_admin._compat import string_types, iteritems
from flask_admin.babel import gettext, ngettext, lazy_gettext
from flask_admin.model import BaseModelView
from flask_admin.model.form import create_editable_list_form
from peewee import PrimaryKeyField, ForeignKeyField, Field... |
__author__ = "Peter Ogden"
__copyright__ = "Copyright 2019, Xilinx"
__email__ = "pynq_support@xilinx.com"
import ctypes
from copy import deepcopy
from xml.etree import ElementTree
from pynq._3rdparty import xclbin
_mem_types = [
"DDR3",
"DDR4",
"DRAM",
"Streaming",
"Preallocated",
"ARE",
"HB... |
import george
import emcee
import numpy as np
from copy import deepcopy
from robo.util import normalization
from robo.models.gaussian_process_mcmc import GaussianProcessMCMC
from robo.models.gaussian_process import GaussianProcess
class FabolasGPMCMC(GaussianProcessMCMC):
def __init__(self, kernel, basis_func,
... |
from fractions import Fraction
import numpy as np
from .core import (UnitsError, UnitConversionError, dimensionless_unscaled,
get_current_unit_registry)
def _d(unit):
if unit is None:
return dimensionless_unscaled
else:
return unit
def get_converter(from_unit, to_unit):
""... |
from collections import defaultdict
import numpy as np
try:
from matplotlib import colors
import matplotlib.cm as cm
except ImportError:
cm, colors = None, None
from bokeh.enums import Palette
from bokeh.plotting import figure, Plot
markers = {'s': {'marker': 'square'},
'd': {'marker': 'diamond'}... |
'''
Tests related to string formatting.
'''
import unittest
import common
class StringFormatTestCase(common.TestCase):
'''
test that new string formatting options are allowed.
'''
def test_format(self):
self.check('test_string_format')
if __name__ == '__main__':
unittest.main() |
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=200)
class Movie(models.Model):
title = models.CharField(max_length=200)
director = models.ForeignKey(Person, models.CASCADE)
class Event(models.Model):
pass
class Screening(Event):
movie = models.ForeignKey(... |
from decorators import _backend
"""Access limits and increment counts without using a decorator."""
def get_limits(request, label, field, periods):
limits = []
count = 10
for period in periods:
limits.extend(_backend.limit(
label,
request,
field=field,
... |
"""
Build arguments parser for the scripts (mapper, reducers and command builder).
"""
import argparse
def get_map_argparser():
"""Build command line arguments parser for a mapper.
Arguments parser compatible with the commands builder workflows.
"""
parser = argparse.ArgumentParser()
parser.add_argu... |
'''
NAME
dewpoint.oauth
DESCRIPTION
This module provides a urllib2 compatible opener for signing requests as
defined by the OAuth 1.0a specification. Only the HMAC-SHA1 signature method
is currently supported.
EXAMPLE
>>> # Basic example using a static consumer token:
>>> from oauth import OAuthHandler, Token, Consumer... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('sms', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='SelfRegistrationInvitation',
fields=[
('id'... |
from ...core import (Add, Dummy, Function, Ge, Gt, I, Integer, Le, Lt,
PrecisionExhausted, Symbol)
from ...logic import false, true
class RoundFunction(Function):
"""The base class for rounding functions."""
@classmethod
def eval(cls, arg):
from .complexes import im
if a... |
from __future__ import print_function, division, absolute_import
from {{cookiecutter.package_name}}.web import create_app
from {{cookiecutter.package_name}}.web.settings import TestConfig, CustomConfig
import pytest
@pytest.fixture(scope='session')
def app():
''' fixture for web app testing '''
object_config = ... |
import os
ROOT = os.path.dirname(os.path.abspath(__file__))
path = lambda *a: os.path.join(ROOT, *a)
DEBUG = True
TEMPLATE_DEBUG = True
SITE_ID = 1
TEST_RUNNER = 'django_nose.runner.NoseTestSuiteRunner'
ADMINS = (
('Joe Admin', 'admin@example.com'),
)
DATABASES = {
'default': {
'NAME': 'test.db',
... |
from __future__ import unicode_literals
from ..utils import MakeSurfaces
def test_MakeSurfaces_inputs():
input_map = dict(args=dict(argstr='%s',
),
copy_inputs=dict(),
environ=dict(nohash=True,
usedefault=True,
),
fix_mtl=dict(argstr='-fix_mtl',
),
hemisphere=dict(argstr='%s',
ma... |
from github3.repos.release import Release, Asset
from .helper import (UnitHelper, UnitIteratorHelper, create_url_helper, mock,
create_example_data_helper)
import github3
import json
import pytest
url_for = create_url_helper(
'https://api.github.com/repos/octocat/Hello-World/releases'
)
get_rele... |
"""
Tests for the permuted_ols function.
"""
import numpy as np
from scipy import stats
from sklearn.utils import check_random_state
from numpy.testing import (assert_almost_equal, assert_array_almost_equal,
assert_array_less, assert_equal)
from nilearn.mass_univariate import permuted_ols
fro... |
"""
Factory functions.
Copyright (c) The Dojo Foundation 2011. All Rights Reserved.
Copyright (c) IBM Corporation 2008, 2011. All Rights Reserved.
"""
"""
Creates a history buffer key from a site ID and sequence ID.
@param {Number} site Integer site ID
@param {Number} seq Integer sequence ID at that site
@returns {Stri... |
import ez_setup
ez_setup.use_setuptools()
from setuptools import find_packages, setup
setup(
name="CHIMERA",
version = "0.1",
packages=find_packages(),
# PROPER uses numpy and scipy
install_requires = ['numpy>=1.8', 'scipy>=0.14', 'pyfits>=3.0', 'pyraf>=2.1', 'photutils>=0.2'],
packa... |
def extractGreenpandatrCom(item):
'''
Parser for 'greenpandatr.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterou... |
import numpy, h5py, pylab
from PnSC_h5io import *
from matplotlib.ticker import FuncFormatter
def myexpformat(x, pos):
for ndigs in range(5):
lab=(('%.'+'%d' %ndigs+'e') %x).replace('e+0','e').replace('e+','e').replace('e0','').replace('e-0','e-')
if eval(lab)==x:
return lab
return l... |
import oauth2 as oauth
import twitter
import urlparse
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.shortcuts import redirect
from regi... |
from django.urls import path
from ..views import popular, snippets
urlpatterns = [
path('', popular.top_tags, name='cab_top_tags'),
path('<slug:slug>/', snippets.matches_tag, name='cab_snippet_matches_tag'),
] |
import os
import requests
import pystache
import xml.etree.ElementTree as ElementTree
from urllib.parse import urljoin
from urllib.request import urlopen
from bs4 import BeautifulSoup
INDEX = 'https://test-is.skaut.cz/JunakWebservice/'
LIB_PATH = 'skautis'
def get_soup(url):
resp = requests.get(url)
resp.raise_... |
import datetime
import logging
from flask import flash, redirect, session, url_for, request, g, make_response, jsonify
from werkzeug.security import generate_password_hash
from wtforms import validators, PasswordField
from wtforms.validators import EqualTo
from flask_babelpkg import lazy_gettext
from flask_login import... |
import os
import shutil
import glob
import time
import sys
import subprocess
import string
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PKG_NAME = os.path.basename(SCRIPT_DIR)
PARAMETERS = None
SRC_DIR = "/home/app/content"
PKG_SRC_DIR = "%s/tct/opt/%s" % (SRC_D... |
from typing import Optional, Union
import numpy as np
import pandas as pd
from matplotlib import pyplot as pl
from matplotlib import rcParams
from anndata import AnnData
from . import _utils
def highly_variable_genes(
adata_or_result: Union[AnnData, pd.DataFrame, np.recarray],
log: bool = False,
show: Optio... |
""" Simple example showing how a Python X-Midas primitive can read
T4000 files into dictionaries easily. """
from XMinter import *
from primitive import *
from t4val import recvT4Tab
hin = m_open(m_pick(1), 'r')
m_sync()
while not mcbreak() :
dictionary = recvT4Tab(hin)
# DON'T HAVE TO DO Grab! The recvT4T... |
from __future__ import absolute_import
from envisage.application_event import * |
import numpy as np
import pandas as pd
from . import SignalDecomposition_AR as tsar
from . import Utils as tsutil
from . import Perf as tsperf
import sys
def is_signal_intermittent(iSeries, iOptions):
series = iSeries - iSeries.min()
zero_values = series[abs(series) < 1e-8]
lZeroRate = zero_values.shape[0] ... |
"""
Alerting for SimpleMonitor
"""
import datetime
import logging
import textwrap
from enum import Enum
from socket import gethostname
from typing import Any, List, NoReturn, Optional, Tuple, Union, cast
import arrow
from ..Monitors.monitor import Monitor
from ..util import (
MonitorState,
check_group_match,
... |
''' calcload.py - Calculate the Waterfall max_load value needed to load the data array for a given file.'''
import sys
from argparse import ArgumentParser
import numpy as np
import blimpy as bl
def calc_max_load(arg_path, verbose=False):
r''' Calculate the max_load parameter value for a subsequent Waterfall instant... |
import gc
import easydict
import numpy as np
import tensorflow as tf
from luminoth.models.base.base_network import (
BaseNetwork, _R_MEAN, _G_MEAN, _B_MEAN, VALID_ARCHITECTURES
)
class BaseNetworkTest(tf.test.TestCase):
def setUp(self):
self.config = easydict.EasyDict({
'architecture': 'vgg_... |
import numpy as np
import pandas as pd
from scipy.linalg import svd, lstsq
from skbio._base import OrdinationResults
from ._utils import corr, svd_rank, scale
from skbio.util._decorator import experimental
@experimental(as_of="0.4.0")
def rda(y, x, scale_Y=False, scaling=1):
r"""Compute redundancy analysis, a type ... |
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Customer(models.Model):
name = models.CharField(max_length=200)
address = models.CharField(max_length=500)
is_active = models.BooleanField(default=T... |
import os.path
import unittest
import numpy as np
import sys
compare_mt_root = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")
sys.path.append(compare_mt_root)
from compare_mt import scorers
from compare_mt.corpus_utils import load_tokens
def _get_example_data():
example_path = os.path.join(compare_mt... |
from celery import task
from django.dispatch.dispatcher import (
_make_id,
Signal,
)
class AsyncSignal(Signal):
def __init__(self, providing_args=None, queue=None):
super(AsyncSignal, self).__init__(providing_args=providing_args)
self.queue = queue
def send(self, sender, **named):
... |
from owslib.coverage.wcsBase import WCSBase, WCSCapabilitiesReader, ServiceException
from urllib import urlencode
from owslib.util import openURL, testXMLValue
from owslib.etree import etree
from owslib.crs import Crs
import os, errno
def ns(tag):
return '{http://www.opengis.net/wcs}'+tag
class WebCoverageService_1... |
"""
This module is to get different formats of molecules from file and web. If you
have any question please contact me via email.
Authors: Zhijiang Yao and Dongsheng Cao.
Date: 2016.06.04
Email: gadsby@163.com
"""
try:
# Python 3
from urllib.request import urlopen
except ImportError:
# Python 2
from url... |
from validator.decorator import version_range
from validator.constants import (FIREFOX_GUID, FENNEC_GUID,
THUNDERBIRD_GUID as TB_GUID, ANDROID_GUID)
FX4_DEFINITION = {FIREFOX_GUID: version_range("firefox", "3.7a1pre", "5.0a2"),
FENNEC_GUID: version_range("fennec", "4.0... |
API_KEY = '2bb5d6b943fc44f0bb6b467450e07ce7' |
""" Test cases for dictionary (Dict) traits. """
from __future__ import absolute_import
from traits.testing.unittest_tools import unittest
from ..trait_types import Dict, Event, Str, TraitDictObject
from ..has_traits import HasTraits, on_trait_change
from ..trait_errors import TraitError
def create_listener():
""" ... |
from collections import defaultdict
from django.template import Template
from cms import api
from cms.models import Placeholder
from cms.test_utils.project.placeholderapp.models import Example1
from cms.test_utils.testcases import TransactionCMSTestCase
from cms.toolbar.toolbar import CMSToolbar
from cms.utils.urlutils... |
import sys
import os
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
import randstr
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'randstr'
copyright = u'2015, Eric Larson'
version ... |
import sys
import os
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
import hexes
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Hexes'
copyright = u'2015, Kit La Touche'
version = ... |
"""Get stats about your activity.
Example:
- my_activity.py for stats for the current week (last week on mondays).
- my_activity.py -Q for stats for last quarter.
- my_activity.py -Y for stats for this year.
- my_activity.py -b 4/5/12 for stats since 4/5/12.
- my_activity.py -b 4/5/12 -e 6/7/12 for stats ... |
import sys
import numpy as np
from fos import *
w = Window( dynamic = True )
scene = Scene( scenename = "Main" )
vert = np.array( [ [0,0,0],
[5,5,0],
[5,10,0],
[10,5,0]], dtype = np.float32 )
conn = np.array( [ 0, 1, 1, 2, 1, 3 ], dtype = np.uint32 )
colt = np.ze... |
{% block meta %}
name: ParsePoseStamped
description:
SMACH template that provides a ParsePoseStamped helper function for, e.g.
PublishMsgState. The function takes an input argument that can be specified
as either a geometry_msgs.msg.Pose type, a geometry_msgs.msg.PoseStamped type,
or a [[3],[4]] list, and retur... |
from pygsp import utils
from pygsp.graphs import NNGraph # prevent circular import in Python < 3.5
class Bunny(NNGraph):
r"""Stanford bunny (NN-graph).
References
----------
See :cite:`turk1994zippered`.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> G = graphs.Bunny()
>>... |
import os, sys
from PIL import Image
size = 28, 28
pathToImageFolder = "/Users/sriramsomasundaram/Desktop/FullHSF/MergedHSF0/"
pathToDestinationFolder = "/Users/sriramsomasundaram/Desktop/HSFresized/"
files_in_dir = os.listdir(pathToImageFolder)
for file_in_dir in files_in_dir:
#outfile = os.path.splitext(infile)[0... |
"""
Identifying function names in a script
======================================
This demonstrates how Sphinx-Gallery identifies function names to figure out
which functions are called in the script and to which module do they belong.
"""
import os # noqa, analysis:ignore
import matplotlib.pyplot as plt
from sphinx_g... |
from __future__ import absolute_import, division, unicode_literals
try:
import urllib.request as urllib_request
import urllib.parse as urllib_parse
except ImportError:
import urllib2 as urllib_request
import urlparse as urllib_parse
import urllib
urllib_parse.urlencode = urllib.urlencode
import json
import re
imp... |
"""STIX 2.1 Domain Objects."""
from collections import OrderedDict
from urllib.parse import quote_plus
import warnings
from stix2patterns.validator import run_validator
from ..custom import _custom_object_builder
from ..exceptions import (
InvalidValueError, PropertyPresenceError, STIXDeprecationWarning,
)
from ..p... |
from django.contrib.auth import backends, load_backend
from django.contrib.auth.models import User
from mailserver.exceptions import PermissionDenied
class MailFromBackend(backends.ModelBackend):
def authenticate(self, request):
name, mail = request['From']
try:
user = User.objects.get(e... |
'''
__main__ -- Main running script for the AstroZeneca data
@author: Max Zwiessele
@copyright: 2015 organization_name. All rights reserved.
@license: BSD3
@contact: m.zwiessele@sheffield.ac.uk
@deffield updated: 29.09.15
'''
import sys
import os
from optparse import OptionParser
from data import load_lib... |
from .context import Context
from .action import Action, Method, Visualizer, Pipeline
from .plugin_manager import PluginManager
from .result import Result, Artifact, Visualization
from .results import Results
from .util import parse_type, parse_format, type_from_ast
from ..core.cite import Citations
__all__ = ['Result'... |
from __future__ import absolute_import, unicode_literals
try:
import south
south_installed = True
except ImportError:
south_installed = False |
import unittest
import six
import pyrtl
from pyrtl.corecircuits import _basic_add
def fastsim_only(sim):
# Mostly useful for allowing people to search for
# where there is not feature parity
# other ways to figure out feature differences are by searching for Simulation
# through this file
return sim... |
"""Simple tools for working with colors."""
import random
from hTools2.modules.sysutils import _ctx
from hTools2.extras.colorsys import *
def random_color(alpha=1.0):
"""Return a random color."""
# FontLab
if _ctx == 'FontLab':
c = int(255 * random.random())
# RoboFont & NoneLab
else:
... |
import functools
from functools import partial
from django import http
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.tokens import default_token_generator
from django.db import IntegrityError, transaction
from django.sho... |
import logging
import os
from chrome_ent_test.infra.core import environment, before_all, test
from infra import ChromeEnterpriseTestCase
@environment(file="../policy_test.asset.textpb")
class ExtensionInstallWhitelistTest(ChromeEnterpriseTestCase):
"""Test the ExtensionInstallBlacklist policy.
https://cloud.googl... |
from diofant import (Derivative, E, I, Integer, O, cos, exp, gamma, log, pi,
sin, tanh)
from diofant.abc import x, y
__all__ = ()
def test_sin():
e = sin(x).series(x, n=None)
assert next(e) == x
assert next(e) == -x**3/6
assert next(e) == x**5/120
def test_cos():
e = cos(x).seri... |
from datetime import datetime
from django.test import TestCase
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from datetime import datetime, timedelta
from ..models import Assignment, AssignmentGroup, Delivery, Deadline
from ..testhelper import TestHelper
from ..models.mo... |
"""
Make sure DefaultCharIsUnsigned option is functional.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'compiler-flags'
test.run_gyp('default-char-is-unsigned.gyp', chdir=CHDIR)
test.build('default-char-is-unsigned.gyp', test.ALL, chdir=CHDI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.