content stringlengths 4 20k |
|---|
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class InboxFeed(Choreography):
def __init__(self, temboo_session):
"""
Create a new... |
# -*- coding: utf-8 -*-
import os
import sys
from django.core.management.base import AppCommand
from django_extensions.management.utils import _make_writeable, signalcommand
class Command(AppCommand):
help = ("Creates a Django template tags directory structure for the given app name"
" in the apps's... |
#=========================================================================
# Mux_test.py
#=========================================================================
from pymtl import *
from pclib.test import TestVectorSimulator
from Mux import Mux
#----------------------------------------------------------... |
## Base Exceptions
class HTTPError(Exception):
"Base exception used by this module."
pass
class HTTPWarning(Warning):
"Base warning used by this module."
pass
class PoolError(HTTPError):
"Base exception for errors caused within a pool."
def __init__(self, pool, message):
self.pool =... |
import re
from libcloud.test import MockHttp
FORMAT_URL = re.compile(r'[./-]')
class BaseRunAboveMockHttp(MockHttp):
def _get_method_name(self, type, use_param, qs, path):
return "_json"
def _json(self, method, url, body, headers):
meth_name = '_json%s_%s' % (FORMAT_URL.sub('_', url), metho... |
#!/usr/local/bin/python
import MDAnalysis, sys, argparse, numpy, math
import MDAnalysis.core.qcprot as qcp
from MDAnalysis.analysis.align import *
#take a topology, trajectory, and selction and output rmsd to the first frame
#throughout the trajectory
parser = argparse.ArgumentParser(description='Calculate RMSD to fir... |
import copy
import numpy as np
from numpy.linalg import pinv
from statsmodels.sandbox import utils_old as utils
class ContrastResults(object):
"""
Results from looking at a particular contrast of coefficients in
a parametric model. The class does nothing, it is a container
for the results from T and F... |
#Taken from http://stackoverflow.com/questions/493174/is-there-a-way-to-convert-number-words-to-integers
def text2int(textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourte... |
from openerp import models, api, exceptions, _
import logging
_logger = logging.getLogger(__name__)
class IrActionsReport(models.Model):
_inherit = 'ir.actions.report.xml'
def _format_template_name(self, text):
try:
from unidecode import unidecode
except ImportError:
... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants_test.pants_run_integration_test import PantsRunIntegrationTest
class PantsEngineIntegrationTest(PantsRunIntegrationTest):
def test_engine_list(self):
... |
"""Convert Gettext PO localization files to .ini files.
See: http://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/ini2po.html
for examples and usage instructions.
"""
from translate.convert import convert
from translate.storage import factory
class reini:
def __init__(self, templatefile... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ToolboxAction.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*************************... |
"""
Name: init
Purpose: Init file for the Blender Add-On
Description:
Marv's Add-On for Re-Volt
"""
import bpy
import os
import os.path
import imp
from bpy.app.handlers import persistent # For the scene update handler
from . import (
common,
layers,
operators,
texanim,
tools,
)
from .props... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from evernote.api.client import EvernoteClient
from evernote.edam.type.ttypes import Note
from evernote.edam.type.ttypes import Resource, ResourceAttributes, Data
# from evernote.edam.error import ttypes as errors
from xml.sax.saxutils import escape
from datetime import dat... |
"""Unit tests for jazzparser.data module
"""
"""
============================== License ========================================
Copyright (C) 2008, 2010-12 University of Edinburgh, Mark Granroth-Wilding
This file is part of The Jazz Parser.
The Jazz Parser is free software: you can redistribute it and/or modif... |
'''author@esilgard'''
#
# Copyright (c) 2013-2016 Fred Hutchinson Cancer Research Center
#
# Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
#
from OneFieldPerSpecimen import OneFieldPerSpecimen
import global_strings as gb
class PathSpecimenType(OneFieldPerSpecimen):
'''... |
from spack import *
class Libconfig(AutotoolsPackage):
"""C/C++ Configuration File Library"""
homepage = "http://www.hyperrealm.com/libconfig/"
url = "https://github.com/hyperrealm/libconfig/archive/v1.6.tar.gz"
force_autoreconf = True
# there is currently a build error with version 1.6, se... |
"""engine.SCons.Platform.sunos
Platform-specific initialization for Sun systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009... |
from __future__ import print_function
# $example on$
from pyspark.ml.clustering import LDA
# $example off$
from pyspark.sql import SparkSession
"""
An example demonstrating LDA.
Run with:
bin/spark-submit examples/src/main/python/ml/lda_example.py
"""
if __name__ == "__main__":
spark = SparkSession \
.... |
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from .abstract_event_listener import AbstractEventListener
def _wrap_elements(result, ef_driver):
... |
import re
from django.contrib.gis import gdal
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class SpatialRefSysMixin(object):
"""
The SpatialRefSysMixin is a class used by the database-dependent
SpatialRefSys objects to reduce redu... |
#!/usr/bin/python
"""
Generate sample SIP-Spectra for 9 time steps, decreasing linearly tau
"""
import os
import numpy as np
import NDimInv.colecole as CC
frequencies = np.logspace(-2, 4, 20)
fin = np.hstack((frequencies, frequencies))
# generate CC parameters
np.random.seed(5)
rho0_1 = np.random.randint(0, 10, size=... |
# coding=utf-8
"""
SNMPCollector for Server Tech PDUs
Server Tech is a manufacturer of PDUs
http://www.servertech.com/
"""
import time
import re
import os
import sys
# Fix Path for locating the SNMPCollector
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
... |
################################################################################
## Toolbox: Transit Network Analysis Tools
## Tool name: Create Percent Access Polygons
## Created by: David Wasserman, Fehr & Peers, https://github.com/d-wasserman
## and: Melinda Morang, Esri
## Last updated: 17 June 2019
########... |
import struct
import time
from packet_utils import *
from packet_base import packet_base
from pox.lib.addresses import EthAddr
from pox.lib.util import initHelper
import logging
lg = logging.getLogger('packet')
#======================================================================
# LLDP PDU
... |
"""Tests for aqt.jax.hlo_utils."""
from absl.testing import absltest
from absl.testing import parameterized
from flax import linen as nn
from jax import random
import jax.numpy as jnp
from aqt.jax import hlo_utils
class HloUtilsTest(parameterized.TestCase):
@parameterized.named_parameters(
dict(
... |
from oslo_utils import strutils
from heat.common.i18n import _
def extract_bool(name, value):
"""Convert any true/false string to its corresponding boolean value.
Value is case insensitive.
"""
if str(value).lower() not in ('true', 'false'):
raise ValueError(_('Unrecognized value "%(value)s"... |
from pyspark import SparkConf
from pyspark import SparkContext
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
import random
#To run: PYSPARK_PYTHON=/opt/cloudera/parcels/Anaconda/bin/python spark-submit spark_visualisehottnessbyartist.py /user/cloudera/song/s... |
from typing import Any, Optional, TYPE_CHECKING
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credential... |
import re
import pymongo
from datetime import datetime
from bson.objectid import ObjectId
from . import Storage
from .. import errors
find_dupe_index_pattern = re.compile(r'\$([a-zA-Z0-9_]+)\s+')
class MongoDBStorage(Storage):
special_fields = { '$where', '$text' }
def __init__(self, db=None, *args, **kwargs):
... |
import json
import os
import sys
import unittest
from api_data_source import APIDataSource
from compiled_file_system import CompiledFileSystem
from local_file_system import LocalFileSystem
from manifest_data_source import ManifestDataSource
from object_store_creator import ObjectStoreCreator
from reference_resolver im... |
"""
Healthscapes Geolytics Module
... |
from copy import deepcopy
import numpy as np
import cudarray as ca
import deeppy as dp
import deeppy.expr as ex
from util import ScaleGradient, WeightedParameter
from ae import NLLNormal
class AEGAN(dp.base.Model, dp.base.CollectionMixin):
def __init__(self, encoder, latent_encoder, decoder, discriminator,
... |
"""
Memoization decorator that caches a function's return value. If later called
with the same arguments then the cached value is returned rather than
reevaluated.
This is a a python 2.x port of `functools.lru_cache
<http://docs.python.org/3/library/functools.html#functools.lru_cache>`_. If
using python 3.2 or later y... |
# -*- coding: utf-8 -*-
from django.http import HttpRequest
from django.template import (
Context, Engine, RequestContext, Template, Variable, VariableDoesNotExist,
)
from django.template.context import RenderContext
from django.test import RequestFactory, SimpleTestCase
class ContextTests(SimpleTestCase):
... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.univention_umc import (
umc_module_for_add,
umc_module_for_edit,
ldap_search,
base_d... |
import os
import signal
import sys
import threading
import time
import pytest
from twitter.common.process import ProcessProviderFactory
from twitter.common.quantity import Amount, Time
from apache.thermos.config.schema import Process, Task
from apache.thermos.core.runner import TaskRunner
from apache.thermos.monitori... |
class w2Grid:
def __init__(self,conn):
self.conn = conn
def getRecords(self, sql, request, cql=None):
sql_components = { 'where': [], 'params': [], 'sort': [] }
if request.get('search',[]):
for search in request['search']:
operator = "="
field = search['field'] # TODO: protect... |
import time
class Hdfs:
def __init__(self, ip, mode, log_prefix):
self.ip = ip
self.mode = mode
self.path = self.get_log_path(log_prefix)
def get_log_path(self, log_prefix):
path = '{pre}/hdfs/{ip}-{mode}-{time}'.format(pre=log_prefix, ip=self.ip, mode=self.mode, time=time.strftime('%Y%m%d%H%M%S'))
return... |
import os
import subprocess
import unittest
import IECore
import IECoreMantra
_dir = os.path.dirname( __file__ )
class RendererTest( unittest.TestCase ):
def __greenSquare( self, r ):
r.shader( "surface", "constant", { "Cd": IECore.V3fData( IECore.V3f( 0, 1, 0 ) ) } )
r.mesh(
IECore.IntVectorData( [ 4, 4 ... |
#!/usr/bin/env python3
"""Classes to parse mailer-daemon messages."""
import calendar
import email.message
import re
import os
import sys
class Unparseable(Exception):
pass
class ErrorMessage(email.message.Message):
def __init__(self):
email.message.Message.__init__(self)
self.sub = ''
... |
from functools import wraps
from django.core.exceptions import ObjectDoesNotExist # NOQA
from django.db.models import signals # NOQA
from django.db.models.aggregates import * # NOQA
from django.db.models.deletion import ( # NOQA
CASCADE, DO_NOTHING, PROTECT, SET, SET_DEFAULT, SET_NULL, ProtectedError,
)
from d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import modify_settings
from . import PostgreSQLTestCase
from .models import CharFieldModel, TextFieldModel
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.postgres'})
class UnaccentTest(PostgreSQLTestCase):
Model = Char... |
"""portality URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... |
"""
Dieses Modul enthält einige Komponenten für den allgemeinen Einsatz.
Enthalten sind die folgenden Komponenten:
- :py:class:`EventCallbackComponent`
"""
from .. import Component
class EventCallbackComponent(Component):
"""
Diese Komponente wartet mit Hilfe eines Empfangsmusters auf Nachrichten,
und ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: vexata_eg
version_added: 2.9
short_description: Manage exp... |
"""
This code was taken from https://github.com/ActiveState/appdirs and modified
to suit our purposes.
"""
from __future__ import absolute_import
import os
import sys
from pip.compat import WINDOWS, expanduser
from pip._vendor.six import PY2, text_type
def user_cache_dir(appname):
r"""
Return full path to t... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from collections import MutableMapping
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.plugins import cache_loader
try:
from __main__ import display
except ImportError:
from ansible... |
# -*- coding: utf-8 -*-
import os
import math
from random import SystemRandom
from ensure import ensure_annotations
random = SystemRandom()
@ensure_annotations
def sample_size(N: int, z: float=1.96, e: float=0.05, p: float=0.5) -> int:
"""
Calculate a sample size that will provide the desired level of con... |
import numpy as np
from numpy import zeros
from AbstractUserModel import AbstractUserModel
class PositionBasedUserModel(AbstractUserModel):
"""Defines a positions based user model."""
def __init__(self, p):
self.p_param = p
def p(self, i):
return self.p_param ** i
def get_clicks(se... |
"""A non-blocking, single-threaded TCP server."""
from __future__ import absolute_import, division, print_function, with_statement
import errno
import os
import socket
import ssl
from tornado.log import app_log
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream, SSLIOStream
from tornado.netutil i... |
import sys
import os
sys.path.append(os.path.expanduser('~/wikisource'))
from ws_category import domain_urls as urls
from ws_namespaces import index as index_name
from common import db
from gen_stats import all_domain
from common import common_html
import urllib
def filter_result(books):
result = []
for key in... |
"""
Australian-specific Form helpers
"""
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
import re
PHONE_DIGITS_RE ... |
#! /usr/bin/env python
import sys
from _lsprof import Profiler, profiler_entry, profiler_subentry
__all__ = ['profile', 'Stats']
def profile(f, *args, **kwds):
"""XXX docstring"""
p = Profiler()
p.enable(subcalls=True, builtins=True)
try:
f(*args, **kwds)
finally:
p.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Integration test focused on the omero.api.IShare interface
a running server.
Copyright 2008-2014 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import time
import pytest
import library as lib
import... |
from oslo_config import cfg
from nova.tests.functional.api_sample_tests import test_servers
CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.legacy_v2.extensions')
class ExtendedAvailabilityZoneJsonTests(test_servers.ServersSampleBase):
extension_name = "os-... |
# Microsoft Access Snapshot Viewer
# CVE-2008-2463
import logging
log = logging.getLogger("Thug")
def PrintSnapshot(self, SnapshotPath = '', CompressedPath = ''):
if SnapshotPath:
self.SnapshotPath = SnapshotPath
if CompressedPath:
self.CompressedPath = CompressedPath
msg = '[Microsoft ... |
import base64
from StringIO import StringIO
from openerp.modules.module import get_module_resource
import openerp.modules.registry
from openerp.osv import osv
from openerp_sxw2rml import sxw2rml
class report_xml(osv.osv):
_inherit = 'ir.actions.report.xml'
def sxwtorml(self, cr, uid, file_sxw, file_type):
... |
"""Test kddcup99 loader. Only 'percent10' mode is tested, as the full data
is too big to use in unit-testing.
The test is skipped if the data wasn't previously fetched and saved to
scikit-learn data folder.
"""
from sklearn.datasets import fetch_kddcup99
from sklearn.utils.testing import assert_equal, SkipTest
def... |
from PyQt5.QtWidgets import QGroupBox, QLabel, QLineEdit, QPushButton, QGridLayout, QMessageBox, QFileDialog
from PyQt5.QtGui import QIntValidator
import os
class CorrectnessGroupBox(QGroupBox):
def __init__(self, test_data_dir='', exe='', max_deduction=0):
def getDir(entry):
dname = QFileDia... |
import unittest
from selenium.webdriver.common.proxy import Proxy, ProxyType
class ProxyTests(unittest.TestCase):
MANUAL_PROXY = {
'httpProxy': 'some.url:1234',
'ftpProxy': 'ftp.proxy',
'noProxy': 'localhost, foo.localhost',
'sslProxy': 'ssl.proxy:1234',
'socksProxy': 'sock... |
try:
import boto
from boto.elasticache.layer1 import ElastiCacheConnection
from boto.regioninfo import RegionInfo
from boto.exception import BotoServerError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
... |
import os
import sys
import unittest
import warnings
from types import ModuleType
from django.conf import ENVIRONMENT_VARIABLE, LazySettings, Settings, settings
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest
from django.test import (
SimpleTestCase, TestCase, Transactio... |
import module as mojom
# This module provides a mechanism for determining the packed order and offsets
# of a mojom.Struct.
#
# ps = pack.PackedStruct(struct)
# ps.packed_fields will access a list of PackedField objects, each of which
# will have an offset, a size and a bit (for mojom.BOOLs).
class PackedField(object... |
# disable missing docstring
# pylint: disable=missing-docstring
from lettuce import world
from nose.tools import assert_equal, assert_in # pylint: disable=no-name-in-module
from terrain.steps import reload_the_page
from common import type_in_codemirror
from selenium.webdriver.common.keys import Keys
@world.absorb
d... |
import os
from testtools import TestCase
from testscenarios.testcase import TestWithScenarios
from jenkins_jobs.modules import builders
from tests.base import get_scenarios, BaseTestCase
class TestCaseModuleBuilders(TestWithScenarios, TestCase, BaseTestCase):
fixtures_path = os.path.join(os.path.dirname(__file__)... |
# -*- coding: utf-8 -*-
"""
This config file runs the simplest dev environment using sqlite, and db-based
sessions. Assumes structure:
/envroot/
/db # This is where it'll write the database file
/edx-platform # The location of this repo
/log # Where we're going to write log files
"""
# We ... |
# -*- coding: utf-8 -*-
"""
flask.ext.security.changeable
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Flask-Security recoverable module
:copyright: (c) 2012 by Matt Wright.
:author: Eskil Heyn Olsen
:license: MIT, see LICENSE for more details.
"""
from flask import current_app as app, request
from werkzeu... |
from django.db import transaction
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AdminPasswordChangeForm
from django.contrib.auth.models import User, Group
from django.contrib import messages
from django.core.exceptions import Pe... |
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
import serial
def serial_class_for_url(url):
"""extract host and port from an URL string"""
parts = urlparse.urlsplit(url)
if parts.scheme != 'alt':
raise serial.SerialException(
'expected a string in the... |
from __future__ import nested_scopes
from twisted.internet import gtk2reactor
gtk2reactor.install()
import gtk
from gtk import glade
from twisted import copyright
from twisted.internet import reactor, defer
from twisted.python import failure, log, util
from twisted.spread import pb
from twisted.cred.credentials impor... |
#!/usr/bin/env python
import argparse
import json
import os
import subprocess
import sys
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--source",
dest="source",
required=True,
help="path to fuego test result file run.json.",
)
parser.add_argument(
"-d",
"--dest",
dest="... |
import warnings
import fixtures
import six
from neutron.api.v2 import attributes
class AttributeMapMemento(fixtures.Fixture):
"""Create a copy of the resource attribute map so it can be restored during
test cleanup.
There are a few reasons why this is not included in a class derived
from BaseTestCa... |
"""
Classes that represent database functions.
"""
from django.db.models import DateTimeField, IntegerField
from django.db.models.expressions import Func, Value
class Coalesce(Func):
"""
Chooses, from left to right, the first non-null expression and returns it.
"""
function = 'COALESCE'
def __ini... |
from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
import time
from tests import pyunit_utils
#----------------------------------------------------------------------
# This test is used to show what happens if we mix datasets but keep
# the file format to orc. We expect it to throw... |
# -*- coding: utf-8 -*-
"""
Migrate QFileDialog methods from PyQt4 to PyQt5
"""
# Adapted from fix_pyqt
# and http://python3porting.com/fixers.html
# Local imports
from lib2to3.fixer_base import BaseFix
class FixQfiledialog(BaseFix):
PATTERN = """
power< 'QFileDialog' trailer< '.' filter=('getOpenFileNameAn... |
"""
This module is kept to provide a helpful warning about its removal.
"""
import logging
import warnings
from twisted.python.failure import Failure
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils.log import failure_to_exc_info
logger = logging.getLogger(__name__)
warnings.warn("Module `sc... |
"""Contains the model definition for the OverFeat network.
The definition for the network was obtained from:
OverFeat: Integrated Recognition, Localization and Detection using
Convolutional Networks
Pierre Sermanet, David Eigen, Xiang Zhang, Michael Mathieu, Rob Fergus and
Yann LeCun, 2014
http://arxiv.org/a... |
import sys, os, threading
from datetime import datetime
from lucene import StandardAnalyzer, VERSION, initVM, Version
from IndexFiles import IndexFiles
if __name__ == '__main__':
if len(sys.argv) < 2:
print IndexFiles.__doc__
sys.exit(1)
env=initVM()
print 'lucene', VERSION
def fn():... |
"""
ZMQ example using python3's asyncio
Bitcoin should be started with the command line arguments:
bitcoind -testnet -daemon \
-zmqpubhashblock=tcp://127.0.0.1:28332 \
-zmqpubrawtx=tcp://127.0.0.1:28332 \
-zmqpubhashtx=tcp://127.0.0.1:28332 \
... |
"""Tools so trivial that tracebacks should not descend into them
We define the ``__unittest`` symbol in their module namespace so unittest will
skip them when printing tracebacks, just as it does for their corresponding
methods in ``unittest`` proper.
"""
import re
import unittest
__all__ = ['ok_', 'eq_']
# Use th... |
import socket
from socket import timeout as SocketTimeout
try: # Python 3
from http.client import HTTPConnection, HTTPException
except ImportError:
from httplib import HTTPConnection, HTTPException
class DummyConnection(object):
"Used to detect a failed ConnectionCls import."
pass
try: # Compiled wit... |
# -*- coding: utf-8 -*-
r'''
werkzeug.script
~~~~~~~~~~~~~~~
.. admonition:: Deprecated Functionality
``werkzeug.script`` is deprecated without replacement functionality.
Python's command line support improved greatly with :mod:`argparse`
and a bunch of alternative modules.
Most ... |
# Convert Sorted List to Binary Search Tree
#
# Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
debug = True
debug = False
from CommonClasses import * # hxl: comment out this line for submission
# hxl: It's easy to create an array to hold ... |
import weakref
from sqlalchemy import util as base_util
from sqlalchemy.orm import attributes
class IdentityMap(dict):
def __init__(self):
self._mutable_attrs = set()
self._modified = set()
self._wr = weakref.ref(self)
def replace(self, state):
raise NotImplementedErr... |
#! /usr/bin/env python
import os, sys, time
lines = open(sys.argv[1], 'rb').readlines()
# logfile format:
# <time(us)> <key>: <value>
# example:
# 16434 read cache: 17
keys = ['read', 'write', 'head movement', 'seek per read byte', 'seek per written byte',
'read operations per second', 'write operations per second... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='FlatPage',
fields=[
... |
import gio
from plugin_base.provider import Mode
class File:
"""This is a wrapper class that provides file-like object but
uses gio.File for actual operations."""
def __init__(self, path, mode):
if mode == Mode.READ:
self._resource = gio.File(path).read()
elif mode == Mode.WRITE:
if gio.File(path).que... |
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from taiga.base import exceptions as exc
from taiga.projects.models import Project
from taiga.hooks.api import BaseWebhookApiViewSet
from . import event_hooks
from netaddr import all_matching_cidrs
from netaddr.core import AddrF... |
#! /usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2010
import re
import waflib
import waflib.Logs as _msg
from waflib import Task
from waflib.TaskGen import extension, feature, before_method, after_method
cy_api_pat = re.compile(r'\s*?cdef\s*?(public|api)\w*')
re_cyt = re.compile('import\\s(\\w+)\\s*$', re.M)
... |
"""
=================================================
Orthogonal distance regression (:mod:`scipy.odr`)
=================================================
.. currentmodule:: scipy.odr
Package Content
===============
.. autosummary::
:toctree: generated/
Data -- The data to fit.
RealData -- Dat... |
# bg is always black.
# effect is white
# func decl: red bold
# class decl: blue bold
# predefined decl: green bold
def <info descr="null" type="INFORMATION" foreground="0xff0000" background="0x000000" effectcolor="0xffffff" effecttype="BOXED" fonttype="1">foo</info>():
pass
class <info descr="null" type="INFORMATIO... |
from __future__ import division
try:
import bb
except RuntimeError as exc:
sys.exit(str(exc))
from bb.ui import uihelper
from bb.ui.buildinfohelper import BuildInfoHelper
import bb.msg
import copy
import fcntl
import logging
import os
import progressbar
import signal
import struct
import sys
import time
impor... |
'''
Naming intermediate images
'''
def name_redimensioned_frames(label, step, ext='.fits'):
dn = '%s_r%s' % (label, ext)
mn = '%s_mr%s' % (label, ext)
return dn, mn
def name_object_mask(label, step, ext='.fits'):
return '%s_mro_i%01d%s' % (label, step, ext)
def name_skybackground(label, step, ex... |
"""Suite Legacy suite: Operations formerly handled by the Finder, but now automatically delegated to other applications
Level 1, version 1
Generated from /System/Library/CoreServices/Finder.app
AETE/AEUT resource version 0/144, language 0, script 0
"""
import aetools
import MacOS
_code = 'fleg'
class Legacy_suite_E... |
"""Create a subscription on a topic."""
# :license: MIT, see LICENSE for more details.
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import mq
import click
@click.command()
@click.argument('account-id')
@click.argument('topic-name')
@click.option('--datacenter', help="Datacenter, E.G.: d... |
"""
A set of functions used to interface with the external megam_ maxent
optimization package. Before megam can be used, you should tell NLTK where it
can find the megam binary, using the ``config_megam()`` function. Typical
usage:
>>> from nltk.classify import megam
>>> megam.config_megam() # pass path to meg... |
import glob
import os
import shutil
import stat
import sys
def usage():
print("""Usage: squashdir.py <dest-dir> <source-dir> ...
Basic tool to copy a directory heirarchy into a flat space.
This crawls an arbitrarily deep heirarchy of files and directories, and copies
each file into the destination directory. The ... |
from ctypes import *
import numpy as np
import scipy.sparse as spp
from numpy.ctypeslib import ndpointer
from indigo.backends.backend import Backend
class NumpyBackend(Backend):
def __init__(self, device_id=0):
super(NumpyBackend, self).__init__()
# -------------------------------------------------... |
from ycmd.completers.completer import Completer
from ycmd.completers.all.identifier_completer import IdentifierCompleter
from ycmd.completers.general.filename_completer import FilenameCompleter
from ycmd.completers.general.ultisnips_completer import UltiSnipsCompleter
class GeneralCompleterStore( Completer ):
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.