content stringlengths 4 20k |
|---|
# -*- coding: UTF-8 -*-
try:
from decimal import Decimal
except:
from django.utils._decimal import Decimal
from django.test import TestCase
from models import *
from satchmo.caching import cache_delete
from satchmo.configuration import config_get_group, config_value
from satchmo.contact.models import AddressBo... |
# -*- 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 field 'TextAnswer.rule_applied'
db.add_column(u'survey_textanswer', 'rule_applied',
... |
#!/usr/bin/env python
""" Command-line usage:
python align.py [options] wave_file transcript_file output_file
where options may include:
-r sampling_rate -- override which sample rate model to use, one of 8000, 11025, and 16000
-s start_time -- start of portion of wavfile to align (in sec... |
## Revised: 10/25/15
## Created: 09/29/15
## Adapted from IncludedGL_byCUI.py and IncludedGLs_byCUI_byTargetPop.pt
## Purpose: final list of included CPGs and their disease categories/GUIs COMBINED WITH Labels found in CPGs
import os
import sys
import csv
## Set path
path = ""
## Initiate file to save results
fName... |
import re
from collections import namedtuple
# From: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html
##########################################################################
# 4.3. Descriptors and Signatures
##########################################################################
# A descriptor is ... |
#!/usr/bin/env python
import requests # pip install requests
import binascii
import javaobj
import io
import struct
import sys
import getpass
import argparse
import logging # To make javaobj's logger be quiet
import sqlite3
import re
import hashlib
logging.disable( logging.CRITICAL )
from read_minimed_next24 import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example plot for LFPy: Single-synapse contribution to the EEG
Execution:
python example_EEG.py
Copyright (C) 2017 Computational Neuroscience Group, NMBU.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Gener... |
'''
A nice coverflow effect for images
'''
#standard imports
import pygame
import os
#our module
from usf.widgets.widget import Widget
from usf.font import fonts
from usf import loaders
from usf import CONFIG
def get_text_transparent(name):
text = loaders.text(name, fonts['mono']['10']).convert()
#FIXME: ... |
#!/usr/bin/env/python
"""
vivocourses.py -- tools for courses and course section in VIVO
See CHANGELOG.md for history
To Do:
-- write test functions
-- get rid of tempita
-- update for VIVO-ISF
-- replace make_x_rdf series with add_x series
-- get rid of count and i in dictionary... |
import json
from datetime import date, datetime, time
from time import mktime, time as timestamp
from django.core.cache import cache
from django.contrib import messages
from django.contrib.auth.models import User
from django.db.models import Sum
from django.http import HttpResponse
from blog.models import Entry
from ra... |
from unittest import TestCase
from latency_meter.client.api import MeasuredLatency
from latency_meter.client.ping_measurement_provider import Pinger, CommandRunner
class TestPinger(TestCase):
def test_given_a_ping_calls_command_runner_with_host(self):
command_runner = MockCommandRunner(
comma... |
"""
https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
https://docs.djangoproject.com/en/1.7/topics/settings/
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Django settings for webapp project.
import os
import sys
import ast # py 2.6 only
def env(key, default=None, valuetype=str, required=Fal... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <<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 Software Foundatio... |
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-ses-boto3',
version='0.1.0',
packages=find_packag... |
from os import walk, stat
from subprocess import check_output
from argparse import ArgumentParser, RawTextHelpFormatter
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import cpu_count
cpu_count = int(cpu_count())
def md5sum(file_path):
try:
rst = ((check_output(('md5sum "%s"' % ... |
from .common import EventBuilder
from .. import utils
class Raw(EventBuilder):
"""
Raw events are not actual events. Instead, they are the raw
:tl:`Update` object that Telegram sends. You normally shouldn't
need these.
Args:
types (`list` | `tuple` | `type`, optional):
The typ... |
from osv import osv
from osv import fields
class OeMedicalHospitalBuilding(osv.Model):
_name = 'oemedical.hospital.building'
_columns = {
'code': fields.char(size=8, string='Code'),
'institution': fields.many2one('res.partner', string='Institution',
hel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
#: NAME = try_command.py
#: DESC = Test commands from command-line
#: VERSION = 0.1
#: AUTHOR = Alexandre Henriet <<EMAIL>>
##
#: EXAMPLE =
#: $ ./try_command.py [--exec=n] check_process_running?match=apache
#:
#: PARAMS =
#: --exec : Command is trully executed. ... |
"""
Django settings for equal_read project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build p... |
class node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
self.parent = None
class tree:
def __init__(self):
self.root = None
def insert(self, num):
current = self.root
parent = None
while current != None:
... |
import datetime as dt
import pytz
import logging
logger = logging.getLogger(__name__) # here "acore.views.impact"
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import loader,Context,RequestContext
from django... |
"""Test TLE file reading, TLE downloading and stroging TLEs to database."""
from pyorbital.tlefile import Tle
import datetime
import unittest
from unittest import mock
import os
from contextlib import suppress
line0 = "ISS (ZARYA)"
line1 = "1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927"
line2... |
import os.path
import operator
import platform
import re
from sickbeard import version
USER_AGENT = 'Sick Beard/alpha2-' + version.SICKBEARD_VERSION.replace(' ', '-') + ' (' + platform.system() + ' ' + platform.release() + ')'
mediaExtensions = ['avi', 'mkv', 'mpg', 'mpeg', 'wmv',
'ogm', 'mp4', 'i... |
from setuptools import setup
def get_version():
import os
import sys
curdir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, curdir)
import framecurve
version = framecurve.__version__
return ".".join(map(str, version))
setup(
name = 'framecurve',
version=get_version(),
au... |
import sys
import os
import re
import ConfigParser
PLATFORM_NAME = "command-line"
PLUGIN_NAME = "pelisalacarta"
# Fichero de configuración global
CONFIG_FILE_PATH = os.path.join( os.getcwd(),'resources','settings.conf')
print "Config file path "+CONFIG_FILE_PATH
configfile = ConfigParser.SafeConfigParser()
configfil... |
import json
import mock
from flask import request
from flask_login import current_user
from flask_login import login_user
from flask_login import logout_user
import config
import api.decorators
import constants.api
import database.user
import util.testing
from api.decorators import hide_if_logged_in
from api.decorato... |
from subprocess import call
from os import path
import hitchpostgres
import hitchselenium
import hitchpython
import hitchserve
import hitchredis
import hitchtest
import hitchsmtp
# Get directory above this file
PROJECT_DIRECTORY = path.abspath(path.join(path.dirname(__file__), '..'))
class ExecutionEngine(hitchtest... |
import ctypes
from ctypes import WinDLL, CDLL, wintypes
shell32 = WinDLL("shell32")
kernel32 = WinDLL("kernel32")
shlwapi = WinDLL("shlwapi")
msvcrt = CDLL("msvcrt")
GetCommandLineW = kernel32.GetCommandLineW
GetCommandLineW.argtypes = []
GetCommandLineW.restype = wintypes.LPCWSTR
CommandLineToArgvW = shell32.Comma... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
__init__.py
---------------------
Date : January 2016
Copyright : (C) 2016 by Matthias Kuhn
Email : <EMAIL>
*********************************************... |
app = None
# All timeperiods
def show_timeperiods():
user = app.request.environ['USER']
_ = user.is_administrator() or app.redirect403()
return {'timeperiods': app.datamgr.get_timeperiods()}
pages = {
show_timeperiods: {
'name': 'TimePeriods', 'route': '/timeperiods', 'view': 'timeperiods'
... |
from zeobuilder import context
from zeobuilder.actions.composed import Action
from zeobuilder.gui import load_image
import gtk.gdk
__all__ = ["Menu", "MenuInfo", "MenuInfoBase"]
class MenuInfoBase(object):
def __init__(self, path, accel_key=None, accel_control=True, accel_shift=False, image_name=None, order=(9... |
# facebook/views/profile.py
from flask import Blueprint, render_template, jsonify, request
import braintree
import logging
import config
mode = braintree.Environment.Sandbox if config.PAYMENT_MODE == 'sandbox' else braintree.Environment.Production
braintree.Configuration.configure(
mode, **config.BRAINTREE)
braint... |
import numpy as np
from latent_space_visualizations.controllers.imshow_controller import ImshowController,ImAnnotateController
from ...core.parameterization.variational import VariationalPosterior
from .base_plots import x_frame2D
import itertools
try:
import Tango
from matplotlib.cm import get_cmap
from ma... |
import math
import numpy as np
import moose
import moose.fixXreacs as fixXreacs
def makeModel():
# create container for model
num = 1 # number of compartments
model = moose.Neutral( '/model' )
compartment = moose.CylMesh( '/model/compartment' )
compartment.x1 = 1.0e-6 # Set it to a 1 micron single-... |
import jinja2
import netaddr
from oslo_config import cfg
from oslo_log import log as logging
import six
from neutron.agent.linux import external_process
from neutron.agent.linux import utils
from neutron.common import constants
from neutron.common import utils as common_utils
RADVD_SERVICE_NAME = 'radvd'
RADVD_SERVI... |
class DirectedGraph(object):
"""Maintains a directed graph."""
def __init__(self):
# Nodes have names, but the nodes themselves are stored by numerical ID to
# save space. Establish maps of name<=>ID, and an ID counter.
self._id_to_name = dict()
self._name_to_id = dict()
self._next_id = 0
... |
from Arlo import Arlo
from datetime import timedelta, date
import datetime
import sys
USERNAME = '<EMAIL>'
PASSWORD = 'blahblahblah'
try:
# Instantiating the Arlo object automatically calls Login(), which returns an oAuth token that gets cached.
# Subsequent successful calls to login will update the oAuth token.
a... |
"""
byceps.services.user.stats_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import datetime, timedelta
from .models.user import User as DbUser
def count_users() -> int:
"""Return the number of users."""
... |
# -*- coding: utf-8 -*-
import os
import unittest
import mock
import pytest
try:
from urllib3.contrib.pyopenssl import (
_dnsname_to_stdlib, get_subj_alt_name
)
from cryptography import x509
from OpenSSL.crypto import FILETYPE_PEM, load_certificate
except ImportError:
pass
def setup_modu... |
import json
from ... topology.topologycontext import *
class MemberActivatedEvent:
def __init__(self):
self.service_name = None
""" :type : str """
self.cluster_id = None
""" :type : str """
self.clusterInstanceId = None
""" :type : str """
self.member_... |
# -*- coding: utf-8; indent-tabs-mode: t; tab-width: 4 -*-
#
# screen.py
#
import curses
from gettext import gettext as _
# wrapper of curses
class Screen:
# key mapping
__KEYMAP = {
curses.KEY_RESIZE: 'RESIZE',
curses.KEY_UP: 'UP',
curses.KEY_DOWN: 'DOWN',
curses.KEY_LEFT: 'LEFT',
curses.KEY... |
from graphviz import Digraph
import json
import copy
import random
import csv
import sys
from django.utils.safestring import mark_safe
from django.template import Template, Context
from tetre.command_utils import setup_django_template_system, percentage
from tetre.command import SentencesAccumulator, ResultsGroupMat... |
# 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 'GeoImage'
db.create_table('lizard_damage_geoimage', (
('id', self.gf('django.d... |
import os
import shutil
import unittest
from tests.context import sbpipe
from sbpipe.utils.dependencies import which
import tests.test_snake_copasi_pe as snake_copasi_pe
import tests.test_snake_copasi_ps1 as snake_copasi_ps1
import tests.test_snake_copasi_ps2 as snake_copasi_ps2
import tests.test_snake_copasi_sim as s... |
import os
import glob
import sys
import math
import shutil
import tempfile
import time
import argparse
import subprocess
import re
########################################################################################################
# use ../helpers.py
sys.path.append('../')
from helpers import copy2temporary, exe... |
import os
import sys
import platform
# Various helpers for the build scripts
def get_lib_dir():
"""Return the library path for SDL and other libraries.
Assumes we're using the pygame prebuilt zipfile on windows"""
if sys.platform.startswith("win"):
if platform.architecture()[0] == '32bit':
... |
from __future__ import unicode_literals
import frappe
from frappe.utils import cint, get_gravatar, format_datetime, now_datetime, get_formatted_email
from frappe import throw, msgprint, _
from frappe.auth import _update_password
from frappe.desk.notifications import clear_notifications
from frappe.utils.user import get... |
"""
Instance app models - Instance
"""
# Imports #####################################################################
import os
from django.conf import settings
from django.core.validators import RegexValidator
from django.db import models
from django.template import loader
from django.utils import timezone
from dj... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 14:15:23 2013
@author: Lam H. Dao <daohailam(at)yahoo(dot)com>
"""
import numpy as np
from struct import pack
from VolUtils import Volume
from FileRoutines import XFile
# Mapping from RAW data type ID to numpy data type ID
RIV_DTYPES = {
'b': 'B', # byte
... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cint
from erpnext.accounts.report.financial_statements import (get_period_list, get_columns, get_data)
from erpnext.accounts.report.profit_and_loss_statement.profit_and_loss_statement import get_net_profit_loss
from erpn... |
#!/usr/bin/env python
import os
import urllib
from setuptools import setup, find_packages, Command
import django_pjm
setup(
name = 'django-pjm',
version = django_pjm.__version__,
packages = find_packages(),
package_data = {
'django_pjm': [
'reference/*.*',
],
},
in... |
import os
import codecs
import shutil
import sys
import egdcodec
from tournament import Tournament, Field
from PyQt4.QtCore import QSettings
codecs.register_error('egd', egdcodec.egd_replace)
if __name__ == "__main__":
settings = QSettings('weirdo', 'pybaduk')
turnname = u'Göteborg Open 2013'
turnpath... |
import unittest
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
from Bio.SeqFeature import SeqFeature, FeatureLocation
from Bio.SeqRecord import SeqRecord
from helperlibs.bio.featurematch import FeatureMatch, find_features
class TestFeatureMatch(unittest.TestCase):
def setUp(self):
self.seq =... |
# -*- coding: utf-8 -*-
# File: layer_norm.py
from ..compat import tfv1 as tf # this should be avoided first in model code
from ..utils.argtools import get_data_format
from .common import VariableHolder, layer_register
__all__ = ['LayerNorm', 'InstanceNorm']
@layer_register()
def LayerNorm(
x, epsilon=1e... |
# coding=utf8
import sublime
import sys
import os
from .Liste import get_root
#from .Project import ProjectSettings, ProjectError, errorSetting
from ..Utils import read_and_decode_json_file, read_file, get_any_ts_view, fn2l, get_any_view_with_root
# ----------------------------------------- CONSTANT ----------------... |
"""
``Pipe`` is a basic pipeline for processing data in sequence. You can create
pipes by composing ``Step`` instances (or any callables).
"""
import abc
import contextlib
import itertools as it
from functools import partial
class Step(object):
"""
base class for steps (for use with Pipe)
"""
__metac... |
# -*- coding: utf-8 -*-
# pylint: disable=C0111,C0103,R0205
import functools
import logging
import threading
import time
import pika
from pika.exchange_type import ExchangeType
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
'-35s %(lineno) -5d: %(message)s')
LOGGER = logging.get... |
from invenio.bibauthorid_config import CLAIMPAPER_ADMIN_ROLE # emitting #pylint: disable-msg=W0611
from invenio.bibauthorid_config import CLAIMPAPER_USER_ROLE # emitting #pylint: disable-msg=W0611
# import invenio.bibauthorid_webapi as webapi
# import invenio.bibauthorid_config as bconfig
from invenio.bibauthorid_f... |
#!/usr/bin/env python
import json
import sqlite3
#
# recreate SQLite database from JSON file
#
allRecipes = []
with open("recipes.json") as jsonFile:
for line in jsonFile:
allRecipes.append(simplejson.loads(line))
try:
# open database and get cursor
connection = sqlite3.connect('recipes.db')
cursor = connection... |
"""Create pathologically bad workloads for malloc fragmentation.
Rationale
=========
Create a set of documents using a key of length A, then remove add the document
with a key of length B (where B > A).
The sizes of the keys are chosen so that documents move through the various
JEMalloc 'bins' and deliberately force... |
#! /usr/bin/env python
from astrodata.AstroData import AstroData, prepOutput
import os
from copy import deepcopy
def ADUToElectron(filelist, odir, oprefix):
"""
This is a function to convert the ADU counts to electrons
by multiply the pixel values by the gain.
Arguments:
filelist: A python l... |
"""Base classes that are extended by low level AMQP frames and higher level
AMQP classes and methods.
"""
class AMQPObject(object):
"""Base object that is extended by AMQP low level frames and AMQP classes
and methods.
"""
NAME = 'AMQPObject'
INDEX = None
def __repr__(self):
items = ... |
'''
Copyright 2020 Google LLC
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to... |
import os, time, sys
import numpy as np
import scipy, math
import pickle
from matplotlib import pyplot
# Imports from tigramite package available on https://github.com/jakobrunge/tigramite
import tigramite
import tigramite.data_processing as pp
from tigramite.independence_tests import ParCorr, GPDC, CMIknn
# Impo... |
import tensorflow as tf
import numpy as np
import os
import re
import json
from bayou.experiments.low_level_sketches.utils import CONFIG_ENCODER, C0, UNK
from bayou.lda.model import LDA
class Evidence(object):
def init_config(self, evidence, save_dir):
for attr in CONFIG_ENCODER:
self.__seta... |
from siphashc import siphash
def raw_hash(*parts: str):
"""Calculates checksum identifying translation."""
data = "".join(part for part in parts)
return siphash("Weblate Sip Hash", data)
def calculate_hash(*parts: str):
"""Calculates checksum identifying translation."""
# Need to convert it from... |
"""
Fast Single Molecule Method (fSMM)
==================================
This module performs the fast Single Molecule Method, based on the Next Reaction Method by Gibson and Bruck [1].
Only user specified reaction will be treated as single molecule reactions, others will be treated as 'normal' exponential reactions... |
from M2Crypto import BIO, Engine, EVP, X509, m2
class Backend(object):
"""Default M2Crypto backend at the moment"""
def __init__(self):
self.name = 'M2Crypto backend'
def load_private_key(self, path):
try:
private = EVP.load_key(path)
except BIO.BIOError, e:
... |
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License");... |
from unittest import TestCase
from nose.tools import ok_, eq_
from nose.tools import assert_not_equal as neq_
#from lambda_function import lambda_size_r, put_cw
import os
import json
import boto3
import placebo
import lambda_function
class LambdaFunctionTestCase(TestCase):
@classmethod
def setup_class(self):
... |
from django.views.generic import ListView, DetailView
from .models import Link, UserProfile
from .forms import UserProfileForm
from django.contrib.auth import get_user_model
from django.views.generic.edit import UpdateView
from django.core.urlresolvers import reverse
class LinkListView(ListView):
model = Link
... |
# Import the Evernote client
from evernote.api.client import EvernoteClient
# Define access token either:
# Developer Tokens (https://dev.evernote.com/doc/articles/dev_tokens.php)
# or OAuth (https://dev.evernote.com/doc/articles/authentication.php)
access_token = "insert dev or oauth token here"
# Setup the client
c... |
"""
The eos_lag_interfaces class
It is in this file where the current configuration (as dict)
is compared to the provided configuration (as dict) and the command set
necessary to bring the current configuration to it's desired end-state is
created
"""
from __future__ import (absolute_import, division, print_function)
... |
import logging
from django import shortcuts
from django import template
from django.core import urlresolvers
from django.template.defaultfilters import title
from django.utils.http import urlencode
from django.utils.translation import string_concat, ugettext_lazy as _
from horizon.conf import HORIZON_CONFIG
from hori... |
from foodgame.entities import EntityLiving
from foodgame.util import Point
from pygame.locals import K_UP, K_DOWN, K_LEFT, K_RIGHT
## Class for the player.
class Player():
## Player Constructor.
def __init__(self, game):
self.game = game
self.entity = EntityLiving(game)
self.entity.spr... |
# Configuration file for jupyterhub.
import os
c = get_config() # noqa
pwd = os.path.dirname(__file__)
c.JupyterHub.spawner_class = 'cassinyspawner.SwarmSpawner'
c.JupyterHub.ip = '0.0.0.0'
c.JupyterHub.hub_ip = '0.0.0.0'
c.JupyterHub.cleanup_servers = False
# First pulls can be really slow, so let's give it a bi... |
# Wall
# depends on amixer
# apt-get install amixer
# Python forward compatibility
from __future__ import (division, absolute_import, print_function,
unicode_literals)
from wall import Brick as _Brick, randstr, Message
import subprocess, re
# TODO: deprecated. Integrate into client menu instead, once availa... |
import shutil
import os
import time
import multiprocessing as mp
import yaml
from montreal_forced_aligner import __version__
from montreal_forced_aligner.corpus.align_corpus import AlignableCorpus
from montreal_forced_aligner.dictionary import Dictionary
from montreal_forced_aligner.aligner import PretrainedAligner
fr... |
'''
BfPy utility classes
'''
import threading
import types
# Code from suds: no changes
def tostr(obj, encoding=None):
""" get a unicode safe string representation of an obj """
if isinstance(obj, basestring):
if encoding is None:
return obj
else:
return obj.encode(enco... |
#!/usr/bin/env python
import roslib
import rospy
import serial
import matlab.engine
import time
import math
import collections
import StringIO as io
import numpy as np
from gait_hmm_ros.msg import imu_vector
from gait_hmm_ros.msg import ardu_msg
from threespace_ros.msg import dataVec
from threespace_ros.msg import Gen... |
import sys
from .. import register_analysis
from .cfg_fast import CFGFast
class OutdatedError(Exception):
pass
class CFG(CFGFast): # pylint: disable=abstract-method
"""
tl;dr CFG is just a wrapper around CFGFast for compatibility issues. It will be fully replaced by CFGFast in future
release... |
import sys
import unittest
from telemetry.core import exceptions
from telemetry.unittest import gtest_progress_reporter
from telemetry.unittest import simple_mock
try:
raise exceptions.IntentionalException()
except exceptions.IntentionalException:
INTENTIONAL_EXCEPTION = sys.exc_info()
class TestFoo(unittest.T... |
"""Testing extensions.
this module is designed to work as a testing-framework-agnostic library,
so that we can continue to support nose and also begin adding new
functionality via py.test.
"""
from __future__ import absolute_import
import sys
import re
py3k = sys.version_info >= (3, 0)
if py3k:
import configp... |
r"""Convert TFDS to numpy arrays to make sure validation data split keeps the same.
Likelihood ratio method evaluates an input under both foreground and
background models. We need to make sure the inputs in the validation dataset
are always the smae set of inputs.
TFDS does not guarantee the split of the training and... |
from sets import Set
import MySQLdb
from kvindex import KVIndex
from spatialdberror import SpatialDBError
import logging
logger=logging.getLogger("neurodata")
class MySQLKVIndex(KVIndex):
def __init__ ( self, db ):
"""Connect to the database"""
self.db = db
self.conn = None
# Connection info
... |
# -*- coding: utf-8 -*-
import json
import os
import pyminifier
try:
import io as StringIO
except ImportError:
import cStringIO as StringIO # lint:ok
# Check to see if slimit or some other minification library is installed and
# Set minify equal to slimit's minify function.
try:
import slimit
js_mi... |
import numpy as np
from numpy import cumsum, sum, searchsorted
from numpy.random import rand
import math
import utils
import core.sentence as sentence
import core.markovchain as mc
import logging
logger = logging.getLogger(__name__)
# Dialogue making class. Need to review where to return a string, where to return a l... |
import unittest
from Crypto.SelfTest.loader import load_tests
from Crypto.SelfTest.st_common import list_test_cases
from Crypto.Util.py3compat import tobytes, b, unhexlify
from Crypto.Cipher import AES, DES3, DES
from Crypto.Hash import SHAKE128
def get_tag_random(tag, length):
return SHAKE128.new(data=tobytes(ta... |
"""
***************************************************************************
ASS_module1_PrepData.py
-------------------------------------
Copyright (C) 2014 TIGER-NET (www.tiger-net.org)
***************************************************************************
* This plugin is part of the Water Ob... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy as np # type: ignore
from onnx import checker, helper
from onnx import TensorProto
class TestChecker(unittest.TestCase):
@property
... |
#-*- coding:utf-8 -*-
from flask import *
from models import board_db
board_page = Blueprint('board_page', __name__)
uid = '1'
@board_page.route('/', methods=['GET'])
def home():
return redirect(url_for('board_page.boards'))
@board_page.route('/board',methods=['GET', 'POST'])
def boards():
if request.method... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import base64
import os
import zlib
import itertools
import six
from six.moves import zip as izip
from . import environment
from .console import log
from . import util
def iter_results_paths(results):
"... |
from __future__ import with_statement, absolute_import
import numpy as np
import os
from lsst.utils import getPackageDir
from lsst.sims.utils import ObservationMetaData
from lsst.sims.catalogs.db import fileDBObject
from lsst.sims.catUtils.baseCatalogModels import StarObj, SNDBObj
from desc.twinkles import create_galax... |
#!/usr/bin/env python
import unittest
import apache_log_parser_split
class TestApacheLogParser(unittest.TestCase):
def setUp(self):
pass
def testCombinedExample(self):
# test the combined example from apache.org
combined_log_entry = '127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700]... |
# pymoku example: PID Controller Plotting Example
#
# This script demonstrates how to configure both PID Controllers
# in the PID Controller instrument. Configuration on the Channel 1
# PID is done by specifying frequency response characteristics,
# while Channel 2 specifies the gain characteristics.
#
# The output res... |
from sqlalchemy import (
Boolean, Column, DateTime, Integer, Unicode, UnicodeText,
CheckConstraint, MetaData, Table, func, delete, sql, select,
)
import attr
METADATA = MetaData()
class NotFound(Exception):
pass
@attr.s
class ModelManager(object):
db = attr.ib()
table = attr.ib()
_detail_... |
import io
import os
class GenBase(object):
"""
This class does generation of the contents and digests files.
"""
def __init__(self,myspec):
self.settings = myspec
def gen_contents_file(self, path):
contents = path + ".CONTENTS"
if os.path.exists(contents):
os.remove(contents)
if "contents" in self.s... |
__revision__ = "$Id: SchweizerIntersection.py,v 1.8 2009-10-27 20:06:27 rliebscher Exp $"
from fuzzy.norm.ParametricNorm import ParametricNorm
from fuzzy.utils import inf_p
class SchweizerIntersection(ParametricNorm):
_range = [ (0.,inf_p) ]
def __init__(self, param=1.):
super(SchweizerIntersection,... |
from util import database
import re
global userlist
def format_hostmask(inp):
"format_hostmask -- Returns a nicks userhost"
try:
return '*!*@{}'.format(inp.split('@')[1])
except:
return inp
def get_hostmask(inp,db):
"userhost -- Returns a nicks userhost"
if '@' in inp or '.' in i... |
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# GTK libraries
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
from gi.repository import Gdk
#-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.