content stringlengths 4 20k |
|---|
# Django settings for main project.
import os
import sys
DEBUG = True
APPEND_SLASH = False
TEMPLATE_DEBUG = DEBUG
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
ADMINS = ()
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'yamzam.sqlite',
... |
import difflib
import sys
import logging
from ..utils import mounted, RpmPackageDb
log = logging.getLogger(__package__)
def init(app):
app.hooks.connect("pre-arg-parse", add_argparse)
app.hooks.connect("post-arg-parse", check_argparse)
def add_argparse(app, parser, subparsers):
if not app.experimenta... |
""" cloghandler.py: A smart replacement for the standard RotatingFileHandler
ConcurrentRotatingFileHandler: This class is a log handler which is a drop-in
replacement for the python standard log handler 'RotateFileHandler', the primary
difference being that this handler will continue to write to the same file if
the... |
from flask import render_template, redirect, request, url_for, flash, make_response
from flask.ext.login import login_user, logout_user, login_required, \
current_user
from . import auth, oauthLogin
from .. import db
from ..models import User
from authomatic.adapters import WerkzeugAdapter
from authomatic import Au... |
# coding=utf-8
from __future__ import absolute_import, division
import os
from typing import Union
from keras.preprocessing.image import img_to_array, array_to_img
import numpy as np
from pathlib import Path
from PIL import Image as PILImage, ImageOps
# I/O
def files_under(path: Path):
for f in path.glob("*"):
... |
import sys
# Adjust path so we can see the src modules running from branch as well
# as test dir:
sys.path.insert(0, './src/')
sys.path.insert(0, '../src/')
sys.path.insert(0, '../../src/') |
"""Logging utilities."""
import asyncio
from asyncio.events import AbstractEventLoop
from functools import partial, wraps
import inspect
import logging
import threading
import traceback
from typing import Any, Callable, Coroutine, Optional
from .async_ import run_coroutine_threadsafe
class HideSensitiveDataFilter(lo... |
"""Various utility classes and functions."""
import codecs
from datetime import timedelta, tzinfo
import os
import re
import textwrap
import time
from itertools import izip, imap
try:
# assigned so they're importable
frozenset = frozenset
set = set
except NameError:
from sets import ImmutableSet as fro... |
# sParse.py
# parse string expressions into connection function calls
"""
String expressions are of the form
* A
* a
* (|AB)
* (+AbCd)
* (+A(|Cd)b)
Reading the following gramar:
::== means 'is defined as'
| means 'or'
'c' means 'the literal c'
* means multiples may occur with min of zero
+ means multiples may occur ... |
import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from tests import pyunit_utils
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
def checkpoint_new_category_in_response():
sv = h2o.upload_file(pyunit_utils.locate("smalldata/iris/setosa_versicolor.csv"))
iris = h2o.upload... |
from . import connections
from .aggs import A
from .analysis import analyzer, char_filter, normalizer, token_filter, tokenizer
from .document import Document, InnerDoc, MetaField
from .exceptions import (
ElasticsearchDslException,
IllegalOperation,
UnknownDslObject,
ValidationException,
)
from .faceted... |
"""
Test module for actions utilities that modify configuration.
"""
import os
import shutil
import unittest
from plinth.actions import superuser_run, run
from plinth import cfg
test_dir = os.path.split(__file__)[0]
root_dir = os.path.abspath(os.path.join(test_dir, os.path.pardir +
... |
import os
from setuptools import setup, find_packages
import bottle_utils
def read(fname):
""" Return content of specified file """
return open(os.path.join(os.path.dirname(__file__), fname)).read()
VERSION = bottle_utils.__version__
MAJOR = '0.3'
NEXT = '0.4'
setup(
name='bottle-utils-lazy',
vers... |
from django.db import models
import decimal
class Transform(models.Model):
description = models.TextField(blank=True,
null=True)
method = models.TextField(blank=False,
null=False)
arg = models.TextField(blank=True,
... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class JWPlatformIE(InfoExtractor):
_VALID_URL = r'(?:https?://content\.jwplatform\.com/(?:feeds|players|jw6)/|jwplatform:)(?P<id>[a-zA-Z0-9]{8})'
_TEST = {
'url': 'http://content.jwplatform.com/player... |
import numpy as np
def dt_GCD(t):
""" Computes the greatest common divisor of the time steps of the times in t
Inputs:
- t [1-dim numpy array of ints]: the times.
WARNING: the times must all be distinct, of INTEGER type, and sorted in ascending order. In principle, the times come from a data file, such that ... |
'''
This state is used to generate the next generation
of the game.
It follows the rules stated at:
- https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
- https://jakevdp.github.io/blog/2013/08/07/conways-game-of-life/
That are as follows:
- Overpopulation: if a living cell ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
import dumpling.fields
class Migration(migrations.Migration):
dependencies = [
('dumpling', '0002_auto_20150413_0830'),
]
operations = [
migrations.Crea... |
# -*- coding: utf-8 -*-
"""Manage temporary directories."""
import os
import shutil
import tempfile
class temporary_directory(object):
"""Create, yield, and finally delete a temporary directory.
>>> with temporary_directory() as directory:
... os.path.isdir(directory)
True
>>> os.path.exists(... |
#!/usr/bin/env python
# encoding: utf-8
import click
import os
import pandas as pd
import datetime
import logging
import logging.config
import traceback
from openweathermap_requests import OpenWeatherMapRequests, get_api_key
import pprint
@click.command()
#@click.option('--expire_after', default=-1, help=u"Cache expi... |
from __future__ import unicode_literals
import logging
import sys
from raven.utils.testutils import TestCase
from raven.utils import six
from raven.base import Client
from raven.handlers.logging import SentryHandler
from raven.utils.stacks import iter_stack_frames
class TempStoreClient(Client):
def __init__(self... |
from mongoengine.errors import NotRegistered
__all__ = ('UPDATE_OPERATORS', 'get_document', '_document_registry')
UPDATE_OPERATORS = set(['set', 'unset', 'inc', 'dec', 'pop', 'push',
'push_all', 'pull', 'pull_all', 'add_to_set',
'set_on_insert', 'min', 'max'])
_docum... |
from six import string_types
import re
from dkrz_forms import utils,config
from IPython.display import display
# from IPython.core.display import HTML
# from collections import OrderedDict
def check_email(email):
if re.match(""r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",email) != None:
return 1
... |
import os
from whoosh import index, qparser
from whoosh.fields import Schema, TEXT, ID
from whoosh.qparser import QueryParser
import sys
import argparse
import json
from bson import json_util
runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))
from lib.Config import Con... |
import time
class Session(object):
"""
Session object are owned by the SessionHandler and maintains a state
between client request. All requests are assigned a session and its lifetime
is at least one request long.
"""
def __init__(self, uid):
self.uid = uid
self.data = dict()
... |
"""Module for the management of multi-process function calls."""
from typing import Tuple
import numpy as np
import SimpleITK as sitk
from pathos import multiprocessing as pmp
import mialab.data.structure as structure
import mialab.data.conversion as conversion
class PicklableBrainImage:
"""Represents a brain i... |
#! /usr/bin/env python
# encoding: utf-8
import os,sys
import Configure,Options,Utils
import ccroot,ar
from Configure import conftest
def find_xlc(conf):
cc=conf.find_program(['xlc_r','xlc'],var='CC',mandatory=True)
cc=conf.cmd_to_list(cc)
conf.env.CC_NAME='xlc'
conf.env.CC=cc
def find_cpp(conf):
v=conf.env
cpp=... |
import argparse, json
from boto.mturk.connection import MTurkConnection
from boto.mturk.qualification import *
from jinja2 import Environment, FileSystemLoader
"""
A bunch of free functions that we use in all scripts.
"""
def get_jinja_env(config):
"""
Get a jinja2 Environment object that we can use to find te... |
from __future__ import unicode_literals
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.views.generic import DetailView
from shuup.admin.utils.urls import get_model_url... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate... |
#!/usr/bin/env python
#
# Bzip2
#
# The bzip2 conditional package, required for RATDB functions
#
# Author O Wasalski - 13/06/2012 <<EMAIL>> : First revision, new file
# Author P G Jones - 23/06/2012 <<EMAIL>> : Refactor of Package Structure
# Author P G Jones - 22/09/2012 <<EMAIL>> : Major refactor of snoing.
#######... |
import sys
def writeVector(q):
"""Writes a vector to text 'n v1 ... vn'"""
return str(len(q))+'\t'+' '.join(str(v) for v in q)
def readVector(text):
"""Reads a vector from text 'n v1 ... vn'"""
items = text.split()
if int(items[0])+1 != len(items):
raise ValueError("Invalid number of items... |
import random
import pytest
def test_mean_filter():
from scitbx.array_family import flex
from dials.algorithms.image.filter import mean_filter
# Create an image
image = flex.random_double(2000 * 2000)
image.reshape(flex.grid(2000, 2000))
# Calculate the summed area table
mean = mean_fi... |
'Convert CSV file to Vowpal Wabbit format.'
'all columns numerical or all categorical - no mixing at the moment'
import sys
import csv
import argparse
def construct_line( label, line ):
new_line = []
# label
try:
label = float( label )
except Exception, e:
pass
if label == 0.0:
if args.convert_zeros:
... |
from unittest import skip
from . import BaseUnitTestCase, BaseUnitTestCaseWithErrors
import os
import shutil
from cupstream2distro import branchhandling
class BranchHandlingTests(BaseUnitTestCase):
def setUp(self):
super(BranchHandlingTests, self).setUp()
# We want the full diff on failures
... |
#!/usr/bin/env python
from pylab import *
from Simplex_optimization import Simplex
from ClampedCubicSpline import *
nnodes = 4
nsplines = nnodes + 1
perNode = 10
nsamp = (nsplines)*perNode
Gen= [0.0]*2*nnodes
def R2omega(R):
return sqrt(1.0/R**3)
T = 3.0
R0 = 1.0
R1 = 0.2
v0=R2omega(R0)
v1=R2... |
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr',
'name': 'LevelMgr',
'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_10/models/cashbotHQ/ZONE07a',
'wantDoors': 1},
1001: {'type... |
import unittest
import sys
import os
import shutil
import asyncio
from snare.cloner import Cloner
from snare.utils.page_path_generator import generate_unique_path
from snare.utils.asyncmock import AsyncMock
class TestReplaceLinks(unittest.TestCase):
def setUp(self):
self.main_page_path = generate_unique_p... |
#!/usr/bin/env python
# Usage: python A_prep_gtf_for_PAR-CLIP.py gencode.v25lift37.annotation_for_UCSC.gtf gencode.v25lift37.annotation_for_UCSC_only_basic_mRNAs.gtf gencode.v25lift37.annotation_for_UCSC_only_basic_mRNAs_gene_trx_list.txt
from __future__ import print_function
import sys
input_file = open(sys.argv[1]... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
from frappe.utils.nestedset import get_descendants_of
def execute(filters=None):
filters = frappe._dict(filters or {})
columns = get_columns(filters)
data = get_data(filters)
return columns, data
def get_column... |
import argparse
import os
import logging
import stat
import sys
import yaml
import zookeeper
from twisted.application import service
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.scripts._twistd_unix import UnixApplicationRunner, UnixAppLogger
from twisted.python.log import PythonLoggin... |
import binascii
from construct import *
# Constants
## Sizes
DEFAULT_HASH_SIZE = 32 # hash size for Blake2s_256 hashing
DEFAULT_PUBLIC_KEY_SIZE = 32
DEFAULT_SIGNATURE_SIZE = 64
DEFAULT_ADDRESS_HASH_SIZE = 28 # hash size for Blake2s_224 hashing
## Protocol constants
VERSION_MAGIC = 16842752
PROTOCOL_MAGIC = 0
MAJ_... |
import os
import re
from pyanaconda.modules.storage.bootloader.base import BootLoaderError
from pyanaconda.modules.storage.bootloader.grub2 import GRUB2
from pyanaconda.core import util
from pyanaconda.core.kernel import kernel_arguments
from pyanaconda.core.configuration.anaconda import conf
from pyanaconda.product i... |
'''Test idlelib.parenmatch.
This must currently be a gui test because ParenMatch methods use
several text methods not defined on idlelib.idle_test.mock_tk.Text.
'''
from idlelib.parenmatch import ParenMatch
from test.support import requires
requires('gui')
import unittest
from unittest.mock import Mock
from tkinter i... |
""" Configuration variables for defining remote applications.
================================ ==============================================
`OAUTHCLIENT_REMOTE_APPS` Dictionary of remote applications. See example
below. **Default:** ``{}``.
`OAUTHCLIENT_SESSION_KEY_PREFIX` Pre... |
from setuptools import setup, find_packages
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
INSTALL_REQUIRES = ['gevent']
if module_exists('psycopg2'):
INSTALL_REQUIRES.append('psycogreen')
INSTALL_REQUIRES.a... |
from utils.utils import Utils
from datamodel.datamodel import LoraRadioMessage
from datamodel.datamodel import SIMessage
class LoraSIMessageToSirapTransform(object):
@staticmethod
def GetInputMessageType():
return "LORA"
@staticmethod
def GetInputMessageSubType():
return "SIMessage"
... |
from django.core.files.base import File
from django.core.files.storage import Storage
from easy_thumbnails import fields as easy_thumbnails_fields, \
files as easy_thumbnails_files
from filer import settings as filer_settings
from filer.utils.filer_easy_thumbnails import ThumbnailerNameMixin
from filer.utils.loader... |
import wx
import os
class SelectDataDirectoryDialog(wx.Dialog):
"""A dialog to be used to display a splash window for
this layout tool. You must also select a valid data
directory for this application to work with. After
you press OK the main frame is loaded and you can begin
to edit your layout of CSP."""
de... |
from django.core.urlresolvers import reverse
from taiga.base.utils import json
from taiga.permissions.permissions import MEMBERS_PERMISSIONS, ANON_PERMISSIONS, USER_PERMISSIONS
from tests import factories as f
from tests.utils import helper_test_http_method, disconnect_signals, reconnect_signals
import pytest
pytest... |
import unittest
from king_phisher import testing
from king_phisher.client.export import *
from king_phisher.client.export import message_template_from_kpm
from king_phisher.client.export import message_template_to_kpm
class ClientExportTests(testing.KingPhisherTestCase):
def test_value_conversions(self):
self.asse... |
from msrest.serialization import Model
class VirtualNetworkGatewaySku(Model):
"""VirtualNetworkGatewaySku details.
:param name: Gateway SKU name. Possible values include: 'Basic',
'HighPerformance', 'Standard', 'UltraPerformance', 'VpnGw1', 'VpnGw2',
'VpnGw3'
:type name: str or
~azure.mgmt... |
"""Python layer for image_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.image.ops import gen_image_ops
from tensorflow.contrib.util import loader
from tensorflow.python.framework import common_shapes
from tensorflow.python.f... |
from unittest import TestCase
import pytest
from anchore_engine.db import get_thread_scoped_session
from anchore_engine.services.catalog import catalog_impl
# This looks unused, but it is
from tests.fixtures import anchore_db
@pytest.mark.skip(
reason="hard to install skopeo (which is needed for this test) in ... |
from pyre.applications.Script import Script
import numpy
# QuadratureApp class
class QuadratureApp(Script):
"""
Python application for generating C++ data files for testing C++
quadrature objects.
"""
# INVENTORY //////////////////////////////////////////////////////////
class Inventory(Script.Invento... |
from django.db import models
import json
from quiz.models import Quiz
class TextQuestion(models.Model):
quiz = models.ForeignKey(Quiz, null=False)
question = models.TextField(blank=False)
answer = models.CharField(max_length=64)
order = models.IntegerField(null=False, default=1)
def __unicode__(self):
return(... |
import networkx as nx
import random
class solver:
def __init__(self, G, delta = 1.0/44):
"""
Args:
delta: "cleanness" parameter. Defaults to the assumed value of 1/44
given in the paper
"""
self.__G__ = G
self.__reset_caches__()
self.... |
""" @file main.py
The main code to run on the STM32F411 at the heart of the IMU guide.
@authors Anthony Lombardi
@authors John Barry
@date 8 December 2016
"""
# === CONSTANTS ===
_LOOP_DELAY = const(100) # [us], number of microseconds to wait between main loops
_ERR_FLAG_MASK = const(0b0111111000000000) # bit plac... |
# encoding: utf-8
from train.sgd import sgd
from tager import Tager
from stats import stats
from model import Model
from data.dataset import features_in_data
def flatten(l):
v = []
for x in l:
v.extend(x)
return v
def cross_validation(dataset, k, *sgd_args, **sgd_kwargs):
"""Perform k-cross v... |
import argparse
import png
from numpy import sqrt,sqrt,array,unravel_index,nditer,linalg,random,subtract,power,exp,pi,zeros,arange,outer,meshgrid
from collections import defaultdict
class MiniSom:
def __init__(self,x,y,input_len,sigma=1.0,learning_rate=0.5):
"""
Initializes a Self Organizing Maps.
x,y - di... |
"""The ColoredFormatter class."""
from __future__ import absolute_import
import logging
import sys
from colorlog.escape_codes import escape_codes, parse_colors
__all__ = ('escape_codes', 'default_log_colors', 'ColoredFormatter',
'LevelFormatter', 'TTYColoredFormatter')
# The default colors to use for th... |
"""
Support for GEOS prepared geometry operations.
"""
from shapely.geos import lgeos
from shapely.impl import DefaultImplementation
class PreparedGeometry(object):
"""
A geometry prepared for efficient comparison to a set of other geometries.
Example:
>>> from shapely.geometry import P... |
from __future__ import with_statement
from weboob.capabilities.video import ICapVideo, BaseVideo
from weboob.tools.backend import BaseBackend
from weboob.capabilities.collection import ICapCollection, CollectionNotFound
from .browser import YoupornBrowser
from .video import YoupornVideo
__all__ = ['YoupornBackend']... |
import icalendar as ical
from datetime import timedelta
from indico.core.index import Catalog
from indico.web.http_api.hooks.base import HTTPAPIHook, IteratedDataFetcher
from indico.web.http_api.metadata.ical import ICalSerializer
from indico.web.http_api.util import get_query_parameter
from indico.web.http_api.respon... |
import contextlib
import multiprocessing
import multiprocessing.managers
import os
import platform
import random
import signal
import socket
import subprocess
import sys
import threading
import time
from .compat import str_join
from .test import TestEntry, domain_socket_path
from .report import ExecReporter, SummaryRe... |
from __future__ import absolute_import
import mock
from oauth2client.client import AccessTokenCredentials
import unittest
from google.cloud.monitoring import Resource
from google.cloud.monitoring import Metric
from google.cloud.monitoring import TimeSeries
import google.datalab
import google.datalab.stackdriver.monit... |
# -*- coding: utf-8
from __future__ import absolute_import
from django.contrib.auth.models import User
from django.test import Client, TransactionTestCase
try:
from django.core.urlresolvers import reverse
except ImportError:
from django.urls import reverse
from lock_tokens.models import LockableModel
from lock_to... |
import logging
from pymongo import MongoClient
import json
from bson import json_util
import time
import datetime
logger = logging.getLogger(__name__)
class UIPusher:
def __init__(self,core,parm):
# register event handler
core.registerEventHandler("controlleradapter", self.controllerHandler)
# register rest ... |
"""Translate python-phonenumbers PhoneNumber to/from protobuf PhoneNumber
Examples of use:
>>> import phonenumbers
>>> from phonenumbers.pb2 import phonenumber_pb2, PBToPy, PyToPB
>>> x_py = phonenumbers.PhoneNumber(country_code=44, national_number=7912345678)
>>> print x_py
Country Code: 44 National Number: 79123456... |
'''
Created on 06.05.2016
@author: mkennert
'''
from kivy.uix.gridlayout import GridLayout
from functions.quadratic import Quadratic
from materialLawEditor.quadraticInformation import QuadraticInformation
from materialLawEditor.quadraticView import QuadraticFunctionView
import numpy as np
from kivy.propert... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.sites.models import Site
from django.apps import apps
from django.forms import fields
from django.forms.models import ModelForm
from django.utils.module_loading import import_string
from django.utils.tra... |
"""
Tor versioning information and requirements for its features. These can be
easily parsed and compared, for instance...
::
>>> from stem.version import get_system_tor_version, Requirement
>>> my_version = get_system_tor_version()
>>> print(my_version)
0.2.1.30
>>> my_version >= Requirement.TORRC_CONTROL_... |
""" Trains an agent with Deep Q Learning or Double DQN on Breakout. Uses OpenAI Gym.
"""
import sys
import os
sys.path.insert(0,os.path.expanduser('~/Library/Python/2.7/lib/python/site-packages/'))
import numpy as np
import cPickle as pickle
import gym
from optparse import OptionParser
import itertools
import random
... |
from flask import abort, session, request
from functools import wraps
from hashlib import sha512
from datetime import datetime
from random import randint
# Adopted from http://flask.pocoo.org/snippets/3/ and then greatly modified
class Protector(object):
parameter = '_csrf_token'
session_key = '_csrf_toke... |
"""Backwards compatibility functional test
Test various backwards compatibility scenarios. Download the previous node binaries:
test/get_previous_releases.py -b v0.19.1 v0.18.1 v0.17.2 v0.16.3 v0.15.2
v0.15.2 is not required by this test, but it is used in wallet_upgradewallet.py.
Due to a hardfork in regtest, it ca... |
# coding: utf-8
from __future__ import unicode_literals
from geopy.geocoders import Yandex
from test.geocoders.util import GeocoderTestBase
class YandexTestCase(GeocoderTestBase):
@classmethod
def setUpClass(cls):
cls.delta = 0.04
def test_unicode_name(self):
"""
Yandex.geocode ... |
"""
Simple linear regression example in TensorFlow
This program tries to predict the number of thefts from
the number of fire in the city of Chicago
"""
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import csv
DATA_FILE = 'data/fire_theft.csv'
# Step 1: read data
with open(DATA_FILE, 'r... |
from warnings import warn
from mizani.palettes import manual_pal
from ..doctools import document
from ..exceptions import PlotnineError, PlotnineWarning
from ..utils import alias
from .scale import scale_discrete, scale_continuous
# All these shapes are filled
shapes = (
'o', # circle
'^', # triangle up
... |
import sys
import os
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyMca5.PyMcaGui.plotting import PlotWindow as pltwin
from PyMca5.PyMcaIO import specfilewrapper as specfile
# external files
from summing import *
#from subtract import *
#from extension import *
#from calDOS import *
#from renormDO... |
########################################################################
# File: OperationHandlerBase.py
########################################################################
""" :mod: OperationHandlerBase
==========================
.. module: OperationHandlerBase
:synopsis: request operation handler ba... |
from distutils.core import setup
setup(name='sshlauncher',
version='2.1',
scripts=['sshlauncher'],
py_modules=['sshctrl'],
install_requires=['pexpect>3.0'],
description='SSHLauncher is allows an easy, scripted, parallel execution of applications on multiple hosts.',
author='Zdravko B... |
import os
import platform
import textwrap
import unittest
import pytest
from conans.test.utils.tools import TestClient
from conans.util.runners import check_output_runner
class VirtualBuildEnvTest(unittest.TestCase):
@pytest.mark.skipif(platform.system() != "Windows", reason="needs Windows")
@pytest.mark.t... |
# -*- coding: utf-8 -*-
""" The tab strip manipulation which appears in Configure / Configuration and possibly other pages.
Usage:
import cfme.web_ui.tabstrip as tabs
tabs.select_tab("Authentication")
print(is_tab_selected("Authentication"))
print(get_selected_tab())
"""
from collections import Mappi... |
from __future__ import division, absolute_import
from __future__ import print_function, unicode_literals
import itertools
import numpy as np
import sklearn.datasets
import sklearn.cross_validation
import sklearn.metrics
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
from treeano.sand... |
"""This module contains a object that represents a Telegram Audio"""
from telegram import TelegramObject
class Audio(TelegramObject):
"""This object represents a Telegram Audio.
Attributes:
file_id (str):
duration (int):
performer (str):
title (str):
mime_type (str):
... |
"""
Allows simplified start of the authentification dialog.
"""
import sys
from PyQt4.QtGui import QApplication
from datafinder.gui.user.dialogs.authentification_dialog.auth_connect_dialog import AuthConnectDialogView
from datafinder.gui.user.dialogs.connect_dialog import ConnectDialogView
from datafinder... |
from contextlib import suppress
from typing import Callable
import urwid
from clisnips.exceptions import ParsingError
from clisnips.tui.syntax import highlight_command, highlight_documentation
from clisnips.tui.widgets.dialog import Dialog, ResponseType
from clisnips.tui.widgets.divider import HorizontalDivider
from ... |
"""App related views."""
from django.utils.translation import ugettext as _
from django.views import generic
from django.contrib.auth import mixins as auth_mixins
from modoboa.admin import models as admin_models
from . import models
class DomainAccessRequiredMixin(auth_mixins.AccessMixin):
"""Check if user ca... |
import random
import pandas as pd
from vincent.colors import brews
# Some sample data to plot.
cat_4 = ['Metric_' + str(x) for x in range(1, 9)]
index_4 = ['Data 1', 'Data 2', 'Data 3', 'Data 4']
data_3 = {}
for cat in cat_4:
data_3[cat] = [random.randint(10, 100) for x in index_4]
# Create a Pandas dataframe fro... |
# urls.py for decomposition
from django.conf.urls import include, url
from decomposition import views
urlpatterns = [
url(r'^view_parents/(?P<decomposition_id>\w+)/(?P<mass2motif_id>\w+)/$', views.view_parents, name='view_parents_decomposition'),
url(r'^get_parents/(?P<decomposition_id>\w+)/(?P<mass2motif_id>\w+)/$'... |
import argparse
import unicodedata
from ejercicio import Ejercicio
from prueba import Prueba
def remover_acentos(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
def abrir_contenedor(nombre_archivo):
archivo = open(nombre_archivo, 'r')
return [l... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 增量式的处理大型XML文档
Desc :
"""
from xml.etree.ElementTree import iterparse
from xml.etree.ElementTree import parse
from collections import Counter
def parse_and_remove(filename, path):
path_parts = path.split('/')
doc = iterparse(filename, ('start', 'end')... |
import os
from flask import Flask, request, session
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.pagedo... |
import pathlib
import unittest
import numpy as np
import pandas as pd
from surgeo.models.surname_model import SurnameModel
class TestSurnameModel(unittest.TestCase):
_SURNAME_MODEL = SurnameModel()
_DATA_FOLDER = pathlib.Path(__file__).resolve().parents[1] / 'data'
def test_get_probabilities(self):
... |
"""
OCCI application
"""
__author__ = 'gpetralia'
from occi import wsgi as occi_wsgi
from api.occi_epa.epa_registry import EPARegistry
from api.occi_epa.json_rendering import EPAJsonRendering
from api.occi_epa.text_occi_rendering import EPATextOcciRendering
class EPAApplication(occi_wsgi.Application):
def __ini... |
#!/usr/bin/env python3
from datetime import datetime
from app.app import db
class Tournament(db.Model):
"""
Represents a tournament
"""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=False)
location = db.Column(db.String)
start = db.Column(db.Date)
end ... |
import random
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
class SaleCoupon(models.Model):
_name = 'sale.coupon'
_description = "Sales Coupon"
_rec_name = 'code'
@api.model
def _generate_code(self):
"""Generate a 20 char long pseudo-random stri... |
"""Hello World API implemented using Google Cloud Endpoints.
Defined here are the ProtoRPC messages needed to define Schemas for methods
as well as those methods defined in an API.
"""
import os
import sys
# https://cloud.google.com/appengine/docs/python/refdocs/google.appengine.tools.devappserver2.endpoints
import ... |
import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... |
"""Tapped Delay Line handler."""
import torch
import torch.nn as nn
class OneStepDelayKernel(nn.Module):
"""Single slot queue OSD kernel."""
def __init__(self, *args, **kwargs):
"""Initialize OSD kernel."""
super().__init__()
self.reset()
def reset(self):
self.state = None
def forward(self,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.