prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
#!/usr/bin/env python3
import asyncio
import contextlib
import datetime
import functools
import importlib
import itertools
import logging
import os
import sys
import traceback
import click
import discord
import config
from cogs.utils import db
from core import Chiaki, migration
# use faster event loop, but fall bac... | bose=False):
# click doesn't like None as a default so we have to settle with an empty string
if not version:
version = None
_load_modules(config.extensions)
pool = await _create_pool()
async with pool.acquire() as conn:
await migration.migrate(version, connection=conn, downgrade=d... | .run_until_complete
run(_migrate(version, downgrade=downgrade, verbose=verbose))
@main.command()
@click.option('--version', default='', metavar='[version]', help='Version to migrate to, defaults to latest')
@click.option('-v', '--verbose', is_flag=True)
def upgrade(version, verbose):
"""Upgrade the database to... |
# -*- coding: utf-8 -*-
"""
pipya main cli file
Copyright (c) 2015 Brunston Poon
This program 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.
Full license in LICENCE.txt
"""
#IMPORT IMPORT IMPORT IMPO... | 3:
| print("""
Please upgrade to Python3, preferably 3.4.* or greater, before continuing""")
toggle = False
sys.exit()
if os.name == "nt":
try:
from colorama import init
init()
except ImportError:
print("colorama is a windows dependency for ANSI colors support")
sys.exit()
d... |
hinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.todo',
'sphinx.ext.pngmath',
'sphinx.ext.ifconfig',
'sphinxcontrib.httpdomain'
]
# Add any paths that contain templates here, relative to th... | Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Octofiles', 'Octofiles Documentation',
author, 'Octofiles',... | oject.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How t |
#!/usr/b | in/env python
# -*- coding:utf-8 -*-
from flask import Flask
from config import *
# create the app
app = Flask(__name__)
# Load default config and override config from config file
app.config.from_object('c | onfig') |
# -*- coding: utf-8 -*-
###############################################################################
#
# GetLoginProfile
# Retrieves the user name and password create date for the specified user.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (th... |
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from Amazon.)
"""
return self._output.get('Response', None)
class GetLoginProfileChoreographyExecution(ChoreographyExecution):
def... | sult_set(self, response, path):
return GetLoginProfileResultSet(response, path)
|
:
self.next = self.__this_string[1]
else:
self.next = None
def step(self):
""" remove the first char from the string """
self.__this_string = self.__this_string[1:]
self.__setup()
return self.this
def step2(self):
""" remove the f... | len(self._text):
if self._text[index][0] == TXT.separator and curr_string != '':
curr_string + | = self._text[index][1]
index = index + 1
break #while self._text:
type_0_1 = (self._text[index][0], self._text[index+1][0])
#if type_0_1 == (TXT.remove, TXT.remove):
# pass
if type_0_1 == (TXT.remove, TXT.se... |
myKeywords):
"""prompt user for a decision on which attribute has to be the key
attribute for the aggregated data and writes the keywords file
This could be swapped to a call to the keyword editor
Args: None
Returns: the value of the aggregation attribute ke... | yMessage = self.runner.result()
# FIXME (Ole): This branch is not covered by the tests
myEngineImpactLayer = self.runner.impactLayer()
if myEngineImpactLayer is None:
myMessage = str(self.tr('No impact layer was c | alculated. '
'Error message: %s\n' % str(myMessage)))
if self.runner.lastTraceback() is not None:
myMessage += '<br/><ul>'
for myItem in self.runner.lastTraceback():
# replace is to tidy up windows paths a little
myMe... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('data_storage', '0002_auto_20150727_23 | 12'),
]
operations = [
migrations.RenameField(
model_name='readonly',
old_name='state',
new_name='stateAbbreviation',
),
migrations.RenameField(
model_name='writeonly',
old_name='s | tate',
new_name='stateAbbreviation',
),
migrations.AddField(
model_name='readonly',
name='stateName',
field=models.TextField(default='sexy jens'),
preserve_default=False,
),
migrations.AddField(
model_name='writeonly... |
#!/usr/bin/python
# find_unicode.py
#
# Author: Jonathan Hosmer
# Date: Sun Feb 15 14:06:15 2015
#
import os
import sys
def help():
print 'Usage: {} [file, [dir, [file, ..]]]'.format(__file__)
print 'Displays line:character position of all non-ascii Unicode character(s) in a file'
def main():
args = sys.... | es:
if f is sys.stdin:
infile = sys.stdin
fname = 'stdin'
else:
fname = f
infile = open(f)
for line_i, line in enumerate(infile):
| for char_i, char in enumerate(line):
if ord(char) > 126:
chars.append(char)
else:
if chars:
print out_str.format(fname, line_i+1, char_i+1-len(chars),
chars=''.join(chars))
... |
import json
import re
import unittest
from datetime import datetime
from coalib.output.JSONEncoder import create_json_encoder
class TestClass1(object):
def __init__(self):
self.a = 0
class TestClass2(object):
def __init__(self):
self.a = 0
self.b = TestClass1()
class TestClass3(... | 0": 1}', json.dumps({0: 1}, **self.kw))
self.assertEqual('{"0": 1}', json.dumps({'0': 1}, **self.kw))
self.assertEqual('{"0": "1"}', json.dumps({'0': '1'}, **self.kw))
def test_time(self):
tf = datetime.today()
self.assertEqual('"' + tf.isoformat() + '"',
| json.dumps(tf, **self.kw))
def test_re_object(self):
uut = re.compile('x')
self.assertEqual('"' + uut.pattern + '"',
json.dumps(uut, **self.kw))
def test_class1(self):
tc1 = TestClass1()
self.assertEqual('{"a": 0}', json.dumps(tc1, **self.kw))
... |
sed 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... | = 'horizon/common/_detail.html'
failure_url = reverse_lazy('horizon:project:routers:index')
network_url = | 'horizon:project:networks:detail'
page_title = "{{ router.name|default:router.id }}"
@memoized.memoized_method
def _get_data(self):
try:
router_id = self.kwargs['router_id']
router = api.neutron.router_get(self.request, router_id)
router.set_id_as_name_if_empty(... |
#!/usr/bin/python
AGO_TELLSTICK_VERSION = '0.0.9'
"""
############################################
#
# Tellstick Duo class
#
# Date of origin: 2014-01-25
#
__author__ = "Joakim Lindbom"
__copyright__ = "Copyright 2014, Joakim Lindbom"
__credits__ = ["Joakim Lindbom", "The ago control team"]
__license__ = "GP... | elf, devId, level):
resCode = td.dim(devId, level)
return self.getErrorString(resCode).lower()
def getName(self, devId):
return td.getName(devId)
def methodsReadable(self, method, default):
return td.methodsReadable(method, default)
def getNumberOfDevices(self):
re... | NumberOfDevices()
def getNumberOfSensors(self):
return td.getNumberOfDevices() # wrong
def getDeviceId(self, i):
return td.getDeviceId(i)
def getModel(self, devId):
return td.getModel(devId)
def registerDeviceEvent(self, deviceEvent):
return td.registerDeviceEvent(de... |
t_delete_container_not_found
return (httplib.NOT_FOUND,
body,
headers,
httplib.responses[httplib.NOT_FOUND])
def _foo_bar_container_foo_bar_object_NOT_FOUND(self, method, url, body,
headers):
# test_... | als(self):
self.mock_response_klass.type = 'UNAUTHORIZED'
try:
sel | f.driver.list_containers()
except InvalidCredsError:
e = sys.exc_info()[1]
self.assertEqual(True, isinstance(e, InvalidCredsError))
else:
self.fail('Exception was not thrown')
def test_list_containers_empty(self):
self.mock_response_klass.type = 'list_con... |
self[name] = values.get(name, '')
# We have to do an extra trick to catch unchecked checkboxes
for name in [name for name in values.keys() if name[9:] in field_names
and name.startswith('checkbox_')]:
if name[9:] not in values:
self[name[9:]] = '0'
... | arameter is no longer needed and will be removed
in version 1.1.1
"""
assert not self.exists, 'Cannot insert an existing ticket'
if 'cc' in self.values:
self['cc'] = _fixup_cc_list(self.values['cc'])
# Add a timestamp
if when is None:
when = date... | self.values['uploadtime'] = self.values['changetime'] = when
self.values['uuid'] = str(self.uuid)
# The owner field defaults to the component owner
if self.values.get('owner') == '< default >':
default_to_owner = ''
if self.values.get('component'):
... |
from __future__ import absolute_import
from .notedown import *
from .mai | n import convert, markdown_template, __version__
# avoid having to require the notebook to install notedown
try:
from .contentsmanager import NotedownContentsManager
except I | mportError:
NotedownContentsManager = 'You need to install the jupyter notebook.'
|
# -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, 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 requi... | de.mac = u"ASDFGHJKLMNOPR"
| node.timestamp = datetime.now()
self.db.add(node)
self.db.commit()
node2 = self.db2.query(Node).filter(
Node.id == node.id
).first()
node2.mac = u"12345678"
self.db2.add(node2)
self.db2.commit()
self.db.query(Node).filter(
Node.i... |
me': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
... | {'default': '0'}),
' | title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'video_url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'project.projectgratefulusers': {
'Meta': {'object_name': 'ProjectGratefulUsers'},
... |
hilled_water_temperature = var_reference_leaving_chilled_water_temperature
# real
var_reference_leaving_condenser_water_temperature = 5.5
obj.reference_leaving_condenser_water_temperature = var_reference_leaving_condenser_water_temperature
# real
var_reference_chilled_water_flow_... | illed_water_inlet_node_name
# node
var_chilled_water_outlet_node_name = "node|Chilled Water Outlet Node Name"
obj.chilled_water_outlet_node_name = var_chilled_water_outlet_node_name
# node
var_condenser_inlet_node_name = "node|Condenser Inlet Node Name"
obj.condenser_inle... | ode_name = var_condenser_inlet_node_name
# node
var_condenser_outlet_node_name = "node|Condenser Outlet Node Name"
obj.condenser_outlet_node_name = var_condenser_outlet_node_name
# real
var_fraction_of_compressor_electric_consumption_rejected_by_condenser = 0.50005
obj.fr... |
import bpy
from .... base_types.node import AnimationNode
class LineMeshNode(bpy.types.Node, AnimationNode):
bl_idname = "an_LineMeshNode"
bl_label = "Line Mesh"
def create(self):
self.newInput("Vector", "Start", "start")
self.newInput("Vector", "End", "end", value = [0, 0, 10])
se... | ut("Vector List", "Vertices", "vertices")
self.newOutput("Edge Indices List", "Edge Indices", "edgeIndices")
def execute(self, start, end, steps):
steps = max(steps, 2)
divisor = steps - 1
| vertices = [start * (1 - i / divisor) + end * i / divisor for i in range(steps)]
edges = [(i, i + 1) for i in range(steps - 1)]
return vertices, edges
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", "travis-ci.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv | )
|
# -*- coding: | utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0014_survey'),
]
operations = [
migrations.AddField(
model_name='survey',
name='question2',
fie... | reserve_default=False,
),
]
|
# -*- coding: utf-8 -*-
# Copyright (c) 2009 - 2014 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing a dialog to manage history.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import pyqtSignal, Qt, QUrl
from PyQt5.QtGui import QFontMetrics, QCursor
from PyQt5.QtWidgets import QD... | slot to handle the context menu request for the bookmarks tree.
@param pos pos | ition the context menu was requested (QPoint)
"""
menu = QMenu()
idx = self.historyTree.indexAt(pos)
idx = idx.sibling(idx.row(), 0)
if idx.isValid() and not self.historyTree.model().hasChildren(idx):
menu.addAction(
self.tr("&Open"), self.__openHistor... |
# -*- coding: utf-8 -*-
# Copyright (C) 2016-2018 Cordell Bloor
# Published under the MIT License
from nose.tools import *
import guardonce.util as go
def test_ok():
contents = '''
#ifndef MATCH_H
#define MATCH_H
'''
g,s,e = go.guess_guard(contents)
assert_equals(g, 'MATCH_H')
assert_equals(s, 1)
... | s(g, 'MATCH_H')
assert_equals(s, 1)
assert_equals(e, 34)
@raises(ValueError)
def test_define():
contents = '''
#ifndef ONE
#define ONE 1
#endif
'''
go.guess_guard(contents)
@raises(ValueError)
def test_define_with_space():
contents = '''
#ifndef ONE
#define ONE 1
#endif
'''
go.guess_guard(co... | nts = '''
#if !defined(MATCH_H)
#define MATCH_H
'''
g,s,e = go.guess_guard(contents)
assert_equals(g, 'MATCH_H')
assert_equals(s, 1)
assert_equals(e, 38)
def test_if_defined_no_parentheses():
contents = '''
#if !defined MATCH_H
#define MATCH_H
'''
g,s,e = go.guess_guard(contents)
assert_equ... |
from django.core.management.base import BaseCommand
from django.conf import settings
from utils.amazon import default_s3_store
from videos.models import Video, VIDEO_TYPE_FLV, VIDEO_TYPE_HTML5
import urllib
import os
import commands
import sys
from django.core.exceptions import ImproperlyConfigured
from django.core.fil... | H):
os.makedirs(THUMBNAILS_PATH)
qs = Video.objects.filter(thumbnail='', videourl__original=True, videourl__type__in=[VIDEO_TYPE_FLV, VIDEO_TYPE_HTML5])
for video in qs:
self.print_to_console(u'Handling %s' % video.__unicode__())
try:
... | )
except ObjectDoesNotExist:
continue
path = self.get_file_path(video, video_url)
if not os.path.exists(path):
self.print_to_console(u'Saving...')
urllib.urlretrieve(video_url.url, path)
self.print_to_c... |
#! /usr/bin/python
import bottle
import settings
| from controller import admin as admin_controller
from controller import email as email_controller
app = application = bottle.Bottle()
# Base url for regular users
app.route(settings.BASEPATH, 'GET', admin_controller.index)
app.route(settings.BASEPATH + '/', 'GET', admin_controller.index)
app.route(
settings.BASEP... | admin_controller.update_self
)
# Email handler
email = bottle.Bottle()
app.mount(settings.EMAIL_PATH, email)
email.route('/', 'POST', email_controller.receive_email)
email.route('/', 'GET', email_controller.test_form)
email.route('', 'GET', email_controller.test_form)
# Ansible admin
admin = bottle.Bottle()
app.moun... |
# https://leetcode.com/problems/build-arra | y-where-you-can-find-the-maximum-exactly-k-comparisons
class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
M = 1000000007
ret = 0
for i in range(k, m+1):
ret += ((i-1)**(k-1)) * (i**(n-k))
return ret % M
# n = 2
# m = 3
# k = 1
# ans = 6
# n = 9
# m ... | = 34549172
# n = 37
# m = 17
# k = 7
# ans = 418930126
sl = Solution()
ret = sl.numOfArrays(n, m, k)
print(ret, "O" if ret==ans else "X") |
import json
import os
import unittest
from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine
from pymatgen.util.testing import PymatgenTest
class PhononBandStructureSymmLineTest(PymatgenTest):
def setUp(self):
with open(
os.path.join(PymatgenTest.TEST_FILES_DIR, "NaCl_phonon_ba... | bs2)
| def test_write_methods(self):
self.bs2.write_phononwebsite("test.json")
def tearDown(self):
if os.path.isfile("test.json"):
os.remove("test.json")
if __name__ == "__main__":
unittest.main()
|
"""Manage Treadmill app manifest."""
from __future__ import absolute_import
import logging
import urllib
import click
from .. import cli
from treadmill import restclient
from treadmill import context
_LOGGER = logging.getLogger(__name__)
_STATE_FORMATTER = cli.make_formatter(cli.InstanceStatePrettyFormatter)
_EN... | allback=cli.handle_context_opt,
expose_value=False)
@click.option('--api', required=False, help='API url to use.',
metavar='URL',
envvar='TREADMILL_STATEAPI')
def show(api):
"""Show state of scheduled applications."""
ctx['api'] = api
@s... | def state(match):
"""Show state of Treadmill scheduled instances."""
apis = context.GLOBAL.state_api(ctx['api'])
return _show_state(apis, match)
@show.command()
@cli.ON_REST_EXCEPTIONS
@click.option('--match', help='Application name pattern match')
def pending(match):
... |
#!/usr/bin/env python
# $Id: pythiaExample.py 545 2012-01-18 06:10:03Z cvermilion $
#----------------------------------------------------------------------
# Copyright (c) 2010-12, Pierre-Antoine Delsart, Kurtis Geerlings, Joey Huston,
# Brian Martin, and Christopher Vermilion
#
#-----------------------... | ')
# Creat TPythia8 object
pythia = TPythia8()
# Single W production
pythia.ReadString('Weak | SingleBoson:ffbar2W = on')
# Force decay W->ev
pythia.ReadString("24:onMode = off")
pythia.ReadString("24:onIfAny = 11 12")
# UE
pythia.ReadString("PartonLevel:MI = off")
# ISR,FSR, beam remnant
pythia.ReadString("PartonLevel:ISR = on")
pythia.ReadString("PartonLevel:FSR = on")
pythia.ReadString("PartonLevel:Remnants... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
import views
from django.contrib.auth.decorators import login_required
urlpatterns = patterns('',
url(r'^library$', views.library, name='profile-library'),
url(r'^stream$', | views.stream, name='profile-stream'),
url(r'^add_photo/', login_required(views.PhotoCreate.as_view(
template_name="imager_images/create_form.html",
success_url='/images/library')),
name='add_photo'),
url(r'^add_album/', login_required(views.AlbumCreate.as_view(
template_name="im... | rl(r'^update_album/(?P<pk>\d+)/$', login_required(views.AlbumUpdate.as_view(
template_name="imager_images/update_album.html",
success_url='/images/library')),
name='update_album'),
url(r'^update_photo/(?P<pk>\d+)/$', login_required(views.PhotoUpdate.as_view(
template_name="imager_ima... |
"""
Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
f... | k_field="object_id1")
@python_2_unicode_compatible
class Comparison(AbstractComparison):
"""
A model that tests having multiple | GenericForeignKeys. One is defined
through an inherited abstract model and one defined directly on this class.
"""
content_type2 = models.ForeignKey(ContentType, models.CASCADE, related_name="comparative2_set")
object_id2 = models.PositiveIntegerField()
other_obj = GenericForeignKey(ct_field="cont... |
import os
path | = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000462.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except I | mportError:
return False
else:
return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString) |
#
# Gordon McMillan (as inspired and influenced by Greg Stein)
#
# subclasses may not need marshal or struct, but since they're
# builtin, importing is safe.
#
# While an Archive is really an abstraction for any "filesystem
# within a file", it is tuned for use with imputil.FuncImporter.
# This assumes it contains pyt... | get_obj_from can make use of further elements in entry.
## """
## if self.os is None:
## import os
## self.os = os
## nm = entry[0]
## pth = entry[1]
## ispkg = self.os.path.splitext(self.os.path.basename(pth))[0] == '__init__'
## self.toc[nm] = ( | ispkg, self.lib.tell())
## f = open(entry[1], 'rb')
## f.seek(8) #skip magic and timestamp
## self.lib.write(f.read())
##
## def save_toc(self, tocpos):
## """Default - toc is a dict
## Gets marshaled to self.lib
## """
## marshal.dump(self.toc, self.lib)
##
## def save_trailer(self, tocpos):
... |
class Point:
Empty = " "
Full = "XX"
def __init__(self, x, y):
if not type(x) == int \
or not type(y) == int:
r | aise Exception('Can only assign int type to x or y value')
self.X = x
self.Y = y
self.Value = self.Empty
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.X == other.X and self.Y == other.Y
def __ne__(self, other):
return not self.__eq__(other)
def __str__(sel... | "
def __repr__(self):
return "P(" + str(self.X) + "," + str(self.Y) + ")"
|
#!/usr/bin/env python
"""Download data files needed by SLURP."""
# Copyright (C) 2012-2013 Constantine Lignos
#
# 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, ... | ath.abspath(__file__))
PIPELINE_URL | = "https://github.com/PennNLP/SUBTLEPipeline/archive/master.zip"
FILENAME = os.path.join(ROOT_DIR, PIPELINE_NAME + ".zip")
download(PIPELINE_URL, FILENAME)
unzip(FILENAME, ROOT_DIR)
# Now we need to additionally unzip the model file contained in the pipeline
print "Decompressing parser model file..."
model_gz = gzip.... |
#####################################################################################
# #
# Script to update Hostname #
# ... | #
#####################################################################################
def updateHostName(nodename,hostname): |
nlist = AdminConfig.list('ServerIndex')
attr=[["hostName", hostname ]]
AdminConfig.modify(nlist,attr)
AdminTask.modifyServerPort('server1', '[-nodeName '+ nodename +' -endPointName BOOTSTRAP_ADDRESS -host '+ hostname +' -port 2809 -modifyShared true]')
AdminTask.modifyServerPort('server1', '[-nodeName '+ node... |
from setuptools import find_packages
from setuptools import setup
with open('README.md') as f:
setup(
name = 'swarm',
version = '0.5.0',
author = 'arvin.x',
author_email = 'arvin.x@icloud.com',
description = | 'A modular distributed penetration test | ing tool',
license = 'GPLv3',
long_description = f.read(),
packages = find_packages(),
scripts = ['swarm.py','swarm_s.py'],
entry_points = {
'console_scripts': [
'swarm = swarm:main',
'swarm-... |
import con | fig
def debug(*args):
if config.DEBUG:
| print(*args) |
#!/usr/bin/env python
from __future__ import division, print_function
def configuration(parent_package='',top_path=None):
from numpy.distutils. | misc_util import Configuration
config = Configuration('compat', parent_package, top_path)
return config
if __name__ == '__main__':
from numpy | .distutils.core import setup
setup(configuration=configuration)
|
from django.con | trib.auth.decorators import user_passes_test
from django.contrib.auth.models import Group
def group_required(names, login_url=None):
"""
Checks if the user is a member of a particular group (or at least one
group from the list)
"""
if not hasattr(names,'__iter__'):
names = [names]
retur... | login_url=login_url)
|
# LogicalFile Management Providers
#
# Copyright (C) 2013-2014 Red Hat, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright not... | ir <directory>
%(cmd)s show <target>
Commands:
list List a directory. When depth is specified, at most depth levels
will be listed recursively.
The files and directories are listed in a tree-like structure.
Possible listed file types are:
... | * P : Pipe file.
* L : Symbolic link.
* S : Unix socket.
createdir Create a directory. The parent directory must exist.
deletedir Delete a directory. The directory must be empty.
show Show detailed information about target. Target can b... |
# @author Avtandil Kikabidze
# @copyright Copyright (c) 2008-2015, Avtandil Kikabidze aka LONGMAN (akalongman@gmail.com)
# @link http://longman.me
# @license The MIT License (MIT)
import os
import sys
import sublime
import sublime_plugin
st_version = 2
if sublime.version() == '... | it, quiet=True)
class CodeFormatterEventListener(sublime_plugin.EventListener):
def on_pre_save(self, view):
view.run_command('code_formatter', {'saving': True})
class CodeFormatterShowPhpTransformationsCommand(sublime_plugin.TextCommand):
def run(self, edit, syntax=False):
import subproc... | latform = sublime.platform()
settings = sublime.load_settings('CodeFormatter.sublime-settings')
opts = settings.get('codeformatter_php_options')
php_path = 'php'
if ('php_path' in opts and opts['php_path']):
php_path = opts['php_path']
php55_compat = False
... |
# Xandikos
# Copyright (C) 2017 Jelmer Vernooij <jelmer@jelmer.uk>, et al.
#
# 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; version 3
# of the License or (at your option) any later version of
# ... | alidFileContents(
self.content_type,
self.content,
"Missin | g header and trailer lines",
)
if not self.addressbook.validate():
# TODO(jelmer): Get data about what is invalid
raise InvalidFileContents(
self.content_type,
self.content,
"Invalid VCard file")
@property
def addressbo... |
# 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... | openstack_dashboard.test import helpers as test
INDEX_URL = reverse('horizon:project:data_processing.job_executions:index')
DETAILS_URL = reverse(
'horizon:project:data_processing.job_executions:details' | , args=['id'])
class DataProcessingJobExecutionTests(test.TestCase):
@test.create_stubs({api.sahara: ('job_execution_list',)})
def test_index(self):
api.sahara.job_execution_list(IsA(http.HttpRequest)) \
.AndReturn(self.job_executions.list())
self.mox.ReplayAll()
res = self... |
from Gaudi.Configuration import *
from Configurables import GaudiSequencer
from Configurables import DaVinci
simulation=False
from Configurables import EventNodeKiller
eventNodeKiller = EventNodeKiller('DAQkiller')
eventNodeKiller.Nodes = ['DAQ','pRec']
#MySequencer.Members+=[eventNodeKiller]
from Configurables impo... | aVinci().InputType='MDST'
#DaVinci().RootInTES='/Event/Bhadron/'
D | aVinci().UserAlgorithms+=[eventNodeKiller,tuple]
DaVinci().TupleFile="Output.root"
DaVinci().HistogramFile="histos.root"
DaVinci().DataType='2012'
DaVinci().EvtMax=-1
DaVinci().PrintFreq=1000
DaVinci().MoniSequence=[tuple]
DaVinci().Simulation=False
|
import logging
from django import template
from django. | conf import settings
from django.core.urlresolvers import reverse
from django.http import Http404
from apps.dasforms.forms import ContactForm
from apps.dasforms.utils import get_form
register = template.Library()
logger = logging.getLogger(__name__)
@register.inclusion_tag('dasforms/inline_form.html', takes_context=... | form = formclass(referer, topic)
action = reverse("dasform", kwargs={'formtype':formtype})
except:
logger.warning('Form class could not be found: %s' % formtype)
form = ContactForm()
action = reverse("dasform", kwargs={'formtype':'ContactForm'})
senturl = reverse("sent")
re... |
#-*- coding:utf8 -*-
def crawl_folder(folder):
import os
os_objects = []
seen = set([folder])
for os_object_name in os.listdir(folder):
full_path = os.path.normpath(os.path.join(folder, os_object_name))
if not full_path in seen:
os_objects.append((full_path, os_object_name... | elf.log_stream.flush()
def log_state(self):
from datetime import datetime
self.log_stream.write("Logger: " + self.name + ", value: " + str(self.value) + ", time: " + str(datetime.now())+ "\n")
self.log_stream.flush() | |
#!/usr/bin/python
# Example using an RGB character LCD wired directly to Raspberry Pi or BeagleBone Black.
import time
import Adafruit_CharLCD as LCD
# Raspberry Pi configuration:
lcd_rs = 27 # Change this to pin 21 on older revision Raspberry Pi's
lcd_en = 22
lcd_d4 = 25
lcd_d5 = 24
lcd_d6 = 23
lcd_d7... | 0.0, 1.0, 0.0)
| lcd.clear()
lcd.message('Noel')
time.sleep(3.0)
lcd.set_color(0.0, 0.0, 1.0)
lcd.clear()
lcd.message('Je vais')
time.sleep(3.0)
lcd.set_color(1.0, 1.0, 0.0)
lcd.clear()
lcd.message('te faire')
time.sleep(3.0)
lcd.set_color(0.0, 1.0, 1.0)
lcd.clear()
lcd.message('des trucs')
time.sleep(3.0)
lcd.se... |
# -*- coding: utf-8 -*-
import logging
from unittest import mock
impor | t olympia.core.logger
from olympia.amo.tests import TestCase
from olympia.users.models import UserProfile
class LoggerTests(TestCase):
@mock.patch('olympia.core.get_remote_addr', lambda: '127.0.0.1')
@mock.patch('olympia.core.get_user', lambda: UserProfile(username=u'fôo'))
def test_get_logger_adapter(se... | a': {
'REMOTE_ADDR': '127.0.0.1',
'USERNAME': u'fôo',
}
}
assert log.process('test msg', {}) == ('test msg', expected_kwargs)
@mock.patch('olympia.core.get_remote_addr', lambda: '127.0.0.1')
@mock.patch('olympia.core.get_user', lambda: None)
def t... |
import json
import datetime
from django.core.files.base import ContentFile
from django.core.exceptions import ValidationError
from django.utils.timezone import utc
from ..models import AgentProfile
from ..exceptions import IDNotFoundError, ParamError
from ..utils import etag
class AgentProfileManager():
def __... | profiles'
raise ParamError(err_msg)
ids = [p.profile_id for p in profs]
else:
ids = self.Agent.agentprofile_set.values_list(
'profile_id', flat=True)
return ids
def delete_profile(self, profile_id):
try:
self.get_profile(p... | e don't want it anyway
except AgentProfile.DoesNotExist:
pass
except IDNotFoundError:
pass
|
# -*- coding: utf-8 -*-
# © 2016 OpenSynergy | Indonesia
# License AGPL-3.0 or later (htt | p://www.gnu.org/licenses/agpl.html).
from . import test_hr_expense
|
# -*- coding: utf-8 -*-
# © 201 | 6 ClearCorp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import account | _invoice_incoterm
|
import datetime
class Store:
def parse(self,line):
fields=line.split('\t')
self.id = fields[0]
self.name = fields[1]
return self
def __repr__(self):
return "Store: id=%s \t name=%s"%(self.id,self.name)
class Product:
def parse(self,line):
fields=line.split('\t')
self.id = fields[0]
self. | name = fields[1]
self.category=fields[2]
return self
def __repr__(self):
return "Product: id=%s \t name=%s"%(self.id,self.name)
class SaleRow:
def parse(self,line):
fields=line.split('\t')
self.day=fields[0] # maybe parse as date? see below:)
# self.day=date | time.datetime.strptime(fields[0],"%Y-%m-%d")
self.store_id=fields[1]
self.product_id=fields[2]
self.quantity=int(fields[3]) # let's parse this
return self
def __repr__(self):
return "SaleRow: day=%s \t store_id=%s \t product_id=%s quantity=%d"%(self.day,self.store_id,self.product_id, self.quantity)
|
se,
*,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.artifactregistry_v1beta2.types.ListRepositor... | self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterator[package.ListPackagesResponse]:
yield self._response
while self._response.next_page_token:
self._re | quest.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[package.Package]:
for page in self.pages:
yield from page.packages
def __repr__(self) -> str:
... |
from mock import MagicMock, patch
import pytest
from adbpy.adb import Adb
from adbpy import Target, AdbError
@pytest.fixture
def adb():
adb = Adb(())
adb.socket = MagicMock()
return adb
def test_get_transport():
assert Adb._get_transport(Target.ANY) == "host:transport-any"
assert Adb._get_transp... | adb_version(adb):
adb.version()
adb.socket.send.assert_called_once_with("host:version")
def test_adb_get_serialno_any(adb):
adb.get_serialno(Target.ANY)
adb.socket.send.assert_called_once_with("host:get-serialno")
def test_adb_get_serialno_serial(adb):
adb.get_serialno("6097191b")
adb.socket.... | h("host-serial:6097191b:get-serialno")
def test_adb_get_product(adb):
adb.get_product("950a8ad5")
adb.socket.send.assert_called_once_with("host-serial:950a8ad5:get-product")
def test_adb_get_devpath(adb):
adb.get_devpath(Target.USB)
adb.socket.send.assert_called_once_with("host-usb:get-devpath")
def ... |
from netools import nextIpInPool, ping, aliveHost, hostsUnDone
def main():
aliveHosts = []
# pool IP
ipStart = "192.168.56.1"
ipEnd = "192.168.56.5"
print"Pools: ", ipStart + " -> " + ipEnd
print"Scanning online Router on netw | ork..."
aliveHosts = aliveHost(ipStart, ipEnd)
print "online Router:"
print aliveHosts
# print"New Hosts Alive in Pools:",hostsUnDone(aliveHosts, aliveHost(ipStart,ipEnd))
if __name__ == '__mai | n__':
main()
|
# This document is part of Acronym
# https://github.com/geowurster/Acronym
# =================================================================================== #
#
# New BSD License
# |
# Copyright (c) 2014, Kevin D. Wurster
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditio... | the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * The names of its contributors may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS... |
wing conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# 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 ... | f.seek(block_height * 80)
h = f.read(80)
f.close()
if len(h) == 80:
h = self.deserialize_header(h)
return h
def get_target(self, index, chain=None):
if index == 0:
return 0x1d00ffff, MAX_TARGET
first = self.... | 1:
last = h
assert last is not None
# bits to target
bits = last.get('bits')
bitsN = (bits >> 24) & 0xff
assert bitsN >= 0x03 and bitsN <= 0x1d, "First part of bits should be in [0x03, 0x1d]"
bitsBase = bits & 0xffffff
assert bitsBase >= 0x800... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.env | iron.setdefault("DJANGO_SETTINGS_MODULE", "django_website.settings")
from django.core.management import execute_from_command_line
| execute_from_command_line(sys.argv)
|
# ##### 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed ... | .active_object and context.active_object.type == "MESH"
def get_layout(self):
"""Returns layout depending where it's drawn into. If popover cre | ate extra box to make it distinguisable between different sub-panels."""
if self.is_popover:
layout = self.layout.box().column()
else:
layout = self.layout
return layout
class SCS_TOOLS_PT_Mesh(_MeshPanelBlDefs, Panel):
"""
Creates "SCS Mesh" panel in the Objec... |
from .engine import Bl | oggingEngine
from .processor import PostProcessor
from .sqlastorage import SQLAStorage
from .storage import Storage
"""
Flask-Blogging is a Flask extension to add blog support to your
web application. This extension uses | Markdown to store and then
render the webpage.
Author: Gouthaman Balaraman
Date: June 1, 2015
"""
__author__ = 'Gouthaman Balaraman'
__version__ = '0.4.2'
|
# 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 Li... | idate
:raises keystone.exception.ValidationError: if `resource_to_validate` is
None. (see wrapper method below).
:raises TypeError: at decoration time when the expected resource to
validate isn't fou | nd in the decorated method's
signature
"""
schema_validator = validators.SchemaValidator(request_body_schema)
schema_validator.validate(resource_to_validate)
def nullable(property_schema):
"""Clone a property schema into one that is nullable.
:param dict property_schema: s... |
#!/usr/bin/python3
import argparse
import os
import sys
import configuration
import shouter
from gitFunctions import Commiter
from gitFunctions import Initializer, Differ
from rtcFunctions import ImportHandler
from rtcFunctions import RTCInitializer
from rtcFunctions import RTCLogin
from rtcFunctions import Workspace... | '--stored', help='Use stored password for the repository connection', action='store_true')
arguments = parser.parse_args()
configuration.setconfigfile(arguments.configfile)
configuration.setUser(arguments.user)
configuration.setPassword(arguments.password)
configuration.setStored(arguments.stored)
... | g = configuration.get()
streamname = config.streamname
branchname = streamname + "_branchpoint"
previousstreamname = config.previousstreamname
offendingbranchname = None
if not Commiter.checkbranchname(streamname):
offendingbranchname = streamname
elif not Commiter.checkbranchname(branch... |
"""
Lua pattern matcher based on a NFA
inspired by
http://swtch.com/~rsc/regexp/regexp1.html
"""
from rpyre.interface.lua import compile_re
from rpyre.matching import find
def main(args):
n = 20
s = args[1]
#s = "(a|b)*a%sa(a|b)*$" | % ("(a|b)" * n, )
print s
evilregex = compile_re(s)
import os
chunks = []
# use os.read to be RPython compatible
while True:
s = os.read(0, 4096)
if not s:
break
chunks.append(s)
s = "".join(chunks)
print len(s)
print find(evilregex, s, 0)
"""
... | from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation.
# 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.apac... | PENDING_UPDATE = "PENDING_UPDATE"
PENDING_DELETE = " | PENDING_DELETE"
INACTIVE = "INACTIVE"
ERROR = "ERROR"
# FWaaS firewall rule action
FWAAS_ALLOW = "allow"
FWAAS_DENY = "deny"
# L3 Protocol name constants
TCP = "tcp"
UDP = "udp"
ICMP = "icmp"
# Network Type constants
TYPE_FLAT = 'flat'
TYPE_GRE = 'gre'
TYPE_LOCAL = 'local'
TYPE_VXLAN = 'vxlan'
TYPE_VLAN = 'vlan'
TYP... |
# au | thor: Milan Kubi | k
|
#####################################################
#
# A library for getting match information for a given team at a given event
# out of the Blue Alliance API
#
# Authors: Andrew Merrill and Jacob Bendicksen (Fall 2014)
#
# Requires the blueapi.py library
######################################################
#thi... | i.getTeamEventMatches(eventKey))):
if blueapi.getTeamEventMatches(eventKe | y)[n]['comp_level'] == 'qf':
matches.append(blueapi.getTeamEventMatches(eventKey)[n]['match_number'])
matches.sort()
return matches
#returns a list of quarterfinal matches that the team played in
def getQFMatches(eventKey):
matches = []
for n in range(0,len(blueapi.getEventMatches(eventKey)... |
# Copyright 2013 OpenStack Foundation
# 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 requ... | n['opt_name']):
| break
else:
self.fail('Extra DHCP option not found in port %s' %
str(retrieved_option))
class ExtraDHCPOptionsIpV6TestJSON(ExtraDHCPOptionsTestJSON):
_ip_version = 6
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.6.1
Generated by: https://github. | com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v2alpha1_horizontal_pod_autoscaler_spec import V2alpha1HorizontalPodAutoscalerSpec |
class TestV2alpha1HorizontalPodAutoscalerSpec(unittest.TestCase):
""" V2alpha1HorizontalPodAutoscalerSpec unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV2alpha1HorizontalPodAutoscalerSpec(self):
"""
Test V2alpha1HorizontalPodAutoscalerSp... |
from django import forms
from django.utils.html import escape
from django.forms.utils import ErrorList
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from booktype.utils.misc import booktype_slugify
from booki.editor.models import BookiGroup
from booktype.ut... | ea(attrs={'rows': '10', 'cols': '40'})
)
group_image = forms.FileField(
label=_('Group image'),
required=False,
widget=RemovableImageWidget(attrs={
'label_class': 'checkbox-inline',
'input_class': 'group-image-removable'
}
)
)
... | 'name', 'description'
]
def __init__(self, *args, **kwargs):
kwargs.update({'error_class': SpanErrorList})
super(BaseGroupForm, self).__init__(*args, **kwargs)
def clean_name(self):
new_url_name = booktype_slugify(self.cleaned_data['name'])
group_data_url_name = BookiG... |
# coding=utf-8
from __future__ import absolute_import
import gevent
from gevent.pywsgi import WSGIHandler
import sys
from webob import Request
from .response import Response
from .socket import Socket
from ..event_emitter import EventEmitter
from .transports import WebsocketTransport
import logging
logger = logging.g... | er_context, *args, **kwargs):
super(EngineHandler, self).__init__(*args, **kwargs)
EventEmitter.__init__(self)
self.server_context = server_con | text
if self.server_context.transports:
self.transports = self.server_context.transports
def bind_framework_info(self, socket):
# Run framework's wsgi application to hook up framework specific info eg. request
# This is why we define /socket.io url in web frameworks and points ... |
e': 'volume',
'device_name': '/dev/vdc'})
])}
bdm = bdi['block_device_mapping'][0]
bdm['connection_info'] = conn_info
disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type,
instance,
... | vif_driver.unplug.assert_called_once_with('inst', 1)
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._unplug_vifs')
@mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain')
def test_cleanup_pass_with_no_mount_device(self, undefine, unp | lug):
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI())
drvr.firewall_driver = mock.Mock()
drvr._disconnect_volume = mock.Mock()
fake_inst = {'name': 'foo'}
fake_bdms = [{'connection_info': 'foo',
'mount_device': None}]
with mock.patch('nova.vir... |
import copy
from threading import Lock
from .metrics_core import Metric
class CollectorRegistry(object):
"""Metric collector registry.
Collectors must have a no-argument method 'collect' that returns a list of
Metric objects. The returned metrics should be consistent with the Prometheus
exposition f... | lf._names_to_collectors[name] = collector
self._collector_to_names[collector] = names
def unregister(self, collector):
"""Remove a collector from the registry."""
with self._lock:
for name in self._collector_to_names[collector]:
| del self._names_to_collectors[name]
del self._collector_to_names[collector]
def _get_names(self, collector):
"""Get names of timeseries the collector produces."""
desc_func = None
# If there's a describe function, use it.
try:
desc_func = collecto... |
lType):
def __init__(self, value2=None, value1=None):
super(notEqualTypeSub, self).__init__(value2, value1, )
supermod.notEqualType.subclass = notEqualTypeSub
# end class notEqualTypeSub
class betweenTypeSub(supermod.betweenType):
def __init__(self, max=None, value=None, min=None):
super(betwe... | , value=None, min=None):
super(notBetweenTypeSub, self).__init__(max, value, min, )
supermod.notBetween | Type.subclass = notBetweenTypeSub
# end class notBetweenTypeSub
class orTypeSub(supermod.orType):
def __init__(self, clause=None):
super(orTypeSub, self).__init__(clause, )
supermod.orType.subclass = orTypeSub
# end class orTypeSub
class andTypeSub(supermod.andType):
def __init__(self, clause=None):... |
ies.
price_entries = prices.get_last_price_entries(entries, None)
return used_open_entries + holdings_entries + price_entries
def report_holdings(currency, relative, entries, options_map,
aggregation_key=None,
sort_key=None):
"""Generate a detailed list of all hold... | of included ones")
parser.add_argument('-o', | '--operating-only',
action='store_true',
help="Only report on operating currencies")
def generate_table(self, entries, errors, options_map):
holdings_list, price_map = get_assets_holdings(entries, options_map)
holdings_list_orig = holdings_lis... |
# -*- coding: utf-8 -*-
from . import app, db
from flask import request, g, session, redirect
from Lotus.model.user import User
from hashlib import md5
from Lotus.lib.msg_code import Msg
import json
@app.route('/user/login', methods=['POST'])
def user_login():
email = request.form.get('email', None)
psw = req... | rs[0].userid
else:
return '{"code":%d,"msg":$s}'.format(Msg[ | 'faild'], 'user not exist')
else:
return '{"code":%d,"msg":$s}'.format(Msg['faild'], 'params not enougth')
@app.route('/user/register', methods=['POST'])
def user_register():
# todo (参数不够)有插入异常怎么办?
# todo 忘记密码..
try:
u = User()
u.username = request.form.get('username', None)
... |
bj.dotted)
# THEN
self.assertEqual(code, actual_coap_obj.code)
class TestCoapMessage(unittest.TestCase):
def test_should_return_version_value_when_version_property_is_called(self):
# GIVEN
version = any_version()
coap_message = coap.CoapMe | ssage(version, any_type(), any_code(), any_message_id(),
any_token(), any_options(), any_payload())
# WHEN
| actual_version = coap_message.version
# THEN
self.assertEqual(version, actual_version)
def test_should_return_type_value_when_type_property_is_called(self):
# GIVEN
_type = any_type()
coap_message = coap.CoapMessage(any_version(), _type, any_code(), any_message_id(),
... |
: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from telestream_cloud_qc.configuration import Configuration
class Partiti... | lf.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PartitionStatusTest):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, | other):
"""Returns true if both objects are not equal"""
if not isinstance(other, PartitionStatusTest):
return True
return self.to_dict() |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'nosedjango'
DATABASE_USER = 'root'
DATABASE_PASSWORD = ''
DATABASE_HO | ST = ''
DATABASE_PORT = ''
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
MEDIA_ROOT = '' |
MEDIA_URL = ''
ADMIN_MEDIA_PREFIX = '/media/'
SECRET_KEY = 'w9*+(qevfn*j2959ikv-_7kj7ivptt#8&n*gy0o&ktisx@%rzt'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.comm... |
"""Leetcode 100. Same Tree
Easy
URL: https://leetcode.com/problems/same-tree/
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and
the nodes have the same value.
Example 1:
Input: 1 1
/ \ ... | = TreeNode(2)
p.right = TreeNode(3)
q = TreeNode(1)
q.left = TreeNode(2)
q.right = TreeNode(3)
print SolutionPreorderRecur().isSameTree(p, q)
print SolutionPreorderIter().isSameTree(p, q)
# Input: 1 1
# / \
# 2 2
# [1... | = TreeNode(2)
q = TreeNode(1)
q.right = TreeNode(2)
print SolutionPreorderRecur().isSameTree(p, q)
print SolutionPreorderIter().isSameTree(p, q)
# Input: 1 1
# / \ / \
# 2 1 1 2
# [1,2,1], [1,1,2]
# Output: false
p = Tre... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 11 17:55:48 2016
用欧拉法计算自行车从静止起步后的速度
@author: nightwing
"""
import matplotlib.pyplot as plt
DENSITY = 1.29 #空气密度(kg/m3)
C = 1.0 #阻力系数
A = 0.33 #截面积(m2)
M = 70.0 #人车质量(kg)
v = 7.0 #转折速度(m/s)
v1 = 0.0 #( | 无阻力)速度(m/s)
v2 = 0.0 #(有阻力)速度(m/s)
P = 400.0 #功率(w)
t = 0 #初始时间
t_max = 200 #截止时间(s)
dt = 0.1 #时间间隔
time = [] #此列表存储时间
velocity1 = [] #此列表存储无空气阻力时的速度
velocity2 = [] #此列表存储有空气阻力时的速度
#---欧拉法计算自行车运动速度---
while t <= t_max:
velocity1.append(v1)
| velocity2.append(v2)
time.append(t)
if v1 <= v:
v1 += P/(M*v)*dt
if v2 <= v:
v2 += P/(M*v)*dt-C*DENSITY*A*v2**2/(2*M)*dt
if v1 > v:
v1 += P/(M*v1)*dt
if v2 > v:
v2 += P/(M*v2)*dt-C*DENSITY*A*v2**2/(2*M)*dt
t += dt
#------------绘图---------------
plt.title("B... |
ython.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import math_ops
from ... | Op raising `InvalidArgumentError` if `cast(x, int_dtype) != x`.
"""
with ops.name_scope(name, values=[x, data]):
x = ops.convert_to_tensor(x, name="x")
if x.dtype.is_integer:
return control_flow_ops.no_op()
message = message or "{} has non-integer components".format(x)
if int_dtype is None... | t_dtype = {
dtypes.float16: dtypes.int16,
dtypes.float32: dtypes.int32,
dtypes.float64: dtypes.int64,
}[x.dtype.base_dtype]
except KeyError:
raise TypeError("Unrecognized type {}".format(x.dtype.name))
return check_ops.assert_equal(
x, math_ops.cast(... |
#!/usr/bin/env python
import os
import sys
## A name of directory containing 'path:...' file
## You can download them using 'make-wget_pathway.sh' script
dir_name = sys.argv[1]
f_summary = open('%s.summary'%dir_name,'w')
f_genes = open('%s.genes'%dir_name,'w')
f_compounds = open('%s.compounds'%dir_name,'w')
gene_to... | if( len(gene_list) == 0 ):
sys.stderr.write('//SKIP// %s(%d) %s\n'%(path_id, len(gene_list), path_name))
continue
f_summary.write('path:%s\t%s\t%d\t%d\n'%(path_id, path_name, len(gene_list), len(comp_list)))
f_summary.close()
f_genes.close()
f_compounds.close()
| |
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 languag... | upper()
else:
| yield (*key, "input"), log_src.upper()
yield (*key, "output"), log_dst.upper()
if is_seq:
yield (*key, "sequential"), sdf_type
for t, v in timings:
yield (*key, t), v
... |
from SamplingAccuracyEvaluation import SamplingAlgorithm as SA
from SamplingAccuracyEvaluation import AccuracyEvaluation as AE
from SamplingAccuracyEvaluation import PrintGraph as PG
from SamplingAccuracyEvaluation import StatisticalCalculation as SC
import operator
def populationListGenerate(filePath, target):
pr... | lation', numOfTrials)
print()
print(str(numOfTrials)+'_ReservoirSampling')
sampleList = SA.sortedReservoirSam(sampleSize, windowList)
tempEvalList = AE.run(windowList, sampleList, jSDP | ieceCount, pAAPieceCount)
SC.sumPerIndex(reservoirEvalList, tempEvalList)
# if numOfTrials == 1: PG.printGraph(sampleList, 'Reservoir', numOfTrials)
print()
print(str(numOfTrials)+'_HashSampling')
sampleList = SA.hashSam(sampleSize, windowList)
te... |
# OpenShot Video Editor is a program that creates, modifies, and edits video files.
# Copyright (C) 2009 Jonathan Thomas
#
# This file is part of OpenShot Video Editor (http://launchpad.net/openshot/).
#
# OpenShot Video Editor is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... | pth = params["bevel_depth"]
text_object.body = params["title"]
text_object.align = params["spacemode"]
text_object.size = params["text_size"]
text_object.space_character = params["width"]
# Get font o | bject
font = None
if params["fontname"] != "Bfont":
# Add font so it's available to Blender
font = load_font(params["fontname"])
else:
# Get default font
font = bpy.data.fonts["Bfont"]
text_object.font = font
text_object = bpy.data.curves["Subtitle"]
text_object.extrude = params["extrude"]
text_object.bevel_dept... |
evel project folder
PROJECT_ROOT = SITE_ROOT.parent
# Site name:
SITE_NAME = SITE_ROOT.basename()
# Id for the Sites framework
SITE_ID = 1
########## END PATH CONFIGURATION
########## DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = bool(get_env_setting('DEBUG', False))
... | ps.enhance',
)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS
########## END APP CONFIGURATION
########## LOGGING CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible l... | opics/logging for
# more details on how to customize your logging configuration.
LOGS_ROOT = get_env_setting('LOGS_ROOT', PROJECT_ROOT / 'logs')
if not isinstance(LOGS_ROOT, path):
LOGS_ROOT = path(LOGS_ROOT)
if not LOGS_ROOT.exists():
LOGS_ROOT.mkdir()
LOGGING = {
'version': 1,
'disable_existing_logge... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011-2013 Martijn Kaijser
#
# 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 ... | t xbmc
import xbmcaddon
### get addon info
__addon__ = xbmcaddon.Addon(id='script.artwork.downloader')
__addonid__ = __addon__.getAddonInfo('id')
__addonname__ = __ | addon__.getAddonInfo('name')
__author__ = __addon__.getAddonInfo('author')
__version__ = __addon__.getAddonInfo('version')
__addonpath__ = __addon__.getAddonInfo('path')
__addonprofile__= xbmc.translatePath(__addon__.getAddonInfo('profile')).decode('utf-8')
__icon__ = __addon__.getAddonInfo('icon')
__... |
# -* | - coding: utf- | 8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import note |
import unittest
from mopidy_tunein import Extension
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Ext | ension()
config = ext.get_default_config()
self.assertIn("[tunein]", config)
self.assertIn("enabled = true", config)
def test_get_config_schema(self):
ext = Extension()
schema = ext.get_config_schema()
self.assertIn("timeout", schema)
| self.assertIn("filter", schema)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
COST_AUTO = 5
class Appartment(object):
"""Appartment class consists of features that have all appartments"""
def __init__(self, address, metro, transportation, rooms, space, price, floor, addInfo):
super(Appartment, self).__init__()
self.address = self.setAd... | e)
self.pric | e = self.setPrice(price)
self.floor = self.setFloor(floor)
self.addInfo = self.setAddInfo(addInfo)
# Getter methods
def getAddress(self):
return self.address
def getMetro(self):
return self.metro
def getTransportation(self):
return self.transportation
def getRooms(self):
return self.rooms
def ge... |
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from projects.models import Project
User = get_user_model()
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('user')
parser.add_argument('nam... | efault='')
def handle(self, *args, **options):
name = ' '.join(options['name'])
description = ' '.join(options['description'])
u = User.objects.get(username=options['user'])
p = Project.objects.create(user=u, name=name, description=description)
p.save()
self.stdo | ut.write(str(p.pk))
|
# -*- coding: utf-8 -*-
import traceback
from datetime import timedelta
from django.core import mail
from django.core.mail import EmailMultiAlternatives, mail_admins
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.utils.translation import ugettext_laz... | format(exc)
body += traceback.format_exc()
mail_admins(s | ubject, body)
else:
attendee.sent_date = timezone.now()
attendee.save()
self.stdout.write(
unicode(_(u'Foram enviados {0} emails\n'.format(num_emails))),
)
|
import sys
import glob
def read_fileb(filename, mode='rb'):
f = open(filename, mode)
try:
return f.read()
finall | y:
f.close()
def write_fileb(filename, value, mode='wb'):
f = open(filename, mode)
try:
f.write(value)
finally:
f.close()
for filename in glob.glob(sys.argv[1]):
data1 = read_fileb(filename)
write_fileb( | filename + '.bak2', data1)
data2lines = read_fileb(filename).strip().split('\n')
data2 = '\n'.join([line.rstrip(
).replace('\t', ' ' * 2) for line in data2lines]) + '\n'
write_fileb(filename, data2)
print filename, len(data1) - len(data2)
|
from hypothesis | .utils.conventions import not_set
def accept(f):
def complex_numbers():
return f()
return complex_numb | ers
|
#
# Created by DraX on 2005.08.08
#
# Updated by ElgarL on 28.09.2005
#
print "importing village master data: Talking Island Village ...done"
import sys
from net.sf.l2j.gameserver.model.quest import State
from net.sf.l2j.gameserver.model.quest import QuestState
from net.sf.l2j.gameserver.model.quest.jy... | 02 or pcId == 0x06 or pcId = | = 0x09:
htmltext = "7026-09.htm"
#mage, wizard, cleric]:
if pcId == 0x0a or pcId == 0x0b or pcId == 0x0f:
htmltext = "7026-10.htm"
#sorceror, necromancer, warlock, bishop, prophet
if pcId == 0x0c or pcId == 0x0d or pcId == 0x0e or pcId == 0x10 or pcId == 0x11:
htmltext = "7026-10.htm"
... |
ib2
from collections import namedtuple
from urllib import urlencode
from urllib import quote
API_BASE = 'https://api.github.com/'
REPO_TYPE_CHOICES = ('all', 'public', 'private', 'forks', 'sources', 'member')
@contextlib.contextmanager
def chdir(dirname=None):
curdir = os.getcwd()
try:
if dirname i... | mes you have SSH keys setup for cloning/pulling
ssh_parser = subparsers.add_parser('ssh', help='use ssh for | cloning/pulling, and use access token for github api access')
ssh_parser.add_argument('-d', '--dir', type=str, dest='directory', required=True, help='full or relative path to store backed up repositories')
ssh_parser.add_argument('-o', '--org', type=str, required=True, help='github organization name')
ssh_... |
""" Return the index by key into the list of LogEntries. """
return self._index
@property
def prev_hash(self):
""" Return the content hash of the previous Log. """
return self._prev_hash
@property
def prev_master(self):
"""
Return the ID of the master of the ... | nes are intended
def __str__(self):
if self.hashtype == HashTypes.SHA1:
fmt = '%013u %40s %40s "%s" %s\n'
else:
fmt = '%013u %64s %64s "%s" %s\n'
return fmt % (self._timestamp, self._key,
self._node_id, self._src, self._path)
def __eq__(self... | == other.timestamp and\
self._key == other.key and\
self._node_id == other.node_id and\
self._src == other.src and\
self._path == other.path
def __ne__(self, other):
return not self.__eq__(other)
def equals(self, other):
"""
The function ... |
#!/usr/bin/env python
import sys
import re
from helpers import *
PROGRAM_USAGE = """
SeqAn invalid identifiers detection script.
USAGE: invalid_identifiers.py BASE_PATH
BASE_PATH is the root path of all the folders to be searched.
This script generates a list of invalid identifiers found in the code base,
paired wi... | '_O_RDONLY',
'_O_RDWR',
'_O_TEMPORARY',
'_O_TRUNC',
'_O_WRONLY',
'_KMER_H',
'_MSC_EXTENSIONS',
'_GLIBCXX_PARALLEL',
'_FILE_OFFSET_BITS',
'_POSIX_SYNCHRONIZED_IO',
'__cplusplus',
'__(force)?inline(__)?... | NS____',
'_INSERTS______',
'_REPLACEMENTS_',
'__int128',
'__SSE2__',
'__m128i',
'__VA_ARGS__',
'__FILE__',
'__LINE__',
'__GET_OPT_H__',
'_OPENMP',
'__SINIX__',
'__sgi',
'__BEOS__',
... |
# Foris - we | b administration interface for OpenWrt based on NETCONF
# Copyright (C) 2017 CZ.NIC, z.s.p.o. <http://www.nic.cz>
#
# 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 Licens... | r version.
#
# This program 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 Lic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.