content string |
|---|
from glob import glob
import os
import nox
REPO_TOOLS_REQ = \
'git+https://github.com/GoogleCloudPlatform/python-repo-tools.git'
DIRS = [
# Hello world doesn't have system tests, just a lint test which will be
# covered by the global lint here.
'authenticating-users',
'background/app',
'backg... |
import numpy as np
import time,sys
import atexit
import serial
class Edwards_p_gauge(object):
def __init__(self, device='/dev/ttyUSB1'):
#Instrument.__init__(self, name, tags=['physical'])
'''
self.add_parameter('condenser_pressure',
type=types.FloatType,
... |
import unittest
import configparser
import os.path
import tempfile
import uuid
import mbm.provider.twitter
import mbm.lib.api
import mbm.config
from unittest.mock import MagicMock
class twitterTestCase(unittest.TestCase):
def setUp(self):
self.real_api = mbm.lib.api.Api
mbm.lib.api.Api = MagicMo... |
"""
Test annexes retrieval
Usage: python tests_parse_annexes.py
"""
import sys
from tlfp.tools import parse_texte
if "--enable-cache" in sys.argv:
from lawfactory_utils.urls import enable_requests_cache
enable_requests_cache()
print("> testing parse_texte without annexes (default)")
result = parse_texte.p... |
"""
Mixins for fields.
"""
from bok_choy.promise import EmptyPromise
from common.test.acceptance.tests.helpers import get_selected_option_text, select_option_by_text
class FieldsMixin:
"""
Methods for testing fields in pages.
"""
def field(self, field_id):
"""
Return field with field... |
import unittest
import pytest
from eyed3.id3 import *
class GenreTests(unittest.TestCase):
def testEmptyGenre(self):
g = Genre()
assert g.id is None
assert g.name is None
def testValidGenres(self):
# Create with id
for i in range(genres.GENRE_MAX):
g = Genr... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import PointStamped, Point, PoseStamped, Pose
from styx_msgs.msg import TrafficLightArray, TrafficLight, Waypoint, Lane
from sensor_msgs.msg import Image, CameraInfo
from cv_bridge import CvBridge
from light_classification.tl_class... |
import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
from treeano.sandbox.nodes import expected_batches as eb
fX = theano.config.floatX
def test_scale_hyperparameter():
network = tn.HyperparameterNode(
"hp",
eb.ScaleHyperpar... |
#!/usr/bin/env python
import re
from cgi import parse_qs
from saml2 import BINDING_HTTP_REDIRECT
# -----------------------------------------------------------------------------
def dict_to_table(ava, lev=0, width=1):
txt = ['<table border=%s bordercolor="black">\n' % width]
for prop, valarr in ava.items():
... |
# ==============================================================================
# title : excel
# description :
# notes :
# IDE : PyCharm Community Edition
# ==============================================================================
import datetime
from itertools import islice
... |
"""
Tests for StaticContentServer
"""
import copy
import datetime
import ddt
import logging
import unittest
from uuid import uuid4
from django.conf import settings
from django.test import RequestFactory
from django.test.client import Client
from django.test.utils import override_settings
from mock import patch
from ... |
from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class News(db.Model, BaseMixin, SerializerMixin):
"""
A notification is stored each time a comment is posted.
"""
change = db.Column(db.Boolean... |
"""
Sergi Caelles (<EMAIL>)
This file is part of the OSVOS paper presented in:
Sergi Caelles, Kevis-Kokitsi Maninis, Jordi Pont-Tuset, Laura Leal-Taixe, Daniel Cremers, Luc Van Gool
One-Shot Video Object Segmentation
CVPR 2017
Please consider citing the paper if you use this code.
"""
from PIL import Image... |
import re
import os
import config.parser as config
from irma.common.utils.utils import UUID
from irma.common.base.exceptions import IrmaValueError, IrmaFileSystemError
def validate_id(ext_id):
""" check external_id format - should be a str(ObjectId)"""
if not UUID.validate(ext_id):
raise ValueError("... |
import json
from util import data_filename
from db_sqlite import LanguageDBsqlite, lazy_property
try:
from models import NonStandard, Language, LanguageName, NonStandardRegion, ExtLang, Region, ScriptName, RegionName, Variant, VariantName
from sqlalchemy.orm.exc import NoResultFound
except ImportError:
prin... |
# mandelbrot_mp.py
# Mandelbrot fractal generator with multiprocessing
import sys
from PIL import Image
import functools
import argparse
import multiprocessing
def mandelbrot_calc_row(y, w, h, max_iteration = 1000):
""" Calculate one row of the mandelbrot set with size wxh """
y0 = y * (2/float(h)) - 1 #... |
# a_matrix.py
# Construct the parameters for the linear optimisation
#
# Import external packages
import networkx as nx
import numpy as np
__all__ = ["a_matrix",
"build_coupled_edges",
"couple_node_sets",
"reduce_to_coupled",
"adjust_capacity_edges"]
def a_matrix(g):
... |
from matrix_solver import MatrixSolver
import sklearn.feature_extraction.text as txt
import numpy as np
from sklearn.datasets.base import Bunch
import os
from master_utils import *
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import jaccard_similarity_score
from sklearn.metrics.pairwise i... |
import braille
import config
import speech
import addonHandler
import appModuleHandler
import controlTypes
from . import lambdaProfileSetup
from .lambdaEdit import LambdaDialogEdit,LambdaMainEditor,LambdaMatrixEdit,LambdaBufferEdit
from NVDAObjects.window import DisplayModelEditableText
import wx
from comtypes import C... |
#! /usr/bin/env python3
import pytest
from ws.client.api import LoginFailed
# TODO: pytest attribute
#@attr(speed="slow")
@pytest.mark.skip(reason="The api fixture was removed.")
class test_user:
"""
Tests intended mostly for detecting changes in the ArchWiki configuration.
"""
props_data = {
... |
"""
Routers provide a convenient and consistent way of automatically
determining the URL conf for your API.
They are used by simply instantiating a Router class, and then registering
all the required ViewSets with that router.
For example, you might have a `urls.py` that looks something like this:
router = route... |
from django.views import generic
from .forms import InvitePersonForm, AcceptForm, DeclineForm
from .models import Invitation
class UserMixin(object):
def get_form_kwargs(self):
kwargs = super(UserMixin, self).get_form_kwargs()
kwargs.update(user=self.request.user)
return kwargs
class In... |
import os,re
IGNORE_UNIQUE_ERRORS = True
SILENT_STATEMENTS = True
DATABASE_VERSION = 1
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
class DatabaseClass:
def __init__(self, db_file='', sql_path=''):
self.db_file = db_file
self.sql_path = sql_path
self._connect()
def _runSQLFile(self, f):
... |
import io
import subprocess
import tempfile
import numpy as np
from scipy import stats
from PIL import Image, ImageFilter
def _imagemagick(image, command, temp_format='jpeg'):
"""
Execute `convert <image path> <command> <output path>` via subprocess,
load and return the resulting image
"""
input... |
import uuid
from datetime import timedelta
import six
from sideboard.lib import cached_property
from sideboard.lib.sa import CoerceUTF8 as UnicodeText, \
UTCDateTime, UUID
from sqlalchemy import and_, exists, func, or_, select
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref, co... |
from django import forms
from product.models import Sale, Payment, Rep, Invoice
class SaleForm(forms.ModelForm):
class Meta:
model = Sale
exclude = ['recorded_date', 'invoice', 'amount']
#def __init__(self, user, *args, **kwargs):
# self.user = user
# super(SaleForm, self).__in... |
import os
import orca
import pandas as pd
def size_term(land_use, destination_choice_coeffs):
"""
This method takes the land use data and multiplies various columns of the
land use data by coefficients from the spec table in order
to yield a size term (a linear combination of land use variables).
... |
"""
Smokes - Contains all smoke tests.
Most of these tests simply check if all the views do not return unexpected server errors.
"""
import datetime
import sys
from shortcuts import ShortcutTestCase
from courses import models
from courses.views import SELECTED_COURSES_SESSION_KEY
from courses.tests.factories import ... |
"""Keystone Caching Layer Implementation."""
import dogpile.cache
from dogpile.cache import proxy
from dogpile.cache import util
from keystone import config
from keystone import exception
from keystone.openstack.common import importutils
from keystone.openstack.common import log
CONF = config.CONF
LOG = log.getLogg... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('accion', '0026_remove_solicitud_recurso_en_espera'),
]
operations = [
migrations.AlterField(
model_name='entrada... |
import time
from threading import Event, Thread
# Import internal modules
from fabtotum.totumduino.gcode import GCodeService
###############################
gcs = GCodeService()
gcs.start()
is_active = True
def temperature_monitor_handler():
global is_active
print "temperature_monitor thread: started"
... |
#!/usr/bin/env python
#
# Original filename: loci.py
#
# Email: <EMAIL>
#
# Summary: Run LOCI on the input frame sequence.
#
import sys, re, gc
import numpy as np
from scipy import interpolate
import multiprocessing
from progressbar import ProgressBar
from locitools import *
from parallel import *
def loci(flux, p... |
from xml.dom import minidom
import sys
id_map = {}
minlat=float("+inf")
maxlat=float("-inf")
minlon=float("+inf")
maxlon=float("-inf")
dom = minidom.parse(sys.stdin)
document = dom.documentElement
def lat2str(lat):
return "{:.7f}".format(lat)
def lon2str(lon):
return "{:.7f}".format(lon)
def process_eleme... |
import re
from django.conf import settings
class SecurityForQuery():
"""
Open Context has 'raw' queries that use PostgresSQL functions to improve performance
It represents a bit of a security risk for SQL injection attacks.
So these methods should not be used unless a passed UUID parameter
is alre... |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from future.builtins import *
from slave.driver import Command, CommandSequence, Driver
from slave.types import Boolean, Enum, Integer, String, Register
import slave.protocol
class SR5113(Driver):
"""The ... |
"""Utility functions for the housecanary.excel package"""
from __future__ import print_function
import json
import csv
import io
import sys
from builtins import map
def normalize_cell_value(value):
"""Process value for writing into a cell.
Args:
value: any type of variable
Returns:
json... |
#!/usr/bin/env python
from __future__ import print_function, division
from PIL import Image
from argparse import ArgumentParser
from sys import stderr
from pysstv import color, grayscale
SSTV_MODULES = [color, grayscale]
def main():
module_map = build_module_map()
parser = ArgumentParser(
descriptio... |
bl_info = {
"name": "Wavefront OBJ format",
"author": "Campbell Barton, Bastien Montagne",
"version": (2, 0, 0),
"blender": (2, 58, 0),
"location": "File > Import-Export",
"description": "Import-Export OBJ, Import OBJ mesh, UV's, "
"materials and textures",
"warning": "",
... |
"""
Test TorrentProvider
"""
from __future__ import print_function, unicode_literals
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
import sickb... |
from pycp2k.inputsection import InputSection
class _each79(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_opt = None
self.Qs_scf = None
self.Xas_scf = None
self.Md = None
self.Pint = None
self.Metad... |
import logging
from time import time
from pymongo.errors import PyMongoError
from helperFunctions.data_conversion import convert_str_to_time
from helperFunctions.object_storage import update_included_files, update_virtual_file_path
from objects.file import FileObject
from objects.firmware import Firmware
from storage... |
from .blocks import (
Block,
)
from .weave import (
Weave,
)
from .query import (
PyQueryUTF,
)
import yaml
class Tangle(Weave):
def tangle(self):
"""Tangle non-code and code blocks."""
self.data, self.blocks = ["""""",[],]
for child in self.query.children().items() if self.quer... |
"""State and behavior for ticket transmission during an operation."""
import abc
import six
from grpc.framework.base import _constants
from grpc.framework.base import _interfaces
from grpc.framework.base import interfaces
from grpc.framework.foundation import callable_util
_TRANSMISSION_EXCEPTION_LOG_MESSAGE = 'Exc... |
"""
Functions and data for Tweet "entities" field and component parts.
@auth dpb
@date 1/14/2014, 2/11/2014
Tweet "entities":
urls: []
media: []
symbols: []
hashtags: []
user_mentions: []
media:
id: <int> // ID of the media object
id_str: <str>
media_url:... |
#!/usr/bin/env python
from textcad import *
import magpie.utility
class Hardware(component.Element):
def __init__(self, name):
component.Element.__init__(self, name = name)
def size_from_diameter():
pass
class CapScrew(component.Element):
def __init__(self, size="M3", length=10):
... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline ... |
from django.contrib.contenttypes.models import ContentType
from django.db.models import Exists, OuterRef
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, generics
from tutelary.mixins import APIPermissionRequiredMixin
from core.mixins import update_permissions
from reso... |
"""
To each region, let's add the number of users that tweeted in the region.
"""
import json
import pymongo
import twitterproj
def via_json():
raise Exception("""This script doesn't work for states because CA has two
documents. Fix this!""")
json_files = [
'json/grids.states.bot_filtered.users.jso... |
"""
.. module: security_monkey.tests.watchers.vpc.test_peering
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Bridgewater OSS <<EMAIL>>
"""
from security_monkey.tests.watchers import SecurityMonkeyWatcherTestCase
from security_monkey.watchers.vpc.peering import Peering
import boto
from moto import m... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_noop
from django.utils.translation import ugettext as _
from corehq.apps.es import users as user_es, filters
from corehq.apps.locations.models import LOCATION_SHARING_PREFIX, LOCATION_REPORTING_PREFIX
from corehq.apps.domain.mod... |
import sys
sys.path.append('/home/jwalker/dynamics/python/atmos-tools')
sys.path.append('/home/jwalker/dynamics/python/atmos-read')
import numpy as np
import xray
import pandas as pd
import matplotlib.pyplot as plt
import atmos as atm
import merra
# -------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
# $Id: reporting.py 56295 2015-06-09 14:29:55Z vboxsync $
"""
Test Result Report Writer.
This takes a processed test result tree and creates a HTML, re-structured text,
or normal text report from it.
"""
__copyright__ = \
"""
Copyright (C) 2010-2015 Oracle Corporation
This file is part of Vi... |
import os
import mimetypes
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from ft_cmd import ICommand
class CommandGet(ICommand):
... |
'''
Marsmello base58 encoding and decoding.
Based on https://Marsmellotalk.org/index.php?topic=1026.0 (public domain)
'''
import hashlib
# for compatibility with following code...
class SHA256:
new = hashlib.sha256
if str != bytes:
# Python 3.x
def ord(c):
return c
def chr(n):
return ... |
from dataclasses import dataclass, field
from typing import Dict, List, NoReturn, Union, Type, Iterator, Set
from dbt.exceptions import raise_dependency_error, InternalException
from dbt.context.target import generate_target_context
from dbt.config import Project, RuntimeConfig
from dbt.config.renderer import DbtProj... |
from pdb import pm
from miasm2.arch.x86.disasm import dis_x86_32
from miasm2.analysis.binary import Container
from miasm2.core.asmbloc import AsmCFG, asm_constraint, asm_bloc, \
asm_label, asm_block_bad, asm_constraint_to, asm_constraint_next, \
bbl_simplifier
from miasm2.core.graph import DiGraphSimplifier, M... |
import unittest,doctest
# from functionsToTestPrefixFreeCodes import testPFCAlgorithm, compressByRunLengths
from partiallySortedArrayWithPartialSumPrecomputed import PartiallySortedArray
from codeTree import Interval, ExternalNode, InternalNode, nodeListToStringOfWeights, nodeListToString, nodeListToWeightList
def INI... |
from murano.common import policy
class RequestContext(object):
"""Stores information about the security context under which the user
accesses the system, as well as additional request information.
TODO: (sjmc7) - extend openstack.common.context
"""
def __init__(self, auth_token=None, user=None,
... |
import math
import ast
import nltk.data, nltk.tag
import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import twitter_samples
from nltk.tokenize import TweetTokenizer
##tagger = nltk.data.load(nltk.tag._POS_TAGGER)
##
##print "0"
##text = nltk.word_tokenize("And now for something c... |
import numpy as np
from ..core import SparseGP
from .. import likelihoods
from .. import kern
from .. import util
from GPy.core.parameterization.variational import NormalPosterior, NormalPrior
from ..core.parameterization.param import Param
from paramz.transformations import Logexp
from ..util.linalg import tdot
class... |
from hashlib import sha256, sha512
from Crypto.Util.asn1 import DerSequence
from OpenSSL.crypto import *
class Certificate(object):
"""A certificate fetched from a remote server."""
def __init__(self, der):
self.DER = der
self.cert = load_certificate(FILETYPE_ASN1, der)
@property
def... |
"""
Serialization support.
"""
import functools
try: # pragma: no cover
import simplejson as json
except ImportError:# pragma: no cover
import json
from twisted.web.resource import Resource
from txyoga import errors, interface
def forContentType(contentType):
def decorator(encoder):
encoder.cont... |
import os
# current path
current = os.getcwd()
# resources path
path = os.path.dirname(os.path.realpath(__file__))
os.chdir(path)
os.chdir('../../')
root_path = os.getcwd()
# Go back
os.chdir(current)
current = os.getcwd()
# Glade Files
MAIN_WINDOW_GLADE = root_path + '/resources/gui/main_window.glade'
DISC_VAR_DI... |
# -*- mode: python; tab-width: 4; indent-tabs-mode: nil -*-
from cloudsn.core.account import AccountCacheMails, AccountManager, Notification
from cloudsn.core.provider import Provider
from cloudsn.core import utils
from cloudsn.core import config
from cloudsn.ui.utils import create_provider_widget, get_widget_by_label
... |
import webapp2
import jinja2
import os, urllib2, re, base64, urllib, datetime
from time import gmtime, strftime
from google.appengine.ext import db
from google.appengine.api import images, files, memcache, users
# cache bustin
#
# feel free to clear memcached from the appengine dashboard if you forget to
# bump this
... |
import re
import json
from subprocess import call, Popen, PIPE
def init_parser(parser):
parser.add_argument('name', type=str, help='Cluster name.')
parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.")
parser.add_argument('--hail-log', '-l', r... |
import discord
import sys
import csv
import datetime
from apscheduler.schedulers.background import BackgroundScheduler
import pickle
import time
import os
client = discord.Client()
def logwrite():
server = client.get_server('214249708711837696')
dt = datetime.datetime.now()
date = str(dt.month) + '/' + st... |
import logging
from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
_logger = logging.getLogger(__name__)
class sale_configuration(osv.TransientModel):
_inherit = 'sale.config.settings'
_columns = {
'group_product_variant': fields.selection([
(0, "No variants on products... |
import arff
import numpy as np
import os
from scipy.stats import wilcoxon
# does a statistical test on the intermediate results of
directory_A = os.path.expanduser('~') + '/nemo/experiments/priorbased_experiments/libsvm_svc/kernel_rbf/uniform__bestN_10__ignore_logscale_False__inverse_holdout_False__oob_strategy_ignor... |
from openerp.osv import orm, fields, osv
from openerp.tools.translate import _
class ir_model_fields(orm.Model):
_inherit = 'ir.model.fields'
def search(
self, cr, uid, args, offset=0, limit=0, order=None, context=None,
count=False):
model_domain = []
for domain in arg... |
from django.contrib import admin
from collections import OrderedDict
from edc_registration.models import RegisteredSubject
from edc_export.actions import export_as_csv_action
from tshilo_dikotla.base_model_admin import MembershipBaseModelAdmin
from ..forms import AntenatalEnrollmentForm
from ..models import Antenata... |
"""
Django settings for anemoController project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR,... |
import csv
import math
import operator
class KNearestNeighbors:
"""
Main class for points classification
"""
def __init__(self, path_to_training_data="../data/training.txt", path_to_test_data="../data/test.txt", k_value=3):
"""
:param KNearestNeighbors self: class instance
:par... |
#!/usr/bin/env python3
# Version 1.1
# Author Alexis Blanchet-Cohen
import argparse
import glob
import os
import subprocess
import util
# Read the command line arguments.
parser = argparse.ArgumentParser(description="Generates trim_galore scripts.")
parser.add_argument("-s", "--scriptsDirectory", help="Scripts direc... |
# code_specific_volume.py
# Randomly selects 12 snippets from a volume, gets you to code them
# manually, and then reports the log of (reference / wage)
# The data structure for the coded snippets is as follows:
# 0) date,
# 1) volumeid
# 2) reference type: a (q)uantity of money "five dollars",
#... |
from django.conf import settings
from django.test.signals import setting_changed
from django.dispatch import receiver
from django.core.exceptions import ImproperlyConfigured
from pyconomic.client import Client
from pyconomic.mock_client import MockClient
client = None
def configure():
"""(Re-)configure pyconomi... |
from django.db import models
from .student import School
class Term(models.Model):
dcid = models.IntegerField(primary_key=True)
id = models.IntegerField()
name = models.CharField(max_length=30)
first_day = models.DateField(db_column='firstday')
last_day = models.DateField(db_column='lastday')
... |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed i... |
#!/usr/bin/env python
"""
Project Euler Problem 21
========================
Let d(n) be defined as the sum of proper divisors of n (numbers less than
n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair
and each of a and b are called amicable numbers.
... |
import pytest
import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_allclose, assert_array_less)
from mne.inverse_sparse.mxne_optim import (mixed_norm_solver,
tf_mixed_norm_solver,
... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-current] EMBL-European Bioinformatics Institute
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... |
import warnings
from numpyro.compat.util import UnsupportedAPIWarning
from numpyro.primitives import module, param as _param, plate, sample # noqa: F401
_PARAM_STORE = {}
def get_param_store():
warnings.warn(
"A limited parameter store is provided for compatibility with Pyro. "
"Value of SVI pa... |
import molpher
from molpher.core.MolpherMol import MolpherMol
from molpher.core._utils import shorten_repr
class ContractBond(molpher.swig_wrappers.core.ContractBond):
def __repr__(self):
return shorten_repr(self.__class__, self)
def morph(self):
ret = super(ContractBond, self).morph()
... |
import os
import shutil
import subprocess
from datetime import date
from pathlib import Path
from django.conf import settings
from django.test import Client
from django_q.tasks import async
from .models import Architecture, BasePackage, Build, Package, Repository
def parse_srcinfo(base_package):
"""Generates an... |
import testtools
from openstack.workflow.v2 import execution
FAKE_INPUT = {
'cluster_id': '8c74607c-5a74-4490-9414-a3475b1926c2',
'node_id': 'fba2cc5d-706f-4631-9577-3956048d13a2',
'flavor_id': '1'
}
FAKE = {
'id': 'ffaed25e-46f5-4089-8e20-b3b4722fd597',
'workflow_name': 'cluster-coldmigration',
... |
from client import Client, NOTIF_SUCCESS
URL = u'/organizations'
BTN_DELETE = u"//a[@class='delete' and contains(@data-confirm, '{0}')]"
BTN_EDIT = (u"//a[normalize-space(.)='{0}' and contains"
"(@href,'organizations')]/"
"../../td/div/a[@data-toggle='dropdown']")
BTN_NEW = u'/organizations/new... |
from django.db import models
from django.db.models import CASCADE
from ajapaik.ajapaik.models import Photo, Profile
class ObjectDetectionModel(models.Model):
model_file_name = models.TextField(max_length=200)
def __str__(self):
return self.model_file_name
class ObjectAnnotationClass(models.Model):... |
import numpy as np
from hyperspy.component import Component
class DoublePowerLaw(Component):
"""
"""
def __init__(self, A=1e-5, r=3., origin=0.,):
Component.__init__(self, ('A', 'r', 'origin', 'shift', 'ratio'))
self.A.value = A
self.r.value = r
self.origin.value = origi... |
"""
Helper lib for instructor_tasks API.
Includes methods to check args for rescoring task, encoding student input,
and task submission logic, including handling the Celery backend.
"""
import hashlib
import json
import logging
import datetime
from celery.result import AsyncResult
from celery.states import FAILURE,... |
import re
from odoo import _
from odoo.addons.component.core import Component
from odoo.addons.connector.components.mapper import (
mapping, external_to_m2o, only_create, convert)
class ProductBuyerExportMapper(Component):
_name = 'oxigesti.product.buyerinfo.export.mapper'
_inherit = 'oxigesti.export.ma... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from django.conf import settings
from opps.views.generic.list import ListView
from opps.containers.views import ContainerList
from opps.containers.models import Container, ContainerB... |
# -*- coding: UTF-8 -*-
"""
``Gassst``
-----------------------
:Authors: Liron Levin
:Affiliation: Bioinformatics core facility
:Organization: National Institute of Biotechnology in the Negev, Ben Gurion University.
.. Note:: This module was developed as part of a study led by Dr. Jacob Moran Gilad
Short Descriptio... |
"""
Cooley-Rupert-style business cycle figures for Backus-Ferriere-Zin paper,
"Risk and ambiguity in models of business cycles," Carnegie-Rochester-NYU
conference paper, April 2014.
FRED codes: ["GDPC1", "PCECC96", "GPDIC96", "OPHNFB"]
(gdp, consumption, investment, labor productivity)
Cooley-Rupert link: http:/... |
import SocketServerThread
import Configuration
import Logging
from drivers.device_driver_manager import DeviceDriverManager
import database.AtHomePowerlineServerDb
import services.TimerService
import disclaimer.Disclaimer
import logging
import signal
import os
import time
import sys
#
# main
#
def main():
logger ... |
'''
@author: Chip Boling
@copyright: 2015 Boling Consulting Solutions. All rights reserved.
@license: Artistic License 2.0, http://opensource.org/licenses/Artistic-2.0
@contact: <EMAIL>
@deffield updated: Updated
'''
import openstack.discovery as osDisc
import linux.discovery as lnxDisc
import opendaylight.... |
"""
Module that contains the exceptions on the script API level.
"""
__version__ = "$Revision-Id:$"
class ScriptApiError(Exception):
"""
Base error class for the script API.
"""
pass
class ConfigurationSupportError(ScriptApiError):
"""
Indicates errors of the config... |
import sys
import os
from BeautifulSoup import BeautifulSoup as BS
from docopt import docopt
import json
doc = """
Usage:
python extract-feedback.py <file.html> <dest>
"""
args = docopt(doc)
filename = args['<file.html>']
with open(filename) as f:
data = f.read()
soup = BS(data)
h3s = soup.findAl... |
#!/usr/bin/env python
"""Rdfvalues for flows."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from typing import Optional
from grr_response_core import config
from grr_response_core.lib import rdfvalue
from grr_response_core.lib.rdfvalues import struc... |
# This file is part of kernelconfig.
# -*- coding: utf-8 -*-
import os
import fnmatch
import re
import shlex
import subprocess
import time
from ..abc import loggable
from . import tmpdir as _tmpdir
__all__ = [
"SubProcException",
"SubProcAlreadyStarted",
"SubProcNotStarted",
"SubProc",
]
class Sub... |
import datetime
import pytz
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from ..models import NewsPost
class NewsPostViewTestCase(TestCase):
def setUp(self):
super(NewsPostViewTestCase, self).setUp()
self.admin_user = U... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.