content string |
|---|
from rest_framework.test import APITestCase
from rest_framework.test import APIRequestFactory, APIClient, \
force_authenticate
from api import views
from api.tests.common import setup_user
class TestDataViews(APITestCase):
def setUp(self):
self.factory = APIRequestFactory()
self.client = APICl... |
from go_to_adjacent_systems import *
from go_somewhere_significant import *
import vsrandom
import launch
import faction_ships
import VS
import Briefing
import universe
import unit
import Director
import quest
escort_num=0
class escort_mission (Director.Mission):
you=VS.Unit()
escortee=VS.Unit()
adjsys=0
... |
from django.conf import settings
from pyslack import SlackClient
# TODO: none static class
class SlackManager:
def __init__(self):
pass
@staticmethod
def enabled():
return settings.SLACK_ENABLED
@staticmethod
def send_general(text):
if settings.SLACK_ENABLED:
... |
from clickatell import Transport
from ..exception import ClickatellError
class Rest(Transport):
"""
Provides access to the Clickatell REST API
"""
def __init__(self, token):
"""
Construct a new API instance with the auth token of the API
:param str token: The auth token
... |
import sys
import socket
import select
import dhcp_packet
import interface
import struct
import _rawsocket
import type_ipv4
import IN
class DhcpNetwork:
def __init__(self, ifname, listen_address="0.0.0.0", listen_port=67, emit_port=68):
netifo = interface.interface()
self.ifname = ifname
... |
import os, polib
from unittest import TestCase
from nose.plugins.skip import SkipTest
from datetime import datetime, timedelta
import extract
from config import CONFIGURATION
# Make sure setup runs only once
SETUP_HAS_RUN = False
class TestExtract(TestCase):
"""
Tests functionality of i18n/extract.py
"""... |
# -*- coding: utf-8 -*-
import os
os_env = os.environ
class Config(object):
SECRET_KEY = os_env.get('CROPSTER_SECRET', 'secret-key') # TODO: Change me
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
BCRYPT_LOG_RO... |
# based on http://pyparsing.wikispaces.com/file/view/simpleArith.py
# and http://pyparsing.wikispaces.com/file/view/simpleSQL.py
# Usual usage of the parser:
# from grades.formulas import ...
# for each calculated grade:
# parsed_expr = parse(formula)
# find all NumericActivities for the course and process into fo... |
import os
import re
import dbus
from time import sleep
from tempfile import NamedTemporaryFile
from os.path import exists, expanduser
from redlib.api.system import sys_command, CronDBus, CronDBusError
from ..util.logger import log
from .desktop import Desktop, DesktopError
from .wpstyle import WPStyle
from .linux_des... |
"""Unit tests for MAC counter."""
import numpy as np
import tvm
from tvm import relay
from tvm.relay import analysis, transform
def run_opt_pass(expr, opt_pass):
assert isinstance(opt_pass, transform.Pass)
mod = relay.Module.from_expr(expr)
mod = opt_pass(mod)
entry = mod["main"]
return entry if i... |
import stix
from stix.common import vocabs
from stix.common import StructuredTextList, VocabString
# bindings
import stix.bindings.ttp as ttp_binding
from mixbox import fields, entities
class MalwareInstance(stix.Entity):
_binding = ttp_binding
_binding_class = _binding.MalwareInstanceType
_namespace = ... |
import unittest2 as unittest
from stencil_grid import *
import math
class BasicTests(unittest.TestCase):
def test_init(self):
grid = StencilGrid([10,10])
self.failIf(grid.dim != 2)
self.failIf(grid.data.shape != (10,10))
self.failIf(grid.interior != [8,8])
self.failIf(grid.g... |
#!/usr/bin/env python
"""This is the GRR Console.
We can schedule a new flow for a specific client.
"""
# pylint: disable=unused-import
# Import things that are useful from the console.
import collections
import csv
import datetime
import getpass
import os
import re
import sys
import time
# pylint: disable=unused-... |
#---------------------------------------------------------------------------------------------------------------|
# Organization: AllenRing |
# -- Created by Ritch ... |
#!/usr/bin/python
class Graph:
"""
Directed Graph class - containing vertices and edges
"""
DEFAULT_WEIGHT = 1
DIRECTED = True
def __init__(self, graph_dict=None):
"""initializes a graph object"""
if graph_dict is None:
graph_dict = {}
self.__graph_dist = ... |
"""Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
Source : Mininet Walkthrough
"""
from mininet.topo i... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from contextlib import contextmanager
from textwrap import dedent
from pants.base.build_environment import get_buildroot
from pants.util.dirutil import safe... |
import cloudinit.util as util
import cloudinit.SshUtil as sshutil
import os
import glob
import subprocess
DISABLE_ROOT_OPTS = "no-port-forwarding,no-agent-forwarding," \
"no-X11-forwarding,command=\"echo \'Please login as the user \\\"$USER\\\" " \
"rather than the user \\\"root\\\".\';echo;sleep 10\""
def handle(_n... |
import datetime
import logging
import os
from google.appengine.ext import ndb
from controllers.base_controller import CacheableHandler
from consts.district_type import DistrictType
from consts.event_type import EventType
from database.district_query import DistrictQuery, DistrictHistoryQuery, DistrictsInYearQuery
fr... |
"""
Provides functionality for multidimensional usage of scalar-functions.
Read the vectorize docstring for more details.
"""
from sympy.core.decorators import wraps
def apply_on_element(f, args, kwargs, n):
"""
Returns a structure with the same dimension as the specified argument,
where each basic eleme... |
from msrest.serialization import Model
class Column(Model):
"""A table column.
A column in a table.
:param name: The name of this column.
:type name: str
:param type: The data type of this column.
:type type: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},... |
from testrunner import testhelp
import os, tempfile
from conary_test import rephelp
from conary.lib import util
from conary.state import ConaryStateFromFile
from conary import checkin
class _VersionControlTestClass:
def testVersions(self):
self.logFilter.add()
oldTmpDir = self.cfg.tmpDir
... |
########################################################################
#
# File Name: ForEachElement.py
#
# Documentation: http://docs.4suite.org/4XSLT/ForEachElement.py.html
#
"""
Implementation of the XSLT Spec for-each stylesheet element.
WWW: http://4suite.org/4XSLT e-mail: <EMAIL>
Copyr... |
import os
from kiwixbuild.platforms import PlatformInfo
from kiwixbuild.utils import pj, copy_tree, run_command
from kiwixbuild._global import option
from .base import (
Dependency,
NoopSource,
Builder as BaseBuilder)
class IOSFatLib(Dependency):
name = "_ios_fat_lib"
Source = NoopSource
c... |
import importscan
import sentaku
from widgetastic.widget import ParametrizedView, Select, Text, View
from widgetastic_patternfly import Input, BootstrapSelect
from widgetastic.utils import deflatten_dict, Parameter, ParametrizedString, ParametrizedLocator
from cfme.common import Taggable
from cfme.exceptions import I... |
#!/usr/bin/python
import urllib2, argparse, logging
import sys, os, re, time
import httplib
import fileinput
import telepot
from daemonize import Daemonize
from BeautifulSoup import BeautifulSoup
from converter import Converter, ffmpeg
BASE_URL = "https://boards.4chan.org/"
TG_TOKEN = "XXXX_REPLACE_WITH_YOUR_OWN_XXXX... |
from google.appengine.ext import ndb
from google.appengine.ext.db import TransactionFailedError
from google.appengine.ext.ndb import Future
from google.net.proto.ProtocolBuffer import ProtocolBufferDecodeError
from google.appengine.api.datastore_errors import BadValueError, BadRequestError
from controller.authenticati... |
"""tests
Revision ID: 2773c6bc4d15
Revises: f5f30064f6ef
Create Date: 2017-04-28 12:29:25.495300
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2773c6bc4d15'
down_revision = 'f5f30064f6ef'
branch_labels = None
depends_on = None
def upgrade():
# ### comm... |
__author__ = "Cyril Jaquier"
__version__ = "$Revision: 696 $"
__date__ = "$Date: 2008-05-19 23:05:32 +0200 (Mon, 19 May 2008) $"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL"
from threading import Lock, RLock
from jails import Jails
from transmitter import Transmitter
from asyncserver import A... |
import os
from io import BytesIO
from PIL import Image
from test.utils import BaseTest
from tri_image.triangle import Triangle
from tri_image.point import Point
from tri_image.sketch import Sketch
from tri_image.utils import RGB
data_folder = os.path.join(os.path.dirname(__file__), "data")
########################... |
from wpilib import CANTalon, Talon, DigitalInput
from maps import motor_map, sensor_map
class Shooter:
left_fly = CANTalon
right_fly = CANTalon
intake_main = CANTalon
intake_mecanum = Talon
ball_limit = DigitalInput
def __init__(self):
self.left_fly = CANTalon(motor_map.left_fly_moto... |
"""
The MIT License (MIT)
Copyright (c) 2016 Zagaran, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge... |
import os
from setuptools import find_packages
from setuptools import setup
import condor
def install_requires():
"""
Yields a list of install requirements.
"""
return [
"SQLAlchemy~=1.3",
"bibtexparser~=0.6.2",
"click~=6.7",
"nltk~=3.4",
"numpy~=1.17",
... |
import os
import shutil
import tempfile
from unittest import TestCase
from packstack.installer.validators import *
from ..test_base import PackstackTestCaseMixin
class ValidatorsTestCase(PackstackTestCaseMixin, TestCase):
def setUp(self):
# Creating a temp directory that can be used by tests
self... |
import time
import atexit
import json
import os
def _timestamp():
return int(time.time())
class Task(object):
total = 0
start = None
issue_id = None
description = ""
class Tasks(object):
file = ""
list = []
def __init__(self, file):
self.file = file
atexit.register(s... |
"""
Test the various response formats.
"""
from shared import *
def test_common():
"""
Common response stuff.
"""
# Ensure that the http options are carried through to the actual response
r = JsonResponse('data', http_status=404,
http_headers={'X-Custom': 'tes... |
#!/usr/bin/python
from elasticsearch import Elasticsearch
from py2neo import neo4j
import re
import json
def get_prefix_inputs(input):
inputs = re.split(delReg, input, flags=re.UNICODE )
inputs.append(input)
return filter(None, inputs)
def get_full_category_path(node):
path = []
traverse_category... |
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.urls import reverse
from wagtail.core.models import Page
from wagtail.tests.utils import WagtailTestUtils
class TestWorkflowHistoryDetail(TestCase, WagtailTestUtils):
fixtures = ['test.json']
def setUp(self):
... |
import os
import shlex
import struct
import platform
import subprocess
def get_terminal_size():
""" getTerminalSize()
- get width and height of console
- works on linux,os x,windows,cygwin(windows)
originally retrieved from:
http://stackoverflow.com/questions/566746/how-to-get-console-window-w... |
"""
Interfaces and base classes for theorem provers and model builders.
``Prover`` is a standard interface for a theorem prover which tries to prove a goal from a
list of assumptions.
``ModelBuilder`` is a standard interface for a model builder. Given just a set of assumptions.
the model builder tries to build... |
from __future__ import absolute_import
from tests import testlib
try:
import unittest
except ImportError:
import unittest2 as unittest
import splunklib.client as client
class KVStoreConfTestCase(testlib.SDKTestCase):
def setUp(self):
super(KVStoreConfTestCase, self).setUp()
self.service.nam... |
from biopandas.pdb import PandasPdb
import os
import numpy as np
import pandas as pd
from nose.tools import raises
from biopandas.testutils import assert_raises
try:
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
except ImportError:
from urllib2 import urlopen, HTTPError, UR... |
from __future__ import unicode_literals
TYPE_MESSAGES = {
'unknown': 'Unknown type: {0}',
'invalid': "Got value `{0}` of type `{1}`. Value must be of type(s): `{2}`",
'invalid_header_type': (
"Invalid type for header: `{0}`. Must be one of 'string', 'number', "
"'integer', 'boolean', or 'a... |
"""
tests specific to "pip install --user"
"""
import imp
import os
import textwrap
from os.path import curdir, isdir, isfile
from pip.backwardcompat import uses_pycache
from tests.lib.local_repos import local_checkout
from tests.lib import pyversion
def _patch_dist_in_site_packages(script):
sitecustomize_path... |
class Stack(object):
def __init__(self):
self.items = []
def __len__(self):
return self.size()
def size(self):
return len(self.items)
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.... |
# -*- coding: utf-8 -*-
from datetime import date
from os.path import join, isfile, exists
from os import makedirs
from shutil import rmtree
from django.test import TestCase
from django.core.exceptions import ValidationError
from django.contrib.gis.geos import Polygon
from django.contrib.auth.models import User
from d... |
import os
import json
from ntb.io.feed_parsers import ntb_nitf
from ntb.io.feed_parsers import stt_newsml # NOQA
from content_api.app.settings import CONTENTAPI_INSTALLED_APPS
from superdesk.default_settings import (
HTML_TAGS_WHITELIST as _HTML_TAGS_WHITELIST, strtobool, CORE_APPS as _CORE_APPS, env
)
ABS_PATH... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
__author__ = 'Yuta Hayashibe'
__version__ = ""
__copyright__ = ""
__license__ = "GPL v3"
import random
import unittest
import slex.corpus.document
class Test(unittest.TestCase):
def setUp(self):
self.metadata = {u"ID": u"TEST-001"}
self.doc... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import os
import glob
from sunpy import config
from sunpy.util.net import download_file
from sunpy.util.cond_dispatch import ConditionalDispatch, run_cls
from sunpy.extern import six
from sunpy.extern.six.moves import map
__al... |
#!/usr/bin/env python
"""\
31.08.2017: Modified by Yuji Ikeda
C version: Dmitri Laikov
F77 version: Christoph van Wuellen, http://www.ccl.net
Python version: Richard P. Muller, 2002.
This subroutine is part of a set of subroutines that generate
Lebedev grids [1-6] for integration on a sphere. The original
C-c... |
'''
Created on 25.10.2010
@author: michi
'''
from ems.converter.tag import Tag,AttributeException,ElementException
class Element(Tag):
'''
classdocs
'''
def interpret(self,xmlDict,inputReader,outputWriter):
if not xmlDict['attributes'].has_key('name'):
raise AttributeException("Tag... |
import requests
from prettytable import PrettyTable
import tty
from pytravis import repos_by_owner
def get_repos_by_owner(owner):
"""Return a list of repos by owner
"""
repos = requests.get(repos_by_owner + str(owner)).json()
if not repos:
raise AttributeError("ERROR: Username %s not found!" %... |
import core
from core import *
import thread
ID_FILETREE_RENAME = wx.NewId()
ID_FILETREE_DELETE = wx.NewId()
class DMFile(str):
pass
class DMIDE_FileTree(wx.TreeCtrl):
""" Handles displaying the files in a project. """
def __init__(self, parent):
wx.TreeCtrl.__init__(self, parent, ID_FILETREE, style = wx.T... |
"""
========================================================
Extract epochs, average and save evoked response to disk
========================================================
This script shows how to read the epochs from a raw file given
a list of events. The epochs are averaged to produce evoked
data and then saved t... |
# -*- coding: utf-8 -*-
import wx
import CustomButton
import TextPanel
import ScrollMessagePanel
import OnlineStatus
import MainFrame
class MessageFrame(MainFrame.MainFrame):
def __init__(self, parent, id, pos, myavatar, title, online):
MainFrame.MainFrame.__init__(self, parent, id, pos)
self.title = t... |
from django.core.management.base import BaseCommand, CommandError
try:
from django.contrib.auth import get_user_model # Django 1.5
except ImportError:
from django_extensions.future_1_5 import get_user_model
from django.contrib.auth.models import Group
from optparse import make_option
from sys import stdout
fro... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
from django.db import connection
from django.db.models import Q
from django.db.models import F
from django.db.models import Count
from django.db.models import Sum
from django.tes... |
import json
import requests
import logging
import sys
import random
from urlparse import urljoin
from django.core.management.base import BaseCommand
from django.conf import settings
from workflow.models import (Organization, TolaUser, WorkflowLevel1,
WorkflowLevel2)
from tola.track_sync i... |
import sys
import pytest
import mfr
# Pydocx .3.14 does not support python 3
if not sys.version_info >= (3, 0):
from mfr_docx import Handler as DocxFileHandler
from mfr_docx.render import render_docx
@pytest.mark.skipif(sys.version_info >= (3, 0),
reason="pydocx 0.3.14 does not support ... |
"""Settings manager for Project Manager."""
import os.path
import gconf
import gnomevfs
from GMATE import files
from GMATE.configuration import get_settings
gmate_settings = get_settings()
HOME_URI = str(files.get_user_home_uri())
DEFAULT_TERMINAL = 'file:///usr/bin/gnome-terminal'
DEFAULT_FILEBROWSER = 'file:///usr... |
import random
import time
import unittest
from silk.config import wpan_constants as wpan
from silk.node.wpan_node import WpanCredentials
from silk.tools.wpan_util import (verify_within, verify_prefix_with_rloc16, verify_no_prefix_with_rloc16)
from silk.utils import process_cleanup
import silk.hw.hw_resource as hwr
imp... |
"""
Mail (SMTP) notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.smtp/
"""
import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage... |
import os
import os.path
import argparse
import smtplib
import hashlib
import socket
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
hostname = socket.gethostname()
parser = argparse.A... |
from os import path
import codecs
from setuptools import setup, find_packages
read = lambda filepath: codecs.open(filepath, 'r', 'utf-8').read()
setup(
name='django-geoip',
version='0.5.2.1',
author='Ilya Baryshev',
author_email='<EMAIL>',
packages=find_packages(exclude=("tests", "test_app", "doc... |
"""MySQL Fabric library
"""
import distutils.version
import os
# Version info as a tuple (major, minor, patch, extra)
__version_info__ = (0, 6, 10, "")
# MySQL Fabric version:
# `PEP-386 <http://www.python.org/dev/peps/pep-0386>`__ format
__version__ = "{0}.{1}.{2}{3}".format(*__version_info__)
# Connector Python v... |
import pymongo
import json
import random
import datetime
import uuid
import bson
positions = ['Flogsta','Polacksbacken','Central Station','Granby','Gamla Uppsala','Uppsala Science Park','Uppsala Centrum','Carolina Rediviva', 'Uppsala Hospital']
coordinates = [[59.851252, 17.593290], [59.840427, 17.647628], [59.858052,... |
import json
import csv
import pandas as pd
import urllib.request
# 1. All counts are at State/UT level
# 2. Only cumulative counts are available at this point
# 3. 'unassigned' cases are ignored
# 5. Wrong state codes are ignored
# 4. Sometimes reports are published more than once. Then we take the last report on that... |
# -*- coding: utf-8 -*-
# http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
from datetime import datetime, timedelta
from flask.ext.classy import FlaskView, route
from sqlalchemy import Date, cast, func
from smsgw.core import db
from smsgw.models import Outbox, SentItem, Inbox
from smsgw.lib.utils import... |
"""
This page is in the table of contents.
The gts.py script is an import translator plugin to get a carving from an gts file.
An import plugin is a script in the interpret_plugins folder which has the function getCarving. It is meant to be run from the interpret tool. To ensure that the plugin works on platforms wh... |
#pylint: disable=C0111
from lettuce import world, step
from terrain.steps import reload_the_page
from xmodule.modulestore import Location
from contentstore.utils import get_modulestore
############### ACTIONS ####################
@step('I have created a Video component$')
def i_created_a_video_component(step):
... |
import unittest
from kona.linalg.memory import KonaMemory
from dummy_solver import DummySolver
class StateVectorTestCase(unittest.TestCase):
def setUp(self):
solver = DummySolver(10, 10, 0)
self.km = km = KonaMemory(solver)
km.primal_factory.request_num_vectors(1)
km.state_facto... |
from sympy.external import import_module
from sympy.utilities.pytest import raises, SKIP
from sympy.core.compatibility import range
theano = import_module('theano')
if theano:
import numpy as np
ts = theano.scalar
tt = theano.tensor
xt, yt, zt = [tt.scalar(name, 'floatX') for name in 'xyz']
else:
#... |
"""
vcf.py
"""
class VCFEntry:
def __init__(self, tokens):
self.chrom = tokens[0]
self.pos = int(tokens[1])
self.id = tokens[2]
self.ref = tokens[3]
self.alt = tokens[4]
self.qual = tokens[5]
self.filter = tokens[6]
self.info = tokens[7]
if le... |
# For each cylinder in the scan, find its ray and depth.
# 03_c_find_cylinders
# Claus Brenner, 09 NOV 2012
from pylab import *
from lego_robot import *
# Find the derivative in scan data, ignoring invalid measurements.
def compute_derivative(scan, min_dist):
jumps = [ 0 ]
for i in xrange(1, len(scan)... |
# -*- coding: utf-8 -*-
'''
Copyright 2011-2015 ramusus
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... |
from __future__ import print_function
import msgpackrpc #install as admin: pip install msgpack-rpc-python
import numpy as np #pip install numpy
import msgpack
import math
import time
import sys
import os
import inspect
import types
import re
class MsgpackMixin:
def to_msgpack(self, *args, **kwargs):... |
"""
homeassistant.components.garage_door.wink
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Wink garage doors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/garage_door.wink/
"""
import logging
from homeassistant.components.garage_door import G... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
dict_get,
ExtractorError,
HEADRequest,
int_or_none,
qualities,
remove_end,
unified_strdate,
)
class CanalplusIE(Info... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
""" Logging setup.
Copyright (c) Karol Będkowski, 2013
This file is part of wxGTD
Licence: GPLv2+
"""
__author__ = "Karol Będkowski"
__copyright__ = "Copyright (c) Karol Będkowski, 2013"
__version__ = "2013-04-27"
import sys
import os.path
import logging
import tempfile
im... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
import os.path
import socket
import psycopg2
import sys
import errno
import logging
import traceback
# Variables de sistema
APP_PATH = '/home/aisuser/aislib/proc_utils/'
BASE_PATH = '/home/aisuser/mt_sync/'
BASE_PATH_CSV = BASE_PATH + "csv/"
BASE_PATH_JSON = B... |
import pygame
from pygame.locals import *
import os
import sys
# -----------
# Constantes
# -----------
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
IMG_DIR = "imagenes"
# ------------------------------
# Clases y Funciones utilizadas
# ------------------------------
def load_image(nombre, dir_imagen, alpha=False):
... |
from google.appengine.ext import db
from exceptions import *
class AziendaData(db.Model):
name = db.StringProperty("")
address = db.PostalAddressProperty("")
piva = db.StringProperty("")
user = db.UserProperty()
eur_h = db.FloatProperty(0)
@staticmethod
def createAziendaData(user, key=None, name=None, address... |
import os
import numpy
from ximpol import XIMPOL_DOC_FIGURES
from ximpol.irf import load_irfs
from ximpol.utils.matplotlib_ import save_current_figure
from ximpol.utils.matplotlib_ import pyplot as plt
from ximpol.core.spline import xInterpolatedUnivariateSplineLinear
from ximpol.core.spline import xInterpolatedBivari... |
#!/usr/bin/env python
""" Dump sis3316 configuration to a file (with -c loads configuration from file)"""
# from __future__ import print_function
import sys, os, argparse, json
#sys.path.append("../")
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import sis3316
def dump_conf(dev):
if not isinst... |
class ChildNotFoundError(Exception):
""" Raised on attempts to look up a non-existent path
"""
def __init__(self, node, child):
self.strerror = "Node %s has no child %s" % (node, child)
class ChildAlreadyExistsError(Exception):
""" Raised on attempts to insert the same child more than one time... |
# -*- coding: 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 'LocationAnswer'
db.create_table(u'survey_locationanswer', (
(u'id', self.gf('dja... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
class SalesManager:
def work(self):
print("Sales Manager working...")
def talk(self):
print("Sales Manager ready to talk")
class Proxy:
def __init__(self):
self.busy = 'No'
self.sales = None
def work(self)... |
"""Example update stack volume visualiser.
press j and k to toggle between two stacks
"""
import sys
import logging
import types
import numpy as np
from renderer import BaseGlutWindow, VolumeRenderer
from parser.tiff_parser import open_tiff
class ExampleVolumeVisualiser(BaseGlutWindow):
def load_image(self, ... |
import httplib
import logging
from functools import wraps
from flask import json, request
from rhsm import certificate
from rhsm import certificate2
from crane import exceptions
from crane import data
logger = logging.getLogger(__name__)
def http_error_handler(error):
"""
handle HTTPError exceptions and r... |
import itertools
import os
import re
import urllib
from twisted.internet import defer
from twisted.internet import utils
from twisted.python import log
from buildbot import config
from buildbot.changes import base
from buildbot.util import ascii2unicode
from buildbot.util.state import StateMixin
class GitPoller(bas... |
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
import sys
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
try:
conn = psycopg2.connect("dbname=tournament")
return conn
except:
print ... |
from game.models import TeamPick,Team
def get_weekly_record(week,team):
wins = len(TeamPick.objects.filter(correct=True,nfl_week=week,team=team))
losses = len(TeamPick.objects.filter(correct=False,nfl_week=week,team=team))
team_weekly_record_dict = {'wins':wins, 'losses':losses}
return team_weekly_re... |
from __future__ import absolute_import, unicode_literals
import sys
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, Group, Permission, PermissionsMixin)
from django.db import models
class CustomUserManager(BaseUserManager):
def _create_user(self, username, email, password,
... |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.literature import pubmed_client
from indra.util import unicode_strs
from nose.plugins.attrib import attr
@attr('webservice')
def test_get_ids():
ids = pubmed_client.get_ids('braf', retmax=10, db='pub... |
from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:9332")
else:
access = Ser... |
import argparse
import boto
import errno
import logging
import os
import socket
import threading
import time
import moto.server
import moto.s3
from girder.utility.s3_assetstore_adapter import makeBotoConnectParams, \
botoConnectS3, S3AssetstoreAdapter
from six.moves import range
_startPort = 31100
_maxTries = 100... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Usage examples
"""
from __future__ import print_function, division
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
from multidensity import SkStJR, SkStBL, SkStDM, SkStAC, MvSt, MvSN
from skewstudent import SkewStudent
def estimate_bivariate_... |
import init_sample
import test_constants as constants
def test_init_sample(mock_sdk_init):
init_sample.init_sample(
project=constants.PROJECT,
location=constants.LOCATION_EUROPE,
experiment=constants.EXPERIMENT_NAME,
staging_bucket=constants.STAGING_BUCKET,
credentials=con... |
# Read a pycbc_inspiral HDF5 trigger file and check that it contains triggers
# compatible with GW150914
# 2016 Tito Dal Canton
import sys
import h5py
import numpy as np
# GW150914 params from my run
# https://www.atlas.aei.uni-hannover.de/~tito/LSC/er8/er8b_c00_1.2.0_run1
gw150914_time = 1126259462.4
gw150914_snr =... |
#!/usr/bin/env python
# Google Code Jam
# Google Code Jam 2016
# Qualification Round 2016
# Problem C. Coin Jam
# Solved all test sets
from __future__ import print_function
def get_coin(length, i):
return '1' + format(i, '#0{0}b'.format(length))[2:] + '1'
def is_coin_jam(coin):
if len(coin) < 2:
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.