code stringlengths 1 199k |
|---|
from paddle.trainer_config_helpers import *
dict_file = "./data/dict.txt"
word_dict = dict()
with open(dict_file, 'r') as f:
for i, line in enumerate(f):
w = line.strip().split()[0]
word_dict[w] = i
is_predict = get_config_arg('is_predict', bool, False)
trn = 'data/train.list' if not is_predict else... |
from flask import jsonify, request
from flask import current_app
from flask.ext.restful import Resource, reqparse
import keystoneclient
import keystoneapi
def get_default_error_message():
return "Unable to process your request.Please contact the site administrator"
class UserAPI(Resource):
def __init__(self):
... |
class Sphere11Exception(Exception):
pass
class AccountNotFound(Sphere11Exception):
"""The account specified is unknown."""
class UnknownResourceType(Sphere11Exception):
"""The resource type is not supported."""
class ResourceNotFound(Sphere11Exception):
"""The specified resource does not exist.""" |
import pytest
from bless.ssh.public_keys.rsa_public_key import RSAPublicKey
from tests.ssh.vectors import EXAMPLE_RSA_PUBLIC_KEY, \
EXAMPLE_RSA_PUBLIC_KEY_NO_DESCRIPTION, EXAMPLE_ECDSA_PUBLIC_KEY, EXAMPLE_RSA_PUBLIC_KEY_N, \
EXAMPLE_RSA_PUBLIC_KEY_E, EXAMPLE_RSA_PUBLIC_KEY_2048, EXAMPLE_RSA_PUBLIC_KEY_1024, \
... |
from __future__ import print_function
import re
import sys
import os
def emit(key, value):
print('{}\t{}'.format(key, value))
def mapper():
with open('f_file.txt', 'r') as fh:
f_key = fh.readline().strip()
emit('file_key', f_key)
if __name__ == '__main__':
mapper() |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
import unittest
from qa.web_tests import config
class TestFilterImages(unittest.TestCase):
def setUp(self):
... |
from recipe_engine.engine_types import ResourceCost
PYTHON_VERSION_COMPATIBILITY = 'PY2+3'
DEPS = [
'step',
]
def RunSteps(api):
with api.step.nest('parent step'):
pass
api.step('null step', [])
api.step('zero step', ['echo', 'hi'], cost=None)
api.step('default step', ['echo', 'hi'])
api.step('max cpu s... |
"""Python 2/3 unicode CSV compatibility layer and convenience functions.""" |
import logging
import socket
import string
import textwrap
import time
from functools import wraps
from typing import TYPE_CHECKING, Callable, Optional, TypeVar, cast
from airflow.configuration import conf
from airflow.exceptions import AirflowConfigException, InvalidStatsNameException
from airflow.typing_compat import... |
"""Start Home Assistant."""
from __future__ import print_function
import argparse
import os
import platform
import subprocess
import sys
import threading
from typing import Optional, List
from homeassistant import monkey_patch
from homeassistant.const import (
__version__,
EVENT_HOMEASSISTANT_START,
REQUIRE... |
import sqlalchemy as SA
import pushmanager.core.db as db
from pushmanager.core.settings import Settings
from pushmanager.core.mail import MailQueue
from pushmanager.core.requesthandler import RequestHandler
import pushmanager.core.util
from pushmanager.core.xmppclient import XMPPQueue
class DeployPushServlet(RequestHan... |
space = "[space]"
specials = set(["[noise]","[vocalized-noise]","[laughter]"])
with open('hyp.txt','r') as fid:
lines = fid.readlines()
fid = open('mergehyp.txt','w')
def averageWords(text_f="/afs/cs.stanford.edu/u/awni/swbd/data/eval2000/text_ctc"):
with open(text_f,'r') as fid:
lines = [l.strip().spli... |
"""Support for the Netatmo cameras."""
import logging
from pyatmo import NoDevice
import requests
import voluptuous as vol
from homeassistant.components.camera import (
PLATFORM_SCHEMA,
Camera,
SUPPORT_STREAM,
CAMERA_SERVICE_SCHEMA,
)
from homeassistant.const import CONF_VERIFY_SSL, STATE_ON, STATE_OFF
... |
from south.utils import datetime_utils as 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 'HotelRoom.booking'
db.add_column(u'p3_hotelroom', 'booking',
s... |
__all__ = ['propagator', 'propagator_steadystate']
import types
import numpy as np
import scipy.linalg as la
import functools
import scipy.sparse as sp
from qutip.qobj import Qobj
from qutip.tensor import tensor
from qutip.operators import qeye
from qutip.rhs_generate import (rhs_generate, rhs_clear, _td_format_check)
... |
from bambou import NURESTFetcher
class NUIKEGatewayProfilesFetcher(NURESTFetcher):
""" Represents a NUIKEGatewayProfiles fetcher
Notes:
This fetcher enables to fetch NUIKEGatewayProfile objects.
See:
bambou.NURESTFetcher
"""
@classmethod
def managed_class(cls):
... |
from rdkit.ML import FeatureSelect as FS
from rdkit import DataStructs as DS
from rdkit import RDConfig
import unittest
class TestCase(unittest.TestCase):
def setUp(self) :
pass
def test0FromList(self) :
examples = []
bv = DS.ExplicitBitVect(5)
bv.SetBitsFromList([0,2,4])
examples.append... |
import hashlib
import logging
from datetime import datetime
from django.db.backends.utils import strip_quotes
from django.db.transaction import TransactionManagementError, atomic
from django.utils import timezone
from django.utils.encoding import force_bytes
logger = logging.getLogger('django.db.backends.schema')
def _... |
import os
from setuptools import (
setup,
find_packages,
)
version = '0.3dev'
shortdesc = "Product shop extension for bda.plone.shop"
longdesc = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
longdesc += open(os.path.join(os.path.dirname(__file__), 'CHANGES.rst')).read()
longdesc += open(os.... |
from __future__ import print_function
import copy
import warnings
import graphviz
import matplotlib.pyplot as plt
import numpy as np
def plot_stats(statistics, ylog=False, view=False, filename='avg_fitness.svg'):
""" Plots the population's average and best fitness. """
if plt is None:
warnings.warn("Thi... |
"""robust_siso.py
Demonstrate mixed-sensitivity H-infinity design for a SISO plant.
Based on Example 2.11 from Multivariable Feedback Control, Skogestad
and Postlethwaite, 1st Edition.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from control import tf, mixsyn, feedback, step_response
s = tf([1, 0],... |
"""
=====================
Statistical inference
=====================
Here we will briefly cover multiple concepts of inferential statistics in an
introductory manner, and demonstrate how to use some MNE statistical functions.
.. contents:: Topics
:local:
:depth: 3
"""
from functools import partial
import numpy a... |
from tests.base_case import ChatBotTestCase
from chatterbot.trainers import ChatterBotCorpusTrainer
class ChatterBotCorpusTrainingTestCase(ChatBotTestCase):
"""
Test case for training with data from the ChatterBot Corpus.
Note: This class has a mirror tests_django/integration_tests/
"""
def setUp(se... |
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from snippets.base import ENGLISH_COUNTRY_CHOICES
class Migration(DataMigration):
def forwards(self, orm):
for country_code, country_name in ENGLISH_COUNTRY_CHOICES:
orm['base.TargetedCountry'... |
import threading
import mock
import urllib3
from django.test import TestCase
import opbeat
from opbeat.contrib.django.models import get_client
from opbeat.traces import trace
try:
from http import server as SimpleHTTPServer
from socketserver import TCPServer
except ImportError:
import SimpleHTTPServer
f... |
from __future__ import unicode_literals
from builtins import str
import datetime, json, logging, os, sys
from django.db import connection
from scrapy import signals
from scrapy.spiders import Spider
from scrapy.spiders import CrawlSpider
from pydispatch import dispatcher
from scrapy.exceptions import CloseSpider, Usage... |
import os
PWD = os.getcwd() # current dir
SP_DIR = os.environ['SP_DIR'] # site-packages dir
PREFIX = os.environ['PREFIX'] # install prefix
EPICS_HOST_ARCH = os.environ['EPICS_HOST_ARCH']
EPICS_INSTALL_PATH = os.path.join(PREFIX, 'epics')
EPICS_BIN_PATH = os.path.join(EPICS_INSTALL_PATH, 'bin', EPICS_HOST_ARCH)
open('co... |
""" Properties for modeling Chart inputs, constraints, and dependencies.
selection spec:
[['x'], ['x', 'y']]
[{'x': categorical, 'y': numerical}]
"""
from __future__ import absolute_import
import numpy as np
import pandas as pd
from bokeh.properties import (HasProps, Either, String, Int, List, Bool,
... |
import os
import pyexcel_io.constants as constants
from pyexcel_io import get_data, save_data
from pyexcel_io.utils import _index_filter
from nose.tools import eq_
def test_index_filter():
current_index, start, limit, expected = (0, 1, -1, constants.SKIP_DATA)
eq_(_index_filter(current_index, start, limit), exp... |
import datetime
from django import forms
from django.utils.translation import ugettext_lazy as _
MONTH_CHOICES = (
('jan', _('January')),
('feb', _('February')),
('mar', _('March')),
('may', _('May')),
('jun', _('June')),
('jul', _('July')),
('aug', _('August')),
('sep', _('September')),
('oct', _('October')),... |
"""
sentry.tsdb.inmemory
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from collections import defaultdict
from datetime import timedelta
from django.utils import timezone
from sent... |
import collections
from django import http
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from django.db import transaction
from django.views.decorators.cache import cache_page
from django.db.models import Q
from funfactory.urlresolvers import reve... |
from __future__ import absolute_import, division, print_function
import pytest
sa = pytest.importorskip('sqlalchemy')
import itertools
import sqlite3
from distutils.version import LooseVersion
import datashape
from odo import into, resource, discover
import numpy as np
import pandas as pd
import pandas.util.testing as ... |
from geventmemcache import MemcacheError, MemcacheResult
from geventmemcache.codec import MemcacheCodec
class MemcacheProtocol(object):
@classmethod
def create(cls, type_):
if isinstance(type_, MemcacheProtocol):
return type_
elif type_ == 'text':
return MemcacheTextProto... |
from __future__ import unicode_literals
import re
import inspect
from copy import deepcopy
from pprint import pformat
from functools import wraps
try:
from collections import Iterable
except ImportError:
Iterable = (list, dict, tuple, set)
try:
import __builtin__ as builtins
except ImportError:
import b... |
"""inotify: Wrapper around the inotify syscalls providing both a function based and file like interface"""
from collections import namedtuple
from .utils import PermissionError, UnknownError, CLOEXEC_DEFAULT
from cffi import FFI
import errno
ffi = FFI()
ffi.cdef("""
/*
* struct inotify_event - structure read from the ... |
import json
from classytags.core import Tag, Options
from cms.utils.encoder import SafeJSONEncoder
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter('json')
def json_filter(value):
"""
Returns the JSON representation of ``value`` in a safe m... |
from gluon import current
from s3 import *
from s3layouts import *
try:
from .layouts import *
except ImportError:
pass
import s3menus as default
red_cross_filter = {"organisation_type.name" : "Red Cross / Red Crescent"}
class S3MainMenu(default.S3MainMenu):
""" Custom Application Main Menu """
# ------... |
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .stop_words import STOP_WORDS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, a... |
"""empty message
Revision ID: 110_add_acknowledged_column
Revises: 100_add_open_status
Create Date: 2015-06-17 11:40:51.427138
"""
revision = '110_add_acknowledged_column'
down_revision = '100_add_open_status'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import column, table
from sqlalchemy import... |
from app import db
from sqlalchemy.dialects.postgresql import JSONB
from util import dict_from_dir
class Contribution(db.Model):
__tablename__ = 'contribution'
id = db.Column(db.Integer, primary_key=True)
person_id = db.Column(db.Integer, db.ForeignKey("person.id"))
package_id = db.Column(db.Text, db.Fo... |
import attr
from duniterpy.documents import block_uid, BlockUID
@attr.s(hash=False)
class BlockchainParameters:
# The decimal percent growth of the UD every [dt] period
c = attr.ib(convert=float, default=0, cmp=False, hash=False)
# Time period between two UD in seconds
dt = attr.ib(convert=int, default=... |
'''
Base objects (list and dict) for RSON
Copyright (c) 2010, Patrick Maupin. All rights reserved.
See http://code.google.com/p/rson/source/browse/trunk/license.txt
'''
def make_hashable(what):
try:
hash(what)
return what
except TypeError:
if isinstance(what, dict):
return t... |
import os
import sys
import logging
import setuptools
PACKAGE_NAME = 'parks'
MINIMUM_PYTHON_VERSION = 3, 6
def check_python_version():
"""Exit when the Python version is too low."""
if sys.version_info < MINIMUM_PYTHON_VERSION:
sys.exit("Python {0}.{1}+ is required.".format(*MINIMUM_PYTHON_VERSION))
def... |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import pytest
import datetime
import isodate
from tableschema import types
from tableschema.config import ERROR
@pytest.mark.parametrize('format, value, result', [
('d... |
"""Implements a character based lcd connected via PCF8574 on i2c."""
from lcd import LcdApi
from pyb import Pin
from pyb import delay, udelay
class GpioLcd(LcdApi):
"""Implements a character based lcd connected via GPIO pins."""
def __init__(self, rs_pin, enable_pin, d0_pin=None, d1_pin=None,
d... |
import array
import binascii
import zmq
import struct
port = 259332
zmqContext = zmq.Context()
zmqSubSocket = zmqContext.socket(zmq.SUB)
zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "hashblock")
zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "hashtx")
zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "rawblock")
zmqSubSocket.setsockopt(zmq.SUB... |
"""Implementes Gfx.Driver gtk.
"""
import math
import gtk, pango
from gtk import gdk
try:
import Gfx
except ImportError:
from . import Gfx
try:
from Compatibility import *
except ImportError:
from . import Compatiblity
globals().update(Compatibility.__dict__)
driverName = "gtkGfx"
stipple_Solid =... |
import unittest
def bubblesort(lst):
for i in range(0, len(lst) - 1):
for j in range(i + 1, len(lst)):
if lst[i] > lst[j]:
# swap values
lst[i], lst[j] = lst[j], lst[i]
return lst
class Test(unittest.TestCase):
def testUnsortedSmall(self):
self.assertEqual([1,2,3,4], bubblesort([4... |
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 'NotificationType'
db.create_table('notify_notificationtype', (
('key', self.gf('django.db.models.fields.Cha... |
"""URLconf for Johnny's test app."""
from django.conf.urls.defaults import *
urlpatterns = patterns('johnny.tests.testapp.views',
(r'^test/template_queries', 'template_queries'),
) |
from __future__ import unicode_literals
MESSAGES = {
"Also available in": "Также доступно на",
"Archive": "Архив",
"Categories": "Категории",
"LANGUAGE": "Русский",
"More posts about": "Больше записей о",
"Newer posts": "Новые записи",
"Next post": "Следующая запись",
"Older posts": "Ста... |
"""
Delphi decision maker
"""
module = "delphi"
if deployment_settings.has_module(module):
# Memberships as component of Groups
s3mgr.model.add_component("delphi_membership",
delphi_group="group_id")
# Problems as component of Groups
s3mgr.model.add_component("delphi_pr... |
from pandac.PandaModules import Vec3, Vec4, Point3, TextNode, VBase4
from direct.gui.DirectGui import DGG, DirectFrame, DirectButton, DirectLabel, DirectScrolledList, DirectCheckButton
from direct.gui import DirectGuiGlobals
from direct.showbase import DirectObject
from direct.showbase import PythonUtil
from toontown.t... |
"""General implementation of walking commits and their contents."""
try:
from collections import defaultdict
except ImportError:
from _compat import defaultdict
import collections
import heapq
import itertools
from dulwich._compat import (
all,
)
from dulwich.diff_tree import (
RENAME_CHANGE_TYPES,
... |
import json
import requests
class MultipartBuilder:
def __init__(self, platform):
self._body = None
self._contents = []
self._boundary = ''
self._multipart_mixed = False
self._platform = platform
def set_multipart_mixed(self, multipart_mixed):
self._multipart_mixe... |
from setuptools import setup
setup(
name="json_to_model",
version="1.1.1",
license='MIT',
description="automatically convert json to model defination",
author='clowwindy',
author_email='clowwindy42@gmail.com',
url='https://github.com/clowwindy/json_to_model',
packages=['json_to_model', '... |
import platform
import subprocess
import sys
def _execute(*args, **kwargs):
result = subprocess.call(*args, **kwargs)
if result != 0:
sys.exit(result)
if __name__ == '__main__':
python_version = platform.python_version()
deps = [
"nose",
]
if python_version < "2.7":
deps.... |
import random
import base64
import hashlib
import string
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from post... |
from __future__ import division
from math import asin, pi, atan2, hypot, sin, cos
from .core import Mesh
from .matrix import Matrix
from .util import distance, normalize
class Sphere(Mesh):
def __init__(self, detail, radius=0.5, center=(0, 0, 0)):
super(Sphere, self).__init__()
self.detail = detail
... |
class V3(object):
def __init__(self, disp):
self.disp = disp
def on_get(self, req, resp):
resp.body = {"version": {
"status": "stable",
"updated": "2013-03-06T00:00:00Z",
"media-types": [{
"base": "application/json",
"type": "ap... |
from twisted.web.http import UNAUTHORIZED
from helper.resource import YuzukiResource
from helper.template import render_template
from model.user import User
class Login(YuzukiResource):
INVALID_CREDENTIAL = u"ID나 비밀번호가 잘못되었습니다."
BLOCKED_USER = u"차단된 계정입니다."
def render_GET(self, request):
return self... |
import re
from UltiSnips.text_objects._mirror import Mirror
class _CleverReplace(object):
"""
This class mimics TextMates replace syntax
"""
_DOLLAR = re.compile(r"\$(\d+)", re.DOTALL)
_SIMPLE_CASEFOLDINGS = re.compile(r"\\([ul].)", re.DOTALL)
_LONG_CASEFOLDINGS = re.compile(r"\\([UL].*?)\\E", r... |
from yade import pack
from yade.gridpfacet import *
young=4.0e6
poisson=3
density=1e3
frictionAngle1=radians(15)
frictionAngle2=radians(15)
frictionAngle3=radians(15)
O.dt=5e-4
O.materials.append(FrictMat(young=4000000.0,poisson=0.5,frictionAngle=frictionAngle1,density=1600,label='spheremat'))
O.materials.append(FrictM... |
from virtManager import util
from virtManager.IPy import IP
from virtManager.libvirtobject import vmmLibvirtObject
class vmmNetwork(vmmLibvirtObject):
@staticmethod
def pretty_desc(forward, forwardDev):
if forward or forwardDev:
if not forward or forward == "nat":
if forwardD... |
'''OpenGL extension ARB.imaging_DEPRECATED
Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_ARB_imaging'
_DEPRECATED = True
GL_CONVOLUTION_1D = c... |
import sys
import os
import ensymble
sys.path.append(os.path.dirname(ensymble.__file__))
from ensymble.actions import *
def main():
pgmname = os.path.basename(sys.argv[0])
debug = False
# Parse command line parameters.
try:
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
#... |
from _pygit2 import GIT_CREDTYPE_USERPASS_PLAINTEXT, GIT_CREDTYPE_SSH_KEY
class UserPass(object):
"""Username/Password credentials
This is an object suitable for passing to a remote's credentials
callback and for returning from said callback.
"""
def __init__(self, username, password):
self.... |
from m5.params import *
from m5.proxy import *
from ControlPlane import ControlPlane
from System import System
class PARDg5VSystemCP(ControlPlane):
type = 'PARDg5VSystemCP'
cxx_header = 'arch/x86/pardg5v_system_cp.hh'
# CPN address 0:0
cp_dev = 0
cp_fun = 0
# Type 'S' System, IDENT: PARDg5VSysCP... |
import pydoc, re, sys, os, glob, signal
import rsf.path as rsfpath
try:
import datetime
have_datetime_module = True
except: # Python < 2.3
have_datetime_module = False
progs = {}
data = {}
docprogs = '''
add attr awefd2d cat cmplx conjgrad cp csv2rsf cut dd disfil dottest get
headerattr headercut headermath... |
from CUBRIDPy.CUBRIDConnection import *
import logging
logging.root.setLevel(logging.INFO)
logging.info('Executing test: %s...' % __file__)
conn = CUBRIDConnection()
conn.connect()
cur = conn.cursor()
try:
query = 'select * from code'
cur.execute(query)
assert cur._total_rows_count == 6
assert cur.rownu... |
"""
Part of the floatcanvas.Utilities package.
This module contains assorted GUI-related utilities that can be used
with FloatCanvas
So far, they are:
RubberBandBox: used to draw a RubberBand Box on the screen
"""
import numpy as np
import wx
from wx.lib.floatcanvas import FloatCanvas, GUIMode
class RubberBandBox(GUIMo... |
"""
Provides testing capabilities for installed copies of Iris.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
import glob
import multiprocessing
import os
import sys
def _failed_images_iter():
"""
Return a generator of [expe... |
import os
import sys
import shutil
_prog = os.path.basename(sys.argv[0])
if len(sys.argv) < 2:
print("{}: Missing working directory argument".format(_prog),
file=sys.stderr)
sys.exit(1)
if len(sys.argv) > 2:
print("{}: Too many arguments ({!r})".format(_prog, sys.argv),
file=sys.stderr)
... |
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
print(s.recv(1024).decode())
msg = ""
while msg != "exit":
msg = input("> ")
s.send(msg.encode())
print(s.recv(1024).decode())
s.close |
from argparse import ArgumentParser
from os import remove
from os.path import splitext
import dbus
try:
from autopilot.emulators.unity import get_state_by_path
except ImportError, e:
print "Error: could not import the autopilot python module."
print "Make sure the autopilot module is in your $PYTHONPATH."
... |
import numpy as np
import cmath
import pylab as plt
Emin = 0.0e0
Emax = 4.0
nk = 200 # number of points of FT
de = (Emax-Emin)/(nk-1)
def fft_sin(nt,dt,data,alfa=0e0):
"""
fourier transform with sin(t)
INPUT:
nt: time steps
dt: time interval
alfa: damping coefficient
OUTPUT:
out: array(Nt), freq... |
import socket
from config import conf
class AS_resolver:
server = None
options = "-k"
def __init__(self, server=None, port=43, options=None):
if server is not None:
self.server = server
self.port = port
if options is not None:
self.options = options
def _s... |
from __future__ import absolute_import, unicode_literals
import math
from pokemongo_bot.cell_workers.utils import distance, format_dist
from pokemongo_bot.step_walker import StepWalker
from pokemongo_bot.cell_workers.base_task import BaseTask
class FollowSpiral(BaseTask):
def initialize(self):
self.steplimi... |
from flask import g
from flask.ext.restplus import Namespace, reqparse, marshal
from app.api.attendees import TICKET
from app.api.microlocations import MICROLOCATION
from app.api.sessions import SESSION
from app.api.speakers import SPEAKER
from app.api.sponsors import SPONSOR
from app.api.tracks import TRACK
from app.h... |
import numpy as np
import pytest
from hyperspy.components1d import Expression
from hyperspy.signals import Signal1D
DEFAULT_TOL = 2.0
BASELINE_DIR = 'plot_model1d'
STYLE_PYTEST_MPL = 'default'
class TestModelPlot:
def setup_method(self, method):
s = Signal1D(np.arange(1000).reshape((10, 100)))
np.ra... |
"""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This program is distributed in the hope that it will be ... |
from __future__ import unicode_literals
import re
import validators
from requests.compat import quote_plus, urljoin
from requests.utils import dict_from_cookiejar
from sickbeard import logger, tvcache
from sickrage.helper.common import convert_size, try_int
from sickrage.providers.torrent.TorrentProvider import Torrent... |
"""
Created on Mon Mar 2 19:12:42 2015
@author: zeke
"""
import csv
import fiona
in_shape= fiona.open('../data/census_2011/sample_shape.shp','r')
keys = []
for rec in in_shape:
keys.append(rec['properties']['DAUID'])
keys.append(rec['properties']['CTUID'])
f501 =open('/home/zeke/data/super_secret/data/501.csv'... |
from test_support import verbose
import strop, sys
def test(name, input, output, *args):
if verbose:
print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
f = getattr(strop, name)
try:
value = apply(f, (input,) + args)
except:
value = sys.exc_type
if value != outpu... |
import inspect
import time
from abc import ABCMeta, abstractmethod
from datetime import datetime
from distutils.version import LooseVersion
from enum import Enum
try:
import ovirtsdk4 as sdk
import ovirtsdk4.types as otypes
import ovirtsdk4.version as sdk_version
HAS_SDK = LooseVersion(sdk_version.VERSI... |
import sublime
import os
import unicodedata
import time
import json
import MavensMate.config as config
from .threads import ThreadTracker
settings = sublime.load_settings('mavensmate.sublime-settings')
def get_version_number():
try:
json_data = open(os.path.join(config.mm_dir,"packages.json"))
data ... |
import ast
import json
import threading
import os
from copy import deepcopy
from util import user_dir, print_error, print_msg, print_stderr
SYSTEM_CONFIG_PATH = "/etc/electrum.conf"
config = None
def get_config():
global config
return config
def set_config(c):
global config
config = c
class SimpleConfig... |
import datetime
from itertools import count
import os
import threading
import time
import urllib.parse
import pytest
import cherrypy
from cherrypy.lib import httputil
from cherrypy.test import helper
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
gif_bytes = (
b'GIF89a\x01\x00\x01\x00\x82\x00\x01\x99... |
"""Login and Registration pages """
from bok_choy.page_object import PageObject, unguarded
from bok_choy.promise import EmptyPromise, Promise
from six.moves.urllib.parse import urlencode
from common.test.acceptance.pages.lms import BASE_URL
from common.test.acceptance.pages.lms.dashboard import DashboardPage
class Regi... |
from __future__ import absolute_import, division
from mock import Mock
from io import BytesIO
from twisted.internet.address import IPv4Address
from twisted.web import server
from twisted.web.http_headers import Headers
from twisted.web.test.test_web import DummyChannel
def request(path, method=b"GET", args=[], isSecure... |
"""
Tests for course_overviews app.
"""
from cStringIO import StringIO
import datetime
import ddt
import itertools
import math
import mock
import pytz
from django.conf import settings
from django.test.utils import override_settings
from django.utils import timezone
from PIL import Image
from lms.djangoapps.certificates... |
from flask.ext.script import Manager
from skylines.database import db
from skylines.model import AircraftModel
manager = Manager(help="Perform operations related to the aircraft tables")
@manager.command
def add_model(name, kind=0, index=0):
""" Add a new aircraft model to the database """
model = AircraftModel... |
{ 'active': False,
'author': u'ADHOC SA',
'category': u'base.module_category_knowledge_management',
'data': [ u'security/law_tracking_group.xml',
u'view/legislature_view.xml',
u'view/treatment_detail_view.xml',
u'view/commission_treatment_view.xml',
... |
"""This file is part of the prometeo project.
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
This program is distributed... |
import sys
import codecs
import logging
import io
import unittest
from lib2to3 import main
class TestMain(unittest.TestCase):
def tearDown(self):
# Clean up logging configuration down by main.
del logging.root.handlers[:]
def run_2to3_capture(self, args, in_capture, out_capture, err_capture):
... |
"""
Tab completion for our interpreter prompt.
"""
from stem.interpreter import uses_settings
try:
# added in python 3.2
from functools import lru_cache
except ImportError:
from stem.util.lru_cache import lru_cache
@uses_settings
def _get_commands(controller, config):
"""
Provides commands recognized by tor.
... |
import ctypes
import ctypes.util
appkit = ctypes.cdll.LoadLibrary(ctypes.util.find_library('AppKit'))
objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))
void_p = ctypes.c_void_p
ull = ctypes.c_uint64
objc.objc_getClass.restype = void_p
objc.sel_registerName.restype = void_p
objc.objc_msgSend.restype = voi... |
import demowlcutils
from demowlcutils import ppxml, WLC_login
from pprint import pprint as pp
from lxml import etree
wlc = WLC_login()
r = wlc.rpc.delete_vlan( number="100" ) |
'''
@author: Frank
'''
import unittest
from kvmagent import kvmagent
from kvmagent.plugins import vm_plugin
from zstacklib.utils import http
from zstacklib.utils import jsonobject
from zstacklib.utils import log
from zstacklib.utils import uuidhelper
from zstacklib.utils import linux
import time
class Test(unittest.Tes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.