prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Micros | oft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class SsoUri(Model):
"""SSO URI required to login to the supplemental portal.
... | o_uri_value: The URI used to login to the supplemental portal.
:type sso_uri_value: str
"""
_attribute_map = {
'sso_uri_value': {'key': 'ssoUriValue', 'type': 'str'},
}
def __init__(self, sso_uri_value=None):
self.sso_uri_value = sso_uri_value
|
import math
class GeoLocation:
'''
Class representing a coordinate on a sphere, most likely Earth.
This class is based from the code smaple in this paper:
http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates
The owner of that website, Jan Philip Matuschek, is the full ow... | on - delta_lon
if min_lon < GeoLocation.MIN_LON:
min_lon += 2 * math.pi
max_lon = self.rad_lon + delta_lon
if max_lon > GeoLocation.MAX_LON:
max_lon -= 2 * math.pi
# a pole is within the distance
else:
min_l... | .MIN_LON
max_lon = GeoLocation.MAX_LON
return [ GeoLocation.from_radians(min_lat, min_lon) ,
GeoLocation.from_radians(max_lat, max_lon) ]
if __name__ == '__main__':
# Test degree to radian conversion
loc1 = GeoLocation.from_degrees(26.062951, -80.238853)
... |
import pytest
from cplpy import run_test, prepare_config
import subprocess as sp
import os
import glob
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os... | .check_output(bldmd, shell=True)
out = sp.check_output(bldcfd, shell=True)
except sp.CalledProcessError as e:
if e.output.startswith('error: {'):
get_subprocess_error(e.outp | ut)
def test_memory_leak():
#Try to run code
cmd = ("mpiexec -n 4 valgrind --leak-check=full --log-file='vg_md.%q{PMI_RANK}' ./md "
+ ": -n 2 valgrind --leak-check=full --log-file='vg_cfd.%q{PMI_RANK}' ./cfd")
with cd(TEST_DIR):
try:
out = sp.check_output("rm -f vg_*", ... |
', priority=100,
condition=lambda: not current_user.is_anonymous)
@bp.route('/')
@login_required
def root():
return angular.template('tooltool.html',
url_for('.static', filename='tooltool.js'),
url_for('.static', filename='tooltool.css'))
@bp.route('/u... | n of files after they have been
verified."""
region, bucket = get_region_and_bucket(region)
if not body.message:
raise BadRequest("message must be non-empty")
if not body.files:
raise BadRequest("a batch must include at least one file")
if body.author:
raise BadRequest("Au... | henticated_email
except AttributeError:
# no authenticated_email -> use the stringified user (probably a token
# ID)
body.author = str(current_user)
# verify permissions based on visibilities
visibilities = set(f.visibility for f in body.files.itervalues())
for v in visibilities... |
###############################################################################
## File : b64decode.py
## Description: Base64 decode a supplied list of strings
## :
## Created_On : Wed Sep 26 12:33:16 2012
## Created_By : Rich Smith (rich@kyr.us)
## Modified_On: Tue Jan 29 16:42:41 2013
## Modi... | ###############
import base64
__author__ = "rich@kyr.us"
__version__ = 1.0
__updated__ = "26/09/2012"
__help__ = "Module for decoding a string from Base64 representation"
__alias__ = ["b64d"]
def Command(pymyo, name, *args):
"""
Base64 decode each argument supplied
"""
for s in args:
try... | myo.output( base64.decodestring(s) )
except:
pymyo.error("Error decoding %s"%(s) ) |
desFromObjects(oObjList):
return fileNodesFromShaders(shadersFromObjects(oObjList))
def fileNodesFromShaders(oMatList):
oFileNodeList = set()
for oMat in oMatList:
oFileNodeList.update(oMat.listHistory(type="file"))
return list(oFileNodeList)
def shadersFromObjects(objList, connectedTo=""):
... | ace(set=sNamespaceToMatch if sNamespaceToMatch else ":")
oMatNotConformList = []
oShapeAssignedList = []
for oMatSG, oMembers in oShadingGroupMembersDct.iteritems():
oNewMatSGs = pm.duplicate(oMatS | G, rr=True, un=True)
oNewMatSG = oNewMatSGs[0]
# print "old shadingGroup: ", oMatSG
# print "new shadingGroup: ", oNewMatSGs[0]
# print "oMembers", oMembers
# print oMembers[0]
for oMember in oMembers:
oShape = oMember.node()
if oShape not in oShapeAss... |
#!/usr/bin/python
impor | t os
import json
def main():
print("Sample Post Script")
files = json.loads(os.environ.get('MH_FILES'))
for filename in files:
print(filename)
if __name__ == "__main__":
| main()
|
from kompromatron.core import app
from kompromatron.views.base i | mport base
# app.register_blueprint(entitie | s)
# app.register_blueprint(relations)
#app.register_blueprint(base)
|
-min=LONGITUDE_MIN
# The min longitude (float in the interval [-180 ; 180])
# -X LONGITUDE_MAX, --longitude-max=LONGITUDE_MAX
# The max longitude (float in the interval [-180 ; 180])
# -z DEPTH_MIN, --depth-min=DEPTH_MIN
# The min depth (float in th... | min_depth = "0.494"
zmax_depth = "0.4942"
# Date - Timerange
yyyystart = 2 | 007
mmstart = 01
yyyyend = 2007
mmend = 12
hhstart = " 12:00:00"
hhend = " 12:00:00"
dd = 1
# Output files
out_path= "C:\Users\Sam\Downloads\glorys_data"
pre_name= "TestPythonExtr_"
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Main Program
#
# Motu Client Call through... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from trainer.models import Language
class AddWordForm(forms.Form):
language = forms.ModelChoiceField(queryset=Language.objects.all())
word = forms.CharField(required=True)
class Create... | .emai | l = self.cleaned_data["email"]
user.name = self.cleaned_data["first_name"]
user.prename = self.cleaned_data["last_name"]
if commit:
user.save()
return user
class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.C... |
import logging
from flask import (
Flask,
request,
Response
)
import requests
app = Flask(__name__)
@app.route('/<path:url>', methods=['GET', 'POST', 'PUT', 'PATCH'])
def proxy( | url):
# extract the re | quest info and change its destination
# how to deal with socketio
if url == "socket.io/":
target = request.base_url
else:
# target = f"http://localhost:80/{url}"
target = f"http://www.google.com/{url}"
data = request.data or request.form
logging.debug(f'url: {url}, target: ... |
"""
WSGI config for SysuLesson project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more infor | mation on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi im | port get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SysuLesson.settings")
application = get_wsgi_application()
|
from django.contrib import admin
|
'''from tester.models import Club,Member,Signup,Event
class admin_club(admin.ModelAdmin):
list_display=["club_name"]
class admin_event(admin.ModelAdmin):
list_display=["event_name"]
class admin_student(admin.ModelAdmin):
list_display=["usn","name"]
class admin_member(admin.ModelAdmin):
list_displ... | (Event,admin_event)
'''
|
State['t'], minThreshold = self.activationThreshold)
if i is None:
continue
# Turn on the predicted state for the best matching cell and queue
# the pertinent segment up for an update, which will get processed if
# the cell receives bottom up in the future.
self.lrnPredictedStat... | = 0:
seqLength = self.learnedSeqLength - self.pamLength
else:
seqLength = self.learnedSeqLength
if self.verbosity >= 3:
print " learned sequence length was:", seqLength
self._updateAvgLearnedSeqLength(seqLength)
# Backtrack to an earlier | starting point, if we find one
backSteps = 0
if not self.resetCalled:
backSteps = self.learnBacktrack()
# Start over in the current time step if reset was called, or we couldn't
# backtrack.
if self.resetCalled or backSteps == 0:
self.lrnActiveState['t'].fill(0)
f... |
'role_id': self.roles.first().id,
'confirm_password': 'four'}
res = self.client.post(USER_CREATE_URL, formData)
self.assertFormError(
res, "form", 'password',
['Password must be between 8 and 18 characters.'])
@test.create_stubs({api.... | tone.role_list(IgnoreArg()).AndReturn(self.roles.list())
api.keystone.get_defa | ult_role(IgnoreArg()) \
.AndReturn(self.roles.first())
self.mox.ReplayAll()
# check password min-len verification
formData = {'method': 'CreateUserForm',
'domain_id': domain_id,
'name': user.name,
'email': user.ema... |
import subprocess as sp
def matches(text):
| return text.startswith('#')
def process(text):
text = text[1:]
result = sp.check_output(text, shell=True).decode('utf-8').rstrip().replace('\\n', '\n')
retu | rn result
|
import os
import sys
from direct.showbase.ShowBase import ShowBase
import panda3d.core as p3d
import blenderpanda
import inputmapper
from nitrogen import gamestates
if hasattr(sys, 'frozen'):
APP_ROOT_DIR = os.path.dirname(sys.executable)
else:
APP_ROOT_DIR = os.path.dirname(__file__)
if not APP_ROOT_DIR:
... | lf)
self.input_mapper = inputmapper.InputMapper(os.path.join(CONFIG_ROOT_DIR, 'input.conf'))
self.accept('quit', sys.exit)
| self.disableMouse()
winprops = self.win.get_properties()
self.win.move_pointer(0, winprops.get_x_size() // 2, winprops.get_y_size() // 2)
winprops = p3d.WindowProperties()
winprops.set_mouse_mode(p3d.WindowProperties.M_confined)
self.win.request_properties(winprops)
... |
# Copyright (c) 2014 Katsuya Noguchi
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis... | ttp_client
from slack.exception import SlackError, \
InvalidAuthError, \
| NotAuthedError, \
AccountInactiveError, \
ChannelNotFoundError, \
ChannelArchivedError, \
NotInChannelError, \
RateLimitedError
class TestRaiseErrorClient(u... |
from __future__ import division
import state
import time
import csv
import random
import sys
POPULATION_SIZE = 100
MAX_COLLISION = 28
VALID_ARGS = "emg"
class FitnessListener():
def __init__(self, qtd=0):
self._qtd = qtd
def log(self):
self._qtd += 1
def retrive_qtd(self):
ret... | else:
sys.exit("--method used, but no method specified for population generation")
elif argstr == "generations":
if len(arguments) > index+1:
genstr = arguments[index+1]
max_generations = c | hoose_generations(genstr)
next_is_literal_argument = True
else:
sys.exit("--generations used, but no number of generations specified")
elif argstr == "mutation":
mutation_rate = arguments[index+1]
next_is_literal_argumen... |
"""!event [num]: Displays the next upcoming H@B event."""
__ | match__ = r"!event( .*)"
| |
# This doesn't work- not updated with eventmaster.py updates
# TODO: Fix This :)
# Import Libraries
import eventmaster
import time
import random
import sys
import unittest
import sys
class InputsTestCase(unittest.TestCase):
def setUp(self):
self.s3 = E2S3.E2S3Switcher()
self.s3.set_verbose(0)
... | != 1: time.sleep(1)
def test_set_valid_name_on_invalid_input(self):
test_str = "PYTEST-{0!s}".format(random.randint(1,10))
self.assertRaises(ValueError, lambda: self.s3.get_input(99).set_Name(test_str))
def test_set_valid_name_on_valid_input | (self):
test_str = "PYTEST-{0!s}".format(random.randint(1,10))
while(self.s3.has_been_processed(self.s3.get_input(0).set_Name(test_str))==0): time.sleep(1)
time.sleep(1)
self.assertEqual(test_str, self.s3.get_input(0).get_Name())
def test_set_invalid_name_on_valid_input(self):
... |
#!/usr/bin/python
import psycopg2
import sys
import pprint
import geocoder
def printProgress(iteration, total, prefix='', suffix='', decimals=2, barLength=100):
filledLength = int(round(barLength * iteration / float(total)))
percents = round(100.00 * (iteration / float(total)), decimals)
bar = '#' * fill... | cted!\n"
# execute our Query
cursor.execute("SELE | CT user_id FROM users2 ")
rows = cursor.fetchall()
i = 0
l = len(rows)
printProgress(i, l, prefix = 'Progress:', suffix = 'Complete', barLength = 50)
for r in rows:
print(r[0])
cursor2 = conn.cursor()
cursor2.execute("delete from users2 where user_id=(%s) and frien... |
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import urllib
import numpy
from six.moves import xrange # pylint: disable=redefined-builtin
SOURCE_URL = 'http://yann.lecun.com/exdb... | e(SOURCE_URL + filename, filepath)
statinfo = os.stat(filepath)
print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
return filepath
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)
def extra | ct_images(filename):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError(
'Invalid magic number %d in MNIST image file: %s' %
... |
ause: {"name": the name of model's field,
"desc": reverse sort on this field if True}
Returns:
([joins], order) - a tuple of joins required for this ordering to work
and ordering clause itself; join is None if no join
required or [(al... | e, attr
if clause.get("desc", False):
order = order.desc()
return | joins, order
join_lists, orders = zip(*[joins_and_order(clause) for clause in order_by])
for join_list in join_lists:
if join_list is not None:
for join in join_list:
query = query.outerjoin(*join)
return query.order_by(*orders)
def _build_expression(self, exp, object_class):
... |
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertR... | lf.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getRightChild(self):
| return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj):
self.key = obj
def getRootVal(self):
return self.key
|
from sys import version, exit
from setuptools import setup
requirements = open("requirements.txt").read().split()
with open("R | EADME.md") as f:
long_description = f.read()
setup(
name = 'bagcat',
version = '0.0.6',
url = 'https://github.com/umd-mith/bagcat/',
author = 'Ed Summers',
author_email = 'ehs@pobox.com',
py_modules = ['bagcat',],
install_requires = requirements,
description = "A command line utilit... | Amazon S3",
long_description=long_description,
long_description_content_type="text/markdown",
entry_points={"console_scripts": ["bagcat=bagcat:main"]},
)
|
"""
tests.test_component_demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests demo component.
"""
import unittest
import homeassistant.core as ha
import homeassistant.components.automation as automation
import homeassistant.components.automation.event as event
from homeassistant.const import CONF_PLATFORM, ATTR_ENTITY_ID
class T... | , self.calls[0].data['some'])
def test_service_specify_entity_id(self):
automation.setup(self.hass, {
automation.DOMAIN: {
CONF_PLATFORM: 'event',
event.CONF_EVENT_TYPE: 'test_event',
automation.CONF_SERVICE: 'test.automation',
aut... | ('test_event')
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
self.assertEqual(['hello.world'], self.calls[0].data[ATTR_ENTITY_ID])
|
from typing imp | ort List
class Solution:
def findMin(self, nums: List[int]) -> int:
first = nums[0]
# Iterate until the next number is less than current.
for num in nums:
if num < first:
| return num
return first
|
values.pop('info_cache', None)
if info_cache is not None:
instance_ref['info_cache'].update(info_cache)
security_groups = values.pop('security_groups', [])
instance_ref['extra'] = models.InstanceExtra()
instance_ref['extra'].update(
{'numa_topology': None,
'pci_requests': None,
... | ault_group = _security_group_ensure_default(context, session)
if 'default' in security_groups:
models.append(default_group)
# Generate a new list, so we don't modify the original
security_groups = [x for x in security_groups if x != 'default']
if security_groups:
... | session, context.project_id, security_groups))
return models
session = get_session()
with session.begin():
if 'hostname' in values:
_validate_unique_server_name(context, session, values['hostname'])
instance_ref.security_groups = _get_sec_group_models(session,
... |
#!/usr/bin/env python
import os.path
import unittest
import pep8
SRC_PATH = os.path.dirname(os.path.dirname(__file__))
EXCLUDE = ['.svn', 'CVS', '.bzr', '.hg', '.git',
'Paste-1.7.5.1-py2.6.egg', 'PasteDeploy-1.5.0-py2.6.egg', 'data']
class AdhocracyStyleGuide(pep8.StyleGuide):
def ignore_code(self, ... | 'E123', # closing bracket does not match indentation of opening
# bracket
'E124', # closing bracket does not match visual indentation
'E126', # continuation line over
'E127', # continuation line over
'E128', # continuation line under
... | E231', # missing whitespace after
'E241', # multiple spaces after
'E251', # no spaces around keyword
'E261', # at least two spaces before inline comment
'E301', # expected 1 blank line
'E302', # expected 2 blank lines
'E303', # too many blan... |
# 0 1 2 4 6 7 9
# / \ |
# 3 8 5
#
# 02:04 -- union(9, 4) --------
# WAS: id[] 0 1 2 4 4 6 6 7 4 9
# NOW: id[] 0 1 2 4 4 6 6 7 4 4
# . . . . . . . . . X
#
# 0 1 2 4 6 7
# /|\ |
# 3 8 9 5
#
#
# 02:12 -- union(2, 1) --------
# WAS: i... | em percolates iff top and bottom are connected by open sites.
#
# model system vacant site occupied site percolates
# ------------------ ---------- ----------- ------------- ----------
# electricity material conductor insulated conducts
# fluid flow material empty blocked... | be percolation...
# 08:12 SUBTEXT OF TODAY'S LECTURE (AND THIS COURSE)
#
# STEPS TO DEVELOPING A USABLE ALGORITHM.
# * Model the problem.
# * Find an algorithm to solve it.
# * Fast enough? Fits in memory?
# * If not, figure out why.
# * Find a way to address the problem.
# * Iterate until satisfied.
# 09:15 QU... |
from pychess.Utils.const import *
class Rating ():
def __init__(self, ratingtype, elo, deviation=DEVIATION_NONE, wins=0,
losses=0, draws=0, bestElo=0, bestTime=0):
self.type = ratingtype
for v in (elo, deviation, wins, losses, draws, bestElo, bestTime):
assert v == None... |
def get_elo (self):
return self._elo
def set_elo (self, elo):
self._elo = elo
def __repr__ (self):
r = "type=%s, elo=%s" % (self.type, self.elo)
if self.deviation != None:
r += ", deviation=%s" % str(self.deviation)
if self.wins > 0:
r... | draws > 0:
r += ", draws=%s" % str(self.draws)
if self.bestElo > 0:
r += ", bestElo=%s" % str(self.bestElo)
if self.bestTime > 0:
r += ", bestTime=%s" % str(self.bestTime)
return r
def copy (self):
return Rating(self.type, self.elo, deviation=... |
from flask import Flask, request, abort
import json
import ndb_util
import model
from google.appengine.api import users
from google.appengine.ext import ndb
from flask_restful import Resource
#TODO auth stuff
class OrganizationApi(Resource):
def get(self, id=None):
id = str(id)
if id is None:
... | User', client_id)
if client_id != id and user_key not in org.workers:
abort(401)
print str(type(org.workers)) + ' ' + str(org.workers) + ' ' + str(user_key)
return org.to_json()
def put(self, id=None):
id = str(id)
client_id = users.get_cu | rrent_user().user_id()
if id is None or client_id != id:
print id + ' ' + client_id
print "first one"
abort(401)
org_key = ndb.Key('Organization', id)
org = org_key.get()
print org
if org is None:
print "second one"
abor... |
Copyright (C) 2008-2017 Olivier Aubert <contact@olivieraubert.net>
#
# Advene 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 2 of the License, or
# (at your option) any later version.
#
# Adve... | **kw):
super(TranscriptionImporter, self).__init__(**kw)
self.transcription_edit=transcription_edit
self.name = _("Transcription importer")
def process_file(self, filename):
if filename != 'transcription':
return None
if self.package is None:
self.in... | rt(self.transcription_edit.parse_transcription())
return self.package
class TranscriptionEdit(AdhocView):
view_name = _("Note taking")
view_id = 'transcribe'
tooltip = _("Take notes on the fly as a timestamped transcription")
def __init__ (self, controller=None, parameters=None, filename=None):... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from projects.models import Project
class Necessity(models.Model):
"""
Item or service that an organization regularly needs
"""
name = models.CharField(verbose_name=_('Name'), max_length=20)
satisfied = models.Bo... | _name=_('Organization email'), blank=True,
help_text=_('Contact email for the organization')
)
homepage_url = models.URLField(
verbose_name=_('Homepage URL'), blank=True,
help_text=_('Organization homepage link'),
)
facebook_url = models.URLField(
verbose_name=_('Facebo... | witter_url = models.URLField(
verbose_name=_('Twitter URL'), blank=True,
help_text=_('Organization twitter link')
)
def __repr__(self):
return '<Organization({})>'.format(self.name)
def __str__(self):
return self.name
|
import cgi
from urllib import urlencode
from Rss_channel import Rss_channel
from Rss_item import Rss_item
class Updates_rss( Rss_channel ):
def __init__(
self,
recent_notes,
notebook_id,
notebook_name,
https_url,
):
if notebook_name == u"Luminotes":
notebook_path = u"/"
elif note... | Luminotes user guide":
notebook_path = u"/guide"
elif notebook_name == u"Luminotes blog":
notebook_path = u"/blog"
else:
notebook_path = u"/notebooks/%s" % notebook_id
notebook_path = https_url + notebook_path
Rss_channel.__init__(
self,
cg | i.escape( notebook_name ),
notebook_path,
u"Luminotes notebook",
recent_notes and [ Rss_item(
title = u"Note updated",
link = self.note_link( notebook_id, notebook_name, note_id, revision, https_url ),
description = cgi.escape( u'A note in <a href="%s">this notebook</a> has bee... |
import tensorflow as tf
"""tf.pow(x,y,name=None)
功能:计算x各元素的y次方。
输入:x,y为张量,可 | 以为`float32`, `float64`, `int32`, `int64`,`complex64`,`complex128`类型。"""
x = tf.constant([[2, 3, 5], [2, 3, 5]], tf.float64)
y = tf.constant([[2, 3, 4]], tf.float64)
z = tf.pow(x, y)
sess = tf.Session()
print(sess.run(z))
sess.close()
"""[[ 4. 27. 625.]
[ | 4. 27. 625.]]"""
|
ort django
django.setup()
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*... | 'Érudit.org Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# ... | y)
texinfo_documents = [
(master_doc, 'ruditorg', 'Érudit.org Documentation',
autho |
fro | m .readtime import *
| |
from __future__ import unicode_literals
from reviewboard.hostingsvcs.tests.testcases import ServiceTests
class RedmineTests(ServiceTests):
"""Unit tests for the Redmine hosting service."""
service_name = 'redmine'
fixtures = ['test_scmtools']
def test_service_support(self):
"""Testing the R... | f.assertTrue(self.service_class.supports_bug_trackers)
self.assertFalse(self.service_class.supports_repositories)
def test_bug_tracker_field(self):
"""Testing the Redmine bug tracker field value"" | "
self.assertFalse(
self.service_class.get_bug_tracker_requires_username())
self.assertEqual(
self.service_class.get_bug_tracker_field(None, {
'redmine_url': 'http://redmine.example.com',
}),
'http://redmine.example.com/issues/%s')
|
#!/usr/bin/env python
import unittest
from tests.logic_t.layer.LogicLayer.util import generate_ll
class SearchTest(unittest.TestCase):
def setUp(self):
self.ll = generate_ll()
self.pl = self.ll.pl
self.admin = self.pl.create_user('name@example.org', None, True)
self.pl.add(self.a... | self.pl.add(user2)
task = self.pl.create_task('one two three')
task.users.append(user1)
self.pl.add(task)
self.pl.commit()
# when
results = self.ll.search('two', user2)
| # then
self.assertIsNotNone(results)
results2 = list(results)
self.assertEqual([], results2)
|
mmit()
food_group = session.\
query(model.FoodGroup).\
filter(model.FoodGroup.name == row_in[3]).\
one()
result = {
'long_desc': row_in[0],
'short_desc': row_in[1],
'manufacturer': row_in[2],
'group_id': food_group.id,
'refuse_pct': row_in[4]
... | el'):
obj.__table__.drop(engine, checkfirst=True)
obj.__table__.create(engine)
fnames = os.listdir(data_dir)
for fname in fnames:
table_class = None
col_order = []
full_fname = os.path.join(data_dir, fname)
if fname == 'DATA_SRC.txt':
table_c... | ors', 'title', 'year', 'journal', 'volume_city',
'issue_state', 'start_page', 'end_page']
elif fname == 'DATSRCLN.txt':
table_class = model.FoodNutrientDataSourceMap
col_order = ['food_id', 'nutrient_id', 'data_source_id']
elif fname == 'DERIV_CD.txt':
... |
self._pack_algo = pack_algo
self._algo_kwargs = kwargs
self._algo_args = args
self._ref_bin = None # Reference bin used to calculate fitness
self._bid = kwargs.get("bid", None)
def _create_bin(self):
return self._pack_algo(self._width, self._height, *self._... | m): What packing algo to use
rotatio | n (bool): Enable/Disable rectangle rotation
"""
self._rotation = rotation
self._pack_algo = pack_algo
self.reset()
def __iter__(self):
return itertools.chain(self._closed_bins, self._open_bins)
def __len__(self):
return len(self._closed_bins)+len(self._open_bins... |
#
#
# File to test behaviour of the Golgi Cell.
#
# To execute this type of file, type '..\..\..\nC.bat -python XXX.py' (Windows)
# or '../../../nC.sh -python XXX.py' (Linux/Mac). Note: you may have to update the
# NC_HOME and NC_MAX_MEMORY variables in nC.bat/nC.sh
#
# Author: Padraig Gleeson
#
# ... | int "See http://www.neuroconstruct.org/docs/python.html for more details"
quit()
sys.path.append(os.environ["NC_HOME"]+"/pythonNeuroML/nCUtils")
import ncutils as nc
projFile = File(". | ./Cerebellum.ncx")
############## Main settings ##################
simConfigs = []
#simConfigs.append("Default Simulation Configuration")
simConfigs.append("Single Golgi Cell")
simDt = 0.001
simulators = ["NEURON", "GENESIS_PHYS", "GENESIS_SI"] # Note: nernst object isn't ... |
# -*- coding: utf-8 -*-
from flask_restful import reqparse
from app.mod_profiles.validators.generic_validators import is_valid_id
# Parser | general
parser = reqparse.RequestParser()
parser.add_argument('username', type=str, required=True)
parser.add_argument('email', type=str, required=True)
parser.add_argument('password', type=str, required=True)
parser.add_argument('profile_id', typ | e=is_valid_id, required=True)
# Parser para recurso POST
parser_post = parser.copy()
# Parser para recurso PUT
parser_put = parser.copy()
parser_put.remove_argument('password')
parser_put.add_argument('password', type=str)
|
"""Models for SQLAlchemy.
This file contains the original models definitions before schema tracking was
implemented. It is used to test the schema migration logic.
"""
import json
from datetime import datetime
import logging
from sqlalchemy import (Boolean, Column, DateTime, ForeignKey, Index, Integer,
... | entOrigin(self.origin),
_process_timestamp(self.time_fired)
)
except ValueError:
# When json.loads fails
_LOGGER.exception("Error converting to event: %s", self)
return None
class States(Base): # type: ignore
"""State change history."""
... | e_id = Column(Integer, primary_key=True)
domain = Column(String(64))
entity_id = Column(String(255))
state = Column(String(255))
attributes = Column(Text)
event_id = Column(Integer, ForeignKey('events.event_id'))
last_changed = Column(DateTime(timezone=True), default=datetime.utcnow)
last_up... |
#
# 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"); you may not... | venv_directory="/VENV", python_bin="pythonVER", system_site_packages=True, requirements=[]
)
self.assertEqual("/VENV/bin/python", python_bin)
mock_execute_in_subprocess.assert_called_once_with(
['virtuale | nv', '/VENV', '--system-site-packages', '--python=pythonVER']
)
@mock.patch('airflow.utils.python_virtualenv.execute_in_subprocess')
def test_should_create_virtualenv_with_extra_packages(self, mock_execute_in_subprocess):
python_bin = prepare_virtualenv(
venv_directory="/VENV",
... |
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
#... |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
################################################# | ##############################
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp import api, fields, models
from openerp.exceptions import UserError
class PersonManagement(models.Model):
_name = 'myo.person.mng'
name = fields.Char('Name', required=True)
alias =... |
#!/usr/bin/env python
"""
This script accepts .csv pipeline output and gives a .ps file with a basic tree structure
"""
__author__ = "Paul Donovan"
__maintainer__ = "Paul Donovan"
__email__ = "pauldonovandonegal@gmail.com"
import sys
import argparse
from ete3 import NCBITaxa
#Display help and usage
parser = argpar... | e.replace(str(char),"_") #Replace ugly strings
NextIndex = int(index) + 1
if NextIndex == len(lineage):
pass
else:
NextTaxid = lineage[NextIndex]
NextName = ncbi.get_taxid_translator([str(NextTaxid)])
NextName = NextName[NextTaxid]
for char in NextN | ame:
if char in BadChars:
NextName = NextName.replace(str(char),"_") #Replace ugly strings
NodeToNode = str('\t"' + str(name) + '" -> "' + str(NextName) + '";\n')
if any(NodeToNode in s for s in TreeList):
pass
else:
Output.write(NodeToNode)
TreeList.append(NodeToNode)
if s... |
('netcdf-c~mpi', when='~mpi')
depends_on('netcdf-c+mpi', when='+mpi')
depends_on('netcdf-cxx')
depends_on('libpng')
depends_on('libtiff')
depends_on('zlib')
depends_on('eigen', when='@8.2.0:' | )
depends_on('double-conversion', when='@8.2.0:')
depends_on('sqlite', when='@8.2.0:')
# For finding Fujitsu-MPI wrapper commands
patch('find_fujitsu_mpi.patch', when='@:8.2.0%fj')
def url_for_version(self, version):
url = "http://www.vtk.org/files/release/{0}/VTK-{1}.tar.gz"
retur... | ld_environment(self, env):
# VTK has some trouble finding freetype unless it is set in
# the environment
env.set('FREETYPE_DIR', self.spec['freetype'].prefix)
def cmake_args(self):
spec = self.spec
opengl_ver = 'OpenGL{0}'.format('2' if '+opengl2' in spec else '')
... |
"""Utility functions for plots."""
from functools import wraps
from os.path import join as pjoin
import matplotlib.pyplot as plt
###################################################################################################
########################################################################################... | pop('file_path', None)
# Check for an explicit argument for whether to save figure or not
# Defaults to saving when file name given (since bool(str)->True; bool(None)->False)
save_fig = kwargs.pop('save_fig', bool(file_name))
# Check any collect any other plot keywords
save_k... | s.setdefault('bbox_inches', 'tight')
# Check and collect whether to close the plot
close = kwargs.pop('close', None)
func(*args, **kwargs)
if save_fig:
full_path = pjoin(file_path, file_name) if file_path else file_name
plt.savefig(full_path, **save_kwargs)
... |
#!/usr/bin/python
# gen_numerics.py: generate numerics.h
import numerics
print """/*
quIRC - simple terminal-based IRC client
Copyright (C) 2010-13 Edward Cree
See quirc.c for license information
numeric: IRC numeric replies
*/
/***
This file is generated by gen_numerics.py from masters in numerics.py.
Do not... | Y); where a numeric is being i | dentified purely on the basis of usage "in the wild", the symbolic name will be completely arbitrary and may not align with usage elsewhere.
*/
/* Error replies */"""
errs = [n for n in numerics.nums.values() if isinstance(n, numerics.NumericError)]
for e in errs:
print str(e)
print """
/* Command responses */"""
rp... |
import django_filters
from rest_framework import filters
class CaseInsensitiveBooleanFilter(django_filters.Filter):
# The default django_filters boolean filt | er *only* accepts True and False
# which is problematic when dealing with non-Python clients. This allows
# the lower case variants, as well as 0 and 1.
def filter(self, qs, value):
if value is no | t None:
lc_value = value.lower()
if lc_value in ["true", "1"]:
value = True
elif lc_value in ["false", "0"]:
value = False
return qs.filter(**{self.field_name: value})
return qs
class AliasedOrderingFilter(filters.OrderingFilter):... |
"""
W | SGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os, sys
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTIN... | n = get_wsgi_application()
|
whom the Software is furnished to do
# so, subject to the following conditions:
#
# The abov | e copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Sof | tware.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABIL... |
import datetime
from django.test import TestCase
from django.utils import timezone
from schedule.models import Event, Rule, Calendar
from schedule.utils import EventListManager
class TestEventListManager(TestCase):
def setUp(self):
weekly = Rule.objects.create(frequency="WEEKLY")
daily = Rule.ob... | t2])
occurrences = eml.occurrences_after(datetime.datetime(2009, 4, 1, 0, 0, tzinfo=self.default_tzinfo))
self.assertEqual(next(occurrences).event, self.event1)
self.assertEqual(next(occurrences).event, self.event2)
self.assertEqual(next(occurrences).event, self.event2)
self.asse... | assertEqual(next(occurrences).event, self.event2)
self.assertEqual(next(occurrences).event, self.event2)
self.assertEqual(next(occurrences).event, self.event1)
occurrences = eml.occurrences_after()
self.assertEqual(list(occurrences), [])
|
import re
import time
import readline
import os
# CONVERT shell colors to the same curses palette
SHELL_COLORS = {
"wr": '\033[1;37;41m', # white on red
"wo": '\033[1;37;43m', # white on orange
"wm": '\033[1;37;45m', # white on magenta
"wb": '\033[1;37;46m', # white on blue
"bw": '\033[1;37;40m', #... | ine and not is_extra and not (header and current_item == 0):
if row:
print ' | '.join(['-'*c2maxw[col] for col in xrange(len(row)) ])
else:
| print ' | '.join(['='*c2maxw[col] for col in xrange(len(extra_line)) ])
def ask_filename(text):
readline.set_completer(None)
fname = ""
while not os.path.exists(fname):
fname = raw_input(text)
return fname
def ask(string,valid_values,default=-1,case_sensitive=False):
""... |
from __future__ i | mport unicode_literals
import frappe
from frappe import _
from erpnext.setup.setup_wizard.operations.install_fixtures import add_market_segments
def execute():
frappe.r | eload_doc('crm', 'doctype', 'market_segment')
frappe.local.lang = frappe.db.get_default("lang") or 'en'
add_market_segments() |
import tkinter as tk
from tkinter import ttk
import pkinter as pk
root = tk.Tk()
menu = tk.Menu(root, type="menubar")
filemenu = tk.Menu(menu)
filemenu.add_command(label="New")
filemenu.add_command(label="Save")
menu.add_cascade(label="File", menu=filemenu)
helpmenu = tk.Menu(menu)
helpmenu.add_checkbutton(label="Abo... | bar.add_separator()
############################################### | ###
statusbar = pk.Statusbar(root)
statusbar.pack(side="bottom", fill="x")
variable = tk.StringVar()
statusbar.bind_widget(button, variable, "A Button", "")
statusbar.bind_widget(checkbutton1, variable, "A Checkbutton", "")
statusbar.bind_widget(checkbutton2, variable, "Another Checkbutton", "")
statusbar.bind_widget(... |
# ----------------------------------------------------------------------------
# Copyright | 2014 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
| # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing p... |
": "H-301",
"attr-address_2": "Street 1",
"attr-address_3": "UK",
"attr-postcode_zip": "G61 3NR",
"attr-date_of_birth": "December 28, 1990",
"attr-account_type": "savings",
"attr-year_opened": "2000",
"attr-account_status": "active"
}
@pytest.fixture(scope="... | nnectionSuggestion
@pytest.fixture(scope="module")
def showAcceptedConnectionWithoutAvailableClaimsOut(
showAcceptedConnectionOut,
showConnectionWithProofRequestsOut):
return showAcceptedConnectionOut + showConnectionWithProofRequestsOut
@pytest.fixture(scope="module")
def showAcceptedConnection... | edConnectionOut,
showConnectionWithProofRequestsOut,
showConnectionWithAvailableClaimsOut):
return showAcceptedConnectionOut + showConnectionWithProofRequestsOut + \
showConnectionWithAvailableClaimsOut
@pytest.fixture(scope="module")
def showConnectionSuggestion(nextCommandsToTryUsageLine... |
from __future__ import print_function, division, absolute_import
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNES... | g" in err_msg:
severity | = "warning"
if hasattr(err, 'severity'):
severity = err.severity
# Raise exception string as JSON string. Thus it can be parsed and printed properly.
error_msg = json.dumps(
{
"exception": type(err).__name__,
"severity": severity,
... |
# Copyright (c) 2016, Daniele Venzano
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | ]
self._add_metric(query, "docker_container_cpu", tags_cpu, aggregators_cpu, limit=0)
tags_memory = {
"field": ["usage"],
"zoe_service_id": service_id
}
aggregators_memory | = [
{"name": "sum", "sampling": {"value": "1", "unit": "minutes"}, "align_sampling": False}
]
self._add_metric(query, "docker_container_mem", tags_memory, aggregators_memory, limit=0)
try:
req = requests.post(self.metrics_url, json=query)
except requests.exceptio... |
f | rom django.contrib import admin
from cobra.core.loading import get_model
| |
# -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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, eithe... | on views.
"""
from weblate.trans.models.unitdata import Suggestion
from weblate.trans.tests.test_views import ViewTestCase
class SuggestionsTest(ViewTestCase):
def add_suggestion_1(self):
return self.edit_unit(
'Hel | lo, world!\n',
'Nazdar svete!\n',
suggest='yes'
)
def add_suggestion_2(self):
return self.edit_unit(
'Hello, world!\n',
'Ahoj svete!\n',
suggest='yes'
)
def test_add(self):
translate_url = self.get_translation().get_tr... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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.
#
# This progr | am is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with th... |
# Copyright © 2018 Red Hat, Inc.
#
# This file is part of Bodhi.
#
# 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 2
# of the License, or (at your option) any later version.
#
# T... | BILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floo | r, Boston, MA 02110-1301, USA.
"""Test the bodhi.server.views package."""
|
import numpy as np
import theano
import theano.tensor as T
from theano_utils import sharedX, floatX, intX
def uniform(shape, scale=0.05):
return sharedX(np.random.uniform(low=-scale, high=scale, size=shape))
def normal(shape, scale=0.05):
return sharedX(np.random.randn(*shape) * scale)
def orthogonal(shape... | random.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
q = u if u.shape == flat_shape else v # pick the one with the correct shape
q = q.reshape(shape)
return sharedX(scale * q[:shape[0], | :shape[1]]) |
try:
from DevelopmentConfig import NasConf
print("Loaded DevelopementConf file")
except ImportError:
from Config import NasConf
print("Loaded Conf file")
from ConfigParser import config_parser_class_tests, Co | nfigParser
from Partition import partition_class_tests
from Disk import disk_class_tests
__author__ = 'm'
# todo .gitignore
# todo learn a proper unit tests
def py_nas_tests():
try:
config = ConfigParser(NasConf)
except Exception as E:
assert False, 'Failed to parse NasConfig\n' + str(E)
... | d.'
assert config_parser_class_tests(), 'Config parser tests have failed'
# todo parted tests
# todo hdparm tests
py_nas_tests()
# todo blkid wrapper
|
fr | om django.conf.urls import patterns, url
from .views import EmailAlternativeView
urlpatterns = patterns(
'',
url(r'^email_alternative/(?P<pk>\d+)/$',
EmailAlternativeView.as_view(),
name='email_alternative' | ),
) |
import re
import unicodedata
from djan | go.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
# List of words you're not allowed to use as a slug
RESERVED_KEYWORDS = [
"account",
"add_to_network",
"cache",
"configuration",
"content",
"comment",
"create" | ,
"delete",
"download",
"id",
"invitations",
"join",
"media",
"media_resource",
"menu_builder",
"new",
"resource",
"remove_from_network",
"search",
"static",
"twistranet",
"twistable",
]
rsvd_kw = "$|".join(RESERVED_KEYWORDS)
SLUG_REGEX = r"(?!%s$)[a-zA-Z_][a... |
F ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Main script to launch AugMix training on ImageNet.
Currently only supports ResNet-50 training... | er.add_argument(
'--no-jsd',
'-nj',
action='store_true',
help='Turn off JSD consistency loss.')
parser.add_argument(
'--all-ops',
'- | all',
action='store_true',
help='Turn on all operations (+brightness,contrast,color,sharpness).')
# Checkpointing options
parser.add_argument(
'--save',
'-s',
type=str,
default='./snapshots',
help='Folder to save checkpoints.')
parser.add_argument(
'--resume',
'-r',
type=str,
... |
import asyncio
import ctypes
import os
import time
import unittest
import sys
clib = ctypes.CDLL('libc.so.6', use_errno=True)
class timespec(ctypes.Structure):
_fields_ = [('tv_sec', ctypes.c_long),
('tv_nsec', ctypes.c_long)]
class itimerspec(ctypes.Structure):
_fields_ = [('it_interval',... | os.close(self._fileno)
def start(s | elf, timeout):
assert self._waiter is None, self._waiter
secs = int(timeout)
nsecs = int((timeout - secs) * 1000000)
param = itimerspec()
param.it_value.tv_sec = secs
param.it_value.tv_nsec = nsecs
param.it_interval.tv_sec = 0
param.it_interval.tv_nsec = 0... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 Google Inc.
#
# 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 req... | refix].sources.txt
- [output_prefix].targets.txt
Args:
sources: Iterator of source strings
targets: Iterator of target strings
output_prefix: Prefix for the output file
"""
source_filename = os.path.abspath(os.path.join(output_prefix, "sources.txt"))
target_filename = os.path.abspath(os.path.jo... | le.write(record + "\n")
print("Wrote {}".format(source_filename))
with io.open(target_filename, "w", encoding='utf8') as target_file:
for record in targets:
target_file.write(record + "\n")
print("Wrote {}".format(target_filename))
def main():
"""Main function"""
if ARGS.type == "copy":
gene... |
""" Unit tests for ``wheezy.templates.engine.Engine``.
"""
import unittest
class EngineTe | stCase(unittest.TestCase):
""" Test the ``Engine``.
"""
def setUp(self):
from wheezy.template.engine import Engine
from wheezy.template.loader import DictLoader
self.engine = Engine(
loader=DictLoader(templates={}),
extensions=[])
def test_template_not_f... | |
self.add_input(input)
self.goto()
# Not sure why this is still needed here.
self.refresh()
def __str__(self):
return type(self).__name__ + ' ' + (self.name or str(self.ordinal))
def set_name(self, name):
if self.name is None:
del Tab.registry[se... | .gui.notebook_widget.remove_page(page)
self.undisplay_s | trips(self.strips)
self.hidden = True
def unhide(self):
if self.hidden:
Common.gui.notebook_widget.append_page(self.widget, gtk.Label())
Common.gui.notebook_widget.set_tab_reorderable(self.widget, True)
self.display_strips(self.strips)
self.hidden... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: messagepath/v1/visibility_rules.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf imp... | erialized_start=381,
serialized_end=45 | 2,
)
_sym_db.RegisterEnumDescriptor(_VISIBILITYRULESATTACHMENT_RULE)
_VISIBILITYRULESATTACHMENT = _descriptor.Descriptor(
name='VisibilityRulesAttachment',
full_name='common.messagepath.v1.VisibilityRulesAttachment',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescr... |
aseInsensitiveEnumMeta, str, Enum)):
"""Shared/dedicated workers.
"""
SHARED = "Shared"
DEDICATED = "Dedicated"
DYNAMIC = "Dynamic"
class ConnectionStringType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Type of database.
"""
MY_SQL = "MySql"
SQL_SERVER = "SQLServer"
... | ensitiveEnumMeta, str, Enum)):
"""Type of the DNS record.
"""
C_NAME = "CName"
A = "A"
class DatabaseType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Database type (e.g. SqlAzure / MySql).
"""
SQL_AZURE = "SqlAzure"
MY_SQL = "MySql"
LOCAL_MY_SQL = "LocalMySql"
POST... | etaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Whether this detector is an Analysis Detector or not.
"""
DETECTOR = "Detector"
ANALYSIS = "Analysis"
CATEGORY_OVERVIEW = "CategoryOverview"
class DnsType(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""Current DNS type
"""
AZU... |
# tf_unet 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.
#
# tf_unet is distributed in the hope that it will be useful,
# but WITHOUT... |
x_test, y_test = data_provider(1)
prediction = net.predict(path, x_test)
print("Testing error rate: {:.2f}%".format(unet.error_rate(prediction, util.crop_to_shape(y_test, prediction.shape))))
class DataProvider(ImageDataProvider):
"""
Extends the default ImageDataProvider to randomly se... | ect the next
image and ensures that only data sets are used where the mask is not empty.
The data then gets mean and std adjusted
"""
def __init__(self, mean, std, *args, **kwargs):
super(DataProvider, self).__init__(*args, **kwargs)
self.mean = mean
self.std = std
def _nex... |
),
)
# CRUD Strings
s3.crud_strings[tablename] = Storage(
label_create = T("Add Modem Channel"),
title_display = T("Modem Channel Details"),
title_list = T("Modem Channels"),
title_update = T("Edit Modem Channel"),
... | m' target=_blank>Tropo.com</a>"))
# CRUD Strings
s3.crud_strings[tablename] = Storage(
label_create = T("Create Tropo Channel"),
title_display = T("Tropo Channel Details"),
title_list = T("Tropo Channels"),
title_update = T("Edit Tropo Channel"),
lab | el_list_button = T("List Tropo Channels"),
label_delete_button = T("Delete Tropo Channel"),
msg_record_created = T("Tropo Channel added"),
msg_record_modified = T("Tropo Channel updated"),
msg_record_deleted = T("Tropo Channel deleted"),
|
m2 = int(init[val]['mean']) + 6 * S
y = yl[m1:m2].copy()
xt = xl[m1:m2]
for peakid in range(max(0, val - S), min(N, val + S + 1)):
if peakid == val:
continue
y -= gauss_box_model(xt, **init... | temporary_path,'chunks'))
self._check_directory(os.path.join(temporary_path,'json'))
pool = mp.Pool(processes=self.procesos)
results = [pool.apply_async(calc_all, args=(ite, data2[0].data, pols2, nrows, temporary_path)) for ite in cols]
results = [p.get() for p in results]
self... | in(temporary_path,'master_weights'))
result = self.create_result(master_weights=os.path.join(temporary_path,'master_weights.tar'))
# shutil.rmtree(temporary_path)
return result
def norm_pdf_t(x):
return np.exp(-0.5 * x * x) / M_SQRT_2_PI
def gauss_box_model_deriv(x, amplitude=1.0, mean=0.... |
atabases:index')
class CreateDatabaseView(horizon_forms.ModalFormView):
form_class = forms.CreateDatabaseForm
form_id = "create_database_form"
modal_header = _("Create Database")
modal_id = "create_database_modal"
template_name = 'project/databases/create_database.html'
submit_label = _("Creat... | lica_source}
return insta | nces
except Exception:
msg = _('Unable to retrieve instance details.')
redirect = reverse('horizon:project:databases:index')
exceptions.handle(self.request, msg, redirect=redirect)
def get_context_data(self, **kwargs):
context = \
super(PromoteToRepli... |
# Copyright (C) 2013-2015 MetaMorph Software, Inc
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this data, including any software or models in source or binary
# form, as well as any drawings, specifications, and documentation
# (collectively "the Data"), to deal in the Data ... |
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Data.
# THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILIT | Y,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE DATA OR... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import urlparse
from scrapy import log
from scrapy.http import Request
from base.base_wolf import Base_Wolf
class Wolf(Base_Wolf):
def __init__(self, *args, **kwargs):
super(Wolf, self).__init__(*args, **kwargs)
self.name = 'henbt'
... | .compile(r'show-')
self.anchor['desc'] = "//*[@class='intro']"
def get_resource(self, item, response, tree):
item = super(Wolf, self).get_resource(item, response, tree)
resource = tree.xpath("//*[@class='original download']//a/@href")
downloads = [urlparse.urljoin(self.base_url, r)... | return self.download_bt(item, [Request(d, cookies=self.cookiejar._cookies,) for d in downloads])
else:
self.log("No Resource DropItem %s" % item['source'], level=log.WARNING)
return None
|
#! | /usr/bin/env python
#!-*- coding:utf-8 -*-
def read(filename):
dic=[]
with open(filename,'r') as fp:
while True:
lines = fp.readlines(100 | 00)
if not lines :
break
for line in lines:
#line = line.strip('\n')
dic.append(line)
return dic
def Write(file,dic):
with open(file,'w') as fp:
for i in dic:
fp.write(i)
if __name__=='__main__':
test = read('outpu... |
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright | 2013, 2014 Sourcefabric z.u. and contributor | s.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import superdesk
from .service import PackagesService
from .resource import PackagesResource
def init_app(app) -> None:
"""In... |
# 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"); you may not use ... | t2.TestCase):
@patch('st2common.runners.parallel_ssh.ParallelSSHClient', Mock)
@patch.object(jsonify, 'json_loads', MagicMock(return_value={}))
@patch.object(ParallelSSHClient, 'run', MagicMock(return_value={}))
@patch.object(ParallelSSHClient, 'connect', MagicMock(return_value={}))
def test_cwd_use... | y',
script_local_libs_path_abs=None,
named_args={}, positional_args=['blank space'], env_vars={},
on_behalf_user='svetlana', user='stanley',
private_key='---SOME RSA KEY---',
remote_dir='/tmp', hosts=['127.0.0.1'], cwd='/test/cwd/'
)
paramiko_r... |
# This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003-2008 Jan Decaluwe
#
# The myhdl library is free softwar | e; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WA... | ITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
... |
#!/usr/bin/env python
#__author__ = 'Andrew'
from acomms import micromodem, unifiedlog
import logging
from time import sleep
import argparse
if __name__ == '__main__':
ap = argparse.ArgumentParser(description ='Connect to a MM for testing purposes')
ap.add_argument("logpath", help="Location ... | rgs = ap.parse_args()
unified_log = unifiedlog.UnifiedLog(log_path=args.logpath, console_log_level=logging.INFO)
um1 = micromodem.Micromodem(name='Micromodem2',unified_log=unified_log)
um1.connect_serial(args.COM, args.Baudrate)
try:
while True:
... | )
finally:
um1.disconnect()
|
-*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | _pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output -------------------------------------... | -json-patch Documentation',
[u'Ashley Wilson'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, tit... |
#!/usr/bin/env python
'''
Use threads and Netmiko to connect to each of the devices. Execute
'show version' on each device. Record the amount of time required to do this.
'''
import threading
from datetime import datetime
from netmiko import ConnectHandler
from my_devices import device_list as devices
def show_ve | rsion(a_device):
'''Execute show version command using Netmiko.'''
remote_conn = ConnectHandler(**a_device)
print
print '#' * 80
print remote_conn.send_command_expect("show version")
print '#' * | 80
print
def main():
'''
Use threads and Netmiko to connect to each of the devices. Execute
'show version' on each device. Record the amount of time required to do this.
'''
start_time = datetime.now()
for a_device in devices:
my_thread = threading.Thread(target=show_version, args=... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : Omero RT
Description : Omero plugin
Date : August 15, 2010
copyright : (C) 2010 by Giuseppe Sucameli (Faunalia)
email : sucameli@faunalia.i... | == None:
return
self.emit( SIGNAL( "geometryEmitted" ), geometry )
def isActive(self):
return self.canvas != None and self.canvas.mapTool() == self.tool
def startCapture(self):
self.canvas.setMapTool( self.tool )
def stopCapture(self):
self.canvas.unsetMapTool( self.tool )
class Drawer(qgis.gui.QgsMa... | canvas)
self.rubberBand = qgis.gui.QgsRubberBand( self.canvas, self.isPolygon )
self.rubberBand.setColor( Qt.red )
self.rubberBand.setBrushStyle(Qt.DiagCrossPattern)
self.rubberBand.setWidth( 1 )
# imposta lo snap a snap to vertex with tollerance 0.9 map units
customSnapOptions = { 'mode' : "to vert... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
parse_duration,
parse_iso8601,
)
class HuajiaoIE(InfoExtractor):
IE_DESC = '花椒直播'
_VALID_URL = r'https?://(?:www\.)?huajiao\.com/l/(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.h... | ion': 2424.0,
'thumbnail': r're:^https?://.*\.jpg$',
| 'timestamp': 1475866459,
'upload_date': '20161007',
'uploader': 'Penny_余姿昀',
'uploader_id': '75206005',
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
feed_json = self._search... |
import _plotly_utils.basevalidators |
class A0Validator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, p | lotly_name="a0", parent_name="carpet", **kwargs):
super(A0Validator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs
)
|
from ... import BaseProvider
class Provider(BaseProvider):
"""
Provider for Philippine IDs that are related to social security
There is no unified social security program in the Philippines. Instead, the Philippines has a messy collection of
social programs and IDs that, when put together, serves as ... | assistance and loaning program
- Philippine Health Insurance Corporation (PhilHeal | th) - Social insurance program for health care
- Unified Multi-Purpose ID (UMID) - Identity card with common reference number (CRN) that serves as a link to
the four previous programs and was planned to supersede the previous IDs, but
i... |
# -*- codin | g: utf-8 -*-
# This file is meant to test that we can also load rules from __init__.py files, this was an issue with pypy before.
from gitlint.rules import CommitR | ule
class InitFileRule(CommitRule):
name = "my-init-cömmit-rule"
id = "UC1"
options_spec = []
def validate(self, _commit):
return []
|
<resOverlayFolders />
<includeSystemProguardFile>false</includeSystemProguardFile>
<includeAssetsFromLibraries>true</includeAssetsFromLibraries>
<additionalNativeLibs />
</configuration>
</facet>
</component>"""
ALL_MODULES_XML_START = """<?xml version="1.0" encoding="UTF-8"?>... | package_prefix = ''
xml += '\n <sourceFolder url="%(url)s" isTestSource="%(is_test_source)s" %(package_prefix)s/>' % {
'url': source_folder['url'],
'is_test_source': str(source_folder['isTestSource']).lower(),
'package_prefix': package_prefix
}
... | ted_source_folder(xml, module)
# Empirically, if there is one source folder, then the <content> element for the
# buck-out/android/gen folder should be listed after the other source folders.
if num_source_folders <= 1:
xml = add_buck_android_source_folder(xml, module)
# Dependencies.
depende... |
# Generated by Django 2 | .0.2 on 2018-03-13 02:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cc', '0003_auto_20180228_1145'),
]
operations = [
migrations.AlterField(
model_name='creditcard',
name='tail_no',
field=models.... | ),
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""extends the standard Python gettext classes
allows multiple simultaneous domains... (makes multiple sessions with different languages easier too)"""
# Copyright 2002, 2003 St James Software
#
# This file is part of jToolkit.
#
# jToolkit is free software; you can redi... | age):
"""gets the translation of the message by searching through all the domains"""
for | translation in self.translations:
tmsg = translation._catalog.get(message, None)
if tmsg is not None:
return tmsg
return message
def ngettext(self, singular, plural, n):
"""gets the plural translation of the message by searching through all the domains"""
for translation in self.tran... |
import sys
imp | ort cv2
import helper as hp
class MSP():
name = "MSP"
def __init__(self):
self.__patterns_num = []
self.__patterns_sym = []
self.__labels_num = []
self.__labels_sym = []
msp_num, msp_sym = "msp/num", "msp/sym"
self.__load_num_patterns(msp_num)
self.__lo... | aths = hp.get_paths(input_dir)
self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths]
self.__labels_num = [hp.get_test(path, "num")[0] for path in paths]
def __load_sym_patterns(self, input_dir):
paths = hp.get_paths(input_dir)
self.__patterns_sym = [hp.get_gra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.