prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from time import strftime
import MySQLdb
api_name = raw_input('API Name: ')
api_url = raw_input('API URL: ')
crawl_frequency = raw_input('A | PI Crawl Frequency(in mins): ')
last_crawl = strftime("%H:%M:%S")
db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="dataweave")
curs | or = db.cursor()
cursor.execute('''INSERT INTO api_list (api_name, api_url, last_crawl, crawl_frequency) VALUES (%s, %s, %s, %s)''', (api_name, api_url, last_crawl, crawl_frequency))
db.commit()
print '\nAPI added!\n' |
from __future__ import unicode_literals
from django import forms
from django.forms.models import inlineformset_factory
from django.forms.widgets import ClearableFileInput
from ...product.models import (ProductImage, Product, ShirtVariant, BagVariant,
Shirt, Bag)
PRODUCT_CLASSES = {
... | ass ProductForm(forms.Mode | lForm):
class Meta:
model = Product
fields = ['name', 'description', 'collection']
class ShirtForm(ProductForm):
class Meta:
model = Shirt
exclude = []
class BagForm(ProductForm):
class Meta:
model = Bag
exclude = []
class ImageInputWidget(ClearableFileI... |
import os.path
from pyneuroml.lems.LEMSSimulation import LEMSSimulation
import shutil
import os
from pyneuroml.pynml import read_neuroml2_file, get_next_hex_color, print_comment_v, print_comment
import random
def generate_lems_file_for_neuroml(sim_id,
neuroml_file,
... | on.id
ls.create_o | utput_file(of0, "%s.%s.v.dat"%(sim_id,population.id))
for i in range(size):
if save_all_segments:
quantity_template_seg = "%s/%i/"+component+"/%i/v"
for segment_id in segment_ids:
quantity... |
from unittest import TestCase
from django.core.management import call_command
from test_app.models import Place
class BatchGeocodeTestCase(TestCase):
def setUp(self):
self.place = Place()
def test_batch_geocode(self):
self.place.address = "14 Rue de Rivoli, 75004 Paris, France"
self.... | self.place.refresh_fro | m_db()
self.assertIsNotNone(self.place.locality)
|
#!/usr/bin/env python
# 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... | oid'])
LABEL = Component(iOS='//XCUIElementTypeStaticText[{}]', Android='//android.widget.TextView[{}]')
BUTTON = Component(iOS='//XCUIElementTypeButton[{}]', A | ndroid='//android.widget.Button[{}]')
TEXTFIELD = Component(iOS='//XCUIElementTypeTextField[{}]', Android='//android.widget.EditText[{}]')
PWDFIELD = Component(iOS='//XCUIElementTypeSecureTextField[{}]', Android='//android.widget.EditText[{}]')
LIST = Component(iOS='//XCUIElementTypeTable/*[{}]', Android='/... |
import sys
from ctypes import create_string_buffer
from ._libsoc import (
BITS_8, BITS_16, BPW_ERROR,
MODE_0, MODE_1, MODE_2, MODE_3, MODE_ERROR, api
)
PY3 = sys.version_info >= (3, 0)
class SPI(object):
def __init__(self, spidev_device, chip_select, mode, speed, bpw):
if not isin... | aw
def write(self, byte_array):
assert len(byte_array) > 0
if PY3:
buff = bytes(byte_array)
else:
buff = ''.join(map(chr, byte_array) | )
api.libsoc_spi_write(self._spi, buff, len(buff))
def rw(self, num_bytes, byte_array):
assert num_bytes > 0
assert len(byte_array) > 0
rbuff = create_string_buffer(num_bytes)
if PY3:
wbuff = bytes(byte_array)
else:
wbuff = ''.join(m... |
ss = models.PositiveSmallIntegerField(
validators=[
validators.MinValueValidator(6),
validators.MaxValueValidator(12),
],
verbose_name=_(u'class'),
)
school_year = models.IntegerField(
validators=[
valid... | e_plural=_(u'alumnis')
def contactable(self):
""" If the alumni agreed to receive information.
"""
return self.interest_level >= 22;
class StudentMark(models.Model):
""" Mark student with some mark.
"""
student = models.ForeignKey(
Student,
verbose_nam... | t'),
)
end = models.DateField(
blank=True,
null=True,
verbose_name=_(u'end'),
)
def __unicode__(self):
return unicode(self.student)
class Meta(object):
abstract = True
class SocialDisadvantageMark(StudentMark):
""" Mark stu... |
s.images import get_image_dimensions
d = get_image_dimensions(self.file.file)
if d: t += "<br/>%d×%d" % (d[0], d[1])
except IOError, e:
t += "<br/>(%s)" % e.strerror
return t
file_type.admin_order_field = 'type'
file_type.short_descriptio... | ientation == 6:
rotation = 270
elif orientation == 8:
rotation = 90
| if rotation:
image = image.rotate(rotation)
image.save(self.file.path)
except (OSError, IOError), e:
self.type = self.determine_file_type('***') # It's binary something
if getattr(self, '_original_file_path', None):
... |
import pymysql.cursors
from model.group import Group
from model.contact import Contact
class DbFixture():
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection = pymysql.connect(host=host... | (id, name, header, footer) = row
list.append(Group(id=str(id), name=name, header=header, footer=footer))
finally:
cursor.close()
return list
def get_contact_list(self):
list =[]
cursor = self.connecti | on.cursor()
try:
cursor.execute("select id, firstname, lastname from addressbook where deprecated='0000-00-00 00:00:00' ")
for row in cursor:
(id, firstname, lastname) = row
list.append(Contact(id=str(id), firstname=firstname, lastname=lastname))
f... |
bl_format_value.setFont(font)
self.lbl_format_value.setObjectName(_fromUtf8("lbl_format_value"))
self.layout_values.addWidget(self.lbl_format_value)
self.lbl_size_value = QtGui.QLabel(self.verticalLayoutWidget_2)
font = QtGui.QFont()
font.setPointSize(9)
self.lbl_size_val... | _file.setObjectName(_fromUtf8("btn_load_text_file"))
self.lbl_num_characters = QtGui.QLabel(self.group_message)
self.lbl_num_characters.setGeometry(QtCore.QRect(180, 220, 811, 20))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Consolas"))
fon | t.setPointSize(10)
self.lbl_num_characters.setFont(font)
self.lbl_num_characters.setAlignment(QtCore.Qt.AlignCenter)
self.lbl_num_characters.setObjectName(_fromUtf8("lbl_num_characters"))
self.lbl_message_info = QtGui.QLabel(self.group_message)
self.lbl_message_info.setGeometry(Q... |
given hash for this file.
List of supported hashes can be obtained from :mod:`hashlib` package.
This reads the entire file.
.. seealso:: :meth:`hashlib.hash.digest`
"""
return self._hash(hash_name).digest()
def read_hexhash(self, hash_name):
""" Calculate given ha... | ecurityDescriptorOwner()
account, domain, typecode = win32security.LookupAccountSid(None, sid)
return domain + u('\\') + account
def __get_owner_unix(self):
"""
Return the name of the owner of this file or directory. Follow
symbolic links.
.. seealso:: :attr:`owner`... | raise NotImplementedError("Ownership not available on this platform.")
if 'win32security' in globals():
get_owner = __get_owner_windows
elif 'pwd' in globals():
get_owner = __get_owner_unix
else:
get_owner = __get_owner_not_implemented
owner = property(
get_owner, N... |
"""
$Id: Opcode.py,v 1.6.2.1 2011/03/16 20:06:39 customdesigned Exp $
This file is part of the pydns project.
Homepage: http://pydns.sourceforge.net
This code is | covered by the standard Python License. See LICENSE for details.
Opcode values in message header. RFC 1035, 1996, 2136.
"""
QUERY = 0
IQUERY = 1
STATUS = 2
NOTIFY = 4
UPDATE = 5
# C | onstruct reverse mapping dictionary
_names = dir()
opcodemap = {}
for _name in _names:
if _name[0] != '_': opcodemap[eval(_name)] = _name
def opcodestr(opcode):
if opcodemap.has_key(opcode): return opcodemap[opcode]
else: return `opcode`
#
# $Log: Opcode.py,v $
# Revision 1.6.2.1 2011/03/16 20:06:39 cu... |
import pickle
import redis
from pod_manager.settings import REDIS_HOST, REDIS_PORT, REDIS_DB
__all__ = [
'get_client',
'cache_object',
'g | et_object'
]
def get_client():
client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
return client
def cache_object(client, key, obj, ttl=60):
pipe = client.pipeline()
data = pickle.dumps(obj)
pipe.set(key, data)
if ttl:
pipe.expire(key, ttl)
pipe.execute()
def get... | oads(data)
return obj
|
import numpy as np
arr = np.arange(10)
arr
arr[5]
arr[5:8]
arr[5:8] = 12
arr
arr_slice = arr[5:8]
arr_slice
arr_slice[1] = 12345
arr
arr_slice[:] = 64
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr2d[2]
arr2d[0, 2]
arr2d[0][2]
arr3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
old_vals... | [:2]
arr2d[:2, 1: | ]
arr2d[2, :1]
arr2d[:, :1]
arr2d[:, :1].shape
arr2d[:2, 1:] = 0
arr2d
|
import sys
sys.p | ath.append('..')
from helpers import render_frames
from graphs.ForwardRendering import ForwardRendering as g
from falcor import *
m.addGraph(g)
m.loadScene('Cerberus/Standard/Cerberus.pyscene')
# default
render_frames(m, 'defau | lt', frames=[1,16,64])
exit()
|
# Codon Usage probability for each scpecie'
USAGE_FREQ = {'E.coli':{'GGG': 0.15,'GGA': 0.11,'GGT': 0.34,'GGC': 0.4,\
'GAG': 0.31,'GAA': 0.69,'GAT': 0.63,'GAC': 0.37,\
'GTG': 0.37,'GTA': 0.15,'GTT': 0.26,'GTC': 0.22,\
'GCG': 0.36,... | 55,\
'TCG': 0.06, 'TTA': 0.07, 'TTG': 0.13, 'CGT': 0.08,\
'GAA': 0.42, 'TAA': 0.28, 'GCA': 0.23, 'GTA': 0.11,\
| 'GCC': 0.4, 'GTC': 0.24, 'GCG': 0.11, 'GTG': 0.47,\
'GAG': 0.58, 'GTT': 0.18, 'GCT': 0.26, 'TGA': 0.52,\
'GAC': 0.54, 'TCC': 0.22, 'TCA': 0.15, 'ATG': 1.0,\
'CGC': 0.19}
}
# Aminoacid to codon translation table
A2C_DICT = {'I'... |
used to insert / create / modify instructions
This class will have to support all the other class creating it.
"""
def __init__(self, current_module = None, context=None):
self.__module = current_module
self.__insertion_point = None
self.__insertion_point_idx = 0
self.__... | self.__current_bb = ip
elif isinstance(ip, Instruction):
self.__insertion_point = ip
self.__insertion_point_idx = ip.parent.find_instruction_idx(ip)
if self.__insertion_point_idx is None:
raise InvalidInstructionException("Count not find instruction in ... | ertion_point_idx += 1
else:
raise InvalidTypeException("Expected either Basic Block or Instruction")
def insert_before(self, ip):
if isinstance(ip, BasicBlock):
self.__insertion_point = ip
self.__insertion_point_idx = -1
self.__current_bb = ip
... |
ate_proxy(self, proxy, proxy_auth):
if proxy and not proxy.scheme == 'http':
raise ValueError("Only http proxies are supported")
if proxy_auth and not isinstance(proxy_auth, helpers.BasicAuth):
raise ValueError("proxy_auth must be None or BasicAuth() tuple")
self.proxy = ... | tinue100=self._continue, timer=self._timer)
self.response._post_init(self.loop)
return self.response
@asyncio.coroutine
def close(self):
if self._writer is not None:
try:
yield from self._writer
finally:
self._ | writer = None
def terminate(self):
if self._writer is not None:
if not self.loop.is_closed():
self._writer.cancel()
self._writer = None
class ClientResponse(HeadersMixin):
# from the Status-Line of the response
version = None # HTTP-Version
status = N... |
"""
This script can be used to ssh to a cloud server started by GNS3. It copies
the ssh keys for a server to a temp file on disk and starts ssh using the
keys.
Right now it only connects to the first cloud server listed in the config
file.
"""
import getopt
import os
import sys
from PyQt4 import QtCore, QtGui
SCR... | _line(sys.argv)
setup()
instances = read_cloud_settings()
if options['action'] == 'ssh':
name, host, private_key, public_key, uid = instances[int(options['server']) - 1]
print('Instance name: {}'.format(name))
print('Host ip: {}'.format(host))
public_key_path = '/tmp/id_rsa... | blic_key_path, 'w').write(public_key)
private_key_path = '/tmp/id_rsa'
open(private_key_path, 'w').write(private_key)
cmd = 'chmod 0600 {}'.format(private_key_path)
os.system(cmd)
print('Per-instance ssh keys written to {}'.format(private_key_path))
cmd = 'ssh -i /tmp/id... |
MILESTONE: {
'type': 'string',
'label': 'Gitlab Milestone',
},
URL: {
'type': 'string',
'label': 'Gitlab URL',
},
REPO: {
'type': 'string',
'label': 'Gitlab Repo Slug',
},
TYPE: {
'... | dated = self.parse_date(updated)
return {
'project': self.extra['project'],
'priority': priority,
'annotations': self.extra.get('annotations', []),
'tags': self.get_tags(),
self.URL: self.extra['issue_url'],
self.REPO: self.extra['project... | self.TITLE: self.record['title'],
self.DESCRIPTION: self.record['description'],
self.MILESTONE: milestone,
self.NUMBER: self.record['iid'],
self.CREATED_AT: created,
self.UPDATED_AT: updated,
self.STATE: state,
self.UPVOTES: ... |
import warnings
from pyzabbix import ZabbixMetric, ZabbixSender
warnings.warn("Module '{name}' was deprecated, | use 'pyzabbix' instead."
"".format(name=__name__), DeprecationWarning)
| |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('taskmanager', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Proj... | olor', validators=[django.core.validators.RegexValidator('(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)')], default='#fff', | max_length=7, help_text='Enter the hex color code, like #ccc or #cccccc')),
('user', models.ForeignKey(verbose_name='user', related_name='profjects', to='taskmanager.Profile')),
],
options={
'ordering': ('user', 'name'),
'verbose_name': 'Project',... |
# -*- coding: utf-8 -*-
import hashlib
import json
import locale
import re
import trac.wiki.formatter
from trac.mimeview.api import Context
from time import strftime, localtime
from code_comments import db
from trac.util import Markup
from trac.web.href import Href
from trac.test import Mock, MockPerm
def md5_hexdi... | % (self.attachment_ticket,
self.attachment_filename),
codecomment=self.id)
if self.line and not self.is_comment_to_changeset:
href += '#L' + str(self.line)
return href
def link_text(self):
if self.is_com... |
if self.is_comment_to_attachment:
return self.attachment_link_text()
# except the two special cases of changesets (revision-only)
# and attachments (path-only), we must always have them both
assert self.path and self.revision
link_text = self.path + '@' + str(self.... |
#!/usr/bin/env python
# encoding: utf-8
from fabric.api import run, env
from cfg import aliyun2_cfg
fr | om helper import update_sys
env.hosts = ['root@{host}'.format(host=aliyun2_cfg['host'])]
env.password = aliyun2_cfg['root_pass']
def restart():
# run('supervisorctl restart drr1')
# run('supervisorctl restart drr2')
run('supervisorctl restart yunsuan1')
run('supervisorctl restart yunsuan2')
run('... | pervisorctl restart gislab')
|
"""Package initialization file for pynoddy"""
import os.path
import sys
import subprocess
# save this module path for relative paths
package_directory = os.path.dirname(os.path.abspath(__file__))
# paths to noddy & topology executables
# noddyPath = os.path.join(package_directory,'../noddy/noddy')
# topologyPath = os... | llest non-null volume. volumes smaller than this are
ignored by the topology algorithm (as they represent pixelation artefacts).
The default is 20 voxels, though thi | s is a global variable and can be changed
with pynoddy.null_volume_threshold.
- *topology_path* = path: location of executable for topology calculation
**Returns**
-Returns any text outputted by the topology executable, including errors.
"""
dvol = kwds.get('ensure_discrete_volume... |
e proper distances"""
# These distances where obtained by gmx distance so they are in nm
ref_id = 13937
results = np.array([0.0, 0.270, 0.285, 0.096, 0.096, 0.015, 0.278, 0.268, 0.179, 0.259, 0.290,
0.270]) * 10
results_grid = run_grid_search(universe, ref_id).get_pair_distances... | ([1., 1., 1.], dtype=np.float32).reshape((1, 3))
if box is None:
pseud | obox = np.zeros(6, dtype=np.float32)
all_coords = np.concatenate([points, query])
lmax = all_coords.max(axis=0)
lmin = all_coords.min(axis=0)
pseudobox[:3] = 1.1*(lmax - lmin)
pseudobox[3:] = 90.
shiftpoints, shiftquery = points.copy(), query.copy()
shiftpoints -=... |
"""
Creates an MySql in Azure.
"""
import settings
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.rdbms import mysql
from msrestazure.azure_exceptions import CloudError
from common.methods import is_version_newer, set_progress
from common.mixins import get_global_id_chars
from infras... | )
CustomField.objects.get_or_create(
name="azure_location",
type="STR",
defaults={
"label": "Azure Location",
"description": "Us | ed by the Azure blueprints",
"show_as_attribute": True,
},
)
CustomField.objects.get_or_create(
name="resource_group_name",
type="STR",
defaults={
"label": "Azure Resource Group",
"description": "Used by the Azure blueprints",
"sho... |
'''Test cases for QImage'''
import unittest
import py3kcompat as py3k
from PySide.QtGui import *
from helper import UsesQApplication, adjust_filename
xpm = [
"27 22 206 2",
" c None",
". c #FEFEFE",
"+ c #FFFFFF",
"@ c #F9F9F9",
"# c #ECECEC",
"$ c #D5D5D5",
"% c #A0A0A0",
... | 8",
"X. c #6D6D6D",
"Y. c #818181",
"Z. c #939393",
"`. c #9E9E9E",
" + c #929292",
".+ c #7D7D7D",
"++ c #ADADAD",
"@+ c #DADADA",
"#+ c #919191",
"$+ c #E1E1E1",
"%+ c #BEBEBE",
"&+ c #ACACAC" | ,
"*+ c #9C9C9C",
"=+ c #B3B3B3",
"-+ c #808080",
";+ c #A8A8A8",
">+ c #393939",
",+ c #747474",
"'+ c #7F7F7F",
")+ c #D1D1D1",
"!+ c #606060",
"~+ c #5C5C5C",
"{+ c #686868",
"]+ c #7E7E7E",
"^+ c #787878",
"/+ c #595959",
". . . + @ # $ % & * = - ; > , ' )... |
SECRET_KEY = 'not-anymore'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = T | rue
USE_L10N = True
USE_TZ = False
DATABASES = {
'default | ': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = [
'reverse_unique',
'reverse_unique_tests',
]
|
# -*- coding: utf-8 -*-
"""
pygments.styles.manni
~~~~~~~~~~~~~~~~~~~~~
A colorful style, inspired by the terminal highlighting style.
This is a port of the style used in the `php port`_ of pygments
by Manni. The style is called 'default' there.
:copyright: Copyright 2006-2019 by the Pygments... | Name.Namespace: 'bold #00CCFF',
Name.Exception: 'bold #CC0000',
Name.Variable: '#003333',
Name.Constant: '#336600',
Name.Label: '#9999FF',
Name.Entity: 'bold #999999',
Name.Attribute: '#330099',
| Name.Tag: 'bold #330099',
Name.Decorator: '#9999FF',
String: '#CC3300',
String.Doc: 'italic',
String.Interpol: '#AA0000',
String.Escape: 'bold #CC3300',
String.Regex: '#33AAAA',
String.Symbol: '#FFCC33',
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | self.rule_set_type = kwargs.get('rule_set_type', None)
self.rule_set_version = kwargs.get('rule_set_version', None)
self.dis | abled_rule_groups = kwargs.get('disabled_rule_groups', None)
|
rting_abstract_count+1)
self.assertEqual(new_abstract.title, 'Silly Walks of the Neanderthals')
self.assertEqual(new_abstract.year, 2015)
starting_author_count = Author.objects.count()
new_author = Author.objects.create(abstract=new_abstract, author_rank=1, first_name="Bob",
... | atlanta.create_fiber_page()
self.assertEqual(Page.objects.count(), starting_page_count+7) # test 6 pages saved
# Create an abstract with two authors
self.assertEqual(Meeting.objects.count(), 3)
self.assertEqual(Abstract.objects.count(), 0)
san_franc | isco = Meeting.objects.get(year=2015)
self.assertEqual(san_francisco.location, 'San Francisco, CA')
new_abstract = Abstract.objects.create(meeting_id=24, contact_email='denne.reed@gmail.com', presentation_type='Paper',
title='Silly Walks of the Neanderthals',
... |
rfile.first_byte_timestamp = 42
r = read_request_head(rfile)
assert r.method == "GET"
assert r.headers["Content-Length"] == "4"
assert r.content is None
assert rfile.reset_timestamps.called
assert r.timestamp_start == 42
assert rfile.read() == b"skip"
def test_read_response():
req = tr... | eaders = self._read(data)
assert headers.fields == [[b"Header", b"one"], [b"Header", b"two"]]
def test_read_continued(self):
data = (
b"Header: one\r | \n"
b"\ttwo\r\n"
b"Header2: three\r\n"
b"\r\n"
)
headers = self._read(data)
assert headers.fields == [[b"Header", b"one\r\n two"], [b"Header2", b"three"]]
def test_read_continued_err(self):
data = b"\tfoo: bar\r\n"
with raises(HttpSyntaxEx... |
"""
Set the configuration variables for fabric recipes.
"""
from fabric.api import env
from fabric.colors import yellow
import os
env.warn_only = True
try:
import ConfigParser as cp
except ImportError:
import configpars | er as cp # Python 3.0
config = {}
_config = cp.SafeConfigParser()
if not os.path.isfile("fabric-recipes.conf"):
print yellow("warning: No config file specified")
_config.read("fabric-recipes.conf")
for section in _config.sections():
opt = _config.items(section)
if section == "global":
env... | elif section == "roledefs":
opt = [(k, v.split(",")) for k, v in opt]
env['roledefs'].update(opt)
else:
config[section] = dict(opt) |
f_progress_50p)
snap_ref_progress_99p = snap_ref_progress.copy()
snap_ref_progress_99p['progress'] = '99%'
snap_ref_progress_99p['status'] = 'error'
db.snapshot_get(ctxt, self.SNAP_UUID).AndReturn(snap_ref_progress_99p)
mox.ReplayAll()
self.assertRaisesAndMessageMatche... | '_nova')
# Stub out the busy wait.
self.stub_out_not_replaying(time, 'sleep')
mox.StubOutWithMock(drv, '_read_info_file')
mox.StubOutWithMock(drv, '_write_info_file')
mox.StubOutWithMock(db, 'snapshot_get')
mox.StubOutWithMock(image_utils, 'qemu_img_info')
mox.Stu... | k(drv, '_ensure_share_writable')
snap_info = {'active': snap_file_2,
self.SNAP_UUID: snap_file,
self.SNAP_UUID_2: snap_file_2}
drv._ensure_share_writable(volume_dir)
drv._read_info_file(info_path, empty_if_missing=True).\
AndReturn(snap_in... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-09 02:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_task_inbox'),
]
operations = [
migrations.AddField(
... | e='due_date',
| field=models.DateField(null=True),
),
]
|
#!/usr/bin/env python
"""
N x N x N Rubik's Cube
"""
| __author__ = "Edwin J. Son <edwin.son@ligo.org>"
__version__ = "0.0.1a"
__date__ = "May 27 2017"
from cub | e import cube
|
k=mask_inv)
output_imgs["pseudo_on_white"]["img"] = cv2.add(cplant1, img_back3)
if filename:
for key in output_imgs:
if output_imgs[key]["img"] is not None:
fig_name_pseudo = str(filename[0:-4]) + '_' + str(channel) + '_pseudo_on_' + \
o... | "hist": cv2.calcHist([norm_channels["g"]], [0], mask, [bins], [0, (bins - 1)])},
"r": {"label": "red", "graph_color": "red",
"hist": cv2.calcHist([norm_channels["r"]], [0], mask, [bins], [0, (bins - 1)])},
"l": {"label": "lightness", "graph_color": "dimgray",
"hist": cv2.cal... | , [bins], [0, (bins - 1)])},
"m": {"label": "green-magenta", "graph_color": "magenta",
"hist": cv2.calcHist([norm_channels["m"]], [0], mask, [bins], [0, (bins - 1)])},
"y": {"label": "blue-yellow", "graph_color": "yellow",
"hist": cv2.calcHist([norm_channels["y"]], [0], mask,... |
from flask import render_template, flash, request, redirect, url_for
from flask_login import login_required
from kernel import agileCalendar
from kernel.DataBoard import Data
from kernel.NM_Aggregates import WorkBacklog, DevBacklog, RiskBacklog
from kconfig import coordinationBookByName
from . import coordination
__a... | coordination.route("/friendliness")
@login_required
def friendliness():
cmp = coordinationBookByName['Friendliness']
backlog = RiskBacklog(*Data.getGlobalComponent(cmp.key))
if backlog.source == 'store':
flash('Data from local storage obtained at {}'.format(backlog.timestamp))
sortedby = request... | n/friendliness.html',
comp=cmp,
reporter=backlog,
sortedby=sortedby,
calendar=agileCalendar)
@coordination.route("/qualityassurance")
@login_required
def qualityassurance():
cmp = coordinationBookByName['Qu... |
from pandac.PandaModules import *
from direct.showbase.PythonUtil import reduceAngle
from otp.movement import Impulse
import math
class PetChase(Impulse.Impulse):
def __init__(self, target = None, minDist = None, moveAngle = None):
Impulse.Impulse.__init__(self)
self.target = target
if min... | elif relH > epsilon:
vH = rotSpeed
else:
vH = 0
if abs(vH * dt) > abs(relH):
vH = relH / dt
if distance > self.minDist and abs(relH) < self.moveAngle:
vForward = self.mover.getFwdSpeed()
else:
vForward = 0
distan... | vForward = distanceLeft / dt
if vForward:
self.vel.setY(vForward)
self.mover.addShove(self.vel)
if vH:
self.rotVel.setX(vH)
self.mover.addRotShove(self.rotVel)
def setMinDist(self, minDist):
self.minDist = minDist
|
#!/usr/bin/env python
# coding: utf-8
# Copyright 2013 The Font Bakery 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/LIC... | format')
parser.add_argument('--autofix', action='store_true', help='Apply autofix')
args = parser.parse_args()
for path in args.ttf_font:
if not os.path.exists(path):
continue
FamilyAndStyleNameFixer(None, | path).apply()
|
"""event_enroll
Revision ID: 425be68ff414
Revises: 3be6a175f769
Create Date: 2013-10-28 11:22:00.036581
"""
#
# # SAUCE - System for AUtomated Code Evaluation
# # Copyright (C) 2013 Moritz Schlarb
# #
# # This program is free software: you can redistribute it and/or modify
# # it under the terms of the GNU Affero Gen... | ral Public License as published by
# # the Free Software Foundation, either version 3 of the License, or
# # any later 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 PURPO... | m. If not, see <http://www.gnu.org/licenses/>.
#
# revision identifiers, used by Alembic.
revision = '425be68ff414'
down_revision = '3be6a175f769'
from alembic import op
#from alembic.operations import Operations as op
import sqlalchemy as sa
event_enroll = sa.Enum('event', 'lesson', 'lesson_team', 'team', 'team_ne... |
il[i].ComputeScale()
self.detail[i].CreateHistogram()
def InitializeHistoFrequency(self,ihisto):
import numpy
# New collection of labels
newlabels=[]
# Loop over datasets
for histo in self.detail:
# Loop over the label
for lab... | histos[0].SetFillStyle(3004)
histos[1].SetFillColor(46)
histos[1].SetFillStyle(3005)
histos[2].SetFillColor(8)
histos[2].SetFillStyle(3006)
histos[3].SetFillColor | (4)
histos[3].SetFillStyle(3007)
histos[4].SetFillColor(6)
histos[4].SetFillStyle(3013)
elif len(histos)==6:
histos[0].SetLineColor(9)
histos[1].SetLineColor(46)
histos[2].SetLineColor(8)
histos[3].SetLineColor(4)
... |
#
# Virtuozzo containers hauler module
#
import os
import shlex
import p_haul_cgroup
import util
import fs_haul_shared
import fs_haul_subtree
name = "vz"
vz_dir = "/vz"
vzpriv_dir = "%s/private" % vz_dir
vzroot_dir = "%s/root" % vz_dir
vz_conf_dir = "/etc/vz/conf/"
vz_pidfiles = "/var/lib/vzctl/vepid/"
cg_image_name ... | ths
def parse_vz_config(body) | :
""" Parse shell-like virtuozzo config file"""
config_values = dict()
for token in shlex.split(body, comments=True):
name, sep, value = token.partition("=")
config_values[name] = value
return config_values
|
import nose
def test_nose_working():
| """
Test that the nose runner is working.
"""
a | ssert True
|
import pytest
from mockito import mock
from app.hook_details.hook_details import HookDetails
pytestmark = pytest.mark.asyncio
@pytest.mark.usefixtures('unstub')
class TestHookDetails:
async def test__hook_details__is_pure_interface(self):
with pytest.raises(NotImplementedError):
f"{HookDetai... | m_values(mock())
with pytest.raises(NotImplementedError):
await HookDetails().should_trigger(mock(), mock())
with pytest.raises(NotImplement | edError):
HookDetails().get_event_type()
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, an open source suite of business apps
# This module copyright (C) 2015 bloopark systems (<http://bloopark.de>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | : 'toolbar',
'q': keywords,
| }
if lang:
language = lang.split("_")
params.update({
'hl': language[0],
'gl': language[1] if len(language) > 1 else ''
})
req = urllib2.Request("%s?%s" % (url, werkzeug.url_encode(params)))
requ... |
from . import util_CMB
import healpy as hp
import numpy as np
import os
import glob
def generate_covariances(m1, inst):
"""
Create a weight map using the smaller eigenvalue of the polarization matrix
The resulting covariances are saved on the disk.
Parameters
----------
* m1: object, conta... | util_CMB.write_map(
path,
cov_combined,
fits_IDL=False,
coord='C',
column_names=['I | ', 'P', 'P'],
column_units=['1/uK2_CMB', '1/uK2_CMB', '1/uK2_CMB'],
partial=True,
extra_header=[
('name', 'SO combined weight maps')])
return cov_combined
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | icenses/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. Se | e the License for the
# specific language governing permissions and limitations
# under the License.
"""
Example DAG demonstrating a workflow with nested branching. The join tasks are created with
``none_failed_or_skipped`` trigger rule such that they are skipped whenever their corresponding
``BranchPythonOperator`` a... |
import typing
from datetime import date, timedelta
def daterange( | start_date: date, end_date: date) -> typing.Iterator[date]:
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(days=n | )
|
ects.append(j)
idlDet[x].rects = validDetRects
def main():
parser = OptionParser(usage="usage: %prog [options] <groundTruthIdl> <detectionIdl>")
parser.add_option("-o", "--outFile",
action="store", type="string", dest="outFile")
parser.add_option("-a", "... | for i,anno in enumerate(detIDL):
validRects = []
for rect in anno.rects:
if (rect.score >= options.minScore):
| validRects.append(rect)
anno.rects = validRects
# Clip detections to the image dimensions
if(options.clipWidth != None or options.clipHeight != None):
min_x = -float('inf')
min_y = -float('inf')
max_x = float('inf')
max_y = float('inf')
if(options.clipWidth != None):
min_x = 0
max_x = options... |
#%% Libraries: Built-In
import numpy as np
#% Libraries: Custom
#%%
class Combiner(object):
def forward(self, input_array, weights, const):
## Define in child
pass
def backprop(self, error_array, backprop_array, learn_weight = 1e-0):
## Define in child
pass
#%%
class Linear... | p_size(self, hes | sian_items, current_coefs, prior_coefs):
step_size = tuple([(1 / hessian) / (current_coefs + prior_coefs) for hessian in hessian_items])
return step_size
def update_backprop(self, backprop_array, weights):
new_backprop = weights.dot(backprop_array).squeeze(axis = 3).swapaxes(0, 2)
... |
# Copyright 2010 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
import os as _os
import re
from portage import _unicode_decode
from portage.exception import InvalidData
#########################################################
# This an re-implementaion of dev-util/lafilefixer-0... | lags that should go into inherited_linker_flags instead of dependency_libs
flag_re = re.compile(b"-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads")
def _parse_lafile_contents(contents):
"""
Parses 'dependency_libs' and 'inherited_linker_flags' lines.
"""
dep_libs = None
inh_link_flags =... | dep_libs = m.group("value")
continue
m = inh_link_flags_re.match(line)
if m:
if inh_link_flags is not None:
raise InvalidData("duplicated inherited_linker_flags entry")
inh_link_flags = m.group("value")
continue
return dep_libs, inh_link_flags
def rewrite_lafile(contents):
"""
Given the con... |
self.addElement(remove)
# Unpacking or unconfiguring of a package must happen after
# its pre-dependencies are configured, or before they are
# unconfigured. We do the same for normal dependencies
# (non-pre) in an advisory fashion.
for req in pk... | # being installed, the | unpack of the dependency
# must necessarily happen before the config of
# the dependent, and in pre-depends the unpack
# of the dependent must necessarily happen
# after the config of the depe... |
import sublime
import unittest
from PackageBoilerplate import package_boilerplate
# Remember:
# Install AAAPT package to run the tests
# Save package_boilerplate to reload the tests
clas | s Test_BasePath(unittest.TestCase):
def test_join_combines_the_packages_path_with_the_supplied_one(self):
result = package_boilerplate.BasePath.join(" | some/new/path")
self.assertEquals(result, sublime.packages_path() + "/PackageBoilerplate/some/new/path")
def test_join_combines_the_packages_path_with_all_the_supplied_arguments(self):
result = package_boilerplate.BasePath.join("some", "new", "path")
self.assertEquals(result, sublime.packag... |
#!/usr/bin/env python3
# Copyright (C) 2016 Job Snijders <job@instituut.net>
#
# This file is part of rtrsub
#
# 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 co... | ing disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY ... | OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT... |
# Same version and same pre-release, check if dev version
if self.is_devversion is other.is_devversion:
vercmp = 0
elif self.is_devversion:
vercmp = -1
else:
vercmp = 1
... | data come from uncertain measurements with uncertainties
greater than floating point epsilon, choosing a tolerance near that
uncertainty may be preferable. The tolerance may be absolute if the
uncertainties are ab | solute rather than relative.
References
----------
.. [1] MATLAB reference documention, "Rank"
http://www.mathworks.com/help/techdoc/ref/rank.html
.. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,
"Numerical Recipes (3rd edition)", Cambridg... |
.slice_ind = 10
assert exc.value.args[0] == "Can only set slice_ind for 3D images"
def test_slice_disabled_for_no_data(self):
client = self.new_client()
assert client.slice_ind is None
with pytest.raises(IndexError) as exc:
client.slice_ind = 10
assert exc.value.... |
s = self.im.new_subset()
client.add_layer(s)
assert s in client.artists
def test_remove_data(self):
client = self.new_client()
self.collect.append(self.im)
s = se | lf.im.new_subset()
client.add_layer(self.im)
assert self.im in client.artists
assert s in client.artists
client.delete_layer(self.im)
assert client.display_data is not self.im
assert not self.im in client.artists
assert not s in client.artists
def test_delete... |
#!/usr/bin/python
from math import exp
import shtest, sys
def exp_test(p, base, types=[], epsilon=0):
if base > 0:
result = [pow(base, a) for a in p]
else:
result = [exp(a) for a in p]
return shtest.make_test(result, [p], types, epsilon)
def insert_into(test, base=0):
test.add_test(e... | tream programs
test = shtest.StreamTest('exp', 1)
test.add_call(shtest.Call(shtest.Call.call, 'exp', 1))
insert_into(test)
test.output_header(sys.stdout)
test.output(sys.stdout, False)
# Test exp2 in stream programs
test = shtest.StreamTest('exp2', 1)
test.add_call(shtest.Call(shtest.Call.call, 'exp2', 1))
insert_into... | ))
insert_into(test, 10)
test.output(sys.stdout, False)
# Test exp in immediate mode
test = shtest.ImmediateTest('exp_im', 1)
test.add_call(shtest.Call(shtest.Call.call, 'exp', 1))
insert_into(test)
test.output(sys.stdout, False)
# Test exp2 in immediate mode
test = shtest.ImmediateTest('exp2_im', 1)
test.add_call(sh... |
from untwisted.network import spawn
from untwisted.event import get_event
from untwisted.splits import Terminator
from re import *
GENERAL_STR = '[^ ]+'
GENERAL_REG = compile(GENERAL_STR)
SESSION_STR = '\*\*\*\* Starting FICS session as (?P<username>.+) \*\*\*\*'
SESSION_REG = compile(SESSION_STR)
TELL_STR = '(?P<... | TELL_REG, data)
try:
nick = m.group('nick')
msg = m.group('msg')
mode = m.group('mode')
except:
pas | s
else:
spawn(spin, TELL, nick, mode, msg)
spawn(spin, '%s tells you:' % nick, mode, msg)
m = match(SAY_REG, data)
try:
nick = m.group('nick')
msg = m.group('msg')
mode = m.group('mode')
except:
pass
else:
spawn(spin, SAY, nick, mode, msg)
... |
from textwrap import dedent
def get_definition_and_inference_st | ate(Script, source):
first, = Script(dedent(source)).infer()
return first._name._value, first._inference_state
def test_function_execution(Script):
"""
We've been having an issue of a mutable list that was changed inside the
function execution. Test if an execution always returns the same result.
... | ence_state(Script, s)
# Now just use the internals of the result (easiest way to get a fully
# usable function).
# Should return the same result both times.
assert len(func.execute_with_values()) == 1
assert len(func.execute_with_values()) == 1
def test_class_mro(Script):
s = """
class X(o... |
import pygame
import sys
from game import constants, gamestate
from game.ai.easy import EasyAI
from game.media import media
from game.scene import Scene
# List of menu options (text, action_method, condition) where condition is None or a callable.
# If it is a callable that returns False, the option is not s... | mg.arrow'], | (x - 25, y + 12))
y += surf.get_height() + 10
def render(self, screen):
screen.blit(media['img.title'], (0, 0))
self.render_options(screen)
def opt_continue(self):
self.manager.switch_scene('main')
return True
def new_match(self, player1, player2):
... |
# -*- test-case-name: twisted.test.test_fdesc -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Utility functions for dealing with POSIX file descriptors.
"""
import os
import errno
try:
import fcntl
except ImportError:
fcntl = None
# twisted imports
from twisted.internet.main ... | BLOCK
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
def setBlocking(fd):
"""
Set the file description of the given file descripto | r to blocking.
"""
if fcntl is None:
return
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
flags = flags & ~os.O_NONBLOCK
fcntl.fcntl(fd, fcntl.F_SETFL, flags)
if fcntl is None:
# fcntl isn't available on Windows. By default, handles aren't
# inherited on Windows, so we can do nothing her... |
x = np.linspace(0, 100, samples)
return a, b, x, samples
def similarity_data() -> Tuple[np.ndarray, np.ndarray, int, np.ndarray, int]:
rotation = np.array([0.1, 0.2, 0.3])
translation = np.array([4, 5, 6])
scale = 2
samples = 100
x = np.random.rand(samples, 3)
return rotation, transl... | e=shape)
if len(shape) == 0:
sign = 1 if np.random.randint(2) > 0 else -1
else:
sign = [1 i | f r > 0 else -1 for r in np.random.randint(2, size=shape)]
x[int(index)] += sign * noise
def test_uniform_line_ransac() -> None:
a, b, x, samples = line_data()
scale = 2.0
y = a * x + b + np.random.rand(x.shape[0]) * scale
data = np.array([x, y]).transpose()
params = pyrobust.RobustEsti... |
import redis
import json
from flask im | port current_app
class CachingService:
rc = None
def cache(self):
if self.rc is None:
self.rc = redis.StrictRedis(host=current_app.config['CACHE_HOST'], port=current_app.config['CACHE_PORT'], db=0)
return self.rc
def get(self, key: str) -> dict:
v = self.cache().get(ke... | ))
return retVal
def set(self, key: str, value: dict):
self.cache().set(key, json.dumps(value))
def remove(self, key: str):
self.cache().delete(key)
|
#!/usr/bin/python
import sys
from subprocess import call
print "Usage: bg_count.py ListOfBamFiles Reference"
try:
li = sys.argv[1]
except:
li = raw_input("Introduce List of indexed BAM files: ")
try:
ref = sys.argv[2]
except:
ref = raw_input("Introduce Reference in FASTA format: ")
files = open(li)... | []
for file in files:
file = file[:-1]
li_bg.append(file+".bg")
name = file.split(".")
li_names.append(name[0])
call("genomeCoverageBed -bg -ibam %s > %s.bg" % (file,file), shell=True)
call("unionBedGraphs -header -i %s -names %s -g %s -empty > samples1and2.txt" % (" ".join(li_bg), " | ".join(li_names), ref+".fai"), shell=True)
call("coverage_seq_bed.py samples1and2.txt", shell=True)
|
'billing-account-name': 'foo',
'apis': [],
'concurrent_api_activation': True,
'service-accounts': []
}
def test_merge_no_iam_policies(self):
"""Test output of the function when there are no IAM policies in the
properties"""
env = {'project_number': '123'}
properties = {}
e | xpected = {
'bindings': [
{
'role': 'roles/owner',
| 'members':
['serviceAccount:123@cloudservices.gserviceaccount.com']
}
]
}
actual_iam_policies = (
p.MergeCallingServiceAccountWithOwnerPermissinsIntoBindings(
env, properties))
self.assertEqual(expected, actual_iam_policies)
def test_merg... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-22 11:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('WorkflowEngine', '0001_initial'),
('tags', '0013_auto_20180925_1142'),
]
operation... | ns.AddField(
model_name='tag',
name='t | ask',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='tags', to='WorkflowEngine.ProcessTask'),
),
migrations.AddField(
model_name='tagstructure',
name='structure_unit',
field=models.ForeignKey(limit_choices_to... |
"""Test that sys.modules is used properly by import."""
from .. import util
import sys
from types import MethodType
import unittest
class UseCache:
"""When it comes to sys.modules, import prefers it over anything else.
Once a name has been resolved, sys.modules is checked to see if it contains
the modul... | riginal_load = mock.load_module
def load_module(self, fullname):
original_load(fullname)
return return_
mock.load_module = MethodType(load_module, mock)
return mock
# __import__ inconsistent between loaders and built-in import when it comes
# to when to use the... | ort_state(meta_path=[mock]):
module = self.__import__('module')
self.assertEqual(id(module), id(sys.modules['module']))
# See test_using_cache_after_loader() for reasoning.
def test_using_cache_for_assigning_to_attribute(self):
# [from cache to attribute]
with se... |
from | __future__ import absolute_im | port
from tridiagonal_core import *
|
ic", "beer on", 2, False
)
mqtt_mock.async_publish.reset_mock()
state = hass.states.get("switch.test")
assert state.state == STATE_ON
await common.async_turn_off(hass, "switch.test")
mqtt_mock.async_publish.assert_called_once_with(
"command-topic", "beer off", 2, False
)
state ... | config2 = copy.deepcopy(DEFAULT_CONFIG[switch.DOMAIN])
config1["name"] = "Beer"
config2["name"] = "Milk"
config1["state_topic"] = "switch/st | ate1"
config2["state_topic"] = "switch/state2"
config1["value_template"] = "{{ value_json.state1.state }}"
config2["value_template"] = "{{ value_json.state2.state }}"
state_data1 = [
([("switch/state1", '{"state1":{"state":"ON"}}')], "on", None),
]
state_data2 = [
([("switch/sta... |
f group_id:
asset_group_list = asset_group_list.filter(id=group_id)
if keyword:
asset_group_list = asset_group_list.filter(Q(name__contains=keyword) | Q(comment__contains=keyword))
asset_group_list, p, asset_groups, page_range, current_page, show_first, show_end = pages(asset_group_list, reques... | add_batch.html', locals(), request)
@require_role('admin')
def asset_del(request):
"""
del a asset
删除主机
"""
asset_id = request.GET.get('id', '')
if asset_id:
Asset.objects.filter(id=asset_id).delete()
if request.method == 'POST':
asset_batch = request.GET.get('arg', '')
... | t('asset_id_all', ''))
if asset_batch:
for asset_id in asset_id_all.split(','):
asset = get_object(Asset, id=asset_id)
asset.delete()
return HttpResponse(u'删除成功')
@require_role(role='super')
def asset_edit(request):
"""
edit a asset
修改主机
"""
... |
#!/usr/bin/env python3
# This script prints a new "servers.json" to stdout.
# It prunes the offline servers from the existing list (note: run with Tor proxy to keep .onions),
# and adds new servers from provided file(s) of candidate servers.
# A file o | f new candidate servers can be created via e.g.:
# $ ./electrum_ltc/scripts/servers.py > reply.txt
import asyncio
import sys
import json
from electrum_ltc.network im | port Network
from electrum_ltc.util import create_and_start_event_loop, log_exceptions
from electrum_ltc.simple_config import SimpleConfig
from electrum_ltc import constants
try:
fname1 = sys.argv[1]
fname2 = sys.argv[2] if len(sys.argv) > 2 else None
except Exception:
print("usage: update_default_servers.... |
# -*- coding: utf-8 -*-
"""Display download counts of GitHub releases."""
__program__ = 'github-d | ownload-count'
__vers | ion__ = '0.0.1'
__description__ = 'Display download counts of GitHub releases'
|
#!/usr/bin/env python
im | port os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", | "sufwebapp1.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
"""HaloEndpoint class"""
import cloudpassage.sanity as sanity
from .utility import Utility as utility
from .http_helper import HttpHelper
class HaloEndpoint(object):
"""Base class inherited by other specific HaloEndpoint classes."""
default_endpoint_version = 1
def __init__(self, session, **kwargs):
... | t = HttpHelper(self.session)
delete_endpoint = "%s/%s" % (self.endpoint(), obje | ct_id)
request.delete(delete_endpoint)
return None
def update(self, object_body):
"""Update. Success returns None"""
request = HttpHelper(self.session)
request_body = utility.policy_to_dict(object_body)
object_id = request_body[self.object_key()]["id"]
sanit... |
# -*- coding: utf | -8 -*-
"""
fudcon.ui.backend
------
fudcon ui back | end application package
"""
|
# -*- coding: utf-8 -*-
#
# amsn - a python client for the WLM Network
#
# Copyright (C) 2008 Dario Freddi <drf54321@gmail.com>
#
# 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... | ,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundati... | import QtGui
from fadingwidget import FadingWidget
from image import Image
class aMSNSplashScreen(QtGui.QSplashScreen, base.aMSNSplashScreen):
def __init__(self, amsn_core, parent):
QtGui.QSplashScreen.__init__(self, parent)
self._theme_manager = amsn_core._theme_manager
def show(self):
... |
## | begin license ##
#
# "Weightless" is a High Performance Asynchronous Networking Library. See http://weightless.io
#
# Copyright (C) 2012-2013, 2017, 2020-2021 Seecr (Seek You Too B.V.) https://seecr.nl
#
# This file is part of "Weightless"
#
# "Weightless" is free software; you can redistribute it and/or modify
# it un... | on 2 of the License, or
# (at your option) any later version.
#
# "Weightless" 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... |
# __init__.py
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Michael Bayer mike_mp@zzzcomputing.com
|
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
__version__ = | '0.3.4'
|
import fechbase
class Records(fechbase.RecordsBase):
def __init__(self):
fechbase.RecordsBase.__init__(self)
self.fields = [
{'name': 'FORM TYPE', 'number': '1'},
{'name': 'FILER FEC CMTE ID', 'number' | : '2'},
{'name': 'ENTITY TYPE', 'number': '3'},
{'name': 'NAME (Payee)', 'number': '4'},
{'name': 'STREET 1', 'number': '5'},
{'name': 'STREET 2', 'numb | er': '6'},
{'name': 'CITY', 'number': '7'},
{'name': 'STATE', 'number': '8'},
{'name': 'ZIP', 'number': '9'},
{'name': 'TRANSDESC', 'number': '10'},
{'name': 'Of Expenditure', 'number': '11-'},
{'name': 'AMOUNT', 'number': '12'},
{'name... |
import contextvars
import gettext
import os
from telebot.asyncio_handler_backends import BaseMiddleware
try:
from babel.support import LazyProxy
babel_imported = True
except ImportError:
babel_imported = False
class I18N(BaseMiddleware):
"""
This middleware provides high-level tool for internat... | Plural translations
"""
if lang is None:
lang = sel | f.context_lang.get()
if lang not in self.translations:
if n == 1:
return singular
return plural
translator = self.translations[lang]
return translator.ngettext(singular, plural, n)
def lazy_gettext(self, text: str, lang: str = None):
if not ... |
tecture}/{project.targetName}")
csbuild.SetIntermediateDirectory("Intermediate/{project.userData.subdir}/{project.activeToolchainName}/{project.outputArchitecture}/{project.targetName}/{project.name}")
csbuild.Toolchain("msvc").AddCompilerFlags(
"/fp:fast",
"/wd\"4530\"",
"/wd\"4067\"",
"/wd\"4351\"",
"/constexp... | t("collections", "collections")
def collections():
csbuild.SetOutput("libsprawl_collections", csbuild.ProjectType.StaticLibrary)
csbuild.EnableHeaderInstall()
@csbuild.project("tag", "tag")
def collections():
csbuild.SetOutput("libsprawl_tag", csbuild.ProjectType.StaticLibrary)
csbuild.EnableHeaderInstall()
@... | ct("network", "network")
def network():
csbuild.SetOutput("libsprawl_network", csbuild.ProjectType.StaticLibrary)
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
@csbuild.project("serialization", "serialization")
def serialization():
csbuild.SetOutput("libsprawl_serialization", csbuild.ProjectType.... |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | VersionHandler(hbase.BaseHandler):
"""Handle request to the /version URL.
Provide the backend version number in use. |
"""
def __init__(self, application, request, **kwargs):
super(VersionHandler, self).__init__(application, request, **kwargs)
def execute_get(self, *args, **kwargs):
response = hresponse.HandlerResponse()
response.result = [
{
models.VERSION_FULL_KEY: ha... |
# -*- coding: utf-8 -*-
#
# This file is part of EventGhost.
# Copyright © 2005-2019 EventGhost Project <http://www.eventghost.org/>
#
# EventGhost 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 versio... | today = gmtime()[:3]
if config.lastUpdateCheckDate != today:
config. | lastUpdateCheckDate = today
wx.CallAfter(eg.CheckUpdate.Start)
# Register restart handler for easy crash recovery.
if eg.WindowsVersion >= 'Vista':
args = " ".join(eg.app.GetArguments())
windll.kernel32.RegisterApplicationRestart(args, 8)
eg.Print(eg.text.MainFrame.Logger.welco... |
"""empty message
Revision ID: 0038 add topics to magazines
Revises: 0037 add magazine_id to emails
Create Date: 2020-02-05 01:29:38.265454
"""
# revision identifiers, used by Alembic.
revision = '0038 add topic | s to magazines'
down_revision = '0037 add magazine_id to emails'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('magazines', sa.Column('topics', sa.String(), nullable=True))
# ### end Alembic commands ###
def dow... | 'topics')
# ### end Alembic commands ###
|
# -*- coding: utf-8 -*-
from GestureAgentsTUIO.Tuio import TuioCursorEvents
from GestureAgentsDemo.Geometry import Ring, Circle
from GestureAgentsDemo.Render import drawBatch
from GestureAgents.Recognizer import Recognizer
import pyglet.clock
from pyglet.sprite import Sprite
from pyglet.resource import Loader
from Ges... | ister(FingerShadow.newAgentCursor, self)
self.curshadows = WeakKeyDictionary()
# Update.register(FingerShadow.update, self)
pyglet.clock.schedule_interval(self.update, .1)
# self.apprecognizerlist = WeakSet()
# AppRecognizer.acquire = notifier(self.NewAppRecognizer, AppRecognizer... | self.curshadows[A] = ff
def update(self, dt=0):
for a in list(self.curshadows.itervalues()):
if a.dead:
del self.curshadows[a.agent]
else:
a.update()
# print len(self.apprecognizerlist)
def NewAppRecognizer(self, *args, **kwargs):
... |
SEC | ONDS_IN | _DAY = 86400
|
models.CharField(('Unique Identifier'), max_length=36, primary_key=True, default=generate_new_uuid)
initialTemperature = models.FloatField(blank=False,validators=[MinValueValidator(0)])
finalTemperature = models.FloatField(blank=False,validators=[MinValueValidator(0)])
#class Meta:
#unique_toget... | linearThermalGradient = models.ForeignKey("linearThermalGradientType_model",blank=True, null=True)
#class Meta:
#unique_together = ()
def __unicode__(self):
return "id: %s" % (self.uuid, )
class linearThermalGradientType_model(models.Model):
uuid = mo | dels.CharField(('Unique Identifier'), max_length=36, primary_key=True, default=generate_new_uuid)
temperatureRightHorizonal = models.FloatField(blank=False)
temperatureLeftHorizontal = models.FloatField(blank=False)
#class Meta:
#unique_together = ("temperatureRightHorizonal","temperatureLeftHorizon... |
ticle, rules=None):
"""Extract info from google scholar article
Doctest:
.. doctest::
Mock:
>>> class Article: pass
>>> article = Article()
>>> article.as_citation = lambda: '''
... @inproceedings{murta2014noworkflow,
... title={noWorkflow: capturing and... | f scripts",
due="Unrelated to my snowballing",
display="noworkflow",
authors="Murta, Leonardo and Braganholo, Vanessa and Chirigati, Fernando and Koop, David and Freire, Juliana",
place=IPAW,
other='Do not ignore other fields',
))
"""
rules = r... | return converter.run(info)
def set_by_info(work, info, set_scholar=True, rules=None):
"""Find attributes that should be modified in a work object to make it match an info object"""
rules = rules or config.BIBTEX_TO_INFO
rules.get("<set_before>", lambda x, y: None)(work, info)
work_keys = {k for ... |
import os
import sys
from os.path import dirname, join |
import pytest
sys.path.insert(0, join(dirname(__file__), "..", ".."))
from wptrunner import browsers
_products = browsers.product_list
_active_products = set()
if "CURRENT_TOX_ENV" in os.environ:
current_tox_env_split = os.environ["CURRENT_TOX_ENV"].split("-")
tox_env_extra_browsers = {
"chrome"... | iver"},
}
_active_products = set(_products) & set(current_tox_env_split)
for product in frozenset(_active_products):
_active_products |= tox_env_extra_browsers.get(product, set())
else:
_active_products = set(_products)
class all_products(object):
def __init__(self, arg, marks={}):
... |
# verify we can test things
self.assertTrue(distro.set_owners(["superlab","basement1"]))
self.assertTrue(profile.set_owners(["superlab","basement1"]))
self.assertTrue(profile.set_kickstart("/tmp/test_cobbler_kickstart"))
self.assertTrue(system.set_owners(["superlab","basement1","b... | y added as a user
# and superlab1 who is in a group in the ownership list
for user in ["admin1","superlab1","basement1"]:
self.assertTrue(1==authorize(self.api, us | er, "save_distro", xo),"%s can save_distro" % user)
self.assertTrue(1==authorize(self.api, user, "modify_distro", xo),"%s can modify_distro" % user)
self.assertTrue(1==authorize(self.api, user, "copy_distro", xo),"%s can copy_distro" % user)
self.assertTrue(1==authorize(self.api, user, ... |
# -*- coding: ut | f-8 -*-
# Generated by Django 1.11 on 2017-07-03 18:14
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("ui", "0003_add_videofile"),
]
operations = [
migrations.Crea... | utoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("created_at", models.DateTimeField(auto_now_add=True)),
("s3_objec... |
r"""
Three.js Enums
These correspond to the enum property names in the THREE js object
"""
# Custom Blending Equation Constants
# http://threejs.org/docs/index.html#Reference/Constants/CustomBlendingEquation
Equations = [
'AddEquation',
'SubtractEquation',
'ReverseSubtractEquation',
'MinEquation',
... | FloatType',
'HalfFloatType'
]
PixelTypes = [
'UnsignedShort4444Type',
'UnsignedShort5551Type',
'UnsignedShort565T | ype'
]
PixelFormats = [
'AlphaFormat',
'RGBFormat',
'RGBAFormat',
'LuminanceFormat',
'LuminanceAlphaFormat',
'RGBEFormat'
]
CompressedTextureFormats = [
'RGB_S3TC_DXT1_Format',
'RGBA_S3TC_DXT1_Format',
'RGBA_S3TC_DXT3_Format',
'RGBA_S3TC_DXT5_Format',
'RGB_PVRTC_4BPPV1_Form... |
rade",
"sec-websocket-accept": "Kxep+hNu9n51529fGidYu7a3wO0="}
self.assertEqual(_validate_header(required_header, key, None), (True, None))
header = required_header.copy()
header["upgrade"] = "http"
self.assertEqual(_validate_header(header, key, None), (False, None))
... | ey, None), (False, None))
header = required_header.copy()
header["connection"] = "something"
self.assertEqual(_validate_header(header, key, None), (False, None))
del header["connection"]
self.assertEqual(_validate_header(header, key, | None), (False, None))
header = required_header.copy()
header["sec-websocket-accept"] = "something"
self.assertEqual(_validate_header(header, key, None), (False, None))
del header["sec-websocket-accept"]
self.assertEqual(_validate_header(header, key, None), (False, None))
... |
#!/usr/bin/env python
from blob import Blob
from foreground_processor import ForegroundProcessor
import cv2
import operator
import rospy
from blob_detector.msg import Blob as BlobMsg
from blob_detector.msg import Blobs as BlobsMsg
import numpy as np
class BlobDetector(ForegroundProcessor):
def __init__(self, nod... | [b.compute_params() for b in blobs] # cpu intensive initialization
return blobs
def process_depth_mask_image(self, rgbd):
blobs = self.find_blobs(rgbd)
#for blob in blobs:
# blob.set_world_coordinates_from_depth(rgbd.depth | _raw)
self.process_blobs(blobs, rgbd)
def publish_blobs(self, blobs):
blobs_msg = BlobsMsg()
for blob in blobs:
blob_msg = blob.to_msg()
blobs_msg.blobs.append(blob_msg)
self.pub.publish(blobs_msg)
def show_blobs(self, blobs, rgbd):
for blob in... |
{ | 'board_id': 812,
'public_url': 'https://p.datadoghq.c | om/sb/20756e0cd4'}
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('flooding_lib', '__first__'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
o... | waterdepth')),
('export_max_flowvelocity', models.BooleanField(default=True, verbose_name='The maximal flowvelocity')),
('export_possibly_flooded', models.BooleanField(default=True, verbose_name='The flooded area')),
('export_arrival_times', models.BooleanField(default=T... | ame='The arrival times')),
('export_period_of_increasing_waterlevel', models.BooleanField(default=True, verbose_name='The period of increasing waterlevel')),
('export_inundation_sources', models.BooleanField(default=True, verbose_name='The sources of inundation')),
('expo... |
import cPickle
class GameState:
# g = GameState(11,22,3,4,5) init
# g.pickle('test.gamestate') save
# x = GameState().unpickle('test.gamestate') lo | ad
def __init__ | (self,rulesfile=None,turns=None,connection=None,
cache=None,verbosity=None, pickle_location=None):
if pickle_location is None:
self.rulesfile = rulesfile
self.turns = turns
self.connection = connection
self.cache = cache
self.verbosity = verbosity
def pickle(self, file_name):
file = open(file_na... |
"""
<This library provides a Python interface for the Telegram Bot API>
Copyright (C) <2015> <Jacopo De Luca>
This program is free software: you can redistribute it and/or modify
it under the terms of the G | NU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later 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 F... | copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
class Location(object):
"""
This object represents a point on the map.
"""
def __init__(self, longitude, latitude):
"""
:param longitude: Longitude as defined by sender... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.