content string |
|---|
"""Helpers for tests that check configuration
"""
import contextlib
import functools
import os
import tempfile
import textwrap
import pip._internal.configuration
from pip._internal.utils.misc import ensure_dir
# This is so that tests don't need to import pip._internal.configuration.
kinds = pip._internal.configurati... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# palette.py
# palette_detect
#
"""
Detect the main colors used in an image.
"""
import colorsys
import multiprocessing
import sys
from PIL import Image, ImageChops, ImageDraw
from collections import Counter, namedtuple
from colormath.color_objects import RGBColor
from... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import pymongo
from pymongo import MongoClient as Connection
from PyExp import AbstractModel
from flask_app.settings import *
import os
import subprocess
from flask_app import app
from flask import redirect, flash
TABLE_NAME = "SomeTable"
db_table = Connection("localho... |
__author__ = 'Joe Linn'
import pylastica.aggregation.abstractaggregation as abstract
class GeoDistance(abstract.AbstractAggregation):
def __init__(self, name, field, origin):
"""
@param name: the name of this aggregation
@type name: str
@param field: the field on which to perform ... |
from __future__ import unicode_literals
from config import settings
import os
import re
import string
import pytz
def clear_screen():
os.system(['clear', 'cls'][os.name == 'nt'])
def print_obj(obj):
for attr, val in obj.__dict__.iteritems():
print "{0}: {1}".format(attr, val)
def convert_to_snake... |
#!/usr/bin/env python
"""
WARNING: This script has no meaning today (post 2008).
Since the standard is now available as .doc. If we assume
that the .doc is valid (according to standard only pdf should)
then there is not point in using this parser anymore today.
Let's write our own python parser to clean up the ... |
from django.conf.urls import patterns, url
from django.contrib.sitemaps.views import sitemap
from django.contrib.auth import views as auth_views
from gitbrowser.views.aux import styles, ContributerAvatarView
from gitbrowser.views.core import ListRepositoriesView, dev_null, RepositoryOverviewView
from gitbrowser.views.m... |
from sympl import Stepper, get_constant, initialize_numpy_arrays_with_properties
import numpy as np
# from scipy.interpolate import CubicSpline
from scipy import sparse
from scipy.sparse.linalg import spsolve
class IceSheet(Stepper):
"""
1-d snow-ice energy balance model.
"""
input_properties = {
... |
from optparse import OptionParser
import sys
sys.path.append("/usr/local/admin")
import sysopsapi.cache_extractor
import re
##########################################################################
def main():
parser = OptionParser(usage="usage: %prog [options]",
version="%prog 1.0")
... |
"""
It is possible to construct samplers that handle binary polynomials - problems
that have binary variables but they are not constrained to quadratic
interactions.
"""
import abc
import warnings
from six import add_metaclass
from dimod.core.composite import Composite
from dimod.higherorder.polynomial import Binary... |
from django.contrib import admin
from django.utils.safestring import mark_safe
from image_helper.fields import SizedImageField
from image_helper.widgets import AdminImagePreviewWidget
from pseudo_cms import models
class ContentAdmin(admin.ModelAdmin):
list_display = ['thumbnail', 'url', 'title', 'page_title']
... |
import tensorflow as tf
from spatial_transformer import transformer
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
from tf_utils import conv2d, linear, weight_variable, bias_variable
# %% Create a batch of three images (1600 x 1200)
# %% Image retrieved from https://raw.githubusercontent.... |
from decimal import Decimal
from pony.orm import *
db = Database("sqlite", "demo.sqlite", create_db=True)
class Customer(db.Entity):
id = PrimaryKey(int, auto=True)
name = Required(unicode)
email = Required(unicode, unique=True)
orders = Set("Order")
class Order(db.Entity):
id = PrimaryKey(int, a... |
#!/usr/bin/env python3
import argparse
import datetime
import http.client
import json
import logging
import os
import re
import requests
from requests.auth import HTTPBasicAuth
import sys
import time
import dateutil.parser
logging.basicConfig(level=logging.DEBUG)
#http.client.HTTPConnection.debuglevel = 1
class api... |
import re
import os
from zipfile import ZipFile
# String from tar that shows the tar contents are different from the
# filesystem
DIFFERENCE_RE = re.compile(r': (.*) differs$')
# When downloading an archive, how much of the archive to download before
# saving to a tempfile (64k)
BUFSIZE = 65536
class UnarchiveError(E... |
# 6.00.2x Problem Set 5
# Graph optimization
#
# A set of data structures to represent graphs
#
class Node(object):
def __init__(self, name):
self.name = str(name)
def getName(self):
return self.name
def __str__(self):
return self.name
def __repr__(self):
return self.nam... |
from __future__ import division, unicode_literals
from math import sin, cos, asin, pi, degrees, radians
import os
import numpy as np
import json
from .core import DiffractionPattern, DiffractionPatternCalculator, \
get_unique_families
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
"""
This module imp... |
import os
import shutil
import pytest
TESTS_DIR = os.path.dirname(__file__)
TEST_FILES_DIR = os.path.join(TESTS_DIR, 'testing_files')
@pytest.yield_fixture(autouse=True)
def workdir(request, tmpdir_factory):
with tmpdir_factory.mktemp('workdir').as_cwd():
wd = os.getcwd()
# copy testing files i... |
#!/usr/bin/env python
import networkx as nx
import re
from sqlalchemy.orm import join, contains_eager
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from igsql.database import Base, db_session, engine
from igsql.model import Location, Media, Tag, User
def graph_add_node(n, g, t):
if t == 'med... |
import wx
from content.icon import icon
from utils.runner import Runner
from resultsWindow import ResultsWindow
class MainWindow(wx.Frame):
def __init__(self, storage):
wx.Frame.__init__(self, None, -1, "musiClr", (100,100), (300,275), wx.DEFAULT_FRAME_STYLE)
self.SetIcon(icon.GetIcon())
#... |
"""
Extends the basic test of the Load algorithm done by the LoadLotsOfFiles
test to encompass the complex multi-file loading that the Load
algorithm is capable of.
"""
import systemtesting
from mantid.api import AnalysisDataService, IEventWorkspace, MatrixWorkspace, WorkspaceGroup
from mantid.simpleapi impor... |
from .utils import thumbmd5
from . import tasks
from .log import Log
from . import work
from .bed.baidupan import BaiduPan
from redis import Redis
from contextlib import contextmanager
from functools import wraps
from sqlalchemy.exc import IntegrityError
log = Log(__name__)
class CoreError(Exception):
pass
de... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... |
import os
from unidecode import unidecode
DATA_FOLDER = 'tarefa2'
ROOT_NODE = '4Rxn7Im3LGfyRkY2FlHhWi'
ROOT_NAME = 'Nick Jonas'
ROOT_DEPTH = 1
INCLUDE_ROOT = True
DIRECTED = False
GRAPH_NAME = 'tarefa2'
def load_successors(node, depth=1, names=None):
successors = set()
path = os.path.join(DATA_FOLDE... |
# -*- coding: utf-8 -*-
'''
Monit service module. This module will create a monit type
service watcher.
'''
from __future__ import absolute_import
# Import python libs
import re
# Import salt libs
import salt.utils
# Function alias to make sure not to shadow built-in's
__func_alias__ = {
'id_': 'id',
'reload... |
from Perceptron import NN
import math
import random
from tkinter import *
from tkinter.ttk import *
from HDFFuncs import *
class MainWindow(Frame):
def __init__(self, parent, geometry=None, n=NN([4,9,8,3], act='sigmoid'), menus=[]):
Frame.__init__(self, parent)
self.parent = parent
sel... |
'''
Module for testing exception handling
'''
######################
# Raising Exceptions #
######################
# Use the function search_n from the functions module inside a new function
# also named search_n. The function should do the same as functions.search_n
# but if the variable is not found in the list the... |
#/###################/#
# Import modules
#
#ImportModules
import ShareYourSystem as SYS
#/###################/#
# Build the model
#
#set
BrianingDebugVariable = 25.
#set
AgentUnitsInt = 1000
#Define
MyPredicter=SYS.PredicterClass(
).mapSet(
{
'BrianingStepTimeFloat':0.02,
'-Populations':[
('|Sensor',... |
from copy import deepcopy
import socket
hostname = socket.gethostname()
GECKO_BRANCHES = {
'v2.1': 'mozilla-beta',
'v2.2': 'mozilla-central',
}
GECKO_CONFIG_TEMPLATE = {
'mozilla-release': {
'generate_git_notes': False, # we can change this when bug 1034725 is resolved
'mapper': {
... |
import codecs
import os
from contextlib import contextmanager
class CyclicIncludeError(Exception):
def __init__(self, path):
Exception.__init__(self, "file %s included again during parsing" % path)
class FileNotFoundError(Exception):
def __init__(self, path):
Exception.__init__(self, "file %... |
"""Robot Framework post-install script for Windows.
This script is executed as the last part of the graphical Windows installation
and during un-installation started from `Add/Remote Programs`.
For more details:
http://docs.python.org/distutils/builtdist.html#postinstallation-script
"""
from __future__ import print_f... |
# -*- 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 'Request.status'
db.add_column(u'requests_request', 'status',
self.gf('... |
from __future__ import with_statement
import base64
import copy
import json
import os
import re
import shutil
import sys
import tempfile
import zipfile
try:
from cStringIO import StringIO as BytesIO
bytes = str
str = unicode
except ImportError:
from io import BytesIO
from xml.dom import minidom
from ... |
import sys
import pickle
from collections import deque
# import the already existing data
try:
f = open('coordinate_list', 'r')
data = list(map(eval, f.readlines()))
f.close()
data = deque(data)
except:
data = deque([(0, 0), ]) # the first number is at 0, 0
# set global values
coordinate = (0, 0... |
"""
Program to make a plummed-common input file for umbrella
sampling of the distance between a membrane and one or more solutes
The atom indices are taken from a Gromacs index file
Examples:
make_plumed.py --solutes AAC1 AAC2
"""
import argparse
from sgenlib import groups
if __name__ == '__main__' :
parser... |
"""
The MatchMaker classes should except a Topic or Fanout exchange key and
return keys for direct exchanges, per (approximate) AMQP parlance.
"""
import itertools
import json
from oslo.config import cfg
from keystone.openstack.common.gettextutils import _ # noqa
from keystone.openstack.common import log as logging... |
"""
Embedded Python Blocks:
Each this file is saved, GRC will instantiate the first class it finds to get
ports and parameters of your block. The arguments to __init__ will be the
parameters. All of them are required to have default values!
"""
import time
import numpy as np
from gnuradio import gr
class blk (gr.syn... |
import os
from flask import current_app
from flask.ext.script import Manager
from alembic import __version__ as __alembic_version__
from alembic.config import Config as AlembicConfig
from alembic import command
alembic_version = tuple([int(v) for v in __alembic_version__.split('.')[0:3]])
class _MigrateConfig(objec... |
from ..testutil import eq_, with_app
from ...model.date import MonthRange
from ..base import TestApp
@with_app(TestApp)
def test_add_schedule(app):
app.show_scview()
scpanel = app.mw.new_item()
scpanel.description = 'foobar'
scpanel.save()
eq_(len(app.sctable), 1)
eq_(app.sctable[0].descriptio... |
import getpass
from time import sleep
from typing import Optional
from sqlalchemy import Column, Index, Integer, String, and_, or_
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm.session import make_transient
from airflow import models
from airflow.configuration import conf
from airflow.exceptions imp... |
from nephoria.baseops.botobaseops import BotoBaseOps
import boto
from boto.ec2.regioninfo import RegionInfo
from boto.cloudformation import CloudFormationConnection
import time
class CFNops(BotoBaseOps):
SERVICE_PREFIX = 'cloudformation'
CONNECTION_CLASS = CloudFormationConnection
EUCARC_URL_NAME = 'cloud... |
from openerp import models, fields
class OpStandard(models.Model):
_name = 'op.standard'
_order = 'sequence'
code = fields.Char('Code', size=8, required=True)
name = fields.Char('Name', size=32, required=True)
course_id = fields.Many2one('op.course', 'Course', required=True)
payment_term = fi... |
__author__ = "Alan Etkin <<EMAIL>>"
__copyright__ = "Copyright (C) 2012 Sistemas Ágiles"
__license__ = "AGPLv3"
import gluon
from gluon import *
import datetime
import config
db = config.db
T = config.env["T"]
session = config.session
request = config.request
# modules = __import__('applications.%s.modules' % conf... |
import core
import docker
import helpers
import time
from pprint import pprint
def remove():
client = docker.from_env(assert_hostname=False)
flag = 0
if client.containers(filters={'name': 'min'}):
client.remove_container('min', force=True)
flag = 1
if client.containers(filters={'name'... |
from gnuradio import gr, gr_unittest
from gnuradio import blocks
import tutorial_swig as tutorial
class qa_qpsk_demod_tags_cpp_cb (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001_t (self):
# set up fg
sel... |
import pandas as pd
class Experiment:
data = False
models = []
results = []
verbose = False
def __init__(self, pathToData=None, data=None, verbose=False):
self.clear()
self.verbose = verbose
if isinstance(pathToData, basestring):
self.data = pd.read_csv(pathToD... |
# Python Credential functions for simplenote.vim
def reset_user_pass(warning=None):
if int(vim.eval("exists('g:SimplenoteUsername')")) == 0:
vim.command("let s:user=''")
if int(vim.eval("exists('g:SimplenotePassword')")) == 0:
vim.command("let s:password=''")
if warning:
vim.command... |
"""Tests for resource tracker claims."""
import uuid
import mock
from oslo_serialization import jsonutils
from nova.compute import claims
from nova import context
from nova import db
from nova import exception
from nova import objects
from nova.pci import manager as pci_manager
from nova import test
from nova.tests.... |
"""
adapted from https://github.com/quark0/darts
"""
import math
import logging
import torch
import torch.nn as nn
from .modules.evolved_modules import NasNetCell, AmoebaNetCell, DARTSCell
import sys
sys.path.append('..')
from utils.cross_entropy import cross_entropy, CrossEntropyLoss
__all__ = ['amoebanet... |
import numpy as np
from pysisyphus.helpers import fit_rigid
from pysisyphus.optimizers.Optimizer import Optimizer
class FIRE(Optimizer):
# https://doi.org/10.1103/PhysRevLett.97.170201
def __init__(self, geometry, dt=0.1, dt_max=1, N_acc=2, f_inc=1.1,
f_acc=0.99, f_dec=0.5, n_reset=0, a_star... |
# -*- coding: utf-8 -*-
import unittest
import bob
class BobTests(unittest.TestCase):
def test_stating_something(self):
self.assertEqual(
'Whatever.',
bob.hey('Tom-ay-to, tom-aaaah-to.')
)
def test_shouting(self):
self.assertEqual(
'Whoa, chill ... |
import os
import inspect
import uuid
import importlib.machinery
################################################################################
# There's a lot of extra book-keeping in some areas to work around the fact that
# Python <3.4 don't consistently provide __file__ as an absolute path.
#
# Specificall... |
"""
This module contains the MoleculeWriter class. It is used to apply
atom names from known topologies to the molecule by using a graph-based
representation of each molecule.
Author: Robin Betz
Copyright (C) 2019 Robin Betz
"""
# This program is free software; you can redistribute it and/or modify it under
# the te... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# no unicode literals
import WatchmanInstance
import WatchmanTestCase
try:
import grp
except ImportError:
# Windows
pass
import os
import random
import stat
import string
import sys
import tempfile
... |
from .exceptions import CardLinkError, CardValidityError
import re
import string
CARD_WHITE=0
CARD_BLACK=1
CARD_PLACEHOLDER_LENGTH=3
class Card(object):
def __init__(self, id=-1, text='', type=CARD_WHITE):
self.id=id
self.__text=text
self.type=type
self.unlinkAll()
def isValid(self, text=None):... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
depends_on = (
("resources", "0001_initial"),
("languages", "0001_initial"),
)
def forwards(self, orm):
# Adding model 'Tr... |
import os
from nose.exc import SkipTest
from tests.test_helper import *
from braintree.test.nonces import Nonces
class TestDocumentUpload(unittest.TestCase):
def setUp(self):
file_path = os.path.join(os.path.dirname(__file__), "..", "fixtures/bt_logo.png")
self.png_file = open(file_path, "rb")
... |
from types import SimpleNamespace
import requests
UserAgent = SimpleNamespace(
aol='Mozilla/4.0 (compatible; MSIE 4.01; AOL 4.0; Windows 95)',
ie='Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)',
chrome='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/530.10 (KHTML, like Gecko) Chrome/ Safari/530.5',
safar... |
"""Loads configurations from .yaml files and expands environment variables.
"""
import copy
import collections
import glob
import math
import os
import pprint
import sys
import yaml
import toolz as tz
from bcbio import utils
import bcbio.pipeline.datadict as dd
class CmdNotFound(Exception):
pass
# ## Generalized... |
#!/usr/bin/env python
# -*- coding: UTF8 -*-
# PYTHON_ARGCOMPLETE_OK
"""
launch a custom IPython shell for evo
author: Michael Grupp
This file is part of evo (github.com/MichaelGrupp/evo).
evo is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
... |
"""This module's scope is the modeling and fitting of Airy functions to data.
"""
__version__ = "0.1.1"
__changelog = {
"0.1.1": {"Tuna": "0.16.5", "Change": "PEP8 and PEP257 compliance."},
"0.1.0": {"Tuna": "0.15.0", "Change": "Added wrapper function fit_airy" }
}
import copy
import logging
import math
try:
... |
from pychron.hardware.kerr.kerr_manager import KerrManager
'''
Fusions Control board
a combination of the logic board and the kerr microcontroller
see Photon Machines Logic Board Command Set for additional information
'''
# =============enthought library imports=======================
from traits.api import Instance, ... |
from lib.aws.exception import AwsServiceException
class RdsErrorCode(object):
'''RDS error code'''
DBInstanceNotFound = u'DBInstanceNotFound'
class RdsDBInstanceNotFoundException(AwsServiceException):
def __init__(self, ex):
if not issubclass(ex.__class__, AwsServiceException):
raise... |
from .rule_primitive import RulePrimitive
from .messages import TransformationException
class Resolver(RulePrimitive):
'''
Detects & resolves any conflict between matches and rewritings.
'''
def __init__(self, external_matches_only=False, custom_resolution=lambda packet: False):
'... |
from __future__ import absolute_import
import samba.getopt as options
from samba.net import Net
from samba.netcmd import (
Command,
Option,
SuperCommand,
CommandError
)
class cmd_vampire(Command):
"""Join and synchronise a remote AD domain to the local server."""
synopsis = "%prog [opti... |
#Boa:Frame:administrasi_surat
import wx
import wx.lib.buttons
def create(parent):
return administrasi_surat(parent)
[wxID_ADMINISTRASI_SURAT,
wxID_ADMINISTRASI_SURATKOTAK_ADMINISTRASI_KEPENDUDUKAN,
wxID_ADMINISTRASI_SURATKOTAK_EDIT_SURAT,
wxID_ADMINISTRASI_SURATKOTAK_LAYANAN_UMUM,
wxID_ADMINISTRASI_SURAT... |
__author__ = '<EMAIL> (David Byttow)'
import logging
import random
import wsgiref
import wsgiref.handlers
from opensocial import *
from google.appengine.ext import db
from google.appengine.ext import webapp
GIFTS = {
'snakes': { 'name': 'some snakes', 'img': 'public/snakes.png' },
'dictator': { 'name': 'a bene... |
import unittest
from owlapy.model import DataRangeType
from owlapy.model import EntityType
from owlapy.model import IRI
from owlapy.model import OWL2Datatype
from owlapy.model import OWLDatatype
from owlapy.model import OWLObjectProperty
from owlapy.model import OWLObjectVisitor
from owlapy.model import OWLObjectVisit... |
import math
from util import in_between, boundary
from libavg import Point2D
class Box:
def __init__(self,x,y,width,height):
self.x=x
self.y=y
self.width=width
self.height=height
def inbound(self,p):
"""find closest position inside of cage for point p"""
newx=bou... |
#!/usr/bin/env python
"""Setup script for the pyparsing module distribution."""
from distutils.core import setup
import sys
import os
from pyparsingOD import __version__ as pyparsing_version
modules = ["pyparsingOD",]
setup(# Distribution meta-data
name = "pyparsingOD",
version = pyparsin... |
#!/usr/bin/env python
"""
** Due to time, I copied most of this from ktbyers.
1. Using SNMPv3 create a script that detects router configuration changes.
If the running configuration has changed, then send an email notification to yourself identifying the router
that changed and the time that it changed.... |
from distutils.core import setup
import os
# Stolen from django-registration
# Compile the list of packages available, because distutils doesn't have
# an easy way to do this.
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
if root_dir:
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.... |
import logging
import arrow
from sqlalchemy.sql import func
from sqlalchemy import between
from airy.utils.date import tz_now
from airy.database import db
from airy.models import Task, TimeEntry
from airy import settings
from airy.serializers import UserSerializer
from airy.exceptions import UserError
logger = loggi... |
#!/usr/bin/python3.5
import os
class DbMatcher:
db = None
suffixes = None
prefixes = None
DIR = os.path.dirname(os.path.realpath(__file__))
@classmethod
def get_rows(cls, filename, split=True):
if not os.path.isfile(filename):
raise Exception('File not exists')
ro... |
# -*- coding: utf-8 -*-
from grow import extensions
from grow.documents import document, document_format, static_document
from grow.extensions import hooks
from .markdown_extras import block_filter as BlockFilter
from .markdown_extras import block_tip as BlockTip
from .markdown_extras import block_video as BlockVideo
... |
from .enum import NamedEnum
from ...i18n import translate as t
#### Directions
DIRECTION_NAMES = [
'North',
'East',
'South',
'West',
]
DIRECTION_DELTA = {
0: (1, 0),
1: (0, 1),
2: (-1, 0),
3: (0, -1),
}
class Direction(NamedEnum):
"Represents a Gobstones direction."
def n... |
from os import path, listdir
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from io import BytesIO, SEEK_CUR
from django.core.management.base import BaseCommand
from nuremberg.documents.models import DocumentCase
from nuremberg.transcripts.models import Transcript, TranscriptPage
class Comm... |
"""Package Index Tests
"""
import sys
import unittest
import urllib.request, urllib.error, urllib.parse
import pkg_resources
import http.client
import distutils.errors
import setuptools.package_index
from .server import IndexServer
class TestPackageIndex(unittest.TestCase):
def test_bad_url_bad_port(... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2013-2017 Alex Forencich
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... |
from __future__ import absolute_import
import os
from celery import Celery
from django.apps import AppConfig
from django.conf import settings
if not settings.configured:
# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") ... |
from lxml import html
import requests
import json
header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
def top_chart():
print "Getting top songs...."
page = requests.get("http://www.billboard.com/charts/hot-100")
tree = html.fromstring(page.content)
so... |
"""Defines the various functions for training the pre-defined MentorNet."""
import numpy as np
import scipy.stats as st
import tensorflow as tf
def logistic(inputs):
"""A baseline logistic model."""
feat_dim = int(inputs.get_shape()[1])
with tf.variable_scope('logistic'):
layer_1 = tf.add(
tf.matmu... |
import sys
from django.conf import settings
from django.forms import widgets
try:
from django.forms.utils import flatatt
except ImportError:
from django.forms.util import flatatt
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
try:
from django.utils.simple... |
#!/usr/bin/env python
"""
Generate Maintainers file used by e.g. the Debian Bug Tracking System
@contact: Debian FTP Master <<EMAIL>>
@copyright: 2000, 2001, 2002, 2003, 2004, 2006 James Troup <<EMAIL>>
@copyright: 2011 Torsten Werner <<EMAIL>>
@license: GNU General Public License version 2 or later
"""
# This prog... |
from django.utils import unittest
from django.utils import functional
from django.contrib import admin as django_admin
from translatable import admin
class TranslationInlineModelAdminTestCase(unittest.TestCase):
def test_has_proper_attributes(self):
self.assertTrue(hasattr(admin.TranslationInlineModelAdmi... |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class URLTree(models.Model):
"""
In this Model are the last parsed URLs saved for reusing.
"""
domain = models.CharField(max_length=255, ... |
from orchestra.models.communication.models import CommunicationPreference
from orchestra.models.communication.models import StaffBotRequest
from orchestra.models.communication.models import StaffingRequestInquiry
from orchestra.models.communication.models import StaffingResponse
from orchestra.models.core.models import... |
import numpy as np
def Hooke(la,mu):
return np.array([[la+2*mu,la,0],[la,la+2*mu,0],[0,0,mu]]);
def BuildIkFunc(Num,nq):
options = {0 : BuildIkFunc0,
1 : BuildIkFunc1,
2 : BuildIkFunc2,
3 : BuildIkFunc3}
return options[Num](nq)
def BuildIkFunc0(nq):
return lambda me,k... |
# -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('events', '0015_stworkshopfeedback_stworkshopfeedbackpost_stworkshopfeedbackpre'),
]
operations = [
migrations.CreateModel(
name='LearnDrupalFeedback',
... |
from __future__ import unicode_literals
from __future__ import absolute_import
try:
import salt.client
except ImportError:
raise RuntimeError(
"You must install salt package to use the salt backend")
from testinfra.backend import base
class SaltBackend(base.BaseBackend):
HAS_RUN_SALT = True
... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpR... |
from __future__ import unicode_literals
import unittest
from nose.tools import *
from py_stringmatching.tokenizer.alphabetic_tokenizer import AlphabeticTokenizer
from py_stringmatching.tokenizer.alphanumeric_tokenizer import AlphanumericTokenizer
from py_stringmatching.tokenizer.delimiter_tokenizer import DelimiterTo... |
from salesking.tests.resources import ResourceBaseTestCase
from salesking import api, resources
class ResourceFactoryTestCase(ResourceBaseTestCase):
def test_contact_resource_save_and_delete_success(self):
clnt = api.APIClient()
model = resources.get_model_class("contact", api=clnt)
c... |
from FactorySystem import InputParameters
import os, sys, shutil
# Get the real path of cluster_launcher
if(os.path.islink(sys.argv[0])):
pathname = os.path.dirname(os.path.realpath(sys.argv[0]))
else:
pathname = os.path.dirname(sys.argv[0])
pathname = os.path.abspath(pathname)
# Add the utilities/python_getpot... |
# -*- coding: utf-8 -*-
"""
CommandLine:
>>> # Profile
utprof.py -m ibeis.algo.hots.qt_inc_automatch --test-test_inc_query:3 --num-init 5000 --stateful-query
utprof.py -m ibeis.algo.hots.qt_inc_automatch --test-test_inc_query:0
python -m ibeis.algo.hots.qt_inc_automatch --test-test_inc_query:3 --ia 0
... |
from itertools import izip
from django.db.models.query import sql
from django.db.models.fields.related import ForeignKey
from django.contrib.gis.db.backend import SpatialBackend
from django.contrib.gis.db.models.fields import GeometryField
from django.contrib.gis.db.models.sql import aggregates as gis_aggregates_modul... |
#!/usr/bin/env python
import subprocess, sys
tee="tee -a" #append
ROOT_DIR=sys.path[0]
script_args = sys.argv
script_name = script_args[0]
def failure():
print ("couldn't parse arguments. Try "+ script_name +" -h")
sys.exit(1);
if len(sys.argv) == 1:
failure()
script_args.pop(0)
script = script_args.po... |
"""
A list of vocabulary words (designed for an ELL class).
"""
class Vocab():
"""
A list of vocabularly words.
Can be instantiated with a file or list of strings.
"""
def __init__(self, wordlist):
"""
Initialize with the provided word list.
Args:
wordlist: a fi... |
#!/usr/bin/python
import paramiko
import datetime
class RemoteTalk(object):
_BUFFER_SZ = 1024
def __init__(self, addr=None, port=22, username=username, password=password):
self._addr = addr
self._port = port # if forward-port used let user pass it
self._username = username
se... |
import unittest
import valideer
from inquiry.query import Query
class Tests(unittest.TestCase):
def test_from(self):
"query: must have a from table"
q = Query()
q.select("column_1")
q.select("column_2")
self.assertRaises(valideer.ValidationError, q, {})
def test_reso... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.