code stringlengths 1 199k |
|---|
"""Example DAG demonstrating the DummyOperator and a custom DummySkipOperator which skips by default."""
from airflow import DAG
from airflow.exceptions import AirflowSkipException
from airflow.operators.dummy_operator import DummyOperator
from airflow.utils.dates import days_ago
args = {
'owner': 'airflow',
's... |
""" Callbacks that handle comment functionality.
"""
from dash.dependencies import ALL, MATCH, Input, Output, State
from .. import id_constants, state
from ..dash_app import app
@app.callback(
# We can't use ALL in the output, so we use MATCH.
# However, since there's only one component with this key, the funct... |
from nosqlhandler import NoSQLDatabase
from bson import ObjectId
from bson.errors import InvalidId
from irma.common.exceptions import IrmaDatabaseError, IrmaValueError
class NoSQLDatabaseObjectList(object):
# TODO derived class from UserList to handle list of
# databaseobject, group remove, group update...
... |
from django.conf.urls import url
from blog.views import IndexView, PostView, CommentView, RepositoryView, RepositoryDetailView, TagListView, \
CategoryListView, AuthorPostListView, CommentDeleteView
urlpatterns = [
url(r'^$', IndexView.as_view()),
url(r'^post/(?P<pk>[0-9]+)$', PostView.as_view()),
url(r... |
'''Utility functions'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import pickle
import numpy as np
from nltk.tokenize import word_tokenize as tokenize
def load_dataset(filename):
'''Load bAbI dataset... |
""" This is a very crude version of "in-memory HBase", which implements just
enough functionality of HappyBase API to support testing of our driver.
"""
import copy
import re
from oslo_log import log
import six
import aodh
from aodh.i18n import _
LOG = log.getLogger(__name__)
class MTable(object):
"""HappyBase.Tab... |
from __future__ import division, absolute_import
from __future__ import print_function, unicode_literals
import treeano
def to_shared_dict(network):
network.build()
if not network.is_relative():
network = network[network.root_node.name]
vws = network.find_vws_in_subtree(is_shared=True)
name_to_s... |
from fabric.api import local, env, run, put, cd, task, sudo, get, settings, warn_only, lcd
from fabric.contrib import project
import boto3
import cloudpickle
import json
import base64
from six.moves import cPickle as pickle
from pywren.wrenconfig import *
import pywren
import time
"""
conda notes
be sure to call conda ... |
class Solution:
def isValid(self, s: str) -> bool:
if len(s) == 0:
return True
closingBraces =[ ')', '}', ']']
openingBraces = ['(', '{', '[']
st = list(s)
temp = []
while st:
curr = st.pop()
if curr in closingBraces:
... |
from rally.benchmark.scenarios import base
from rally.benchmark import utils as bench_utils
class CeilometerScenario(base.Scenario):
"""Base class for Ceilometer scenarios with basic atomic actions."""
RESOURCE_NAME_PREFIX = "rally_ceilometer_"
def _get_alarm_dict(self, **kwargs):
"""Prepare and ret... |
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import salt.modules.neutron as neutron
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock
from tests.support.unit import TestCase
class MockNeutron:
"""
Mock of neutron
"""
@staticmethod
def g... |
from __future__ import unicode_literals
import json
from werkzeug.exceptions import BadRequest
class ResourceNotFoundError(BadRequest):
def __init__(self, message):
super(ResourceNotFoundError, self).__init__()
self.description = json.dumps({
"message": message,
'__type': 'Re... |
import sys
import json
import urllib
import tablib
import logging
import requests
import prettytable
from cliff.command import Command
from cliff.show import ShowOne
from .utils import read_creds
class Getissue(ShowOne):
"""
* Get list of issues
"""
log = logging.getLogger(__name__ + '.Getissue')
re... |
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*\'(.*)\'',
open('tdfscrape/tdfscrape.py').read(),
re.M
).group(1)
with open('README.md', 'rb') as f:
long_descr = f.read().decode('utf-8')
setup(
name='cmdline-bootstrap',
packages=['tdfscrape'],
entry_points... |
import os
from rqalpha.interface import AbstractMod
vn_ctp_path = None
class VNPYMod(AbstractMod):
def __init__(self):
self._env = None
self._gateway = None
def start_up(self, env, mod_config):
global vn_ctp_path
vn_ctp_path = os.path.join(mod_config.vn_trader_path, 'gateway/ctpG... |
from contextlib import contextmanager
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
Iterator,
Optional,
Sequence,
TextIO,
Type,
Union,
)
from funcy import cached_property
if TYPE_CHECKING:
from rich.status import Status
from rich.text import Text ... |
import logging
import pytest
import requests
import retrying
from test_util.marathon import get_test_app, get_test_app_in_docker
MESOS_DNS_ENTRY_UPDATE_TIMEOUT = 60 # in seconds
def _service_discovery_test(cluster, docker_network_bridge):
"""Service discovery integration test
This test verifies if service disc... |
"""Tests for lite.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
import numpy as np
from tensorflow.lite.python import lite
from tensorflow.lite.python import lite_constants
from tensorflow.lite.python.interpreter import Inte... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.base.address import BuildFileAddress, SyntheticAddress, parse_spec
from pants.base.address_lookup_error import AddressLookupError
from pants.base.build_envir... |
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Application',
fields=[
('id', models.AutoField(... |
from typing import Optional, Tuple, List
from .routes import _Routes
from .helpers import *
from .http_request_manager import _HttpRequestManager
from .authentication import get_auth_by_type
from .exceptions import *
from domino._version import __version__
import os
import logging
import requests
import functools
impor... |
import elasticsearch_dsl as dsl
class AWSIdNameMapping(dsl.DocType):
class Meta:
index = 'awsidnamemapping'
key = dsl.String(index='not_analyzed')
rid = dsl.String(index='not_analyzed')
name = dsl.String(index='not_analyzed')
date = dsl.Date(format='date_optional_time||epoch_millis')
@cl... |
"""
This is the single point of entry to generate the sample configuration
file for Nova. It collects all the necessary info from the other modules
in this package. It is assumed that:
* every other module in this package has a 'list_opts' function which
return a dict where
* the keys are strings which are the grou... |
import urllib2, sys, os, urllib
import getopt
from streaminghttp import register_openers
STATUS_LIST = ['ASR', 'ALIGN', 'EDIT', 'UPLOAD', 'PUBLISH', 'TRANSCODE']
STATUS_CODE = dict((v,k) for k, v in dict(enumerate(STATUS_LIST, start=1)).iteritems())
def usage():
print """
Synopsis:
Python API client to be u... |
import logging
from django.utils.translation import ugettext_lazy as _
import horizon.exceptions
import horizon.tables
import horizon.tabs
from horizon.utils import memoized
import horizon.workflows
from watcher_dashboard.api import watcher
from watcher_dashboard.content.goals import tables
from watcher_dashboard.conte... |
from pyspark import SparkContext
from optparse import OptionParser
from fileUtil import FileUtil
import codecs
import json
def processkarmaconfig(jsonkc):
classes = []
for config in jsonkc:
if "roots" in config:
for root in config["roots"]:
if "root" in root:
... |
from keras.layers.core import Layer, InputSpec
import keras.backend as K
import theano.tensor as T
import theano
class Subtensor(Layer):
"""
Selects only a part of the input.
Args:
start (int): Start index
stop (int): Stop index
axis (int): Index along this axis
"""
def __ini... |
"""Motor MCP342X hardware monitor configuration."""
from makani.avionics.firmware.drivers import mcp342x_types
from makani.avionics.firmware.serial import motor_serial_params as rev
from makani.avionics.motor.firmware import config_params
mcp342x_default = {
'name': '',
'address': 0x0,
'channel': mcp342x_ty... |
def main():
print("Start")
a = [2, 9, 1, 19, 16]
print("Original array: {}".format(a))
first = a[0]
left = [i for i in a[1:] if i < first]
right = [i for i in a[1:] if i > first]
print("Left array: {}".format(left))
print("Right array: {}".format(right))
result = quick_sort(a)
print("Quick sorted ar... |
"""Utilities to export a model for batch prediction."""
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import signature_constants
from tensorflow.python.saved_model import signature_def_utils
from... |
"""
GPFS Driver for shares.
Config Requirements:
GPFS file system must have quotas enabled (`mmchfs -Q yes`).
Notes:
GPFS independent fileset is used for each share.
TODO(nileshb): add support for share server creation/deletion/handling.
Limitation:
While using remote GPFS node, with Ganesha NFS, 'gpfs_ssh_privat... |
import proto # type: ignore
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import field_mask_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(
package="google.cloud.functions.v1",
manifest={
"CloudFunctionStatus",
... |
"""
Created on Wed Jul 16 10:24:47 2014
@author: Georgiana
"""
import sys, httplib, uuid, random,time
import time
import socket
import struct
import random
httplib.HTTPConnection.debuglevel = 0
SLEEP_SECONDS = 120
currentIps=[]
BaseURL = '128.130.172.215:8080'
ServiceID= 'M2MDaaS'
def executeRESTCall(restMethod, servic... |
import time
from collections import OrderedDict
from dataclasses import dataclass
from random import random
import pygame
import json
import queue
from utils import threadmanager
import config
import logsupport
from logsupport import ConsoleWarning, ConsoleDetail
from stores import valuestore
'''
At the generic level d... |
"""Support for Efergy sensors."""
import logging
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_CURRENCY, POWER_WATT, ENERGY_KILO_WATT_HOUR
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity im... |
from __future__ import print_function
import os
import re
import sys
from shlex import split as cmd_split
from osrf_pycommon.process_utils import execute_process
from catkin_tools.common import format_env_dict
from catkin_tools.common import parse_env_str
def prepare_arguments(parser):
add = parser.add_argument
... |
import uuid as uuid_lib
from oslo_config import cfg
from jacket.tests.compute.functional.api_sample_tests import api_sample_base
from jacket.tests.compute.unit.image import fake
CONF = cfg.CONF
CONF.import_opt('vpn_image_id', 'compute.cloudpipe.pipelib')
CONF.import_opt('osapi_compute_extension',
'compu... |
'''
ucloud python sdk client.
'''
from api import umon, unet, uhost, udisk
from utils import base
class Client(object):
'''
ucloud python sdk client.
'''
def __init__(self, base_url, public_key, private_key, debug=False,
timing=False):
self.base_url = base_url
self.priva... |
from .exception import get_response_error
class Key(object):
DefaultContentType = "application/oct-stream"
def __init__(self, bucket=None, name=None):
self.bucket = bucket
self.name = name
self.resp = None
self.content_type = self.DefaultContentType
def __repr__(self):
... |
from smv import *
from smv.dqm import *
from pyspark.sql.functions import col, lit
import testSmvFramework2
import time
class I1(SmvModule):
def requiresDS(self):
return []
def run(self, i):
return self.smvApp.createDF(
"a:Integer;b:Double",
"1,0.3;0,0.2;3,0.5")
class M1(... |
from flask import Flask
from flask import jsonify
from flask import request
from sqlalchemy import or_
from oslo_config import cfg
from my_dev_server.db import base
from my_dev_server import config
from my_dev_server.db import models
from my_dev_server import logger
from my_dev_server.server import exceptions
from my_d... |
import gettext
class Version(object):
def __init__(self, canonical_version, final):
self.canonical_version = canonical_version
self.final = final
@property
def pretty_version(self):
if self.final:
return self.canonical_version
else:
return '%s-dev' % (... |
import hashlib
import json
from kubernetes.client.models import (V1Volume,
V1PersistentVolumeClaimVolumeSource)
from . import _pipeline
def prune_none_dict_values(d: dict) -> dict:
return {
k: prune_none_dict_values(v) if isinstance(v, dict) else v
for k, v in d... |
"""A lot of utilies for:
- Operations on paths
- Counting
"""
from itertools import islice
import operator
import heapq
import datetime
import calendar
import re
from pysec import lang
def xrange(start, stop, step=1):
"""This xrange use python's integers and have not limits of
machine integers."""
s... |
"""File for compiling and checking typescript."""
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import sys
from core import python_utils
from . import common
_PARSER = argparse.ArgumentParser(
description="""
Run the script from the oppia root folder:
p... |
import os
import base64
import binascii
from collections import namedtuple
import hexdump
import intervaltree
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QBrush
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QMouseEvent
from PyQt5.QtGui import QKeySequence
from PyQt5.QtGui import QFontDatabase
import... |
import sys
from dlab.fab import *
from dlab.meta_lib import *
from dlab.actions_lib import *
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--elastic_ip', type=str, default='')
parser.add_argument('--edge_id', type=str)
args = parser.parse_args()
if __name__ == "__main__":
local_l... |
import numpy as np
from math import ceil
TAGS = {'image_width': '0100', # short
'image_length': '0101', # short
'bits_per_sample': '0102', # short array
'compression': '0103', # short
'photometric': '0106', # short
'stri... |
from __future__ import unicode_literals
"""A version of PyMongo's thread_util for Motor."""
import datetime
try:
from time import monotonic as _time
except ImportError:
from time import time as _time
import greenlet
class MotorGreenletEvent(object):
"""An Event-like class for greenlets."""
def __init__(... |
from twython import TwythonStreamer
from twython import Twython
from twython.exceptions import TwythonError
import re
import pprint
import sqlite3
import time
import json
import random
from tweet_parse_utils import *
conn = sqlite3.connect('tweets.db')
r = random.Random()
keyfile = "prklsuomi.keys"
me = 3075601787
api ... |
"""Runs fio benchmarks.
Man: http://manpages.ubuntu.com/manpages/natty/man1/fio.1.html
Quick howto: http://www.bluestop.org/fio/HOWTO.txt
"""
import json
import logging
import posixpath
import re
import time
import jinja2
from perfkitbenchmarker import configs
from perfkitbenchmarker import data
from perfkitbenchmarker... |
"""Factory to build detection model."""
from official.vision.detection.modeling import maskrcnn_model
from official.vision.detection.modeling import retinanet_model
from official.vision.detection.modeling import shapemask_model
def model_generator(params):
"""Model function generator."""
if params.type == 'retinane... |
"""The Geometric distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tens... |
import time
import os
import datetime
import math
import dateutil.parser
from html.parser import HTMLParser
import urllib.request
DEF_BASE_DIR = '/var/local/ercotsum'
DEF_DEMAND_DIR = '/var/local/rainbarrel'
DEF_ZONE = 'LZ_NORTH'
DEF_DELIVERY = 4.1543 # From 2021-9-1
TDU_MONTHLY = 3.42
RETAIL_MONTHY = 10.00
TAXES_FEE... |
"""Defines a command message that creates job models"""
from __future__ import unicode_literals
import logging
from django.db import transaction
from django.utils.timezone import now
from data.data.data import Data
from data.data.value import JsonValue
from data.data.json.data_v6 import convert_data_to_v6_json, DataV6
... |
from __future__ import print_function
import os.path
import os
import re
import imp
import sys
import shutil
import PythonAPI as api
class CopyCurrent(api.PythonAPIRule):
def __init__(self, config):
super(CopyCurrent, self).__init__(config)
def run(self, inputFile, outputFile, encoding):
shutil.copy(inputFile, ou... |
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.ya... |
import os
def link_lines(directory):
def linkable(f):
if not f.startswith('.'):
_, suffix = os.path.splitext(f)
return suffix in ['', '.json']
files = sorted(f for f in os.listdir(directory) if linkable(f))
yield '<table>'
for i, filename in enumerate(files):
if i... |
import socket
import logging
import os
import errno
import cPickle as pickle
from cStringIO import StringIO
log = logging.getLogger(__name__)
CMD_TERMINATOR = '\r\n'
class ConnectionAbortedException(socket.error):
def __init__(self):
# Software caused connection abort
socket.error.__init__(self, err... |
core_store_students_programs = False
core_store_students_programs_path = 'files_stored'
core_experiment_poll_time = 30 # seconds
core_facade_soap_port = 10123
core_facade_xmlrpc_port = 19345
core_facade_json_port = 18345
admin_facade_json_port = 18545
core_web_facade_port = 19745
weblab_db_username... |
import math
from leap import Leap
def to_vector(leap_vector):
return Vector(leap_vector.x, leap_vector.y, leap_vector.z)
def angle_between_vectors(vector1, vector2):
# cos(theta)=dot product / (|a|*|b|)
top = vector1 * vector2 # * is dot product
bottom = vector1.norm() * vector2.norm()
angle = math... |
__author__ = 'kotaimen'
__date__ = '5/30/14'
""" Verify the "Ooops" in shapely are still broken """
import unittest
import functools
import geojson.base
import shapely
import shapely.geometry
import shapely.wkt
import shapely.ops
import shapely.speedups
import pyproj
class TestShapelySpeedups(unittest.TestCase):
de... |
import time
import random
from collections import deque
topics = ["war", "smileys", "nick", "motivation", "voedsel", "plannedwars", "activewars", "participate", "withdraw"]
randomwords = ['tafelpoot', 'olifantenteennagel', 'rijstpap', 'autoradioantennevlaggetje', 'muggenvleugel', ]
action = chr(1) + "ACTION "
topicCach... |
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 'NewsItem'
db.create_table('news_newsitem', (
('id', self.gf('django.db.models.fields.AutoField')(primary_ke... |
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gems.settings')
app = Celery('gems')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) |
import sys
class Loader:
def __init__(self, code_size, data_size=0):
from peachpy.util import is_int
if not is_int(code_size):
raise TypeError("code size must be an integer")
if not is_int(data_size):
raise TypeError("data size must be an integer")
if code_siz... |
from .. import engines
from ..errors import SimError
class ExplorationTechniqueMeta(type):
def __new__(mcs, name, bases, attrs):
import inspect
if name != 'ExplorationTechniqueCompat':
if 'step' in attrs and not inspect.getargspec(attrs['step'])[3]:
attrs['step'] = mcs._s... |
'''
@author Luke Campbell <LCampbell@ASAScience.com>
@file ion/services/dm/ingestion/test/ingestion_management_test.py
@date Mon Jul 2 13:50:40 EDT 2012
@description Testing for Ingestion Management Service
'''
from pyon.public import PRED
from pyon.util.unit_test import PyonTestCase
from pyon.util.int_test import Ion... |
"""
Generated lexer tests
~~~~~~~~~~~~~~~~~~~~~
Checks that lexers output the expected tokens for each sample
under lexers/*/test_*.txt.
After making a change, rather than updating the samples manually,
run `pytest --update-goldens tests/lexers`.
To add a new sample, create a new file matchi... |
"""
MINDBODY Public API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from swagger_client.m... |
import numpy as np
import ndhist
h = ndhist.ndhist(((np.array([0,1,2], dtype=np.dtype(np.int64)), "x", 1, 1),
(np.array([0,1,2], dtype=np.dtype(np.float64)), "y")
)
, dtype=np.dtype(np.float64)
)
print(h.ndvalues_dtype)
print("bc org shape:", h.b... |
from flask import flash, redirect, render_template, request, url_for
from onetimemsg import app
from onetimemsg.database import db_session
from onetimemsg.models import Message
from onetimemsg.forms import MessageForm
from onetimemsg.utils import uid_generator
@app.route('/')
def index():
form = MessageForm()
r... |
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mc2.settings')
app = Celery('proj')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) |
import logging
import numbers
import re
import sqlite3
from dateutil import parser
from six import text_type
from redash import models
from redash.permissions import has_access, not_view_only
from redash.query_runner import guess_type, TYPE_STRING, BaseQueryRunner, register
from redash.utils import json_dumps, json_loa... |
import sys
def parseString(stream):
return stream.readline().rstrip()
def isPangram(string):
s = list(string)
f = [False]*26
for i in s:
if(i != " "):
index = ord(i) - ord('a')
f[index] = True
for v in f:
if v == False:
return False
return True... |
import mufsim.gamedb as db
import mufsim.stackitems as si
from mufsim.interface import network_interface as netifc
from mufsim.logger import log
from mufsim.insts.base import Instruction, instr
@instr("awake?")
class InstAwakeP(Instruction):
def execute(self, fr):
who = fr.data_pop_object()
fr.data_... |
"""GO Grouper Plotting objects."""
import sys
import os
import collections as cx
from goatools.gosubdag.plot.gosubdag_plot import GoSubDagPlot
from goatools.gosubdag.gosubdag import GoSubDag
from goatools.gosubdag.go_tasks import get_go2parents_go2obj
from goatools.grouper.colors import GrouperColors
__copyright__ = "C... |
import re
import time
import mimetypes
from flask import abort, current_app
from .name import ItemName
from .decorators import async
from .hashing import compute_hash, hash_new
from ..utils.date_funcs import FOREVER
MAX_FILENAME_LENGTH = 250
class Upload(object):
_filename_re = re.compile(r'[^a-zA-Z0-9 \*+:;.,_-]+'... |
from video import Video, Keyframe
import process_aligned_json as pjson
import processvideo as pvideo
import processframe as pframe
import cv2
import util
import os
from figure import Figure
class Lecture:
def __init__(self, video_path, aligned_transcript_path):
self.video_path = video_path
if (self.... |
class ExampleCtrl4(object):
"""Mealy transducer.
Internal states are integers, the current state
is stored in the attribute "state".
To take a transition, call method "move".
The names of input variables are stored in the
attribute "input_vars".
Automatically generated by tulip.dumpsmach on ... |
from django import forms
from django.utils.translation import ugettext_lazy
from onadata.apps.viewer.models.data_dictionary import DataDictionary
class QuickConverter(forms.Form):
xls_file = forms.FileField(label=ugettext_lazy("XLS File"))
def publish(self, user):
if self.is_valid():
return ... |
from django.urls import reverse
from django.views.generic import DateDetailView
from comp.articles.models import Article
class ArticleDetailView(DateDetailView):
model = Article
date_field = "publish"
month_format = "%m"
def get_context_data(self, **kwargs):
context = super(ArticleDetailView, se... |
from mapentity.views import (MapEntityLayer, MapEntityList, MapEntityJsonList, MapEntityFormat,
MapEntityDetail, MapEntityDocument, MapEntityCreate, MapEntityUpdate, MapEntityDelete)
from geotrek.core.views import CreateFromTopologyMixin
from .models import (PhysicalEdge, LandEdge, Competen... |
"""
Use backend agg to access the figure canvas as an RGB string and then
convert it to a Numeric array and pass the string it to PIL for
rendering
"""
from pylab import *
from matplotlib.backends.backend_agg import FigureCanvasAgg
plot([1,2,3])
canvas = get_current_fig_manager().canvas
agg = canvas.switch_backends(Fig... |
"""Version utilities."""
import re
from ganeti import constants
_FULL_VERSION_RE = re.compile(r"(\d+)\.(\d+)\.(\d+)")
_SHORT_VERSION_RE = re.compile(r"(\d+)\.(\d+)")
FIRST_UPGRADE_VERSION = (2, 10, 0)
CURRENT_VERSION = (constants.VERSION_MAJOR, constants.VERSION_MINOR,
constants.VERSION_REVISION)
def... |
from sys import path, version_info
from os.path import sep
path.insert(1, path[0]+sep+'codec'+sep+'ber')
import ber.suite
path.insert(1, path[0]+sep+'codec'+sep+'cer')
import cer.suite
path.insert(1, path[0]+sep+'codec'+sep+'der')
import der.suite
from pyasn1.error import PyAsn1Error
if version_info[0:2] < (2, 7) or \
... |
import re
from django.contrib.auth.models import User
from django.forms import ValidationError
from nose.tools import eq_
from pyquery import PyQuery as pq
from users.forms import (RegisterForm, EmailConfirmationForm, EmailChangeForm,
PasswordChangeForm, PasswordConfirmationForm)
from users.test... |
import os, sys
sys.path.insert(0, '..')
PROJECT_ROOT = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT':... |
import corepy.lib.extarray as extarray
import corepy.arch.spu.isa as spu
import corepy.arch.spu.platform as env
import corepy.arch.spu.lib.dma as dma
from corepy.arch.spu.lib.util import load_word
if __name__ == '__main__':
a = extarray.extarray('i', range(0, 32))
b = extarray.extarray('i', [0 for i in range(0, 32)... |
import datetime
from django.utils.translation import ugettext_lazy as _
from django.db import models
from filer.fields.image import FilerImageField
from cms.models.fields import PlaceholderField
from adminsortable.fields import SortableForeignKey
from parler.models import TranslatableModel, TranslatedFields
from django... |
from sequana.taxonomy import Taxonomy
from sequana.taxonomy import NCBITaxonomy
from . import test_dir
def test_taxonomy(tmp_path):
n = NCBITaxonomy(f"{test_dir}/data/names_filtered.dmp", f"{test_dir}/data/nodes_filtered.dmp")
filename = tmp_path / "taxo.dat"
n.create_taxonomy_file(filename)
# default i... |
"""
Build helpers for setup.py.
Includes package dependency checks and monkey-patch to numpy.distutils
to work with Cython.
Notes
-----
The original version of this file was adapted from NiPy project [1].
[1] http://nipy.sourceforge.net/
"""
import os
import shutil
import glob
import fnmatch
from distutils.cmd import C... |
from flask import Blueprint, abort, jsonify, redirect, request, url_for
from scout.server.extensions import store
from scout.server.utils import public_endpoint, templated
from . import controllers
hpo_bp = Blueprint("phenotypes", __name__, template_folder="templates")
@hpo_bp.route("/phenotypes", methods=["GET"])
@tem... |
import sys
from mixbox.binding_utils import *
from . import cybox_common
class WindowsHandleListType(GeneratedsSuper):
"""The WindowsHandleListType type specifies a list of Windows handles,
for re-use in other objects."""
subclass = None
superclass = None
def __init__(self, Handle=None):
if ... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0017_add_nationality'),
]
operations = [
migrations.AddField(
model_name='profile',
name='image',
field=m... |
from __future__ import absolute_import, division, print_function
from datashape import dshape
import blaze
from blaze.compute.ops.ufuncs import add, mul
from blaze.compute.air import from_expr, ExecutionContext
def make_graph():
a = blaze.array(range(10), dshape('10, int32'))
b = blaze.array(range(10), dshape('... |
"""Fichier contenant le module primaire meteo."""
from random import choice, randint
from math import ceil
from abstraits.module import *
from . import commandes
from .config import cfg_meteo
from .perturbations import perturbations
from .perturbations.base import BasePertu, AUCUN_FLAG
class Module(BaseModule):
"""... |
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use sendgrid to send emails
- Use MEMCACHIER on Heroku
'''
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from .common import * # noqa
SECURE_P... |
"""
The :mod:`nilearn.input_data` module includes scikit-learn tranformers and
tools to preprocess neuro-imaging data.
"""
from .nifti_masker import NiftiMasker
from .multi_nifti_masker import MultiNiftiMasker
from .nifti_region import NiftiLabelsMasker, NiftiMapsMasker |
"""
.. module:: burpui.filter
:platform: Unix
:synopsis: Burp-UI filter module.
.. moduleauthor:: Ziirish <hi+burpui@ziirish.me>
"""
class BUIMask(object):
"""Mask client/servers based on user preferences or user ACL"""
def init_app(self, app):
"""Initialize the mask
:param app: Applicat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.