prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
@param p_mi: the Media Player to free.
'''
f = _Cfunctions.get('libvlc_media_player_release', None) or \
_Cfunction('libvlc_media_player_release', ((1,),), None,
None, MediaPlayer)
return f(p_mi)
def libvlc_media_player_retain(p_mi):
'''Retain a reference to a media player o... | ction('libvlc_media_player_play', ((1,),), None,
ctypes.c_int, MediaPlayer)
return f(p_mi)
def libvlc_media_player_set_pause(mp, do_pause):
'''Pause or resume (no effect if there is no media).
@param mp: the Media Player.
@ | param do_pause: play/resume if zero, pause if non-zero.
@version: LibVLC 1.1.1 or later.
'''
f = _Cfunctions.get('libvlc_media_player_set_pause', None) or \
_Cfunction('libvlc_media_player_set_pause', ((1,), (1,),), None,
None, MediaPlayer, ctypes.c_int)
return f(mp, do_pause... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-28 13:35
from __future__ import unicode_literals
from django.conf import settings
from django. | db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUT | H_USER_MODEL),
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='AccountRules',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('permissions', models.C... |
'invalid'),
id=11)))
self.assertEquals(self.server.transport.value(),
str(pureldap.LDAPMessage(
pureldap.LDAPBindResponse(
resultCode=ldaperrors.LDAPProtocolError.resultCode,
errorMessage='Version 4 not supported'),
id=11)))
... | ), id=2)))
self.assertEquals(self.server.transport.value(),
str(pureldap.LDAPMessage(
pureldap.LDAPSearchResultEntry(
objectName='',
attributes=[ ('supportedLDAPVersion', ['3']),
('namingContexts', ['dc=example,dc=com']),
... | ]),
id=2))
+ str(pureldap.LDAPMessage(
pureldap.LDAPSearchResultDone(resultCode=ldaperrors.Success.resultCode),
id=2)),
)
def test_delete(self):
self.server.dataReceived(str(pureldap.LDAPMessage(
pureldap.L... |
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | s existing filter (if any) is unchanged.'))
parser.add_argument(
'--output-version-format', required=False,
| help=('Format of the log entries being exported. Detailed information: '
'https://cloud.google.com/logging/docs/api/introduction_v2'),
choices=('V1', 'V2'))
def GetLogSink(self):
"""Returns a log sink specified by the arguments."""
client = self.context['logging_client_v1beta3']
re... |
#!/usr/bin/env python
# Support a YAML file hosts.yml as external inventory in Ansible
# Copyright (C) 2012 Jeroen Hoekx <jeroen@hoekx.be>
#
# 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, eit... | []
def __repr__(self):
return "Group('%s')"%(self.name)
def get_hosts(self):
""" List all hosts in this group, including subgroups """
result = [ host for host in self.hosts ]
for group in self.subgroups:
for host in group.get_hosts():
if host not in ... |
result.append(host)
return result
def add_host(self, host):
if host not in self.hosts:
self.hosts.append(host)
host.add_group(self)
def add_subgroup(self, group):
if group not in self.subgroups:
self.subgroups.append(group)
... |
te')
@test.idempotent_id('0d148aa3-d54c-4317-aa8d-42040a475e20')
def test_aggregate_create_delete(self):
# Create and delete an aggregate.
aggregate_name = data_utils.rand_name(self.aggregate_name_prefix)
aggregate = self.client.create_aggregate(name=aggregate_name)
self.addClean... | # set the metadata of the aggregate
meta = {"key": "value"}
body = self.client.set_metadata(aggregate['id'], meta)
self.assertEqual(meta, body["metadata"])
# verify the metadata has been set
body = self.client.get_aggregate(aggregate['id'])
self.assertEqual(meta, body["m... | f test_aggregate_create_update_with_az(self):
# Update an aggregate and ensure properties are updated correctly
aggregate_name = data_utils.rand_name(self.aggregate_name_prefix)
az_name = data_utils.rand_name(self.az_name_prefix)
aggregate = self.client.create_aggregate(
name... |
import logging
import datetime
import mediacloud.api
import re
from server import mc
from server.auth import is_user_logged_in
from server.util.csv import SOURCE_LIST_CSV_METADATA_PROPS
logger = logging.getLogger(__name__)
TOPIC_MEDIA_INFO_PROPS = ['media_id', 'name', 'url']
TOPIC_MEDIA_PROPS = ['story_count', 'me... | dd in the media sources they specified
if len(media_ids) > 0:
media_ids = media_ids.split(',') if isinstance(media_ids, str) else media_ids
query_media_ | ids = " ".join(map(str, media_ids))
query_media_ids = re.sub(r'\[*\]*', '', str(query_media_ids))
query_media_ids = " media_id:({})".format(query_media_ids)
query += '(' + query_media_ids + ')'
if len(media_ids) > 0 and len(tags_ids) > 0:
query += " OR "
... |
javelin.create_tenants([self.fake_object['name']])
mocked_function = self.fake_client.identity.create_tenant
self.assertFalse(mocked_function.called)
def test_create_users(self):
self.fake_client.identity.get_tenant_by_name.return_value = \
self.fake_object['tenant']
... | elin.create_routers([self.fake_object])
mocked_function = self.fake_client.networks.create_router
self.assertFalse(mocked_function.called)
def test_create_secgroup(self):
self.useFixture(mockpatch.PatchObject(javelin, "client_for_user",
| return_value=self.fake_client))
self.fake_client.secgroups.list_security_groups.return_value = (
|
# -*- coding: utf-8 -*-
# Generated by Django 1. | 10.4 on 2018-03-05 05:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sponsors', '0012_sponsor_level_smallint'),
]
operations = [
migrations.AlterField(
model_name='sponsor',
... | yCon Taiwan 2016'), ('pycontw-2017', 'PyCon Taiwan 2017'), ('pycontw-2018', 'PyCon Taiwan 2018')], default='pycontw-2018', verbose_name='conference'),
),
]
|
###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# mod... | 2
# of the License, or (at your option) any later version.
#
# In addition, as a special exception, the copyright holders of
# ilastik give you permission to combine ilastik with applets,
# workflows and plugins which are not covered under the GNU
# General Public License.
#
# See the LICENSE file for details. License ... | ailable
# on the ilastik web site at:
# http://ilastik.org/license.html
###############################################################################
import sys
from functools import partial
from PyQt4.QtGui import QApplication
import threading
# This function was copied from: http://bugs.python.org/issue1230540... |
from __future__ import division
import encoder
import socket_class as socket
import threading
import time
import sys
rightC,leftC = (0,0)
s = None
IP = "10.42.0.1"
host = 50679
class sendData(threading.Thread):
def __init__(self,waitTime):
self.waitTime = waitTime
threading.Thread.__init__(self)
... | ecv(10)
print "sent",str(rightC),",",str(leftC)
time.sleep(self.waitTime)
def right():
global rightC
rightC += 1
print "right: ",rightC,"\t","left :",leftC
def left():
global leftC
leftC += 1
print "right: ",rightC,"\t","left :",leftC
def | checkArgs():
global IP,host
if(len(sys.argv)!=1):
IP = sys.argv[1]
host = sys.argv[2]
if __name__ == "__main__":
"""if 2 arguments are passed in overwrite IP and port number to those values else use IP = 10.42.0.1 and 50679"""
encoder.encoderSetup()
if len(sys.argv) in (1,3):
... |
import numpy as np
import scipy.sparse as sp
from scipy.optimize import fmin_l_bfgs_b
from Orange.classification import Learner, Model
__all__ = ["LinearRegressionLearner"]
class LinearRegressionLearner(Learner):
def __init__(self, lambda_=1.0, preprocessors=None, **fmin_args):
'''L2 regularized linear ... | =0)) / np.std(data.X, axis=0) # normalize
data.X = np.hstack((data.X, np.ones((d | ata.X.shape[0], 1)))) # append ones
m = LinearRegressionLearner(lambda_=1.0)
c = m(data) # fit
print(c(data)) # predict
'''
super().__init__(preprocessors=preprocessors)
self.lambda_ = lambda_
self.fmin_args = fmin_args
def cost_grad(self, theta, ... |
f tearDownClass(cls):
cls.selenium.quit()
super(BasicTestCase, cls).tearDownClass()
def setUpBasic(self, prop, base_url, entity):
self.property = prop
self.entity = entity
self.base_url = base_url
self.verificationErrors = []
# Login test... | .find_element_by_id("id_last_name").clear()
driver.find_element_by_id("id_last_name").send_keys("Obama2")
driver.find_element_by_id("id_start_date").click()
driver.find_element_by_id("id_start_date").clear()
driver.find_element_by_id("id_start_date").send_keys("2013-01-15")
drive... | y_id("id_permanent_address1").clear()
driver.find_element_by_id("id_permanent_address1").send_keys("6666 Wrong St.")
driver.find_element_by_css_selector("input[type=\"submit\"]").click()
self.assertTrue(self.is_element_present(By.XPATH, "//ul[contains(@class, 'errorlist') and .//text() = 'This f... |
# -*- coding: utf-8 -*-
#
# sample documentation build configuration file, created by
# sphinx-quickstart on Mon Apr 16 21:22:43 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | e of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any | paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every pag... |
#!/ | usr/bin/env python
import gtk
#import NoteBuffer
import notemeister
class Note:
def __init__(self, path=None, title='', body='', link='', wrap="1"):
self.path = path
self.title = title
self.body = body
self.link = link
self.wrap = wrap
self.buffer = notemeister.NoteBuffer.NoteBuffer()
self.buffer.set... | dy)
|
#!/usr/bin/env python
import setuptools
# Hack to prevent stupid TypeError: 'NoneType' object is not callable error on
# exit of python setup.py test # in multiprocessing/util.py _exit_function when
# running python setup.py test (see
# http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
i... | mportError:
pass
setuptools.setup(
name='orwell.agent',
version='0.0.1',
description='Agent connecting to the game server.',
author='',
author_email='',
packages=setuptools.find_packages(exclude="test"),
test_suite='nose.collector',
install_requires=['pyzmq', 'cliff'],
... | ice = orwell.agent.main:main',
]
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Topic :: Utilities',
'Programming Language :: ... |
#!/usr/bin/env python3
"""
py_fanos_test.py: Tests for py_fanos.py
"""
import socket
import sys
import unittest
import py_fanos # module under test
class FanosTest(unittest.TestCase):
def testSendReceive(self):
left, right = socket.socketpair()
py_fanos.send(left, b'foo')
fd_out = []
msg = py_f... | ssertEqual(b'spam', msg)
self.assertEqual(3, len(fd_out))
print(fd_out)
left.close()
msg = py_fanos.recv(right)
self.assertEqual(None, msg) # Valid EOF
right | .close()
class InvalidMessageTests(unittest.TestCase):
"""COPIED to native/fanos_test.py."""
def testInvalidColon(self):
left, right = socket.socketpair()
left.send(b':') # Should be 3:foo,
try:
msg = py_fanos.recv(right)
except ValueError as e:
print(type(e))
print(e)
els... |
# Copyright 2012 NetApp
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | :param snapshot: The :class:`ShareSnapshot` to delete.
"""
self._delete("/snapshots/%s" % common_base.getid(snapshot))
def _do_force_delete(self, snapshot, action_name="force_delete"):
"""Delete the specified snapshot ignoring its current state."""
return self._action(action_name, c... | n_base.getid(snapshot))
@api_versions.wraps("1.0", "2.6")
def force_delete(self, snapshot):
return self._do_force_delete(snapshot, "os-force_delete")
@api_versions.wraps("2.7") # noqa
def force_delete(self, snapshot):
return self._do_force_delete(snapshot, "force_delete")
def upd... |
#!/usr/bin/env python
"""Run pytest with coverage and generate an html report."""
from sys import argv
from os import system as run
# To run a specific file with debug logging prints:
# py -3 -m pytest test_can.py --log-cli-format="%(asctime)s.%(msecs)d %(levelname)s: %(message)s (%(filename)s:%(lineno)d)" -... | arg = ''
# All source files included in coverage
includes = '../*'
if | len(argv) >= 2:
arg = argv[1]
if ':' in argv[1]:
includes = argv[1].split('::')[0]
other_args = ' '.join(argv[2:])
run(run_str.format(includes, arg, other_args))
# Generate the html coverage report and ignore errors
run('python -m coverage html -i')
if __name_... |
from uuid import uuid4, UUID
from behave import given, when, then
from formencode import Invalid, validators
@given("I made a Device linking request")
@given("I have made a Device linking request")
@when("I make a Device linking request")
def make_device_linking_request(context):
current_directory = context.enti... | nk_device(
str(uuid4()),
user_identifier,
current_directory.id
)
except Exception as e:
context.current_exception = e
# Device manager steps
@given("I have a linked device")
def link_device(context):
context.execute_steps(u'''
Given I made a Device link... | ical_device(context):
sdk_key = context.entity_manager.get_current_directory_sdk_keys()[0]
context.sample_app_device_manager.set_sdk_key(sdk_key)
linking_code = context.entity_manager.get_current_linking_response().code
context.sample_app_device_manager.link_device(linking_code)
# We should now be ... |
# -*- coding: utf-8 -*-
import sys
from argparse import ArgumentParser
from DatabaseLogin import DatabaseLogin
from GlobalInstaller import GlobalInstaller
from PyQt5 import QtWidgets
from Ui_MainWindow import Ui_MainWindow
# import damit Installer funktioniert. auch wenn diese nicht hier benoetigt werd... | help=r"Setzt Flag für die Installation von Sequenzen.")
parser.add_argument('--inst_tab_save', action='store_true', default=False,
help=r"S | etzt Flag für die Installation von Tab Save Tabellen.")
parser.add_argument('--inst_tab', action='store_false', default=True,
help=r"Entfernt Flag für die Installation von Tab Tabellen.")
parser.add_argument('--inst_view', action='store_false', default=True,
h... |
or the
requested NIC
"""
cmd_result = virsh.dumpxml(self.name, uri=self.connect_uri)
if cmd_result.exit_status:
raise exceptions.TestFail("dumpxml %s failed.\n"
"Detail: %s.\n" % (self.name, cmd_result))
thexml = cmd_resul... | self.create_serial_console()
else:
raise virt_vm.VMStartError(self.name, result.stderr.strip())
# Pull in mac addresses from libvirt guest definition
for index | , nic in enumerate(self.virtnet):
try:
mac = self.get_virsh_mac_address(index)
if not nic.has_key('mac'):
logging.debug("Updating nic %d with mac %s on vm %s"
% (index, mac, self.name))
nic.mac = mac
... |
# -*- coding: utf-8 -*-
from __futur | e__ import unicode_literals, absolute_import
"""
django_twilio specific settings.
"""
from .utils import discover_twilio_credentials
TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN = discover_twilio_cred | entials()
|
, 2),))
assert fractional_slice(('x', 3, 5.1), {0: 2, 1: 3}) == \
(getitem, ('x', 3, 5), (slice(None, None, None), slice(-3, None)))
assert fractional_slice(('x', 2.9, 5.1), {0: 2, 1: 3}) == \
(getitem, ('x', 3, 5), (slice(0, 2), slice(-3, None)))
def test_ghost_internal():
x = n... | 21, 22, 23, 23],
[ 24, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 31],
[ 3 | 2, 32, 33, 34, 35, 36, 35, 36, 37, 38, 39, 39],
[ 40, 40, 41, 42, 43, 44, 43, 44, 45, 46, 47, 47],
[ 48, 48, 49, 50, 51, 52, 51, 52, 53, 54, 55, 55],
[ 56, 56, 57, 58, 59, 60, 59, 60, 61, 62, 63, 63],
[100, 100, 100, 100, 100, 100, 100, 100, 100, 1... |
uuid' % (self._ds.name)
expected_image_path = '[%s] vmware_temp/tmp-uuid/%s/%s-flat.vmdk' % (
self._ds.name, self._image_id, self._image_id)
expected_image_path_parent = '[%s] vmware_temp/tmp-uuid/%s' % (
self._ds.name, self._image_id)
expected_path_to_create = '[... | '_base')
base_folder = self._vmops._get_base_folder()
self.assertEqual('7.7.7.7_base', base_folder)
def test_get_base_folder_cache_prefix(se | lf):
self.flags(cache_prefix='my_prefix', group='vmware')
self.flags(image_cache_subdirectory_name='_base')
base_folder = self._vmops._get_base_folder()
self.assertEqual('my_prefix_base', base_folder)
def _test_reboot_vm(self, reboot_type="SOFT"):
expected_methods = ['get_o... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe import _
from frappe.model.document import Document
from frappe.model.rename_doc import rename_doc
clas... | :
if self.is_billable:
if self.disabled:
frappe.db.set_value('Item', self.item, 'disabled', 1)
else:
frappe.db.set_value(' | Item', self.item, 'disabled', 0)
def update_item_and_item_price(self):
if self.is_billable and self.item:
item_doc = frappe.get_doc('Item', {'item_code': self.item})
item_doc.item_name = self.medication_name
item_doc.item_group = self.item_group
item_doc.description = self.description
item_doc.stock_... |
""" TODO: Add docstring """
import re
import pexpect
class MediaObject(object):
"""Represents an encodable object"""
def __init__(self, input_filename, output_filename):
self.input_filename = input_filename
self.output_filename = output_filename
self.media_duration = self.get_media_d... | rocess and saves | the output to a list, then uses
regex to find the duration of the media and return it as an integer.
"""
info_process = pexpect.spawn("/usr/bin/avprobe " + self.input_filename)
subprocess_output = info_process.readlines()
info_process.close
# Non-greedy match on charact... |
m __future__ import division
from __future__ import print_function
#import cv2
from scipy.misc import imresize
from scipy.misc import imread
import numpy as np
try:
import cPickle as pickle
except ImportError:
import pickle
import os
import math
import tensorflow as tf
from utils.timer import Timer
from utils.cyt... | st_actdir = '../activations_retrained'
if not os.path.exists(test_actdir):
os.mkdir(test_actdir)
# define a folder for zero fractions
test_zerodir = './zero_fractions'
if not os.path.exists(test_zerodir):
os.mkdir(test_zerodir)
for i in range(num_images):
im = imread(imdb.image_path_at(i))
_... | boxes = im_detect(sess, net, im)
_t['im_detect'].toc()
# write act summaries to tensorboard
# writer.add_summary(act_summaries)
# record the zero fraction -> only for vgg16
# zero_frac = []
# for layer_ind in range(13):
# batch_num,row,col,filter_num = acts[layer_ind].shape
# zero_... |
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | g 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 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT... |
(token.getY2())
except TypeError:
pass
import numpy as np
if len(lX) > 0:
a,bx = np.polyfit(lX, lY, 1)
lPoints = ','.join(["%d,%d"%(xa,ya) for xa,ya in zip(lX, lY)])
# print 'ANLGE:',math.degrees(math.at... | dFeature(feature)
#
if 'virtual' in lAttributes:
ftype= featureObject.BOOLEAN
feature = featureObject()
feature.setName('f')
feature.setTH(TH)
feature.addNode(self)
feature.setObjectName(self)
feature.setValue(self.g... | etType(ftype)
self.addFeature(feature)
if 'bl' in lAttributes:
for inext in self.next:
ftype= featureObject.NUMERICAL
feature = featureObject()
baseline = self.getBaseline()
nbl = inext.getBaseli... |
def add(x, y):
return | x + y
x = 0
import pdb; pdb.set_trace()
x = add(1, 2)
| |
# This script has to run using the Python executable found in:
# /opt/mgmtworker/env/bin/python in order to properly load the manager
# blueprints utils.py module.
import argparse
import logging
import utils
class CtxWithLogger(object):
logger = logging.getLogger('internal-ssl-certs-logger')
utils.ctx = CtxWi... | ('networks', {})
networks['default'] = internal_rest_host
cert_ | ips = [internal_rest_host] + list(networks.values())
utils.generate_internal_ssl_cert(ips=cert_ips, name=internal_rest_host)
utils.store_cert_metadata(internal_rest_host, networks,
filename=args.metadata)
|
"""
Copyright (C) 2017 Open Source Robotics Foundation
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... | , other):
return self.e == other.e and self.n == other.n and self.u == other.u
def __hash__(self):
return hash((self.e, self.n, self.u))
def to_ecef(self, origin):
# this doesn't work at the poles because longitude is not uniquely defined there
sin_lon = origin._sin_lon()
... | rray([[-sin_lon, -cos_lon * sin_lat, cos_lon * cos_lat],
[cos_lon, - sin_lon * sin_lat, sin_lon * cos_lat],
[0, cos_lat, sin_lat]])
enu_vector = np.array([[self.e], [self.n], [self.u]])
ecef_vector = np.dot(global_to_ece... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
FS Pairtree storage - Reverse lookup
====================================
Conventions used:
From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html version 0.1
This is an implementation of a reverse lookup index, using the pairtree path spec to
record the li... | s(self._dirpath)
enc_id = id_e | ncode(new_id)
if not os.path.isfile(enc_id):
with open(os.path.join(self._dirpath, enc_id), "w") as f:
f.write(new_id)
def _exists(self, id):
if os.path.exists(self._dirpath):
return id_encode(id) in os.listdir(self._dirpath)
else:
return False
def append(self, *args):
... |
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (us... | = True
# Choose between 'default' and 'includehidden' | .
#epub_tocscope = 'default'
# Fix unsupported image types using the PIL.
#epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#e |
# Generated by Django 2.2.17 on 20 | 21-01-28 01:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('discounts', '0010_merge_20191028_1925'),
]
operations = [
migrations.AddField(
model_name='registrationdiscount',
name='applied',
field=m... | yRegistrationDiscount',
),
]
|
nder the BSD style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ i... | f_report(report):
filename = report[JSON_INDEX_FILENAME]
kind = report[JSON_INDEX_KIND] |
line = report[JSON_INDEX_LINE]
error_type = report[JSON_INDEX_TYPE]
msg = report[JSON_INDEX_QUALIFIER]
infer_loc = ''
if JSON_INDEX_INFER_SOURCE_LOC in report:
infer_loc = _text_of_infer_loc(report[JSON_INDEX_INFER_SOURCE_LOC])
return '%s:%d: %s: %s%s\n %s' % (
filename,
... |
query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
... | deserialized
path | _format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.s... |
#!/usr/bin/env python3
import sys
from pathlib import Path
ALLOWED_SUFFIXES = ['.feature',
'.bugfix',
'.doc',
'.removal',
'.misc']
def get_root(script_path):
folder = script_path.absolute().par | ent
while not (folder / '.git').exists():
folder | = folder.parent
if folder == folder.anchor:
raise RuntimeError("git repo not found")
return folder
def main(argv):
print('Check "CHANGES" folder... ', end='', flush=True)
here = Path(argv[0])
root = get_root(here)
changes = root / 'CHANGES'
failed = False
for fname in c... |
for p in pad.GetListOfPrimitives():
if is_plottable(p):
if p.GetName() != "__frame":
plottables.append({'p': asrootpy(p.Clone(gen_random_name()))})
for legend_entry in legend_entries:
if p == legend_entry.GetObject():
... | # vertical:
if self.legend.position.startswith('t'):
leg_hight = leg.y2 - leg.y1
leg.y2 = 1 - pad_p | lot.GetTopMargin() - ytick_length
leg.y1 = leg.y2 - leg_hight
elif self.legend.position.startswith('b'):
leg_hight = leg.y2 - leg.y1
leg.y1 = pad_plot.GetBottomMargin() + ytick_length
leg.y2 = leg.y1 + leg_hight
# horizontal:
... |
from pyramid.httpexceptions import HTTPMovedPermanently
from pyramid.view import view_config
from zeit.redirect.db import Redirect
import json
@view_config(route_name='redirect', renderer='string')
def check_redirect(request):
redirect = Redirect.query().filter_by(source=request.path).first()
if redirect:
... | ive (https etc.)?
raise HTTPMovedPermanently(
'http://' + request.headers['Host'] + redirect.target)
else:
return ''
@view_config(route_name='add', re | nderer='string', request_method='POST')
def add_redirect(request):
body = json.loads(request.body)
Redirect.add(body['source'], body['target'])
return '{}'
|
from staffjoy.resource import Resource
from staffjoy.resources.location import Location
from staffjoy.resources.admin import Admin
from staffjoy.resources.organization_worker import OrganizationWorker
class Organization(Resource):
PATH = "organizations/{organization_id}"
ID_NAME = "organization_id"
def g... | self):
return Admin.get_all(parent=self)
def get_admin(self, id):
return Admin.get(parent=self, id=id)
def create_admin(self, **kwargs):
"""Typically just pass email"""
return Admin.create(parent=self, **kwargs)
def get_workers(self, **kwargs):
return OrganizationW... | t_all(parent=self, **kwargs)
|
from setuptools import setup, find_packages
from fccsmap import __version__
test_requirements = []
with open('requirements-test.txt') as f:
test_requirements = [r for r in f.read().splitlines()]
setup(
name='fccsmap',
version=__version__,
author='Joel Dubowy',
license='GPLv3+',
author_email='... | on :: 3.8",
"Operating System :: POSIX",
"Operating System :: MacOS"
],
url='https://github.com/pnwairfire/fccsmap/',
description='supports the look-up of FCCS fuelbed information by lat/lng or vector geo spatial data.',
install_requires=[
"afscripting>=2.0.0",
# Note: nu... | ed manually beforehand
"shapely==1.7.1",
"pyproj==3.0.0.post1",
"rasterstats==0.15.0"
],
dependency_links=[
"https://pypi.airfire.org/simple/afscripting/",
],
tests_require=test_requirements
)
|
#!/usr/bin/env python
people = 30
cars = 40
trucks = 15
if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars")
else:
print("We can't decide.")
if trucks > cars:
print("Tha | t's too many trucks.")
elif trucks < cars:
print("Maybe we coudl take the trucks.")
else:
print("We still can't decide.")
if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("F | ine, let's stay home then.")
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger
yt_api_e... | _url(search_query)]
)
else:
search_query = '|'.join(query.values()[0])
logger.info("Searching Youtube for query '%s'", search_query)
return SearchResult(
uri='youtube:search',
tracks=search_youtube(search_query)
... | (YoutubePlaybackProvider, self).play(track)
|
import unittest
import pysal
import numpy as np
import random
class Test_Maxp(unittest.TestCase):
def setUp(self):
random.seed(100)
np.random.seed(100)
def test_Maxp(self):
w = pysal.lat2W(10, 10)
z = np.random.random_sample((w.n, 2))
| p = np.ones((w.n, 1), float)
floor = 3
solution = pysal.region.Maxp(
w, z, floor, floor_variable=p, initial=100)
self.assertEquals(solution.p, 29)
self.assertEquals(solution.regions[0], [4, 14, 5, 24, 3, 25, 15, 23])
def test_inference(self):
w = pysal.wei... | = 3
solution = pysal.region.Maxp(
w, z, floor, floor_variable=p, initial=100)
solution.inference(nperm=9)
self.assertAlmostEquals(solution.pvalue, 0.20000000000000001, 10)
def test_cinference(self):
w = pysal.weights.lat2W(5, 5)
z = np.random.random_sample((w.n,... |
class Node(object):
def __init__(self,pos,parent,costSoFar,distanceToEnd):
self.pos = pos
self.parent = parent
self.costSoFar = costSoFar
self. | distanceToEnd = distanceToEnd
self.totalCost = distan | ceToEnd +costSoFar
|
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView, DeleteView
from catalog.views.base import GenericListView, GenericCreateView
from catalog.models import Astronaut, CrewedMission
from catalog.forms import AstronautForm
from catalog.filters import AstronautFilter
from d... | ass AstronautCreateView(GenericCreateView):
model = Astronaut
form_class = AstronautForm
success_url = reverse_lazy("astronaut_list")
def form_valid(self, form):
obj = form.save(commit=False)
obj.creator = self.request.user
obj.save()
return super(AstronautUpdat | eView, self).form_valid(form)
def get_success_url(self):
return reverse("astronaut_detail", args=(self.object.pk,))
class AstronautUpdateView(UpdateView):
model = Astronaut
form_class = AstronautForm
template_name = "catalog/generic_update.html"
initial = {}
def form_valid(self, form... |
# hello_asyncio.py
import asyncio
import tornado.ioloop
import tornado.web
import tornado.gen
from tornado.httpclient import AsyncHTTPClient
try:
import aioredis
except ImportError:
print("Please install aioredis: pip install aioredis")
exit(0)
class AsyncRequestHandler(tornado.web.RequestHandler):
""... | ods on Tornado's ``AsyncIOMainLoop`` instance.
Subclasses have to implement one of `get_async()`, `post_async()`, etc.
Asynchronous method should be decorated with `@asyncio.coroutine`.
Usage example::
class MyAsyncRequestHandler(AsyncRequestHandler):
@asyncio.coroutine
de... | self.write({'html': html})
You may also just re-define `get()` or `post()` methods and they will be simply run
synchronously. This may be convinient for draft implementation, i.e. for testing
new libs or concepts.
"""
@tornado.gen.coroutine
def get(self, *args, **kwargs):
"""Handle GET... |
# -*- coding: utf-8 -*-
#
# Python documentation build configuration file
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
... | spath('tools/sphinxext'))
# General configuration
# ---------------------
extensions = ['sphinx.ext.refcounting', 'sphinx.ext.coverage',
'sphinx.ext.doctest', 'pyspecific']
templates_path = ['tools/sphinxext'] |
# General substitutions.
project = 'Python'
copyright = '1990-%s, Python Software Foundation' % time.strftime('%Y')
# The default replacements for |version| and |release|.
#
# The short X.Y version.
# version = '2.6'
# The full version, including alpha/beta/rc tags.
# release = '2.6a0'
# We look for the Include/pat... |
import zlib, base64, sys
MAX_DEPTH = 50
if __name__ == "__main__":
try:
hashfile = open("hashfile", "r")
except:
print("ERROR: While opening hash file!")
sys.exit(-1)
line_number = 0
depths = [0 for _ in range(MAX_DEPTH)]
for line in hashfile.readlines():
... | print(
"Bad entry on line " + str(line_number) + " (ignored): " + line.strip()
)
continue
hash = l[0]
dept | h = int(l[1])
score = int(l[2])
fen = " ".join(l[3:])
depths[depth] += 1
hashfile.close()
print("-- Depths --")
for i in range(MAX_DEPTH):
if not depths[i]:
continue
print("{:2d}: {:8d}".format(i, depths[i]))
print("------------")
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-21 04:50
from __futur | e__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies | = [
('blog', '0011_auto_20170621_1224'),
]
operations = [
migrations.AddField(
model_name='category',
name='slug',
field=models.SlugField(default=''),
),
migrations.AddField(
model_name='tag',
name='slug',
f... |
from django.conf.urls import patterns, url
from django.core.urlresolvers import reverse
from django.http import Http404
from modeltree.tree import MODELTREE_DEFAULT_ALIAS, trees
from restlib2.params import Parametizer, IntParam, StrParam
from avocado.export import BaseExporter, registry as exporters
from avocado.query... | params = self.get_params(request)
# Configure the query options used for retrieving the results.
query_options = {
| 'export_type': export_type,
'query_name': self._get_query_name(request, export_type),
}
query_options.update(**kwargs)
query_options.update(params)
try:
row_data = utils.get_result_rows(context, view, query_options,
... |
# Copyright 2013 Nebula 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
#
# Unl | ess required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#... | six
from cliff import command
from cliff import lister
from cliff import show
from openstackclient.common import parseractions
from openstackclient.common import utils
class CreateContainer(lister.Lister):
"""Create new container"""
log = logging.getLogger(__name__ + '.CreateContainer')
def get_parse... |
ue=["foo"]))
def test_debug_application_debug_endpoint(self):
registry, server, debugged_app = TestDebuggedJsonRpcApplication.get_app()
environ = {
"SERVER_NAME": "localhost",
"SERVER_PORT": "5060",
"PATH_INFO": "/debug/1234",
"REQUEST_METHOD": "POST",... | g.DebuggedApplication.debug_application.called
class TestServer(obj | ect):
@staticmethod
def _create_mock_registry():
mock_registry = mock.Mock()
mock_registry.json_encoder = json.JSONEncoder()
mock_registry.json_decoder = json.JSONDecoder()
mock_registry.dispatch.return_value = json.dumps({
"jsonrpc": "2.0",
"id": "foo",
... |
#!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def test_sign_verify(self):
def do_test(secret_exponent, val_list):
public_point = public_pair_for_secret_exponent(generat... | for v in val_list:
signature = sign(generator_secp256k1, secret_exponent, v)
r = verify(generator_secp256k1, public_point, v, signature)
# Check that the 's' value is ' | low', to prevent possible transaction malleability as per
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in-signatures
assert signature[1] <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
assert r == True
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------
# File Name: utils.py
# Author: Zhao Yanbai
# Thu Oct 30 06:33:24 2014
# Description: none
# ------------------------------------------------------------------------
import loggi... | int(logic)
return (logic == 0 or logic == 1 or logic == 2)
class PageBase(object):
def __init__(self) :
self.ActionMap = { }
| self.action = ''
self.SetActionHandler('New', self.New)
self.SetActionHandler('Add', self.Add)
self.SetActionHandler('Del', self.Del)
self.SetActionHandler('Edit', self.Edit)
self.SetActionHandler('List', self.List)
self.SetActionHandler('Search', self.Sea... |
h+"greenblock/"
match_path = spath+"matches/"
rb_path = spath+"redblock/"
s1_path = spath+"stuffed/"
s2_path = spath+"stuffed2/"
s3_path = spath+"stuffed3/"
arbor_path = upath+"arborgreens/"
football_path = upath+"football/"
sanjuan_path = upath+"sanjuans/"
print('SVMPoly')
#Set up am SVM with a poly kernel
extract... | th,s3_path]
classes = ['s1','s2','s3']
classifierBagTree.train | (path,classes,disp=display,subset=n) #train
print('Test')
[pos,neg,confuse] = classifierBagTree.test(path,classes,disp=display,subset=n)
files = glob.glob( os.path.join(path[0], '*.jpg'))
for i in range(10):
img = Image(files[i])
cname = classifierBagTree.classify(img)
print(files[i]+' -> '+cname)
classifi... |
("days_to_keep_positive", "CHECK(days_to_keep >= 0)",
"I cannot remove backups from the future. Ask Doc for that."),
]
name = fields.Char(
string="Name",
compute="_compute_name",
store=True,
help="Summary of this backup process",
)
folder = fields.Char(
... | for name in remote.listdir(rec.folder):
if (name.endswith(".dump.zip") and
| os.path.basename(name) < oldest):
remote.unlink(name)
@api.multi
@contextmanager
def cleanup_log(self):
"""Log a possible cleanup failure."""
try:
_logger.info("Starting cleanup process after database backup: %s",
... |
f:', name_='ResourceAllocationSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='Reso... | \n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
| def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(ResourceAllocatio... |
'''
pyttsx setup script.
Copyright (c) 2009, 2013 Peter Parente
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHO... | THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE | LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
'''
from setuptools import setup,... |
#!/usr/bin/env python
# encoding: utf-8
"""
Generic | stock functions
"""
class Stock(object):
"""
Generic Stock informat | ion
"""
def __init__(self, symbol, name, sector):
super(Stock, self).__init__()
self.symbol = symbol
self.name = name
self.sector = sector
|
from __future__ import print_function
import sys
import subprocess
class AutoInstall(object):
_loaded = set()
@classmethod
def find_module(cls, name, path, target=None):
if path is None an | d name not in cls._loaded:
cls._loaded.add(name)
print("Installing", name)
try:
out = subprocess.check_output(['sudo', sys.executable, '-m', 'pip', 'install', name])
print(out)
except Exception as e:
print("Failed" + e.messa... | )
return None
sys.meta_path.append(AutoInstall)
|
# ----------------------------------------------------------------------------
# Copyright (c) 2017-, labman development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------... | nfigParser()
with open(self.conf_fp, 'U') as conf_file:
config.readfp(conf_file)
_required_sections = {'postgres'}
if not _required_sections.issubset(set(config.sections())):
missing = _required_sections - set(config.sections())
raise RuntimeError(', '.join(m... | ation"""
self.test_environment = config.getboolean('main', 'TEST_ENVIRONMENT')
self.log_dir = config.get('main', 'LOG_DIR')
def _get_postgres(self, config):
"""Get the configuration of the postgres section"""
self.user = config.get('postgres', 'USER')
self.admin_user = confi... |
# coding: utf-8
#
# Copyright © 2010—2014 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Comm... | ses', 'named', 'arg', 'wrap_errors', 'expects_obj']
def named(new_name):
"""
| Sets given string as command name instead of the function name.
The string is used verbatim without further processing.
Usage::
@named('load')
def do_load_some_stuff_and_keep_the_original_function_name(args):
...
The resulting command will be available only as ``load``. To ad... |
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge... | oftware, | and to
# permit persons to whom the Software is furnished to do so, subject to
# the following 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... |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def ExtensionFaultTypeInfo(vim, *args, **kwargs):
'''This data object type describes faul... | args):
setattr(obj, name, arg)
for name, value in kwargs.items():
if name in required + optional:
setattr(obj, name, value)
else:
raise InvalidArgumentError("Invalid argument: %s. Expected one | of %s" % (name, ", ".join(required + optional)))
return obj
|
import unittest
import json
import forgi.threedee.utilities._dssr as ftud
import forgi.threedee.model.coarse_grain as ftmc
import forgi.graph.residue as fgr
class TestHelperFunctions(unittest.TestCase):
def test_dssr_to_pdb_atom_id_validIds(self):
self.assertEqual(ftud.dssr_to_pdb_resid(
"B.C24... | ", (" ", 13, " ")))
self | .assertEqual(ftud.dssr_to_pdb_resid(
"A.5BU36"), ("A", (" ", 36, " ")))
self.assertEqual(ftud.dssr_to_pdb_resid(
"C.C47^M"), ("C", (" ", 47, "M")))
self.assertEqual(ftud.dssr_to_pdb_resid(
"C.5BU47^M"), ("C", (" ", 47, "M")))
self.assertEqual(ftud.dssr_to_pdb_... |
'''
pysplat is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any lat | er version.
pysplat is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY | ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with kicad-footprint-generator. If not, see < http://www.gnu.org/licenses/ >.
(C) 2016 by Thomas Poi... |
# -*- coding: | utf-8 -*-
from tornado.options import define
define('debug', default=False, type=bool)
# Tornado的监听端口
define('port', default=8888, type=int)
# WHoosh Search相关
define('whoosh_ix_path', default='/Users/liushuai/Desktop/index', type=str)
# MongoDB
define('mongo_a | ddr', default='127.0.0.1', type=str)
define('mongo_port', default=27017, type=int)
|
import unittest
import os
import numpy as np
from tools.sampling import read_log_file
from tools.walk_trees import walk_trees_with_data
from tools.game_tree.nodes import ActionNode, BoardCardsNode, HoleCardsNode
LEDUC_POKER_GAME_FILE_PATH = 'games/leduc.limit.2p.game'
class SamplingTests(unittest.TestCase):
def... | players = read_log_file(
LEDUC_POKER_GAME_FILE_PATH,
| 'test/sample_log.log',
['player_1', 'player_2'])
callback_was_called_at_least_once = False
def node_callback(data, node):
nonlocal callback_was_called_at_least_once
if isinstance(node, ActionNode):
callback_was_called_at_least_once = True
... |
yName = os.environ.get("DISPLAY")
if not displayName:
raise QtileError("No DISPLAY set.")
if not fname:
# Dots might appear in the host part of the display name
# during remote X sessions. Let's strip the host part first.
displayNum = displayName.... | self._drag = None
self.ignoreEvents = set([
xcffib.xproto.KeyReleaseEvent,
xcffib.xproto.ReparentNotifyEvent,
xcffib.xproto.CreateNotifyEvent,
# DWM handles this to help "broken focusing windows".
xcffib.xproto.MapNotifyEvent,
xcffib.... | xcffib.xproto.NoExposureEvent
])
self.conn.flush()
self.conn.xsync()
self._xpoll()
# Map and Grab keys
for key in self.config.keys:
self.mapKey(key)
# It fixes problems with focus when clicking windows of some specific clients like xterm
... |
# Copyright (C) 2007, Eduardo Silva <edsiper@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 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
# MERCHANTAB... | along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
from gi.repository import Gdk
from sugar3.graphics import style
from sugar3.graphics.palette import WidgetInvoker
def _get_screen_area():
frame_thickness = style.GRID_CELL_SIZ... |
# | !/usr/bin/env python
NAME = 'F5 Trafficshield'
def is_waf(self):
for hv in [['cookie', '^ASINFO='], ['server', 'F5-TrafficShield']]:
r = self.matchheader(hv)
if r is None:
return
elif r:
return r
# the following based on nmap's http-waf-fingerprint.nse
if ... | e
|
"""Implementation of :class:`SymPyRealDomain` class. """
from sympy.polys.domains.realdomain import RealDomain
from sympy.polys.domains.groundtypes import SymPyRealType
class SymPyRealDomain(RealDomain):
"""Domain for real numbers based on SymPy Float type. """
dtype = SymPyRealType
zero = dtype(0)
... | return SymPyRealType(a)
def from_QQ_python(K1, a, K0):
"""Convert a Python `Fraction` object to `dtype`. """
return SymPyRealType(a.numerator) / a.denominator
def from_ZZ_sympy(K1, a, K0):
"""Convert a SymPy `Integer` object to `dtype`. """
return SymPyRealType(a.p)
def... | |
rField')(max_length=40))
# Changing field 'LibertySessionSP.django_session_key'
db.alter_column(u'saml_libertysessionsp', 'django_session_key', self.gf('django.db.models.fields.CharField')(max_length=40))
# Changing field 'LibertyAssertion.provider_id'
db.alter_column(u'saml_libertyass... | 'accept_slo': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'allow_create': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'back_url': ('django.db.models.fields.Ch | arField', [], {'default': "'/'", 'max_length': '200'}),
'binding_for_sso_response': ('django.db.models.fields.CharField', [], {'default': "'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact'", 'max_length': '200'}),
'enable_binding_for_sso_response': ('django.db.models.fields.BooleanField', [],... |
'service': {
'name': 'telegram',
'username': update.message.from_user.username,
},
'type': 'web_service_binding',
'version': 1,
},
'ctime': int(time.time()),
'expire_in': 60 * 60 * 24 *... | , proof = check_key(bot,
json.loads(info.proof_object), info.sig | ned_block,
info.telegram_username, info.user_id)
if succes == 'no_expiry':
bot.send_message(chat_id=update.message.chat_id,
text="😕 \"@{}\" on telegram. "
"But the proof has no expiry set, so be careful... |
nse, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS I... |
)
self.assertIsNotNone(create_file_task)
ti1 = TaskInstance(task=create_file_task, execution_date=datetime.now())
ti1.run()
# get remote file to local
get_test_task = SFTPOperator(
task_id="test_sftp",
ssh_hook=self.hook,
... |
)
self.assertIsNotNone(get_test_task)
ti2 = TaskInstance(task=get_test_task, execution_date=datetime.now())
ti2.run()
# test the received content
content_received = None
with open(self.test_local_filepath, 'r') as f:
|
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# Funciones y parametros arbitrarios
def funcion | (**nombres):
print (type(nombres))
for alumno in nombres:
print ("%s es alumno y tiene %d años" % (alumno, nombres[alumno]))
return nombres
#diccionario = {"Adrian":25, "Niño":25, "Roberto":23, "Celina":23}
print (funcion(Adrian = 25, Nino = 25, Roberto = 23, Celina | = 23))
|
# Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,... | todo_text):
"""
Pre-proces | ses user input when adding a task.
It detects a priority mid-sentence and puts it at the start.
"""
todo_text = re.sub(r'^(.+) (\([A-Z]\))(.*)$', r'\2 \1\3',
p_todo_text)
return todo_text
todo_text = _preprocess_input_todo(p_todo_... |
##
# Copyright 2012-2016 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemi | sh Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild is free software: you can redistribute it and/or mo... | |
"""
Django settings for myclass project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
#... | ate.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'myclass.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#data... | ult': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAt... |
from fabric.api import env
from fabric.context_managers import cd
from fabric.operations import run, local, put
env.shell = '/bin/bash -l -c'
env.user = 'd'
env.roledefs.update({
'staging': ['staging.solebtc.com'],
'production': ['solebtc.com']
})
# Heaven will execute fab -R staging deploy:bra | nch_name=master
def deploy(branch_name):
deployProduction(branch_name) if env.roles[0] == | 'production' else deployStaging(branch_name)
def deployStaging(branch_name):
printMessage("staging")
codedir = '$GOPATH/src/github.com/solefaucet/solebtc'
run('rm -rf %s' % codedir)
run('mkdir -p %s' % codedir)
local('git archive --format=tar --output=/tmp/archive.tar %s' % branch_name)
l... |
from game import models
from game.method.in_game import thread_fields, Thread_field
from game.tool.room_tool import *
from game.tool.tools import to_json
# 实时获得房间信息 room_id
def get_room_info(request):
room_id = int(request.POST['room_id'])
room = get_room_by_id(room_id)
print(room_id)
print... | sers_status[owner_id] = True
# all_ready = True
# if room_id == room.owner:
# for u in room.users:
# if not room.users_status[u]:
# all_ready = False
# break
# if all_ready:
# # 全部准备好
# room.status = True
# ... | 是房主
# return 0
#
#
# # 检查是否开始游戏了 room_id
# def check_room_status(request):
# room_id = request.POST.get('room_id')
# # 找到此房间
# room = get_room_by_id(room_id)
# if room.status:
# # 已经开始了
# return 0
# else:
# # 还没有开始
# return 0
|
sys.stdout = gclient.gclient_utils.MakeFileAutoFlush(sys.stdout)
sys.stdout = gclient.gclient_utils.MakeFileAnnotated(sys.stdout)
def tearDown(self):
self.assertEquals([], self._get_processed())
gclient.Dependency.CreateSCM = self._old_createscm
sys.stdout = self._old_sys_stdout
os.chdir(self.pre... | 0')
def _dependencies(self, jobs):
"""Verifies that dependencies are processed in the right order.
e.g. if there is a | dependency 'src' and another 'src/third_party/bar', that
bar isn't fetched until 'src' is done.
Args:
|jobs| is the number of parallel jobs simulated.
"""
parser = gclient.OptionParser()
options, args = parser.parse_args(['--jobs', jobs])
write(
'.gclient',
'solutions = [\... |
from os import system
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
def clear_bu | ffer_cache():
system('free -g')
system('sync')
system("sudo sed -n 's/0/3/w /proc/sys/vm/drop_caches' /proc/sys/vm/drop_caches")
system('sync')
system("sudo sed -n 's/3/0/w /proc/sys/vm/drop_caches' /proc/sys/vm/drop_caches")
system('free -g')
return True
def is_even(n):
return n%2 == 0
server = SimpleXMLRPCS... | erver.register_function(clear_buffer_cache, 'clear_buffer_cache')
server.register_function(is_even, 'is_even')
server.serve_forever()
|
# Standard imports
import unittest
import json
import logging
from datetime import datetime, timedelta
# Our imports
from emission.clients.gamified import gamified
from emission.core.get_database import get_db, get_mode_db, get_section_db
from emission.core.wrapper.user import User
from emission.core.wrapper.client im... | e'] = 9
airSection['_id'] = section['_id'] + "_air"
self.SectionsColl.insert(airSection)
airSection['confirmed_mode'] = ''
ai | rSection['_id'] = section['_id'] + "_unconf"
self.SectionsColl.insert(airSection)
# print("Section start = %s, section end = %s" %
# (section['section_start_datetime'], section['section_end_datetime']))
self.SectionsColl.save(section)
def setupUserAn... |
from flas | k import Flask
server = Flask(__name__)
server.config['SERVER_N | AME'] = '127.0.0.1:5001'
from app import endpoints
|
form '{entity_name}_{column_name}'. For example, in the `game`
table, the `gsis_id` column must be named `game_gsis_id` in
`row`.
"""
obj = cls(db)
seta = setattr
prefix = cls._sql_primary_table() + '_'
slice_from = len(prefix)
for k in row:
... | from_aliases=None, to_aliases=None):
"""
Given a **sub class** `cls_to` of `nfldb.Entity`, produce
a SQL `LEFT JOIN` clause.
If the primary keys in `cls_from` and `cls_to` have an empty
intersection, then an assertion error is raised.
Note that the first tabl... | re `None`.
`from_aliases` are only applied to the `from` tables and
`to_aliases` are only applied to the `to` tables. This allows
one to do self joins.
"""
if from_table is None:
from_table = cls_from._sql_primary_table()
if to_table is None:
to_t... |
rint "Exception info %s " % sys.exc_info()[0]
return -128
return result
if method == 'EnqueueCopyBuffer':
try:
nid = int(args['id'])
sourcebuffer = int(args['SourceBuffer'])
destinationbuffer = int(args['DestinationBuffer'])
bytecount = i... | 'Kernel'])
gwo = args['GWO']
gws = args['GWS']
lws = args['LWS']
result = PyOpenCLInterface.EnqueueNDRangeKernel(nid, kernel, gwo, gws, lws)
except:
print "Exception caught in DispatchCommandQueues.%s " % method
print "Exception info %s " %... | -128
return result
if method == 'EnqueueTask':
try:
nid = int(args['id'])
kernel = int(args['Kernel'])
result = PyOpenCLInterface.EnqueueTask(nid, kernel)
except:
print "Exception caught in DispatchCommandQueues.%s " % method
print... |
env('GIT','git')
BASH = os.getenv('BASH','bash')
# OS specific configuration for terminal attributes
ATTR_RESET = ''
ATTR_PR = ''
COMMIT_FORMAT = '%h %s (%an)%d'
if os.name == 'posix': # if posix, assume we can use basic terminal escapes
ATTR_RESET = '\033[0m'
ATTR_PR = '\033[1;36m'
COMMIT_FORMAT = '%C(bol... | ranch = 'pull/'+pull+'/merge'
local_merge_branch = 'pull/'+pull+'/local-merge'
devnull = open(os.devnull,'w')
try:
subprocess.check_call([GIT,'checkout','-q',branch])
except subprocess.CalledProcessError as e:
print("ERROR: Cannot check out branch %s." % (branch), file=stderr)
s... | ','-q',host_repo,'+refs/pull/'+pull+'/*:refs/heads/pull/'+pull+'/*'])
except subprocess.CalledProcessError as e:
print("ERROR: Cannot find pull request #%s on %s." % (pull,host_repo), file=stderr)
sys.exit(3)
try:
subprocess.check_call([GIT,'log','-q','-1','refs/heads/'+head_branch], std... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import six
from cryptography import utils
from cryptography.x509.oid imp... | elf):
return "<NameAttribute(oid={0.oid}, value={0.value!r})>".format(self)
class Name(object):
def __init__(self, attributes):
self._attributes = attributes
def get_attributes_for_oid(self, oid):
return [i for i | in self if i.oid == oid]
def __eq__(self, other):
if not isinstance(other, Name):
return NotImplemented
return self._attributes == other._attributes
def __ne__(self, other):
return not self == other
def __hash__(self):
# TODO: this is relatively expensive, if... |
# *****************************************************************
# Copyright (c) 2013 Massachusetts Institute of Technology
#
# Developed exclusively at US Government expense under US Air Force contract
# FA8721-05-C-002. The rights of the United States Government to use, modify,
# reproduce, release, perform, disp... | Description: IBM TA2 wire class
#
# Modifications:
# Date Name Modification
# ---- ---- ------------
# 22 Oct 2012 SY Original Version
# *****************************************************************
import ibm_circuit_object as ico
class IBMInputWi... | ircuit):
"""Initializes the wire with the display name and circuit specified."""
ico.IBMCircuitObject.__init__(self, displayname, 0.0, 0, circuit)
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | nates | around the input coordinate, within the
specified radius.
2. For each coordinate, use a uniform hash function to
deterministically map it to a real number between 0 and 1. This is the
"order" of the coordinate.
3. Of these coordinates, pick the top W by order, where W is the
number of active bits desired in... |
# coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | scope: Optional[Text] = None,
loss_collection: tf.compat.v1.GraphKeys = tf.compat.v1.GraphKeys.LOSSES,
reduction: tf.compat.v1.losses.Reduction = tf.compat.v1.losses.Reduction
.SUM_BY_NONZERO_WEIGHTS,
quantile: float = 0.5) -> types.Float:
"""Adds a Pinball loss for quantile regression.
```
... | n.wikipedia.org/wiki/Quantile_regression#Quantiles
`weights` acts as a coefficient for the loss. If a scalar is provided, then
the loss is simply scaled by the given value. If `weights` is a tensor of size
`[batch_size]`, then the total loss for each sample of the batch is rescaled
by the corresponding elemen... |
'''
Notice:
1. The function for jit should locate in mfs
2. For the usage of jit types and signatures, please refer Numba documentation <http://numba.github.com/numba-doc/0.10/index.ht | ml>
'''
from dpark import _ctx as dpark, jit, autojit
import numpy
@jit('f8(f8[:])')
def add1(x):
sum = 0.0
for i in xrange(x.shape[0]):
sum += i*x[i]
return sum
@autojit
def add2(x):
sum = 0 | .0
for i in xrange(x.shape[0]):
sum += i*x[i]
return sum
def add3(x):
sum = 0.0
for i in xrange(x.shape[0]):
sum += i*x[i]
return sum
rdd = dpark.makeRDD(range(0, 10)).map(lambda x: numpy.arange(x*1e7, (x+1)*1e7))
print rdd.map(add1).collect()
print rdd.map(add2).collect()
print r... |
Returns:
- resp: server response if successful
- list: list of strings returned by the server in response to the
HELP command
"""
return self._longcmdstring('HELP', file)
def _statparse(self, resp):
"""Internal: parse the response line of a STAT, NEXT, LAST,... | _num, path] = resp.split()
except ValueError:
raise NNTPReplyError(resp)
else:
return resp, path
def date(self):
"""Process the DATE command.
Returns:
- resp: server response if successful
- date: datetime object
"""
resp = sel... | elem = resp.split()
if len(elem) != 2:
raise NNTPDataError(resp)
date = elem[1]
if len(date) != 14:
raise NNTPDataError(resp)
return resp, _parse_datetime(date, None)
def _post(self, command, f):
resp = self._shortcmd(command)
# Raises a spe... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Lice... | elf.ratio)
self.PlotIndicator("Data", self.vix_sma, self.vxv_sma)
# OnData event is the primary entry point for you | r algorithm. Each new data point will be pumped in here.
def OnData(self, data):
# Wait for all indicators to fully initialize
if not (self.vix_sma.IsReady and self.vxv_sma.IsReady and self.ratio.IsReady): return
if not self.Portfolio.Invested and self.ratio.Current.Value > 1:
... |
from distutils.core import setup, Extension, Command
from distutils.command.build import build
from distutils.command.build_ext import build_ext
from distutils.command.config import config
from distutils.msvccompiler import MSVCCompiler
from distutils import sysconfig
import string
import sys
mkobjs = ['column', 'cust... |
build_options = ('build_base', 'build_purelib', 'build_platlib')
for option in build_options:
val = getattr(self, option)
if val:
setattr(build, | option, getattr(self, option))
build.ensure_finalized()
for option in build_options:
setattr(self, option, getattr(build, option))
def run(self):
# Invoke the 'build' command to "build" pure Python modules
# (ie. copy 'em into the build tree)
self.run_c... |
, '--step_length', type=int, default=100,
help='Number of iterations between samples.')
parser.add_argument('-init', '--initial_soln', nargs="*",
help='Initial solution to use.')
parser.add_argument('-r', '--num_initial', default=1, type=int,
... |
realMutations = (m, n, genes, patients, geneToCases, patientToGenes )
outputDirViz = realOutputDir + "/viz/"
C.ensure_dir(outputDirViz)
# Perform visualization
C.output_comet_viz(RC.get_parser().parse_args(realCometArgs), realMutations, \
results | Table, maxStat, args.num_permutations)
# Destroy the temporary di |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.