prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from typing import Optional, Dict, Union, List
from .singleton import Singleton
class Arguments(metaclass=Singleton):
"""
Arguments singleton
"""
class Name:
SETTINGS_FILE: str = 'settings_file'
SETTINGS: str = 'settings'
INIT: str = 'init'
VERBOSE: str = 'verbose'
... | [Arguments.Name.CLIENT_SECRET]
self.oauth_token: Optional[str] = None
self.first: Optional[int] = arguments[Arguments.Name.FIRST]
self.timezone: Optional[str] = arguments[Arguments.Name.TIMEZONE]
self.includes: Optional[str] = arguments[Arguments.Name.INCLUDES]
# Arguments that ... | f.video_ids: List[int] = []
self.formats: List[str] = []
self.channels: List[str] = []
self.users: List[str] = []
# Videos
if arguments[Arguments.Name.VIDEO]:
self.video_ids = [int(video_id) for video_id in arguments[Arguments.Name.VIDEO].lower().split(',')]
... |
d have received a copy of the GNU Lesser General Public
# License along with MDTraj. If not, see <http://www.gnu.org/licenses/>.
##############################################################################
# part of the code below was taken from `openpathsampling` see
# <http://www.openpathsampling.org> or
# <http:/... | n
Parameters
----------
dct : dict
the dictionary containing a state representation of the class.
Returns
-------
:class:`StorableMixin`
the reconstructed storable object
"""
| if dct is None:
dct = {}
if hasattr(cls, 'args'):
args = cls.args()
init_dct = {key: dct[key] for key in dct if key in args}
try:
obj = cls(**init_dct)
if cls._restore_non_initial_attr:
non_init_dct = {
... |
# -*- coding: utf-8 -*-
#抓取网易公开课链接并下载对应的相视频名称和视频格式
#By | : obnjis@163.com
#Python 2.7 + BeautifulSoup 4
#2014-12-18
#断点续传功能等待下一版本
#eg: python 163—video.py http://v.163.com/special/opencourse/ios7.html
from bs4 | import BeautifulSoup
import re
import sys,os
import urllib
import codecs
#显示百分比
def rpb(blocknum, blocksize, totalsize):
percent = 100.0 * blocknum * blocksize / totalsize
if percent > 100:percent = 100
#格式化输出下载进度
sys.stdout.write("'[%.2f%%] \r" % (percent) )
#让下载百分比再同一行不断刷新,不需要换行
sys.stdout.fl... |
"""
The "travel from home to the park" example from my lectures.
Author: Dana Nau <nau@cs.umd.edu>, May 31, 2013
This file should work correctly in both Python 2.7 and Python 3.2.
"""
import pyhop
import random
import sys
from utils_plan import *
fr | om util_plot import *
# state variables
state1 = pyhop.State('state')
state1.status = 3
state1.concepts = ["Concept A", "Concept B", "Concept C"]
state1.relations = ["Relation | A", "Relation B", "Relation C"]
state1.concepts_heard_count = [0,0,0]
state1.relations_heard_count = [0,0,0]
state1.variables = pyhop.State('variables')
state1.variables.affect = pyhop.State('affect')
state1.variables.affect.skill = 0
state1.variables.affect.challenge = 0
state1.variables.affect.boredom = 2
state1.vari... |
# -*- coding: utf-8 -*-
from Scraping4blog import Scraping4blog
import sys,os
sys.path.append(os.path.dir | name(os.path.abspath(__file__)) + '/../util')
from settings import SettingManager
def main():
conf = SettingManager()
instance = Scraping4blog(conf)
instance.run()
if __name__ | == "__main__":
main()
|
'''OpenGL extension OES.blend_subtract
This module customises the behaviour of the
OpenGL.raw.GLES1.OES.blend_subtract to provide a more
Python-friendly API
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/OES/blend_subtract.txt
'''
from OpenGL import platform, const... | eturn boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtensio | n( _EXTENSION_NAME )
### END AUTOGENERATED SECTION |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module is Copyright (c) 2009-2013 General Solutions (http://gscom.vn) All Rights Reserved.
#
# This program is free software: you can redistribute it and/or... | out 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
####################... | #####
{
"name" : "Vietnam Chart of Accounts",
"version" : "1.0",
"author" : "General Solutions",
'website': 'http://gscom.vn',
"category" : "Localization/Account Charts",
"description": """
This is the module to manage the accounting chart for Vietnam in OpenERP.
===============================... |
# -*- coding: utf-8 -*-
# Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the
# University of Virginia, University of Heidelberg, and University
# of Connecticut School of Medicine.
# All rights reserved.
# Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
# Properties, Inc.,... | .TestSuite(map(Test_CReport,tests))
if(__name__ == '__main__'):
unittest | .TextTestRunner(verbosity=2).run(suite())
|
import os, sys
from mod_python import util, Cookie
def _path(): return '/'.join(os.path.realpath(__file__).split('/')[:-1])
if _path() not in sys.path: sys.path.insert(0, _path())
def _load(req, page, dev= False):
"""
if not dev:
branch= 'html'
page= 'maintenance'
f= open('%s/%s/%s.html' %(_path(), branch, p... | t((item.split('=') for item in req.subprocess_env['QUERY_STRING'].split('&')))
page= params['page']
return _load(req, page, dev= True)
#def client(req): ret | urn _load(req, 'client') |
#
# Author: Henrique Pereira Coutada Miranda
# Example script to plot the weigth of the atomic species in the bandstructure
#
from qepy import *
import sys
import argparse
import matplotlib.pyplot as plt
folder = 'bands'
npoints = 20
p = Path([ [[0.0, 0.0, 0.0],'G'],
[[0.5, 0.0, 0.0],'M'],
[[1.... | ,10))
for n,(orb,title) in enumerate(zip([mo,s,mo+s],['mo','s','mos2'])):
ax = plt.subplot(1,3,n+1)
| plt.title(title)
pxml.plot_eigen(ax,path=p,selected_orbitals=orb,size=40)
ax.set_ylim([-7,6])
plt.show()
if args.plot_orbital:
pxml = ProjwfcXML('mos2',path=folder)
print pxml
# select orbitals to plot
# example1 mo, s2
mo = list(xrange(16)) #list containing the indexes o... |
#!/usr/bin/env python3
# Copyright (C) 2020-2021 The btclib developers
#
# This file is part of btclib. It is subject to the licen | se terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed exce | pt according to the terms contained in the LICENSE file.
"""btclib.bip32 non-regression tests."""
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 27 01:20:46 2016
@author: caioau
"""
import matplotlib.pyplot as plt
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
def main():
G = nx.DiGraph() # G eh um grafo direcionado
# gera o grafo apartir de suas are... | isso?
nx.draw_networkx_edges(G,pos, edge_color=colors) # desenha as arestas
nx.draw_networkx_labels(G,pos) # desenha os labels das arestas
nx.draw_networkx_edge_labels(G,pos,edge_label | s=edge_labels) # desenha os labels dos nos
nx.draw_networkx_nodes(G,pos,node_color='w') # desenha os nos
plt.axis('off') # desativa os eixos
plt.savefig(pngfilename)
plt.close("all")
if __name__ == "__main__":
main()
|
impo | rt builtins
# exec being part of builtins is Python 3 only
builtins | .exec("print(42)") # $getCode="print(42)"
|
#!/usr/bin/env python
from __future__ import print_function
from molmod import *
# 0) Load the molecule and set the default graph
mol = Molecule.from_file("dopamine.xyz" | )
mol.set_default_graph()
# 1) Build a list of atom indexes involved in angles.
angles = []
# First loop over all atoms on the molecule.
for i1 in range(mol.size):
# For each atom we will find all bending angles centered at the current
# atom. For this we construct (an ordered!) list of all bonded neighbors.
... | ndex, i0 in enumerate(n):
# The third loop iterates over all other neighbors that came before i1.
for i2 in n[:index]:
# Each triple is stored as an item in the list angles.
angles.append((i0, i1, i2))
# 2) Iterate over all angles, compute and print.
print("An overview of all be... |
import sys
from typing import List
from .device import Device
from .enumeratehelper import EnumerateHelper
class DeviceManager(object):
__instance = None
@classmethod
def instance(cls):
if cls.__instance is None:
helper = EnumerateHelper()
cls.__instance = cls(helper)
... | evice = Device()
device.name = event["name"]
device.id = event["id"]
device.type = Device.TYPE_KEYBOARD
self.devices.append(device)
print("[INPUT] Keyboard device added:", device.name)
return de | vice
def add_mouse_device(self, event):
device = Device()
device.name = event["name"]
device.id = event["id"]
device.type = Device.TYPE_MOUSE
self.devices.append(device)
print("[INPUT] Mouse device added:", device.name)
return device
def remove_all_devic... |
r.state_methods():
# we search up to the To
end = self.statePattern.search (stateGroup[0]).start ()
# so we turn SetBlaatToOne to GetBlaat
get_m = 'G'+stateGroup[0][1:end]
# we're going to have to be more clever when we set_config...
... | gh at least the attributes in self._vtkObjectNames
for vtkObjName in self._vtkObjectNames:
try:
vtkObjPD = getattr(self._config, vtkObjName)
vtkObj = getattr(self, vtkObjName)
except AttributeError:
print "PickleVTKObjectsModuleMixin: %s n... | for method, val in vtkObjPD[0]:
if val:
eval('vtkObj.%s()' % (method,))
else:
# snip off the On
eval('vtkObj.%sOff()' % (method[:-2],))
for stateGroup, val in vtkObjPD[1]:
... |
from bluepy.btle import *
import time
import serial
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
start_time = time.time()
data = []
data2 = []
data3 = []
data4 = []
angles = []
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
pen = pg.mkPen('k', width=8)
app = QtGui.QAppl... | .setData(x[-50:-1], angles2[-50:-1])
app.processEvents()
timer = QtCore.QTimer()
timer.t | imeout.connect(update)
timer.start(0)
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_() |
import os
import urllib2
import json
import re
##### Convert a name to a variable name
def cleanName(name):
return re.sub('[\W_]+', '', name.replace('&','And'))
##### Load the categories endpoint
file = urllib2.urlopen('http://api.simplegeo.com/1.0/features/categories.json')
contents = json.loads(file.read())
... | tegory;\n\
typedef NSString * SGFeatureSubcategory;\n'
# Feature types
output += '\n#pr | agma mark Feature Types\n\n'
for typ in types:
output += '#define SGFeatureType' + cleanName(typ) + ' @\"' + typ + '\"\n'
# Feature categories (Context)
output += '\n#pragma mark Feature Categories (Context)\n\n'
for cat in fcats:
output += '#define SGFeatureCategory' + cleanName(cat) + ' @\"' + cat + '\"\n'
... |
import praw
import codecs
import unidecode
import os
import requests
import datetime
import regex as re
from collections import Counter
import RAKE
Rake = RAKE.Rake('foxstoplist.txt')
try:
requests.packages.urllib3.disable_warnings()
except:
pass
subreddits = ["earthporn", "japanpics"]
class redditLogger:
... | p_from_all(limit=None)
submissions = set()
for s in (atop,):
for link in s:
submissions.add(link)
titles = list()
for each in submissions:
t = self.generateName(each)
#self.upGoerFive(titles)
def generateName(self, sub):
rawti... | '\n',]
blanksubs = [
'[\[\(].*[\)\]]',
'/r/.*',
'[0-9]',
'photo.* ',
'o[cs]']
for pattern in spacesubs:
rawtitle = re.sub(pattern, ' ', rawtitle)
for pattern in blanksubs:
rawtitle = re.sub(pattern, '', rawtitle)... |
from __future__ import absolute_import
|
from django.conf.urls import patterns, include, url
from .views import Handler
handler = Handler.as_view()
urlpatterns = patterns('',
url(r'^$', handler, name= | 'feincms_home'),
url(r'^(.*)/$', handler, name='feincms_handler'),
)
|
#TODO replace RPSGame with this class(for clarity)
__author__ = "Paul Council, Joseph Gonzoph, Anand Patel"
__version__ = "sprint1"
__credits__ = ["Greg Richards"]
# imports
from ServerPackage import Game
class RockPaperScissors(Game.Game):
""" this class simulates two players playing a game of rock, paper, sci... | wo_move != 1) \
or (player_one_move == 1 and player_two_move != 2) \
or (player_one_move == 2 and player_two_move != 0):
# result is tuple with points each player has earned respectively
result = (1, 0)
| else:
result = (0, 1)
elif move_one_legal and not move_two_legal:
result = (1, 0)
elif not move_one_legal and move_two_legal:
result = (0, 1)
else:
result = (0, 0)
return result
def is_legal(self, move):
"""
C... |
import os
import sys
class Widget(object):
"" | "
Widget is a User Interface (UI) component object. A widget
object claims a rectagular region of its content, is responsible
for all drawing within that region.
"""
def __init__(self, name, width=50, height=50):
self.name = name
self.resize(width, height)
def size(self):
... | ght = width, height |
# -*- coding: utf-8 -*-
#
# | Copyright (C) 2011-2012 Charles E. Vejnar
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#
"""
Interface classes with the `Vienna RNA <http://www.tbi.univie.ac.at/RNA>`
executable programs.
"""
import re
import subprocess
import tempfile
try:
from... | xcept ImportError:
#: Workaround for Python2.
#: http://stackoverflow.com/a/9877856
import os
def which(pgm):
path = os.getenv('PATH')
for p in path.split(os.path.pathsep):
p = os.path.join(p, pgm)
if os.path.exists(p) and os.access(p, os.X_OK):
return p
class RNAvienna(object):
... |
from rlpy.Representations import IndependentDiscretization
from rlpy.Domains import GridWorld, InfiniteTrackCartPole
import numpy as np
from rlpy.Tools import __rlpy_location__
import os
def test_number_of_cells():
""" E | nsure create appropriate # of cells (despite ``discretization``) """
mapDir = os.path.join(__rlpy_location__, "Domains", "GridWorldMaps")
mapname=os.path.join(mapDir, "4x5.txt") # expect 4*5 = 20 states
domain = GridWorld(mapname=mapname)
rep = IndependentDiscretization(domain, discretization=100)
... | st_phi_cells():
""" Ensure correct features are activated for corresponding state """
mapDir = os.path.join(__rlpy_location__, "Domains", "GridWorldMaps")
mapname=os.path.join(mapDir, "4x5.txt") # expect 4*5 = 20 states
domain = GridWorld(mapname=mapname)
rep = IndependentDiscretization(domain)
... |
from mieli.api import organization
from django.db import transaction
from django.conf import settings
from agora.api import link
@transaction.atomic
def create(user, **kwargs):
org = organization.get_by_username(user.username)
if org == None:
raise Exception("unknown organization for user '%s'" % user.... | ] = user.email
kwargs['first_name'] = 'Mieli user'
kwargs['__auth'] = True
r = lnk.post('user/register', **kwargs)
if 'errors' in r:
raise Exception(r['errors'])
login_kwargs = {}
login_kwargs['identification'] = kwargs['username']
login_kwargs['password'] = kwargs['password2']
l... | er'] = kwargs['username']
link_kwargs['token'] = login_['apikey']
link.create(org.domain, **link_kwargs)
def login(lnk, identification, password=settings.AGORA_DEFAULT_KEY):
return lnk.post('user/login', identification=identification, password=password, __session=True)
@transaction.atomic
def delete(user,... |
import multiprocessing
import numpy as np
def configure(num_jobs=8, TEST=False, subtract=0, num_proc=None, num_thread_per_proc=None):
'''
num_jobs is typically the # of genes we are parall | elizing over
'''
if num_proc is None:
num_proc = multiprocessing.cpu_count() - subtract
if num_jobs > num_proc:
num_jobs = num_proc
if num_threa | d_per_proc is None:
num_thread_per_proc = int(np.floor(num_proc/num_jobs))
if TEST:
num_jobs = 1
num_thread_per_proc = 1
try:
import mkl
mkl.set_num_threads(num_thread_per_proc)
except ImportError:
print "MKL not available, so I'm not adjusting the numbe... |
(self, key, item):
super().__setitem__(key, item)
if key not in self._keys:
self._keys.append(key)
x = C(d={'foo':0})
y = copy.deepcopy(x)
self.assertEqual(x, y)
self.assertEqual(x._keys, y._keys)
self.assertIsNot(x, y)
... | .assertEqual(x, y)
def test_copy_copy(self):
class C(object):
def __init__(self, foo):
self.foo = foo
def __copy__(self):
return C(self.foo)
x = C(42)
y = copy.copy(x)
self.assertEqual(y.__class__, x.__class__)
| self.assertEqual(y.foo, x.foo)
def test_copy_registry(self):
class C(object):
def __new__(cls, foo):
obj = object.__new__(cls)
obj.foo = foo
return obj
def pickle_C(obj):
return (C, (obj.foo,))
x = C(42)
sel... |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# 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 appli | cable 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 permissions and
# limitations under the License.
import hashlib, os
from .mai... | e = 'test{}'.format(i)
print(name)
dir = os.path.join('tests', name)
rawdex = read(os.path.join(dir, 'classes.dex'), 'rb')
for bits in range(256):
opts = options.Options(*[bool(bits & (1 << b)) for b in range(8)])
classes, errors = translate(rawdex, opts=opts)
assert not errors
... |
event, bb.runqueue.runQueueExitWait):
if not main.shutdown:
main.shutdown = 1
continue
if isinstance(event, bb.event.LogExecTTY):
if log_exec_tty:
tries = event.retries
while tries:
... | of %d (%s)" % (event.stats.completed + event.stats.active + event.stats.failed + 1, event.stats.total, event.taskstring))
continue
if isinstance(event, bb.runqueue.runQueueTaskStarted):
if event.noexec:
tasktype = 'noexec task'
else:
... | %d (%s)",
tasktype,
event.stats.completed + event.stats.active +
event.stats.failed + 1,
event.stats.total, event.taskstring)
continue
if isinstance(event, bb.runqueue.runQueu... |
import pygame
import numpy
def add_noise(surface):
mask = surface.copy()
mask.set | _colorkey((255,255,255))
screen_array = pygame.surfarray.pixels3d(surface)
noise = numpy.random.random((surface.get_width(), s | urface.get_height())) * 255
screen_array *= noise[:, :, numpy.newaxis]
del screen_array
surface.blit(mask, (0,0))
surface = mask
|
from pyvows import Vows, expect
from minopt import minopt
@Vows.batch
class Minopt(Vows.Context):
def topic(self):
return minopt(['--baz', 'hello', '--foo', 'bar', '-baz',
'--riff=wobble', '--hey', '-ho', 'world'],
{' | string': ['a', 'hey', 'w'],
'boolean': ['baz', 'h', 'o', 'q']})
def should_parse_long_arguments(self, topic):
expect(topic['foo']).to_equal('bar')
expect(topic['riff']).to_equal('wobble')
def should_parse_short_arguments(self, topic):
expected = (True, True)
... | e_true()
expect(topic['h']).to_be_true()
expect(topic['o']).to_be_true()
def should_parse_strings(self, topic):
expect(topic['a']).to_be_empty()
expect(topic['hey']).to_be_empty()
def should_parse_unnamed_args(self, topic):
expect(topic['_']).to_equal(['hello', 'world']... |
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
# pylint: disable=W0212,W0613
from twisted.internet.defer import Deferred, DeferredList
from twisted.python.failure import Failure
from twisted.trial.unittest import TestCase
import smartanthill.litemq.exchange as ex
from smartanthill.exceptio... | t": ex.ExchangeFanout}.items():
self.assertIsInstance(
ex.ExchangeFactory().newExchange("exchange_name", type_),
class_
)
| self.assertRaises(
AttributeError,
lambda: ex.ExchangeFactory().newExchange("exchange_name",
"unknown-type")
)
def test_queue_ack_success(self):
message, properties = "Test message", {"foo": "bar"}
def _ca... |
phonenumber',
"Work phone": 'phonenumber',
"HomeStreet": 'address',
"HomePostalCode": 'address',
"HomeCity": 'address',
"HomeCountry": 'address',
"HomeState": 'address',
"Organisation": 'text',
"BusinessPostalCode": 'address',
"BusinessStreet": 'address',
"BusinessCity"... | self._ | extractValue(atts, 'mobile', contactObject, 'Phone')
if not atts['mobile']:
self._extractValue(atts, 'mobile', contactObject, 'Mobile phone')
self._extractValue(atts, 'phone', contactObject, 'Home phone')
self._extractValue(atts, 'officePhone', contactObject, 'Work ph... |
3,
'LOGOUT' : 0x04,
'GET_USER' : 0x05,
'GET_ONLINE_USER' : 0x06,
'GET_USER_INFO' : 0x07,
'GET_GROUP' : 0x08,
'GET_GROUP_INFO' : 0x09,
'SEND_MSG' : 0x0A,
'REPLY_MSG' : 0x0B,
'SEND_GMSG' : 0x0C,
'REPLY_GMSG' : 0x0D,
'END' : 0xFF
}
# user and group i... | == COMMANDS['LOGOUT']:
pass
elif cmd == COMMANDS['GET_USER']:
client.stk_getuser_ack(data)
elif cmd == COMMANDS['GET_ONLINE_USER']:
client.stk_getonlineuser_ack(data)
elif cmd == COMMANDS['GET_USER_INFO']:
client.stk_getuserinfo_ack(data)
elif cmd == COMMANDS['GET_GROUP']:
client.stk_get... | ta)
elif cmd == COMMANDS['REPLY_MSG']:
pass
|
the httplib_ssl.py file pointing '
'to a file which contains a list of trusted CA '
'certificates')
self.client_id = client_id
self.key = base64.b64decode(key) if key is not None else None
self.use_https = use_https
self.verify_cer... | start_time = time.time()
while threads and (start_time + timeout) > time.time():
for thread in threads:
if not thread.is_alive() and thread.response:
status = self.verify_response(thread.response,
return_respo... | e)
if status:
if return_response:
return status
else:
return True
threads.remove(thread)
# Timeout or no valid response received
raise Exception('NO_VALID_ANS... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import json
import urllib
import urllib2
import sys
con = None
con = psycopg2.connect("host='54.227.245.32' port='5432' dbname='pmt' user='postgres' password='postgres'")
cnt = 0
sqlFile = sys.argv[1]
print 'Argument List:', str(sys.argv[1])
t | ry:
cur = con.cursor()
for line in file(sqlFile, 'r'):
cnt = cnt + 1
cur | .execute(line.strip())
print cnt
con.commit()
except Exception, e:
print 'Error %s' % e
finally:
if con:
con.close()
|
n. "Deep Residual Learning for Image Recognition"
'''
import mxnet as mx
def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=256, memonger=False):
"""Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
nu... | x.sym.Convolution(data=act2, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True,
workspace=workspace, name=name + '_conv3')
bn3 = mx.sym.BatchNorm(data=conv3, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3')
if dim_match:
... | (1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_conv1sc')
shortcut = mx.sym.BatchNorm(data=conv1sc, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc')
if memonger:
shortcut._set_attr(mirror_stage='True')
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core | .exceptions import ValidationError
from django.forms.util import flatatt, ErrorDict, ErrorList
from django.test import | TestCase
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy
class FormsUtilTestCase(TestCase):
# Tests for forms/util.py module.
def test_flatatt(self):
###########
# flatatt #
###########
self.assertEqual(flatatt({'id': "head... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | timizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python.client import session
from tensorflow.python.fr | amework import constant_op
from tensorflow.python.framework import random_seed
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import test
def weight(shape):
"""weights generates a weight of a given shape."... |
"""United States Macroeconomic data"""
__docformat__ = 'restructuredtext'
COPYRIGHT = """This is public domain."""
TITLE = __doc__
SOURCE = """
Compiled by Skipper Seabold. All data are from the Federal Reserve Bank of St.
Louis [1] except the unemployment rate which was taken from the National
Bureau of... | realdpi - Real gross private domestic investment (Bil. of chained 2005
US$, seasonally adjusted annual rate)
cpi - End of the quarter consumer pr | ice index for all urban
consumers: all items (1982-84 = 100, seasonally adjusted).
m1 - End of the quarter M1 nominal money stock (Seasonally adjusted)
tbilrate - Quarterly monthly average of the monthly 3-month treasury bill:
secondary market rate
unemp - Seasona... |
import logging
import os
from autotest.client.shared import error
from virttest import data_dir
@error.context_aware
def run_kexec(test, params, env):
"""
Reboot to new kernel through kexec command:
1) Boot guest with x2apic cpu flag.
2) Check x2apic enabled in guest if need.
2) Install a new kern... | logging.info("Current kernel is: %s" % cur_kernel_version)
cmd = params.get( | "check_installed_kernel")
output = session.cmd_output(cmd, timeout=cmd_timeout)
kernels = output.split()
new_kernel = None
for kernel in kernels:
kernel = kernel.strip()
if cur_kernel_version not in kernel:
new_kernel = kernel[7:]
if not new_kernel:
raise error.Te... |
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Ignore indention messages, since legacy scripts use 2 spaces instead of 4.
# pylint: disable=bad-indentation,docstring-section-indent
# pylint: disable... | interface=self._interface,
serialname=self._serial,
debuglog=self._debug)
self.suart.run()
self.pty = pty_driver.ptyDriver(self.suart, [])
def reinitialize(self):
"""Reinitialize the connect after a reset/discon | nect/etc."""
self.close()
self._init()
def close(self):
"""Close out the connection and release resources.
Note: if another TinyServod process or servod itself needs the same device
it's necessary to call this to ensure the usb device is available.
"""
self.suart.close()
|
# Copyright 2019 Oihane Crucelaegui - AvanzOSC
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from datetime import datetime, timedelta
from pytz import timezone, utc
from odoo import api, fields, models
class ResourceCalendar(models.Model):
_inherit = 'resource.calendar'
hour_gap = f... | r_gap(self):
today = fields.Date.context_today(self)
year, week_num, day_of_week = today.isocalendar()
start_dt = datetime.strptime(
| '{}-W{}-1'.format(year, week_num-1), "%Y-W%W-%w").replace(
tzinfo=utc)
end_dt = start_dt + timedelta(days=7, seconds=-1)
for record in self:
# Set timezone in UTC if no timezone is explicitly given
if record.tz:
tz = timezone((record or self).tz)
... |
# coding: utf-8
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from registration import forms as registration_forms
from kobo.static_lists import SECTORS, COUNTRIES
USERNAME_REGEX = r'^[a-z][a-z0-9_]+$'
USERNAME_MAX_LENGTH = 30
USERNAME_INV... | s.RadioSelect,
choices=(
('male', _('Male')),
('female', _('Female')),
('other', _('Other')),
)
)
sector = forms.ChoiceField(
label=_('Sector'),
required=False,
choices=(('', ''),
) + SECTORS,
)
... | '),) + COUNTRIES,
)
class Meta:
model = User
fields = [
'name',
'organization',
'username',
'email',
'sector',
'country',
'gender',
# The 'password' field appears without adding it here; adding it
... |
# | -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-04-23 05:02
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wallet', '0002_auto_20160418_0334'),
]
operations = [
migrations.RenameField(
... | lletmasterkeys',
old_name='encrypted_seed',
new_name='encrypted_mnemonic',
),
]
|
#from satpy import Scene
from satpy.utils import debug_on
debug_on()
#from glob import glob
#base_dir="/data/COALITION2/database/meteosat/radiance_HRIT/case-studies/2015/07/07/"
#import os
#os.chdir(base_dir)
#filenames = glob("*201507071200*__")
#print base_dir
#print filenames
##global_scene = Scene(reader="hrit_ms... | BWCompositor("test", standard_name="ndvi")
composite = compositor((local_scene["ndvi"], ))
img = to_image(composite)
#from trollimage import colormap
#dir(colormap)
# 'accent', 'bl | ues', 'brbg', 'bugn', 'bupu', 'colorbar', 'colorize', 'dark2', 'diverging_colormaps', 'gnbu', 'greens',
# 'greys', 'hcl2rgb', 'np', 'oranges', 'orrd', 'paired', 'palettebar', 'palettize', 'pastel1', 'pastel2', 'piyg', 'prgn',
# 'pubu', 'pubugn', 'puor', 'purd', 'purples', 'qualitative_colormaps', 'rainbow', 'rd... |
# 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 t... | ypoint name.
:param str name: The name of the object to get.
:returns: An auth plugin class.
:rtype: :py:class:`keystoneauth1.loading.BaseLoader`
:raises keystonauth.exceptions.NoMatchingPlugin: if a plugin cannot be
created.
"""
try:
... | voke_on_load=True,
name=name)
except RuntimeError:
raise exceptions.NoMatchingPlugin(name)
return mgr.driver
def get_plugin_options(name):
"""Get the options for a specific plugin.
This will be the list of options that is registered and loaded by the
... |
# Copyright (c) 2015-2016 Western Digital Corporation or its affiliates.
#
# 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 versio... | t__(self)
self.data_size = 1024
self.start_block = 1023
self.setup_log_dir(self.__class__.__name__)
self.compare_file = self.test_log_dir + "/" + "compare_file.txt"
| self.write_file = self.test_log_dir + "/" + self.write_file
self.create_data_file(self.write_file, self.data_size, "15")
self.create_data_file(self.compare_file, self.data_size, "25")
def __del__(self):
""" Post Section for TestNVMeCompareCmd """
TestNVMeIO.__del__(self)
d... |
#!/usr/bin/env python
impor | t os
from django.core import management
os.environ['DJANGO_SETTINGS_MODULE'] = 'kgadmin.conf.settings'
if __name__ == "__main__":
management.execute_from | _command_line()
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from wtforms import validators
from jinja2 import Markup
from studio.core.engines import db
from riitc.models import NaviModel, ChannelModel
from .base import BaseView
from .forms import CKTextAreaField
class Navi(BaseView):
column_labels = {'name... | .edit_form(obj=obj)
delattr(form, 'articles')
delattr(form, 'channels')
| delattr(form, 'all_articles')
delattr(form, 'date_created')
return form
|
from _ | _future__ import unicode_literal | s
from django.apps import AppConfig
class IngestConfig(AppConfig):
name = 'ingest'
|
1
from onshape_client.oas.model_utils import ( # noqa: F401
ModelComposed,
ModelNormal,
ModelSimple,
date,
datetime,
file_type,
int,
none_type,
str,
validate_get_composed_info,
)
try:
from onshape_client.oas.models import btm_parameter_boolean144_all_of
except ImportError:... | a: E501
"value": (bool,), # noqa: E501
"atomic": (bool,), # noqa: E501
"documentation_type": (str,), # noqa: E501
"end_source_location": (int,), # noqa: E501
"node_id": (str,), # noqa: E501
"short_descriptor": (str,), # noqa: E501
| "space_after": (btp_space10.BTPSpace10,), # noqa: E501
"space_before": (btp_space10.BTPSpace10,), # noqa: E501
"space_default": (bool,), # noqa: E501
"start_source_location": (int,), # noqa: E501
}
@staticmethod
def discriminator():
return Non... |
va(self):
import omero.cli
import omero.java
# Copied from db.py. Needs better dir detection
cwd = omero.cli.CLI().dir
server_jar = cwd / "lib" / | "server" / "server.jar"
cmd = ["ome.services.util.JvmSettingsCheck", "--psutil"]
p = omero.java.popen(["-cp", str(server_jar)] + cmd)
o, e = p.communicate()
if p.poll() != 0:
LOGGER.warn("Failed to invoke java:\nout:%s\nerr:%s",
| o, e)
rv = dict()
for line in o.split("\n"):
line = line.strip()
if not line:
continue
parts = line.split(":")
if len(parts) == 1:
parts.append("")
rv[parts[0]] = parts[1]
try:
... |
#!/usr/bin/env python
"""
Input: fasta, int
Output: tabular
Return titles with lengths of corresponding seq
"""
import sys
assert sys.version_info[:2] >= ( 2, 4 )
def compute_fasta_length( fasta_file, out_file, keep_first_char, keep_first_ | word=False ):
infile = fasta_file
| out = open( out_file, 'w')
keep_first_char = int( keep_first_char )
fasta_title = ''
seq_len = 0
# number of char to keep in the title
if keep_first_char == 0:
keep_first_char = None
else:
keep_first_char += 1
first_entry = True
for line in open( infile ):
lin... |
class User(object):
_instance = None
def __new__(cls, *args):
if not cls._instance:
cls._instance = super(User, cls).__new__(cls, *args)
return cls._instance
@property
def is_authenticated(self) | :
return True
@property
def is_active(self):
return True
@property
def is_anonymous(self):
return False
@staticmethod
def get_id():
return '1'
@staticmethod
def g | et_by_id(*args):
return User()
|
import tkinter as tk
from .convertwidget import ConvertWidget
class SpeedWidget(ConvertWidget):
"""Widget used to convert weight and mass units
Attributes:
root The Frame parent of the widget.
| """
def __init__(self, root):
super(SpeedWidget, | self).__init__(root)
self.root = root
self._init_frames()
self._init_binds()
def _init_frames(self):
# Creation of the main frame
f_main = tk.Frame(self.root)
f_main.pack(fill="both", expand="yes", side=tk.TOP)
def _init_binds(self):
pass
if __name__ =... |
# Copyright 2014 PerfKitBenchmarker Authors. All rights reserved.
#
# 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 appli... | 'Additional paths to search for data files. '
'These paths will be searched prior to using files '
'bundled with PerfKitBenchmarker.')
_RESOURCES = 'resources'
class ResourceNotFound(ValueError):
"""Error raised when a resource could not be fo... | ""An interface for loading named resources."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def ResourceExists(self, name):
"""Checks for existence of the resource 'name'.
Args:
name: string. Name of the resource. Typically a file name.
Returns:
A boolean indicating whether the reso... |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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,
... | t.run()
output = "myrpcgen.py %s -o %s rpcif.x\nmyrpcgen.py\n"
expect_clnt = output % ('-l', test.workpath('rpcif_clnt.c'))
e | xpect_h = output % ('-h', test.workpath('rpcif.h'))
expect_svc = output % ('-m', test.workpath('rpcif_svc.c'))
expect_xdr = output % ('-c', test.workpath('rpcif_xdr.c'))
test.must_match('rpcif_clnt.c', expect_clnt)
test.must_match('rpcif.h', expect_h)
test.must_match('rpcif_svc.c', expect_svc)
test.must_match('rpcif_x... |
# -*- coding: utf-8 -*-
# Copyright 2012 Jaap Karssenberg <jaap.karssenberg@gmail.com>
import gtk
from zim.fs import TrashNotSupportedError
from zim.config import XDG_DATA_HOME, data_file
from zim.templates import list_template_categories, list_templates
from zim.gui.widgets import Dialog, BrowserTreeView, Button, ... | et_sensitive(custom is not None)
if custom is None:
return
if not custom.exists():
self._delete_button.set_sensitive(False)
def on_view(self, *a):
# Open the file, witout waiting for editor to return
custom, default = self.view.get_selected()
if custom is None:
return # Should not have been sensi... | self.ui.open_file(custom)
else:
assert default and default.exists()
self.ui.open_file(default)
def on_copy(self, *a):
# Create a new template in this category
custom, default = self.view.get_selected()
if custom is None:
return # Should not have been sensitive
if custom.exists():
source = cust... |
import unittest
from db.migrations import migrations_util
class TestMigra | tionUtil(unittest.TestCase):
"""Test the CLI API."""
@classmethod
def setUpClass(cls):
cls.db_path = '/some/random/path/file.db'
def setUp(self):
self.parser = migrations_util.make_argument_parser(self.db_path)
def test_cli_parser_default(self):
options = self.parser.parse... | elf.assertEqual(options.action, 'upgrade')
def test_cli_parser_user(self):
other_db_path = '/some/other/path/file.db'
options = self.parser.parse_args([
'downgrade',
'--path',
other_db_path
])
self.assertEqual(options.path, other_db_path)
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-present, Cl | oudZero, Inc. All rights reserved.
# Licensed under the BSD-style license. See LICENSE file in the project root for full license information.
"""
Plugin used to extract all contextual information we can from EC2 network-interface (ENI) Cloudtrail Events.
"""
import lambda_tools
import reactor.common.cznef as cznef
... | eeds more scrutiny. It's very likely these lists are not quite right.
logger = lambda_tools.setup_logging('reactor')
event_categories = cznef.CategorizedEventNames()
event_categories.modification_events = {
'AssignIpv6Addresses',
'AssignPrivateIpAddresses',
'AssociateAddress',
'DisassociateAddress',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Minimal web interface to cve-search to display the last entries
# and view a specific CVE.
#
# Software is free software released under the "Modified BSD license"
#
# Copyright (c) 2017 Pieter-Jan Moreels - pieterjan.moreels@gmail.com
# imports
import json
import os... | import API, APIError
class Advanced_API(API):
def __init__(self):
super().__init__()
routes = [{'r': '/api/admin/whitelist', 'm': ['GET'], 'f': self.api_admin_whitelist},
{'r': '/api/admin/blacklist', 'm': ['GET'], 'f': s | elf.api_admin_blacklist},
{'r': '/api/admin/whitelist/export', 'm': ['GET'], 'f': self.api_admin_whitelist},
{'r': '/api/admin/blacklist/export', 'm': ['GET'], 'f': self.api_admin_blacklist},
{'r': '/api/admin/whitelist/import', 'm': ['PUT'], 'f': self.api_admin_import_white... |
from django.db | import models
from django.contrib.auth.models import User
from django.contrib import admin
from api.models import Hackathon
from hackfsu_com.admin import hackfsu_admin
class WifiCred(models.Model):
hackathon = models.ForeignKey(to=Hackathon, on_delete=models.CASCADE)
username = models.CharField(max_length=100... | :
return '[WifiCred {}]'.format(self.username)
@admin.register(WifiCred, site=hackfsu_admin)
class WifiCredAdmin(admin.ModelAdmin):
list_filter = ('hackathon',)
list_display = ('username', 'assigned_user',)
list_editable = ()
list_display_links = ('username',)
search_fields = ('assigned_us... |
# Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | rain_client_epochs_per_round=client_epochs_per_round,
train_client_batch_size=client_batch_size,
crop_shape=crop_shape)
_, cifar_test = cifar10_dataset.get_centralized_datasets(
crop_shape=crop_shape)
input_spec = cifar_train.cre | ate_tf_dataset_for_client(
cifar_train.client_ids[0]).element_spec
model_builder = functools.partial(
resnet_models.create_resnet18,
input_shape=crop_shape,
num_classes=NUM_CLASSES)
loss_builder = tf.keras.losses.SparseCategoricalCrossentropy
metrics_builder = lambda: [tf.keras.metrics.S... |
self.target.id,
self.driver.name,
)
class BackupTargetRecoveryPoint(object):
"""
A backup target recovery point
"""
def __init__(self, id, date, target, driver, extra=None):
"""
:param id: Job id
:type id: ``str``
:param date: The date tak... |
:param target: Backup target to delete
:type target: Instance of :class:`.BackupTarget`
:param start_date: The start date to show jobs between (optional)
:type | start_date: :class:`datetime.datetime`
:param end_date: The end date to show jobs between (optional)
:type end_date: :class:`datetime.datetime``
:rtype: ``list`` of :class:`.BackupTargetRecoveryPoint`
"""
raise NotImplementedError(
"list_recovery_points not impleme... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from GestureAgentsTUIO.Tuio import TuioAgentGenerator
import Gest | ureAgentsPygame.Screen as Screen
from pygame.locals import *
class MouseAsTuioAgentGenerator(object):
def __init__(self):
sel | f.pressed = False
self.myagent = None
self.sid = -1
self.screensize = Screen.size
def event(self, e):
if e.type == MOUSEBUTTONDOWN:
self.pressed = True
self.myagent = TuioAgentGenerator.makeCursorAgent()
self._updateAgent(self.myagent, e)
... |
from django import forms
from django.core.files import File
from django.conf import settings
from .widgets import FPFileWidget
import urllib2
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
class FPFieldMixin():
widget = FPFileWidget
default_mimetypes = "*/*"
... | es a File object"""
if not data or not data.startswith('http'):
return None
url_fp = urllib2.urlopen(data)
name = "fp-file"
disposition = url_fp.info().getheader('Content-Disposition')
if disposition:
name = disposition.rpartition("filename=")[2].strip | ('" ')
filename = url_fp.info().getheader('X-File-Name')
if filename:
name = filename
size = long(url_fp.info().getheader('Content-Length', 0))
fp = File(StringIO(url_fp.read()), name=name)
fp.size = size
return fp
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
"""
「石取りゲーム1」(「C言語による最新アルゴリズム事典」6ページより)
"""
def ge | t_num(message):
sys.stdout.write(message)
n = ''
while (not n.isdigit()):
n = raw_input()
return int(n)
n = get_num(u"石の数?")
m = get_num(u"1回に取れる最大の石の数?" | )
if (n < 1 or m < 1):
sys.exit(1)
my_turn = True
while(n != 0):
if (my_turn):
x = (n - 1) % (m + 1)
if (x == 0):
x = 1
print(u"私は%d個の石を取ります." % x)
else:
r = False
while (not r or x <= 0 or m < x or n < x):
x = get_num(u"何個取りますか?")
... |
],
'7': [543.7372, 1288.546, 4.424041, 4.69879],
'11': [411.3944, 2275.093, 4.39259, 4.796765],
'12': [440.3333, 2197.091, 4.476098, 4.667141],
'14': [441.1307, 2233.011, 4.403062, 4.860253],
'21': [599.2163, 1978.542, 4.40423, 4.894037],
... | 4,31.39354,0.02637788,0.2685742]]),
'2': np.matrix([[12610.98, 4598.212, 15.72022, 10.93343],
[4598.212, 76695.1, 35.53953, 32.24821],
[15.72022, 35.53953, 0.3856857, 0.04138077],
[10.93343, 32.2 | 4821, 0.04138077, 0.2402458]]),
'3': np.matrix([[20287.03, -945.841, 23.69788, 19.12778],
[-945.841, 85500.7, 32.35261, 42.61164],
[23.69788, 32.35261, 0.408185, 0.05798509],
[19.12778, 42.61164, 0.05798... |
"""
File: tonal_permutation.py
Purpose: Class defining a function on one tonality based on a permatuation specification.
"""
from transformation.functions.tonalfunctions.tonal_permutation import TonalPermutation
class TonalityPermutation(TonalPermutation):
"""
Class implementation of a permutation on a set... | y = tonality
domain_to | nes = tonality.annotation[:len(tonality.annotation) - 1]
TonalPermutation.__init__(self, cycles, domain_tones)
@property
def tonality(self):
return self._tonality
|
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.model.docume | nt import Document
from frappe.contacts.address_and_contact import load_address_and_contact
STANDARD_USERS = ("Guest", "Administrator")
class Member(Document):
def onload(self):
"""Load address and contacts in `__onload`"""
load_address_and_contact(self)
def validate(self):
if self.name not in STA | NDARD_USERS:
self.validate_email_type(self.email)
self.validate_email_type(self.name)
def validate_email_type(self, email):
from frappe.utils import validate_email_add
validate_email_add(email.strip(), True) |
from behave import given, when, then
from genosdb.models import User
from genosdb.exceptions import UserNotFound
# 'mongodb://localhost:27017/')
@given('a valid user with values {username}, {password}, {email}, {first_name}, {last_name}')
def step_impl(context, username, password, email, first_name, last_name):
... | ,
last_name=last_name)
@when('I add the user to the collection')
def step_impl(context):
context.user_service.save(context.base_user)
@then('I check {user_name} exists')
def step_impl(co | ntext, user_name):
user_exists = context.user_service.exists(user_name)
assert context.base_user.username == user_exists['username']
assert context.base_user.password == user_exists['password']
assert context.base_user.email == user_exists['email']
assert context.base_user.first_name == user_exists[... |
import sys
from arrowhead.core import Step
from arrowhead.core import ErrorArrow
from arrowhead.core import NormalArrow
from arrowhead.core import ValueArrow
def print_flow_state(flow, active_step_name=None, file=sys.stdout):
"""
Display the state of a given flow.
:param flow:
A Flow, instance o... | the state
of the entire flow. The output is composed of many lines. The output will
contain all of the internal state of the flow (may print stuff like
passwords if you stored any).
"""
# show flow name
print("[{}]".format(flow.Meta.name).center(40, "~"), file=file)
# show flow global state... | startswith("_"):
continue
# steps are handled later
if (isinstance(f_v, Step) or
(isinstance(f_v, type) and issubclass(f_v, Step))):
continue
# skip Meta
if f_k == 'Meta':
continue
if needs_header:
print("STATE:", fi... |
#!/usr/bin/env python3
# -*- coding: | utf-8 -*-
"""This | file contains everything needed to interface with JUnit"""
#####
# pyCheck
#
# Copyright 2012, erebos42 (https://github.com/erebos42/miscScripts)
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundatio... |
self.description = "CleanMethod = KeepCurrent"
sp = pmpkg("dummy", "2.0-1")
self.addpkg2db("sync", sp)
sp = pmpkg("bar", "2.0-1")
self.addpkg2db("sync", sp)
sp = pmpkg("baz", "2.0-1")
self.addpkg2db("sync", sp)
lp = pmpkg("dummy", "1.0-1")
self.addpkg2db("local", lp)
lp = pmpkg("bar", "2.0-1")
self.addpkg2db("loca... | reatelocalpkgs = True
self.addrule("PACMAN_RETCODE=0")
self.addrule("CACHE_EXISTS=dummy|2.0-1")
self.addrule("!CACHE_EXISTS=dummy|1.0-1")
s | elf.addrule("CACHE_EXISTS=bar|2.0-1")
self.addrule("CACHE_EXISTS=baz|2.0-1")
|
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# 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 app... | with padd | le.static.program_guard(paddle.static.Program()):
# The input type must be Variable.
self.assertRaises(TypeError, F.maxout, 1)
# The input dtype must be float16, float32, float64.
x_int32 = paddle.fluid.data(
name='x_int32', shape=[2, 4, 6, 8], dtype='int3... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
fro... | name='mfs',
version='0.1.0',
license='MIT license',
description='mfs is a set of utilities to ease image download from some Russian modelling forums',
long_description='%s\n%s' % (
re.compile('^.. start-badges.*^.. end-badges', re.M | re.S).sub('', read('README.rst') | ),
re.sub(':[a-z]+:`~?(.*?)`', r'``\1``', read('CHANGELOG.rst'))
),
author='Alexandre Ovtchinnikov',
author_email='abc@miroag.com',
url='https://github.com/miroag/mfs',
packages=find_packages('src'),
package_dir={'': 'src'},
py_modules=[splitext(basename(path))[0] for path in glob('s... |
tion and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT H... | ted(self, value):
""" Set last_time_resync_initiated value.
Notes:
Time that the resync was initiated
This attribute is named `lastTimeResyncInitiated` in VSD API.
"""
self._last_time_resync_initiated = value
... | otes:
ID of the user who last updated the object.
This attribute is named `lastUpdatedBy` in VSD API.
"""
return self._last_updated_by
@last_updated_by.setter
def last_updated_by(self, value):
""" Set last_updated_by val... |
self._run_additional_callbacks = run_additional_callbacks
self._run_tree = run_tree
self._callbacks_loaded = False
| self._callback_plugins = []
self._start_at_done = False
self._result_prc = None
# make sure the module path (if specified) is parsed and
# added to the module_loader object
if options.module_path is not None:
for path in options.module_path.split(os.p... | ictionary is used to keep track of notified handlers
self._notified_handlers = dict()
# dictionaries to keep track of failed/unreachable hosts
self._failed_hosts = dict()
self._unreachable_hosts = dict()
self._final_q = multiprocessing.Queue()
# A temporary file (... |
ecode import unidecode
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailadmin.utils import send_mail
from wagtail.wagtailcore import hooks
from wagtail.wagtailcore.models import Orderable, Page, UserPagePermissionsProxy, get_page_models
from .forms import FormBuilder, WagtailAdminFormPage... | modes = [
('form', 'Form'),
('landing', 'Landing page'),
]
def serve_preview(self, request, mode):
if mode == 'landing':
return render(
request,
self.get_landing_page_template(reques | t),
self.get_context(request)
)
else:
return super(AbstractForm, self).serve_preview(request, mode)
class AbstractEmailForm(AbstractForm):
"""
A Form Page that sends email. Pages implementing a form to be send to an email should inherit from it
"""
to_a... |
#!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Extract UserMetrics "actions" strings from the Chrome source.
This program generates the list of known actions we expect to see in ... | orwardMenu_']:
actions.add(dir + 'ShowFullHistory')
actions.add(dir + 'Popup')
for i in range(1, 20):
actions.add(dir + 'HistoryClick' + str(i))
actions.add(dir + 'ChapterClick' + str(i))
# Actions for new_tab_ui.cc.
for i in range(1, 10):
actions.add('MostVisited%d' % i)
def AddWebKit... | .
"""
action_re = re.compile(r'''\{ [\w']+, +\w+, +"(.*)" +\},''')
editor_file = os.path.join(path_utils.ScriptDir(), '..', '..', 'webkit',
'glue', 'editor_client_impl.cc')
for line in open(editor_file):
match = action_re.search(line)
if match: # Plain call to RecordAction... |
import os.path
import sys
from setuptools import setup, Command
class Tox(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import tox
sys.exit(tox.cmdline([]))
setup(
name="kafka-python",
versio... | ["distribute"],
tests_require=["tox"],
cmdclass={"test": Tox},
packages=["kafka"],
author="David Arthur",
author_email="mumrah@gmail.com",
url="https://github.com/mumrah/kafka-python",
license="Copyright 2012, David Arthur under Apache License, v2.0",
description="Pure Python client fo... | orted by the
protocol as well as broker-aware request routing. Gzip and Snappy compression
is also supported for message sets.
"""
)
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Feedback'
db.create_table(u'auxiliary_feedback', (
(u'id', self.gf('django.db.mo... | o.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staf... | [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30'... |
"""events
Revision ID: 9c92c85163a9
Revises: 666668eae682
Create Date: 2016-05-09 19:04:44.498817
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '9c92c85163a9'
down_revision = '666668eae682'
def upgrade():
op.cre... | def downgrade():
op.create_table('processing_log',
sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=Tr | ue),
sa.Column('id', sa.BIGINT(), nullable=False),
sa.Column('operation', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('component', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('source_location', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('content_ha... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: KevinMidboe
# @Date: 2017-02-08 14:00:04
# @Last Modified by: KevinMidboe
# @Last Modified time: 2017-02-16 17:08:08
import requests
from pprint import pprint
try:
from plexSearch import plexSearch
except ImportError:
from plex.plexSearch import plexSearc... | _code == 401:
return {"errors": "api key is not valid."}
elif r.status_code == 404:
return {"errors": "Please check url. (404)"}
elif r.status_code == requests.codes.ok and r.json()['total_results'] == 0:
return {"errors": "No results found."}
return r.json()
if __name__ == "__main__":
import sys
print(... | tmdbSearch("star+wars",1)) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# | self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
list = []
self.helper(list, root, 0)
return list[::-1]
def helper(self, list, root, level):
if root == None:
return
if level >=... | TestObjects import *
b = BinaryTree()
s = Solution()
print s.levelOrderBottom(b.root)
|
from __future__ import absolute_import
from datetime import datetime
from django.core.urlresolvers import reverse
from sentry.models import Release
from sentry.testutils import APITestCase
class ProjectReleaseListTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
team = sel... | jects.create(
project=project2,
| version='1',
)
url = reverse('sentry-api-0-project-releases', kwargs={
'project_id': project1.id,
})
response = self.client.get(url, format='json')
assert response.status_code == 200, response.content
assert len(response.data) == 2
assert res... |
import unittest
from convert import convert
class TestConvert(unittest.TestCase):
def testEmptyJsonParse(self):
generated = convert.parse(convert._load_json_files("./jsonSamples/minimal.json")[0])
def testGlossaryJsonParse(self):
generated = convert.parse(convert._load_json_files("./jsonSampl... | print "".join(f["content"]) | |
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
# This script is called by snmptrapd and sends
# a | ll traps to the mkeventd
#
# Bastian Kuhn, bk@mathias-kettner.de
# If you use this script please keep in mind that this script is called
# for every trap the server receives.
# To use this Script, you have to configure your snmptrad.conf like that:
# authCommunity execute public
# traphandle default /path/to/this/scri... |
# -*- coding: utf-8 -*-
import pathlib
from typing import Union
import lxml.etree
def save_as_xml(
element_tree: Union[lxml.etree._Element, lxml.etree._ElementTree],
filepath: Union[str, pathlib.Path],
pretty_print: bool = True) -> None:
"""save ElementTree in the file as XML... | th)
with filepath.open(mode='w', encoding='utf-8', newline='') as file:
file.write(lxml.etree.tostring(
element_tree,
encoding='utf-8',
pretty_print=pretty_print,
| xml_declaration=True).decode('utf-8'))
|
self.assertRaises(Exc, d.update, FailingUserDict())
class badseq(object):
def __iter__(self):
return self
def next(self):
raise Exc()
self.assertRaises(Exc, {}.update, badseq())
self.assertRaises(ValueError, {}.update, [(1, 2, 3)])
... | ct):
def __repr__(self):
raise Exc()
d = {1: BadRepr()}
self.assertRaises(Exc, repr, d)
def test_le(self):
self.assert_(not ({} < {}))
self.assert_(not ({1: 2} < {1L: 2L}))
class Exc(Exception): pass
class BadCmp(object):
de... | d1 < d2
except Exc:
pass
else:
self.fail("< didn't raise Exc")
def test_missing(self):
# Make sure dict doesn't have a __missing__ method
self.assertEqual(hasattr(dict, "__missing__"), False)
self.assertEqual(hasattr({}, "__missing__"), False... |
# -*- coding: utf-8 -*-
# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folde | r of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
from django.contrib.auth import get_user_model
from django.utils.transl | ation import ugettext_lazy as _
from rest_framework import serializers
from akvo.rsr.forms import (check_password_minimum_length, check_password_has_number,
check_password_has_upper, check_password_has_lower,
check_password_has_symbol)
from akvo.rsr.models impor... |
from opc.drivers.baseclass import RopDriver
class Driver(RopDriver):
"""
Just pass back the raw data to the caller fo | r rendering | by the app
"""
def __init__(self, width, height, address):
pass
def putPixels(self, channel, pixels):
return pixels
def sysEx(self, systemId, commandId, msg):
pass
def setGlobalColorCorrection(self, gamma, r, g, b):
pass
def terminate(self):
pass
|
#!/usr/bin/env python2.7
# __BEGIN_LICENSE__
#
# Copyright (C) 2010-2012 Stanford University.
# All rights reserved.
#
# __END_LICENSE__
# rectify.py
#
# Usage: rectify.py <lightfield_image.{tif,png,etc}> [--pixels-per-lenslet <ppl>]
#
# This script simply applies a rectification from a
# campixel_to_camlens.warp fil... |
calibr | ation_file = options.calibration_file
# Default output filename has a -RECTIFIED suffix
if not options.output_filename:
fileName, fileExtension = os.path.splitext(filename)
output_filename = fileName + '-RECTIFIED' + fileExtension
else:
output_filename = opti... |
p.random.randn(1,1),
np.random.rand(1,1),
ndim=2)
x1 = X1.get_moments()
X2 = GaussianARD(np.random.randn(3,2),
np.random.rand(3,2),
ndim=2)
x2 = X2.get_moments()
m0 = tau * data * np.sum(n... | np.array([True, False, True])
F = SumMultiply('i,i->i', X1, X2)
Y = GaussianARD(F, tau,
plates=(3,),
ndim=1)
Y.observe(data*np.ones((3,2)), mask=mask)
m0 = tau * data * np.sum(mask[:,np.newaxis] * x2[0],
axi... | m1 = -0.5 * tau * np.sum(mask[:,np.newaxis,np.newaxis]
* x2[1]
* np.identity(2),
axis=0,
keepdims=True)
check_message(m0, m1, 0,
'i->i',
... |
jango.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['cms.Section']", 'null': 'True', 'through': "orm['cms.SectionItem']", 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '250', 'blank': 'True'}),
'title': ... | , 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '250', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '250'} | ),
'views': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'cms.sectionitem': {
'Meta': {'ordering': "['order']", 'object_name': 'SectionItem'},
'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Article']"}),
... |
# -*- coding: utf-8 -*-
import json
import datetime
from decimal import Decimal
from requests.packages.urllib3.util import parse_url
from .models import BaseModel
from .errors import OptimoError
DEFAULT_API_VERSION = 'v1'
class CoreOptimoEncoder(json.JSONEncoder):
"""Custom JSON encoder that knows how to ser... |
class OptimoEncoder(CoreOptimoE | ncoder):
"""Custom JSON encoder that knows how to serialize
:class:`optimo.models.BaseModel <BaseModel>` objects.
"""
def default(self, o):
if isinstance(o, BaseModel):
return o.as_optimo_schema()
return super(OptimoEncoder, self).default(o)
def validate_url(url):
"""As... |
BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIA... | text import caret, document, layout
import cocos
from cocos.director import director
from base_layers import | Layer
from util_layers import ColorLayer
__all__ = ['PythonInterpreterLayer']
class Output:
def __init__(self, display, realstdout):
self.out = display
self.realstdout = realstdout
self.data = ''
def write(self, data):
self.out(data)
class MyInterpreter(code.In... |
# Copyright 2014 The Chromium Authors. All | rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'recipe_engine/step',
'url',
]
def RunSteps(api):
api.step('step1',
['/bin/echo', api.url.join('foo', 'bar', 'baz')])
api.step('step2',
['/bin/echo', api.url.jo... | ])
api.step('step4',
['/bin/echo', api.url.join('//foo/bar//', '//baz//')])
api.url.fetch('fake://foo/bar', attempts=5)
api.url.fetch('fake://foo/bar (w/ auth)', headers={'Authorization': 'thing'})
def GenTests(api):
yield api.test('basic')
|
import os
import json
from django.test import TestCase
from documents.models import Document
from documents.exporters.sql import (MysqlExporter, OracleExporter,
PostgresExporter, SQLiteExporter)
TEST_DOCUMENT_PATH = os.path.join(os.path.dirname(__file__),
... | ame` varchar(255)
);
CREATE TABLE `users_roles` (
`users_id` int,
`roles_id` int,
FOREIGN KEY(`users_id`) REFERENCES `users` (`id`),
FOREIGN KEY(`roles_id`) REFERENCE | S `roles` (`id`)
);
CREATE TABLE `roles` (
`id` int PRIMARY KEY,
`name` varchar(255)
);
CREATE TABLE `roles_permissions` (
`roles_id` int,
`permissions_id` int,
FOREIGN KEY(`roles_id`) REFERENCES `roles` (`id`),
FOREIGN KEY(`permissions_id`) REFERENCES `permissions` (`id`)
);
CREATE TABLE `users` (
`id` int PRIM... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.