code stringlengths 1 199k |
|---|
import sys
args=sys.argv
outputPath=args[1]
ali=args[2]
molA=args[3]
molB=args[4]
aliOutputName=args[5]
tempAliList=ali.split('|')
aliList=[]
for aliLine in tempAliList:
aliList.append(aliLine.split())
molAInfo=[]
with open(molA,'r') as molAIn:
molAInfo=molAIn.readlines()
appendAHead=list(filter(lambda x: '> <B... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_compute_network_info
description:
- Gather info for GCP Network
short_description: Gather info for ... |
import os, sys, re, subprocess
def findDepApps(dep_names):
dep_name = dep_names.split('~')[0]
app_dirs = []
moose_apps = ['framework', 'moose', 'test', 'unit', 'modules', 'examples']
apps = moose_apps[:]
# First see if we are in a git repo
p = subprocess.Popen('git rev-parse --show-cdup', stdout=subprocess.... |
import sys
import traceback
import inspect
_max_reported_output_size = 1 * 1024 * 1024
_reported_output_chunk_size = 50000
PY2 = sys.version_info[0] == 2
if PY2:
text_type = unicode # noqa: F821
binary_type = str
else:
text_type = str
binary_type = bytes
_sys_stdout_encoding = sys.stdout.encoding
if PY... |
from lymph.serializers import msgpack_serializer
from lymph.utils import make_id
class Message(object):
ACK = b'ACK'
REP = b'REP'
REQ = b'REQ'
NACK = b'NACK'
ERROR = b'ERROR'
def __init__(self, msg_type, subject, packed_body=None, headers=None, packed_headers=None, msg_id=None, source=None, lazy... |
import csv
from telemetry.results import page_measurement_results
from telemetry.value import merge_values
class CsvPageMeasurementResults(
page_measurement_results.PageMeasurementResults):
def __init__(self, output_stream, output_after_every_page=None):
super(CsvPageMeasurementResults, self).__init__(output_... |
from six import moves
import unittest
import numpy
from chainer import cuda
from chainer.functions.connection import convolution_2d
from chainer.functions.connection import local_convolution_2d
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import co... |
from __future__ import absolute_import
from __future__ import print_function
import re
from twisted.trial import unittest
from buildbot.steps.shell import WarningCountingShellCommand
class TestWarningCountingShellCommand(unittest.TestCase):
# Makes sure that it is possible to suppress warnings even if the
# war... |
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Get-GPPPassword',
'Author': ['@obscuresec'],
'Description': ('Retrieves the plaintext password and other information for '
'accounts pu... |
"""Self-test suite for Crypto.Cipher.CAST"""
__revision__ = "$Id$"
test_data = [
# Test vectors from RFC 2144, B.1
('0123456789abcdef', '238b4fe5847e44b2',
'0123456712345678234567893456789a',
'128-bit key'),
('0123456789abcdef', 'eb6a711a2c02271b',
'01234567123456782345',
'80... |
"""Enumerate dataset transformations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.util import deprecation
from tensorflow.python.util.tf_export import tf_export
@deprecation.deprecated(None, "Use `tf.data.Dataset.enumerate()")
@t... |
"""Add router availability zone
Revision ID: dce3ec7a25c9
Revises: ec7fcfbf72ee
Create Date: 2015-09-17 09:36:17.468901
"""
revision = 'dce3ec7a25c9'
down_revision = 'ec7fcfbf72ee'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('router_extra_attributes',
sa.Column('ava... |
import pyDes
import urllib
import re
from regexUtils import parseTextToGroups
from javascriptUtils import JsFunctions, JsUnpacker, JsUnpackerV2, JsUnpacker95High, JsUnwiser, JsUnIonCube, JsUnFunc, JsUnPP, JsUnPush
def encryptDES_ECB(data, key):
data = data.encode()
k = pyDes.des(key, pyDes.ECB, IV=None, pad=Non... |
DOCUMENTATION = '''
---
module: panos_dag
short_description: create a dynamic address group
description:
- Create a dynamic address group object in the firewall used for policy rules
author: "Luigi Mori (@jtschichold), Ivan Bojer (@ivanbojer)"
version_added: "2.3"
requirements:
- pan-python
options:
dag_nam... |
from coalib.misc.Decorators import generate_ordering, generate_repr
from coalib.parsing.StringProcessing import Match
@generate_repr("begin", "inside", "end")
@generate_ordering("begin", "inside", "end")
class InBetweenMatch:
"""
Holds information about a match enclosed by two matches.
"""
def __init__(... |
"""Tests for swift.common.utils"""
from collections import defaultdict
import logging
import socket
import time
import unittest
from uuid import uuid4
from eventlet import GreenPool, sleep, Queue
from eventlet.pools import Pool
from swift.common import memcached
from mock import patch, MagicMock
from test.unit import N... |
from __future__ import division, print_function, absolute_import
from scipy.stats import hypergeom, bernoulli, boltzmann
import numpy as np
from numpy.testing import assert_almost_equal, assert_equal, assert_allclose
def test_hypergeom_logpmf():
# symmetries test
# f(k,N,K,n) = f(n-k,N,N-K,n) = f(K-k,N,K,N-n) =... |
import sqlalchemy as sa
class ProxyDict(object):
def __init__(self, parent, collection_name, mapping_attr):
self.parent = parent
self.collection_name = collection_name
self.child_class = mapping_attr.class_
self.key_name = mapping_attr.key
self.cache = {}
@property
de... |
import unittest
import glob
import sys
import os
from IECore import *
class TestJPEGImageWriter(unittest.TestCase):
def __verifyImageRGB( self, imgNew, imgOrig, maxError = 0.004 ):
self.assertEqual( type(imgNew), ImagePrimitive )
if "R" in imgOrig :
self.assert_( "R" in imgNew )
self.assert_( "G" in imgNew )... |
__all__ = ['Character', 'Complex', 'Float',
'PrecisionError', 'PyObject', 'Int', 'UInt',
'UnsignedInt', 'UnsignedInteger', 'string', 'typecodes', 'zeros']
from functions import zeros
import string # for backwards compatibility
typecodes = {'Character':'c', 'Integer':'bhil', 'UnsignedInteger':'BH... |
import unittest
from _basic import *
class BasicExampleTest(unittest.TestCase):
def testIt(self):
# test virtual functions
class D(C):
def f(self, x=10):
return x+1
d = D()
c = C()
self.assertEqual(c.f(), 20)
self.assertEqual(c.f(3), 6)
... |
import pymongo
import os
CONNECTION_STRING = "mongodb://localhost" # replace it with your settings
CONNECTION = pymongo.MongoClient(CONNECTION_STRING)
'''Leave this as is if you dont have other configuration'''
DATABASE = CONNECTION.blog
POSTS_COLLECTION = DATABASE.posts
USERS_COLLECTION = DATABASE.users
SETTINGS_COLL... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_application_rule_settings
short_description: Configur... |
import sys, os, random, time
from math import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import ode
def scalp (vec, scal):
vec[0] *= scal
vec[1] *= scal
vec[2] *= scal
def length (vec):
return sqrt (vec[0]**2 + vec[1]**2 + vec[2]**2)
def prepare_GL():
"""Prepare dra... |
from model import *
train_model("model.ckpt") |
"""
***************************************************************************
providermetadata.py
---------------------
Date : June 2019
Copyright : (C) 2019 by Martin Dobias
Email : wonder dot sk at gmail dot com
******************************************... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_guest_snapshot
short_description: Manages virtual machin... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: cs_region
short_description: Manages regions on Apache CloudStack based clouds.
description:
- Add, update and remove regions.
version_added: "2.... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course_modes', '0007_coursemode_bulk_sku'),
('bulk_email', '0005_move_target_data'),
]
operations = [
migrations.CreateModel(
name='C... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
user_orm_label = '%s.%s' % (User._meta.ap... |
import django.dispatch
post_compress = django.dispatch.Signal(providing_args=['type', 'mode', 'context']) |
"""Simple-to-use Python interface to The TVDB's API (thetvdb.com)
Example usage:
>>> from tvdb_api import Tvdb
>>> t = Tvdb()
>>> t['Lost'][4][11]['episodename']
u'Cabin Fever'
"""
__author__ = "dbr/Ben"
__version__ = "1.9"
import os
import time
import urllib
import urllib2
import getpass
import StringIO
import tempfil... |
import os
import re
from MenuList import MenuList
from Components.Harddisk import harddiskmanager
from Tools.Directories import SCOPE_CURRENT_SKIN, resolveFilename, fileExists
from enigma import RT_HALIGN_LEFT, eListboxPythonMultiContent, \
eServiceReference, eServiceCenter, gFont
from Tools.LoadPixmap import LoadPixm... |
from __future__ import absolute_import
import locale
import logging
import os
import sys
import pip._vendor
from pip._vendor import pkg_resources
from pip._vendor.certifi import where
from pip import __file__ as pip_location
from pip._internal.cli import cmdoptions
from pip._internal.cli.base_command import Command
fro... |
import urllib
from oslo_config import cfg
from nova.tests.functional.api_sample_tests import api_sample_base
CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.legacy_v2.extensions')
class InstanceUsageAuditLogJsonTest(api_sample_base.ApiSampleTestBaseV21):
ADMIN_... |
"""This file invokes predictionmetricsmanager.py tests
TODO: Move these tests to unit test format.
"""
from nupic.frameworks.opf.predictionmetricsmanager import (
test as predictionMetricsManagerTest)
if __name__ == "__main__":
predictionMetricsManagerTest() |
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.dns.drivers.liquidweb import LiquidWebDNSDriver
from libcloud.test import MockHttp
from libcloud.test.file_fixtures import DNSFileFixtures
from libcloud.test.secrets import DNS_PARAMS_LIQUIDWEB
from libcloud.dns.types import ZoneDoesNotExis... |
r"""HTTP/1.1 client library
<intro stuff goes here>
<other stuff, too>
HTTPConnection goes through a number of "states", which define when a client
may legally make another request or fetch the response for a particular
request. This diagram details these state transitions:
(null)
|
| HTTPConnection()
... |
"""Base SQL and DDL compiler implementations.
Classes provided include:
:class:`~sqlalchemy.sql.compiler.SQLCompiler` - renders SQL
strings
:class:`~sqlalchemy.sql.compiler.DDLCompiler` - renders DDL
(data definition language) strings
:class:`~sqlalchemy.sql.compiler.GenericTypeCompiler` - renders
type specification st... |
from vtk import *
source = vtkRandomGraphSource()
source.DirectedOff()
source.SetNumberOfVertices(50)
source.SetEdgeProbability(0.01)
source.SetUseEdgeProbability(True)
source.AllowParallelEdgesOn()
source.AllowSelfLoopsOn()
source.SetStartWithTree(True)
centrality = vtkBoostBrandesCentrality ()
centrality.SetInputConn... |
import os
import Utils
import samba_utils
from samba_git import find_git
def git_version_summary(path, env=None):
git = find_git(env)
if git is None:
return ("GIT-UNKNOWN", {})
env.GIT = git
environ = dict(os.environ)
environ["GIT_DIR"] = '%s/.git' % path
environ["GIT_WORK_TREE"] = path
... |
"""Bayesian Data Analysis, 3rd ed
Chapter 2, demo 3
Simulate samples from Beta(438,544), draw a histogram with quantiles, and do
the same for a transformed variable.
"""
import numpy as np
from scipy.stats import beta
import matplotlib.pyplot as plt
plt.rc('font', size=14)
plt.rc('lines', color='#377eb8', linewidth=2)
... |
"""Tests for the gradient of `tf.sparse_tensor_dense_matmul()`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
class SparseTensorDenseMatMulGradientTest(tf.test.TestCase):
def _sparsify(self, x):
x[x < 0.5]... |
import sys, os, re
import unittest
from decimal import Decimal
from testutils import *
_TESTSTR = '0123456789-abcdefghijklmnopqrstuvwxyz-'
def _generate_test_string(length):
"""
Returns a string of composed of `seed` to make a string `length` characters long.
To enhance performance, there are 3 ways data is... |
from Site import Site
from SiteStorage import SiteStorage |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import copy
from ansible.plugins.action.normal import ActionModule as _ActionModule
from ansible.module_utils.six import iteritems
from ansible.module_utils.ce import ce_argument_spec
from ansible.module_utils.basic impor... |
"""
categories: Modules,array
description: Looking for integer not implemented
cause: Unknown
workaround: Unknown
"""
import array
print(1 in array.array('B', b'12')) |
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from diamond.collector import Collector
from memory import MemoryCollector
class T... |
from pyspark.sql import SparkSession
from pyspark.ml.feature import FeatureHasher
if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("FeatureHasherExample")\
.getOrCreate()
# $example on$
dataset = spark.createDataFrame([
(2.2, True, "1", "foo"),
(3.3... |
"""Contains definitions for the preactivation form of Residual Networks.
Residual networks (ResNets) were originally proposed in:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
The full preactivation 'v2' ResNet variant implemented in this module... |
"""The co2signal component.""" |
import BoostBuild
import MockToolset
t = BoostBuild.Tester(arguments=['toolset=mock', '--ignore-site-config', '--user-config='], pass_toolset=0)
MockToolset.create(t)
t.write("libtiff/tiff.h", 'libtiff')
t.write("libtiff/tiff.c", 'tiff')
t.write("Jamroot.jam", """
path-constant here : . ;
using libtiff : : <source>$(he... |
from application.auth import requires_auth
from application.direct import Base
from flask import Flask, request, Response
from pyextdirect.api import create_api
from pyextdirect.router import Router
from wsgiref.handlers import CGIHandler
app = Flask('haproxy')
@app.route('/direct/router', methods=['POST'])
@requires_a... |
'''
Progress Bar
============
.. versionadded:: 1.0.8
.. image:: images/progressbar.jpg
:align: right
The :class:`ProgressBar` widget is used to visualize the progress of some task.
Only the horizontal mode is currently supported: the vertical mode is not
yet available.
The progress bar has no interactive elements ... |
"""Views for debugging and diagnostics"""
import pprint
import traceback
from django.http import Http404, HttpResponse, HttpResponseNotFound
from django.contrib.auth.decorators import login_required
from django.utils.html import escape
from django_future.csrf import ensure_csrf_cookie
from edxmako.shortcuts import rend... |
import os, pkg_resources
from twisted.python import log
from twisted.internet import reactor
from twisted.application import service
from twisted.web.server import Site
from twisted.web.static import File
from autobahn.websocket import WebSocketServerFactory, \
WebSocketServerProtocol
fro... |
import sys
pythonpath = sys.argv[1]
scriptfile = sys.argv[2]
sys.argv = sys.argv[2:]
sys.path.append(pythonpath)
execfile(scriptfile) |
"""Tests for distutils.command.build_py."""
import os
import sys
import io
import unittest
from distutils.command.build_py import build_py
from distutils.core import Distribution
from distutils.errors import DistutilsFileError
from distutils.tests import support
from test.support import run_unittest
class BuildPyTestCa... |
def City(response):
return {
'city': response.city.name,
'continent_code': response.continent.code,
'continent_name': response.continent.name,
'country_code': response.country.iso_code,
'country_name': response.country.name,
'dma_code': response.location.metro_code,
... |
"""
This is the POX network controller framework.
Presently, this basically means it's a framework for writing OpenFlow
controllers, some utilities, and some examples.
""" |
import unittest
from ctypes import *
import _ctypes_test
class ReturnFuncPtrTestCase(unittest.TestCase):
def test_with_prototype(self):
# The _ctypes_test shared lib/dll exports quite some functions for testing.
# The get_strchr function returns a *pointer* to the C strchr function.
dll = CD... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class action_traceability(osv.osv_memory):
"""
This class defines a function action_traceability for wizard
"""
_name = "action.traceability"
_description = "Action traceability "
def action_traceability(self, cr, uid, ids... |
"""Gradients for operators defined in data_flow_ops.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import... |
"""
Collect stats from puppet agent's last_run_summary.yaml
* yaml
"""
try:
import yaml
except ImportError:
yaml = None
import diamond.collector
class PuppetAgentCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(PuppetAgentCollector,
... |
"""Test dlmodule.c
Roger E. Masse revised strategy by Barry Warsaw
"""
from test.test_support import verbose,TestSkipped, import_module
dl = import_module('dl', deprecated=True)
sharedlibs = [
('/usr/lib/libc.so', 'getpid'),
('/lib/libc.so.6', 'getpid'),
('/usr/bin/cygwin1.dll', 'getpid'),
('/usr/li... |
print """
__________________________________________________________________
MODULE BASICS.PY : BASIC POSTGRES SQL COMMANDS TUTORIAL
This module is designed for being imported from python prompt
In order to run the samples included here, first create a connection
using : cnx = basics.DB(...)
The ... |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('scipy',parent_package,top_path)
config.add_subpackage('cluster')
config.add_subpackage('constants')
config.add_subpackage('fftpack')
config.add_subpackage('integrate')
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ipa_group
author: Thomas Krahn (@Nosmoht)
short_description: Ma... |
import sys
for i in xrange(50):
for j in xrange(5):
for k in xrange(20022):
print(20000 * i + k)
for line in sys.stdin:
pass |
"""Module to host the ChangeGitBranch class and test_git_executable function.
"""
import os
import subprocess
import misc_utils
class ChangeGitBranch(object):
"""Class to manage git branches.
This class allows one to create a new branch in a repository based
off of a given commit, and restore the original t... |
from datetime import date, datetime
from collections import defaultdict
from openerp.tests import common
from openerp.exceptions import except_orm
class TestNewFields(common.TransactionCase):
def test_00_basics(self):
""" test accessing new fields """
# find a discussion
discussion = self.en... |
import datetime
import openerp
from openerp import api, models
from openerp.osv import fields, osv
class stock_production_lot(osv.osv):
_inherit = 'stock.production.lot'
def _get_date(dtype):
"""Return a function to compute the limit date for this type"""
def calc_date(self, cr, uid, context=Non... |
class C:
def __matmul__(self, other): |
from __future__ import unicode_literals
DATE_FORMAT = r'j \d\e F \d\e Y'
TIME_FORMAT = 'G:i:s'
DATETIME_FORMAT = r'j \d\e F \d\e Y \a \l\e\s G:i'
YEAR_MONTH_FORMAT = r'F \d\e\l Y'
MONTH_DAY_FORMAT = r'j \d\e F'
SHORT_DATE_FORMAT = 'd/m/Y'
SHORT_DATETIME_FORMAT = 'd/m/Y G:i'
FIRST_DAY_OF_WEEK = 1 # Monday
DATE_INPUT_FO... |
class Foo:
def xyzzy(self): pass
def x(p):
if isinstance(p, Foo):
p.xyzzy() |
def foo():
"""<the_doc>Doc of foo.
It has two lines."""
pass
<the_ref>foo |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.facts.collector import BaseFactCollector
class Network:
"""
This is a generic Network subclass of Facts. This should be further
subclassed to implement per platform. If you subclass this,
... |
"""
Common checksum routines.
"""
__all__ = ['luhn']
import warnings
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
warnings.warn(
"django.utils.checksums will be removed in Django 2.0. The "
"luhn() function is now included in django-localflavor 1.1+.",
RemovedIn... |
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 model 'UserSignupSource'
db.create_table('student_usersignupsource', (
('id', self.gf('django.db.models.fields.Aut... |
from __future__ import unicode_literals
import os
from collections import OrderedDict
from django.contrib.staticfiles.finders import get_finders
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.files.storage import FileSystemStorage
from django.core.management.base import BaseCommand,... |
"""
Django Unit Test and Doctest framework.
"""
from django.test.client import Client, RequestFactory
from django.test.testcases import TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature
from django.test.utils import Approximate |
from xwing.network.transport.socket.backend.rfc1078 import send, recv
class Connection:
def __init__(self, loop, sock):
self.loop = loop
self.sock = sock
async def recv(self):
'''Try to recv data. If not data is recv NoData exception will
raise.
:param timeout: Timeout in... |
"""
pydebsign.debsign
-----------------
debsign process as follows;
1. Signing .dsc file with GPG key.
2. Retrieve size and md5, sha1, sha256 checksums from signed .dsc.
3. Rewrite of above values at .changes.
4. Siging .changes file with GPG key.
optional:
How to verify signed files ``dput -o .changes`` command.
----
... |
from __future__ import print_function, absolute_import, division
from punch.vcs_use_cases import use_case
class VCSStartReleaseUseCase(use_case.VCSUseCase):
def __init__(self, repo):
self.repo = repo
def execute(self):
self.repo.pre_start_release()
return self.repo.start_release() |
from flask import Flask, render_template, request, jsonify
from helpers import predict
import os
application = Flask(__name__)
application.config.from_object(os.environ['APP_SETTINGS'])
@application.route("/")
def hello():
return render_template("index.html")
@application.route("/texts", methods=["POST"])
def analyze... |
import _plotly_utils.basevalidators
class MaxpointsValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="maxpoints", parent_name="carpet.stream", **kwargs):
super(MaxpointsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import cPickle, os.path, time, glob
DEPS_FORMAT_VERSION = 6
class DepsRecord:
"""Record of dependencies of a group of output files generated by
one run of bakefile on its input files."""
def __init__(self):
self.deps = []
self.outputs = [] # (filename,method) tuples
class Dep:
"""Entr... |
from contextlib import contextmanager
from sqlalchemy.types import NULLTYPE, Integer
from sqlalchemy import schema as sa_schema
from . import util
from .compat import string_types
from .ddl import impl
__all__ = ('Operations',)
class Operations(object):
"""Define high level migration operations.
Each operation ... |
""" S3 Form Builders
@copyright: 2012 (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 the Software without
restriction, including without lim... |
import _plotly_utils.basevalidators
class HovertemplateValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="hovertemplate", parent_name="scatter", **kwargs):
super(HovertemplateValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_... |
import numpy
import os
import sklearn.datasets as datasets
import sklearn.svm as svm
import sklearn.cross_validation as cross_validation
import sklearn.metrics as metrics
import sklearn.preprocessing as preprocessing
from tyrehug.settings import DATA_DIR, get_dir
learner = svm.SVC(kernel='linear', C=1)
data_dir = get_d... |
from upload import * |
import random
import os
import yaml
insults = yaml.load(open(os.path.dirname(__file__) + '/insults.yml'))
def generateInsult():
column1 = random.choice(insults['column1'])
column2 = random.choice(insults['column2'])
column3 = random.choice(insults['column3'])
print("\n" + "Thou", column1, column2, colum... |
import re
import sys
sys.path.append("./")
import jieba
import numpy as np
import pandas as pd
from gensim import corpora, models, similarities
from utility.async_decor import async_wrapper
from utility.logger_decor import exception
from utility.mongodb import MongoDBManager
class Docsim(object):
"""
文本相似度
... |
"""
Fits a transit model together with a Gaussian Process model created by celerite to lightcurve observations
"""
import sys, os
import pickle
import json
import time
import logging
from pathlib import Path
import importlib
from multiprocessing.pool import Pool
import signal
import numpy as np
import matplotlib.pyplot... |
"""EatFirst FileSystem tests."""
import os
from io import BytesIO
from faker import Faker
from flask import current_app
from efs import EFS
fake = Faker()
TEST_FILE = 'test_file.txt'
RANDOM_DATA = BytesIO(fake.sha256().encode())
def test_create_file(app, delete_temp_files):
"""Test file creation."""
assert app
... |
def bit_reverse(num):
bits = list('{:032b}'.format(num))
bits.reverse()
return int(''.join(bits), 2) |
from django import forms
from django.forms import models as models_form
from easy_select2 import Select2
from . import models
from apps.utils import forms as utils, constants
class GradoEscolaridadForm(utils.BaseFormAllFields):
title = 'Grado de escolaridad'
class Meta(utils.BaseFormAllFields.Meta):
mod... |
import hashlib
import logging
from datetime import datetime
import memcache
import sh
from croniter import croniter
TIMEOUT = 21600
ADDRESS = '127.0.0.1:11211'
FILE_NAME = "schedule.txt"
def main():
logging.basicConfig(level=logging.DEBUG)
processes = []
mc = memcache.Client([ADDRESS], debug=0)
def run(... |
class Grammar():
"""
A Grammar contains all the necessary information for a language to be parsed.
productions : ? -- The rules for generating the language.
nonterminals : set(str) -- The non-terminals of the productions.
terminals: set(str) -- The terminals of the productions.
start: str -- The... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.