content stringlengths 4 20k |
|---|
import base64
import os
import unittest
from py_vulcanize import project as project_module
from py_vulcanize import resource_loader
from py_vulcanize import fake_fs
from py_vulcanize import module
class StyleSheetUnittest(unittest.TestCase):
def testImages(self):
fs = fake_fs.FakeFS()
fs.AddFile('/src/foo... |
import unittest
from restless.tnd import TornadoResource, _BridgeMixin
from restless.utils import json
from tornado import testing, web, httpserver, gen
from restless.constants import UNAUTHORIZED
class TndBaseTestResource(TornadoResource):
"""
base test resource, containing a fake-db
"""
fake_db = [... |
import ssl
import pytest
from six.moves import builtins
from hum_proto import ssl_utils
class ExceptionForTest(Exception):
pass
class TestStubSSLContext(object):
def test_init(self):
result = ssl_utils.StubSSLContext('protocol')
assert result.protocol == 'protocol'
assert result.c... |
#! /usr/env/python
"""
This script builds several of Landlab's key grid documentation files, based
around Sphinx and the new LLCATS type declaration system. The files affected
are:
landlab.grid.base.rst
landlab.grid.raster.rst
landlab.grid.voronoi.rst
landlab.grid.radial.rst
landlab.grid.hex.rst
It takes the files na... |
from multiprocessing import Pool,Process,Queue, Manager, TimeoutError ,JoinableQueue
from mawie.models.File import File
import os
class Updator():
def __init__(self):
self.pool = Pool(processes=2)
self.numProcess = 2
self.updateQueueFile()
self.pool.map(self.task,self.queueFiles)
... |
import pytest
from eche.env import get_default_env
from eche.eche_types import List
from eche.tests import eval_ast_and_read_str
import eche.step2_eval as step
@pytest.mark.parametrize("test_input,expected_value", [
('(+ 1)', 1),
('(+ 0)', 0),
('(+ 1 2)', 3),
('(+ 1 2 3)', 6),
('(+ 2 3)', 5),
... |
__author__ = 'alisonbento'
import flask_restful
from flask_restful import reqparse
import hsres
from src.dao.appliancedao import ApplianceDAO
import src.resstatus as _status
from src.scheme_loader import SchemeLoader
from src.lib.service_caller import call_service
class EventResource(hsres.HomeShellResource):
... |
from unittest import TestCase
import sys
from io import StringIO
from traceback import print_exc
from seecr.test.io import stdout_replaced, stderr_replaced, stdin_replaced
class IOTest(TestCase):
def testStdInReplaced_withGivenStream(self):
idStdin = id(sys.stdin)
_in = StringIO('string\nio\n'... |
from OpenGL.GL import *
from .. GLGraphicsItem import GLGraphicsItem
from pyqtgraph import QtGui
__all__ = ['GLAxisItem']
class GLAxisItem(GLGraphicsItem):
"""
**Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>`
Displays three lines indicating origin and orientation of local coordina... |
#-*- coding=utf-8 -*-
import urllib
from django.shortcuts import render, get_object_or_404
from kitabu.search.available import Clusters as ClustersSearcher, Subjects as SubjectSearcher, FindPeriod
from kitabu.search.reservations import SingleSubjectManagerReservationSearch
from lanes.models import Lane, LaneReservat... |
from codecs import open
from collections import namedtuple
import os
import logging
from itertools import chain
import re
import six
from six.moves import range
from . import (
Messages, Constants,
blocks, params, ports, errors, utils, schema_checker
)
from .Config import Config
from .cache import Cache
from... |
import unittest
import uuid
from Selenium2Library.locators import WindowManager
from mockito import *
from selenium.common.exceptions import NoSuchWindowException
class WindowManagerTests(unittest.TestCase):
def test_select_with_invalid_prefix(self):
manager = WindowManager()
browser = mock()
... |
"""Compare two or more dashds to each other.
To use, create a class that implements get_tests(), and pass it in
as the test generator to TestManager. get_tests() should be a python
generator that returns TestInstance objects. See below for definition.
TestNode behaves as follows:
Configure with a BlockStore and... |
import os
import unittest
import numpy
import chainer
from chainer.exporters import caffe
import chainer.functions as F
import chainer.links as L
from chainer import testing
# @testing.parameterize([
# {'layer': 'LinearFunction'},
# {'layer': 'Reshape'},
# {'layer': 'Convolution2DFunction'},
# {'lay... |
"""
Main API for the workflows.
If you want to run a workflow using the workflows module,
this is the high level API you will want to use.
"""
from invenio_base.globals import cfg
from werkzeug.utils import cached_property, import_string
from .errors import WorkflowWorkerError
from .utils import BibWorkflowObjectI... |
""" $lic$
Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of
Stanford University
This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiative.
This program is distributed in the hope that it wi... |
from __future__ import absolute_import
import os, re, HTMLParser
from urlparse import urlparse
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from wagtail.wagtailcore.templatetags import wagtailcore_tags... |
import cocotb
from cocotb.result import TestFailure
from cocotb.clock import Clock
from cocotb.triggers import RisingEdge, FallingEdge, ClockCycles, ReadOnly
from cocotb.result import TestFailure
class MultipyAccumulateCellTB(object):
def __init__(self, dut):
self.dut = dut
s... |
class GridCell:
def __init__(self, parent_grid, x_pos, y_pos):
self.parent_grid = parent_grid
self.players = []
self.x_pos = x_pos
self.y_pos = y_pos
self.player_with_ball = None
self.has_ball = None
self.parent_zone = None # TODO: A grid cell must know its... |
"""Symbolic primitives + unicode/ASCII abstraction for pretty.py"""
from __future__ import print_function, division
import sys
import warnings
unicode_warnings = ''
from sympy.core.compatibility import u, unicode, range
# first, setup unicodedate environment
try:
import unicodedata
def U(name):
"""... |
import logging
import traceback
import json
from django.shortcuts import render
from django.http import HttpResponse
from helpers.exceptions import NotAuthorizedException
logger = logging.getLogger(__name__)
# TODO so we are using this as the catch ALL, and report error, as the last resort
# this is fine, except the... |
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = """
options:
provider:
description:
- B(Deprecated)
- "Starting with Ansible 2.5 we recommend using C(connection: network_cli)."
- This option is only required if you are using NX-API.
- For m... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: type_Result.py
from types import *
import mcl.object.IpAddr
RESULT_DATA_TYPE_INITIAL = 1
RESULT_DATA_TYPE_ADDED = 2
RESULT_DATA_TYPE_REMOVED = 3
RESU... |
# Thai Thien
# 1351040
import pytest
import cv2
import sys
import sys, os
import numpy as np
import upload
# make sure it can find detector.py file
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
import util
from detector import Detector
image_path = './image/cat.jpg'
blob_path = './image/blobsam... |
#!/data/apps/python/2.7.2/bin/python
import sys, string, random
import sequence
#
# turn on psyco to speed up by 3X
#
if __name__=='__main__':
try:
import psyco
#psyco.log()
psyco.full()
psyco_found = True
except ImportError:
# psyco_found = False
pass
# print >> sys.stderr, "psyco_found... |
from climate.api.v1 import service as service_api
from climate.api.v1 import utils as utils_api
from climate.api.v1 import v1_0 as api
from climate import tests
class RESTApiTestCase(tests.TestCase):
def setUp(self):
super(RESTApiTestCase, self).setUp()
self.api = api
self.u_api = utils_ap... |
# encoding: utf-8
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 'Task'
db.create_table('tasks_task', (
('id', self.gf('django.db.models.fields.... |
from essentia_test import *
from random import randint
class TestEffectiveDuration(TestCase):
def testEmpty(self):
input = []
self.assertEqual(EffectiveDuration()(input), 0.0)
def testZero(self):
input = [0]*100
self.assertAlmostEqual(EffectiveDuration()(input), 0.)
def ... |
from __future__ import absolute_import
from ._gmres_mgs import gmres_mgs
from ._gmres_householder import gmres_householder
__all__ = ['gmres']
def gmres(A, b, x0=None, tol=1e-5, restrt=None, maxiter=None, xtype=None,
M=None, callback=None, residuals=None, orthog='householder',
**kwargs):
"""... |
import py
import os
import pytest
import numpy as np
import scipy as sp
import openpnm as op
class HDF5Test:
def setup_class(self):
ws = op.Workspace()
ws.settings['local_data'] = True
self.net = op.network.Cubic(shape=[2, 2, 2])
Ps = [0, 1, 2, 3]
Ts = self.net.find_neighb... |
#!/usr/bin/env python
import urllib2
import base64
import zlib
import threading
from threading import Lock
import json
import sys
import ssl
# Tune CHUNKSIZE as needed. The CHUNKSIZE is the size of compressed data read
# For high volume streams, use large chuck sizes, for low volume streams, decrease
# CHUNKSIZE. Mi... |
import maya.cmds as cmds
from tank import TankError
import config_constants as configCONST
from apps.app_logger import log
from sg_shd_lib import findConnections
def loadSceneAssemblyPlugins(tankError = False):
## PLUGIN CHECK
## First try to make sure the plugins are loaded in maya
if not cmds.pluginInfo... |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
from os.path imp... |
import pytest
from openff.toolkit.typing.chemistry import *
from openff.toolkit.utils.toolkits import OPENEYE_AVAILABLE
# TODO: Evaluate which tests in this file should be moved to test_toolkits
toolkits = []
if OPENEYE_AVAILABLE:
from openff.toolkit.utils.toolkits import OpenEyeToolkitWrapper, RDKitToolkitWrappe... |
import unittest
import numpy as np
from bltest import attr
import vg
from lace.cache import sc, vc
from lace.mesh import Mesh
class TestGeometryMixin(unittest.TestCase):
debug = False
@attr('missing_assets')
def test_cut_across_axis(self):
original_mesh = Mesh(filename=sc('s3://bodylabs-assets/exa... |
"""Contains configuration options for NetApp drivers.
Common place to hold configuration options for all NetApp drivers.
Options need to be grouped into granular units to be able to be reused
by different modules and classes. This does not restrict declaring options in
individual modules. If options are not re usable ... |
"""
Copyright 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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 2
of the License, or (at your ... |
# coding: utf-8
#In order of performance
try:
import ujson as json
except ImportError:
try:
import simplejson as json
except ImportError:
import json
from ..base import ObjectifyObject
class ObjectifyModel(ObjectifyObject):
__fetch_attr__ = None
__serializer__ = json.dumps
... |
"""Encoding and decoding audio using FFmpeg."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.ffmpeg.ops import gen_decode_audio_op_py
from tensorflow.contrib.ffmpeg.ops import gen_decode_video_op_py
from tensorflow.contrib.ffmpeg.... |
"""Utility functions for geometrical entities.
Contains
========
intersection
convex_hull
closest_points
farthest_points
are_coplanar
are_similar
"""
from __future__ import division, print_function
from sympy import Function, Symbol, solve
from sympy.core.compatibility import (
is_sequence, range, string_types)
... |
#-*- coding: utf-8 -*-
"""
Ads app forms module
This module provides default forms to work with Ad, AdContact, AdSearch forms.
"""
from django import forms
from django.http import QueryDict
from geoads.models import AdPicture, AdContact, AdSearch, AdSearchResult, Ad
from geoads.utils import geocode
class AdPictureF... |
import datetime
import logging
import mockery2
from mockery2.config import sensors
def listsensors():
"""Returns list of current sensors"""
return sorted(sensors.keys())
def dumpsensors():
"""Returns all sensors and their current parameters"""
l = []
for s in sorted(sensors):
l.append({... |
import latus
from enum import IntEnum
LOG_FILE = latus.__application_name__ + '.log'
LATUS_KEY_FILE_EXT = '.lky'
DB_EXTENSION = '.db'
ENCRYPTION_EXTENSION = '.fer'
UNENCRYPTED_EXTENSION = '.une'
DESCRIPTION = 'Secure file sync with low impact to cloud storage.'
MAIN_FILE = 'main.py'
MAKE_DIRS_MODE = 0o775
# todo: m... |
"""
Import/Export Contacts API
"""
import csv
from django.http import HttpResponse
import StringIO
from treeio.identities.models import Contact, ContactType, ContactField, ContactValue
import re
import urlparse
class ProcessContacts():
"Import/Export Contacts"
"""
def export_contacts(self, contacts):... |
# encoding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import re
import warnings
from django.utils.encoding import force_text, python_2_unicode_compatible
@python_2_unicode_compatible
class BaseInput(object):
"""
The base input type. Doesn't do much. You want `... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
int_or_none,
qualities,
unescapeHTML,
url_or_none,
)
class YapFilesIE(InfoExtractor):
_YAPFILES_URL = r'//(?:(?:www|api)\.)?yapfiles\.ru/get_player/*\?.*?\bv=(?P<id>\w+)'
... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from math import ceil
from flask import jsonify, request
from sqlalchemy import desc, asc
from flexget.api import api, APIResource
from flexget.api.app imp... |
import argparse
import datetime
import json
import sys
import pyspark
from visits_detector.core import FilterAndMapToIndexMapper, ExtractEventsReducer
from visits_detector.core.components.params import EventExtractionStageParams
from visits_detector.core.helpers.geo_index import build_geo_index_from_point_index
from ... |
"""Demo for XGBoost ML Pipeline Generator."""
from ml_pipeline_gen.models import XGBoostModel
from model.taxi_preprocess import load_data
def _upload_data_to_gcs(model):
load_data(model.data["train"], model.data["evaluation"])
def main():
config = "config.yaml"
pred_input = [[
1.0, -0.56447923, ... |
"""
Shared constants across the VMware driver
"""
from nova.compute import power_state
from nova.network import model as network_model
MIN_VC_VERSION = '5.1.0'
NEXT_MIN_VC_VERSION = '5.5.0'
# The minimum VC version for Neutron 'ovs' port type support
MIN_VC_OVS_VERSION = '5.5.0'
DISK_FORMAT_ISO = 'iso'
DISK_FORMAT_V... |
"""Starter script for Nova Metadata API."""
import sys
from oslo_config import cfg
from nova.conductor import rpcapi as conductor_rpcapi
from nova import config
from nova import objects
from nova.objects import base as objects_base
from nova.openstack.common import log as logging
from nova.openstack.common.report im... |
from .proto import types_pb2 as pb
from .utils import AbstractProtoWrapper
__all__ = ['DataType', 'IntegerType', 'DoubleType', 'BooleanType',
'ArrayType', 'StructField', 'StructType',
'merge_proto_types', 'merge_types']
class DataType(AbstractProtoWrapper):
def __init__(self, _proto):
assert _proto
# T... |
from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import cStringIO as StringIO
from scipy import misc, ndimage
from skimage import feature
import numpy as np
import torch
from torch.autograd import Variable
from config import Config
fro... |
import asyncio
import asynqp
import logging
log = logging.getLogger(__name__)
class DataIndexer:
RECONNECT_TIMEOUT = 1
def __init__(self, *, loop, **params):
self.params = params
self.loop = loop
# Connect/reconnect logic
@asyncio.coroutine
def start(self):
# connect t... |
"""
tools for interfacing with system
"""
import sys
import platform
import os
import json
import psutil
from pprint import PrettyPrinter
# my os environment var
def get_environ_variables():
"""
return the environments variables (list)
"""
return os.environ.data
# tools for platform ... |
from collections import OrderedDict
from distutils import util
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
from google.api_core import client_options as client_options_lib # type: ignore
from google.api_core import exceptions # type: ignore
from google.api_core import gapic_v1... |
import numpy as np
from scipy import sparse
import atgraph_sparse, atmath, atgraph
# Code length calculation
def twolevelCodelengthFromTrans(T_csr, member, u=None, Hu=None, uMod=None, TMod=None):
if u is None:
# Compute stationnary distrigution
(crap, u) = atgraph.arnoldi(T_csr, k=1)
u = np... |
#!/usr/bin/python
import sys, time, re, threading
from executable import Executable
'''
Sends an ARP Request given a source ip, source hw address and a target ip.
Disregards the reply. Use to spoof arp for hosts with arp snooping on.
If you use the same target ip and source ip, this looping program will
be making ... |
'''
http://www.scipy.org/Cookbook/Finding_Convex_Hull
'''
# ============= enthought library imports =======================
# ============= standard library imports ========================
# ============= local library imports ==========================
from numpy import arctan, pi, cross, asarray, apply_along_axis... |
#!/usr/bin/env python
# coding=utf-8
"""
Prime permutations
Problem 49
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases
by 3330, is unusual in two ways:
(i) each of the three terms are prime, and,
(ii) each of the 4-digit numbers are permutations of one another.
There are no ari... |
#! /usr/bin/env python
"""
Project: Python Chess
File name: ChessGUI_text.py
Description: Draws a text based chess board in the console window.
Gets user input through text entry.
Copyright (C) 2009 Steve Osborne, srosborne (at) gmail.com
http://yakinikuman.wordpress.com/
"""
from ChessRules import ChessRul... |
"""Controllers for the Oppia collection learner view."""
from core.controllers import base
from core.domain import collection_services
from core.domain import config_domain
from core.domain import rights_manager
from core.domain import summary_services
from core.platform import models
import feconf
import utils
(user... |
from twisted.words.protocols import irc
from txircd.modbase import Command
class PartCommand(Command):
def onUse(self, user, data):
if "targetchan" not in data:
return
reason = data["reason"] if "reason" in data else None
for channel in data["targetchan"]:
if user no... |
"""
BlackDog
Copyright (C) 2014 Snaipe, Ojukashi
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 ... |
"""
Methods for importing mediawiki pages, images via the simplemediawki
wrapper to the MediaWiki API.
Copyright (C) 2014 Angus Gratton
Licensed under New BSD License as described in the file LICENSE.
"""
from __future__ import print_function, unicode_literals, absolute_import, division
import simplemediawiki
import r... |
"""
Messaging model forms
"""
from django import forms
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from treeio.core.models import Object, ModuleSetting
from treeio.core.conf import settings
from treeio.core.decorators import preprocess_form
from treeio.messaging.model... |
#!/usr/bin/env python3
from __future__ import print_function
import os
import sys
import subprocess
from distutils.util import convert_path
from setuptools import setup
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
def fread(fname):
with open(os.path.join(CURRENT_DIR, fname)) as f:
return f.... |
#!/usr/bin/env python
from __future__ import print_function
#import keras
#from keras.datasets import mnist
#from keras.models import Sequential
#from keras.layers import Dense, Dropout, Flatten
#from keras.layers import Conv2D, MaxPooling2D
#from keras import backend as K
import os, random
import numpy as np
from pept... |
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import *
from datetime import datetime,time
from datetime import date
from django.utils import timezone
from time import time
from datetime import datetime, timedelta
from ADM.models import *
# Create your models he... |
"""Implementation of paginate query."""
from oslo_log import log as logging
from six.moves import range
import sqlalchemy
from cinder import exception
from cinder.i18n import _, _LW
LOG = logging.getLogger(__name__)
# copied from glance/db/sqlalchemy/api.py
def paginate_query(query, model, limit, sort_keys, marke... |
from django.db import models
from django.db.models.fields.related import ManyToOneRel
from django.db.models.fields import AutoField
# Create your models here.
class ManualUpdateModel(models.Model):
class Meta:
abstract = True
def auto_save(self):
updated_fields = []
for field in type(... |
"""
MUV dataset loader.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import deepchem
def load_muv(featurizer='ECFP', split='index', K=4):
"""Load MUV datasets. Does not do train/test split"""
# Load MUV dataset
print("About to load ... |
"""Presubmit script for android buildbot.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
"""
_DELETIONS_ONLY_FILES = (
'build/android/findbugs_filter/findbugs_known_bugs.txt',
)
def _CheckDeletionsOnlyFiles(input_api, output_api):
"... |
"""Fixer for except statements with named exceptions.
The following cases will be converted:
- "except E, T:" where T is a name:
except E as T:
- "except E, T:" where T is not a name, tuple or list:
except E as t:
T = t
This is done because the target of an "except" clause must be a
... |
"""Tests for distutils.dir_util."""
import unittest
import os
import shutil
from distutils.dir_util import (mkpath, remove_tree, create_tree, copy_tree,
ensure_relative)
from distutils import log
from distutils.tests import support
class DirUtilTestCase(support.TempdirManager, unittes... |
import argparse
import daemon
import extras
import gear
import logging
import os
import pbr.version
import signal
import sys
pid_file_module = extras.try_imports(['daemon.pidlockfile', 'daemon.pidfile'])
class Server(object):
def __init__(self):
self.args = None
self.config = None
self.ge... |
import argparse
from neutronclient.common import utils
from neutronclient.i18n import _
from neutronclient.neutron import v2_0 as neutronv20
class ListFirewallRule(neutronv20.ListCommand):
"""List firewall rules that belong to a given tenant."""
resource = 'firewall_rule'
list_columns = ['id', 'name', '... |
# -*- coding: utf-8 -*-
"""
Django settings for ankieta project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.pat... |
"""Zone entity and functionality."""
from homeassistant.const import ATTR_HIDDEN, ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.helpers.entity import Entity
from homeassistant.util.location import distance
from .const import ATTR_PASSIVE, ATTR_RADIUS
STATE = "zoning"
def in_zone(zone, latitude, longitude, radius... |
from __future__ import with_statement
import os
import sys
import glob
import shutil
import time
import subprocess
import getopt
import tarfile
import win32api
import win32con
pythonVersion = sys.version[:3]
def create_toolkit_release(trunk, install_dir, work_dir, version="DEV"):
"""Create the vision toolkit releas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A data/file compress utility module. You can easily programmatically add files
and directorys to zip archives. And compress arbitrary binary content.
- :func:`zip_a_folder`: add folder to archive.
- :func:`zip_everything_in_a_folder`: add everything in a folder to arc... |
from corehq.apps.reports.util import get_INFilter_element_bindparam
from dimagi.utils.couch.database import get_db
from corehq.apps.domain.utils import DOMAIN_MODULE_KEY
import fluff
def flat_field(fn):
def getter(item):
return unicode(fn(item) or "")
return fluff.FlatField(getter)
def add_to_module... |
from __future__ import print_function
import os, sys, numpy, pplot
def main(fname, no_print):
"""Show how to use pplot library to generate presentation-quality plots."""
###
# Series definition (Series class)
###
# Extract data from a comma-separated (csv)
# file using the CsvSource class
... |
import http.cookies
from aiohttp import hdrs
from datetime import datetime, timedelta
def cors_headers(headers, nocreds=False):
origin = headers.get(hdrs.ORIGIN, '*')
if origin == 'null':
origin = '*'
cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),)
ac_headers = headers.get(hdrs.ACCESS_CO... |
#!/usr/bin/env python
import pika
import uuid
import sys
import threading
import os
import getopt
import random
m_id=0
def on_request(ch, method, props, body):
print "Sending %s to be transformed" % (body,)
key=(method.routing_key).replace("request", "transform")
ch.basic_publish(exchange='Australia_NZ_Exchange'... |
"""
This is a helper module for the challenges database table.
It is used by the lib.tokenclass
The method is tested in test_lib_challenges
"""
import logging
from log import log_with
from ..models import Challenge
from datetime import datetime
log = logging.getLogger(__name__)
@log_with(log)
def get_challenges(ser... |
# -*- coding: utf-8 -*-
from datetime import datetime
from decimal import Decimal
from django.db import models
from django.db.models import Q
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from markitup.fields import MarkupField
from symposion.proposals.models import Prop... |
from ducktape.services.service import Service
from muckrake.defaults import DEFAULT_JDK
import time
import abc
import os.path
def create_hadoop_service(context, num_nodes, hadoop_distro, hadoop_version, jdk=DEFAULT_JDK):
if hadoop_distro == 'cdh':
hadoop_home = '/opt/hadoop-cdh/'
if hadoop_vers... |
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import assignment2_helper as helper
# Look pretty...
matplotlib.style.use('ggplot')
# Do * NOT * alter this line, until instructed!
scaleFeatures = True
# TODO: Load up the dataset and remove any and all
# Rows that have a nan. You should be a p... |
# BUILTINS
import os
import subprocess
import socket
import platform
import urllib # use urllib to stay compatible to python 2.4
import time
import json
# removed apt because of missing dependencies during pip-installation
# import apt
# OTHER
import psutil # use psutil 2.1.3 for python < 2.6
import prettytable
impo... |
# -*- coding: utf-8 -*-
"""
Highcharts Demos
Area range and line: http://www.highcharts.com/demo/arearange-line
"""
from highcharts import Highchart
H = Highchart(width=750, height=600)
ranges = [
[1246406400000, 14.3, 27.7],
[1246492800000, 14.5, 27.8],
[1246579200000, 15.5, 29.6],
[1246665600000, 16.... |
"""
This module manages the interaction with the remote service. Just ask, we will
do our best to satisfy your request
"""
from __future__ import absolute_import
import lib.validate as validate
class AdHocError(Exception):
"""
Your ad hoc command does not look great
"""
pass
class AdHoc(object):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
black_rhino is a multi-agent simulator for financial network analysis
Copyright (C) 2012 Co-Pierre Georg (<EMAIL>)
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 Softwa... |
import socket
import pickle
import struct
import abc
class SocketBase(object):
"""
Using a metaclass to leave room for a UDP socket at a later date.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, host="localhost", port=9000):
self._host = host
self._port = port
self._connected = False
@ab... |
from tcga_encoder.utils.helpers import *
from tcga_encoder.data.data import *
from tcga_encoder.definitions.tcga import *
#from tcga_encoder.definitions.nn import *
from tcga_encoder.definitions.locations import *
#from tcga_encoder.algorithms import *
import seaborn as sns
from sklearn.manifold import TSNE, locally_li... |
# encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python3/dist-packages/PyQt4/QtGui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
class QTransform(): # skipped bases: <class 'sip.simplewrapper'>
"""
QTransform()
QTransform(float, float,... |
"""Preprocessing recipes from the literature"""
from typing import Optional
from anndata import AnnData
from .. import preprocessing as pp
from ._deprecated.highly_variable_genes import (
filter_genes_dispersion,
filter_genes_cv_deprecated,
)
from ._normalization import normalize_total
from .. import logging ... |
#coding=UTF-8
from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext
from pyspark.sql.types import *
from datetime import date, datetime, timedelta
import sys, re, os
st = datetime.now()
conf = SparkConf().setAppName('PROC_O_CEN_CBOD_SAACNACN').setMaster(sys.argv[2])
sc = SparkContext(conf = conf)
s... |
REF = 'GRCh38.p4'
FASTAREF='/home/ubuntu/russ/ncbi/GCF_000001405.30_GRCh38.p4_genomic.fna'
HISATREF = "/home/ubuntu/refs/hisat_index/GRCh38.p4"
# STAR50REF =
# STAR100REF =
# DATASETS = "SRR1295542".split()
THREADS = 10
rule all:
input: "SRR959265.GRCh38.p4.hisat.sorted.sra"
sample = 'SRR959265'
# SRA ->... |
"""Oppia test suite.
In general, this script should not be run directly. Instead, invoke
it from the command line by running
bash scripts/run_backend_tests.sh
from the oppia/ root folder.
"""
# Pylint has issues with import order of argparse.
#pylint: disable=wrong-import-order
import argparse
import os
import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.