prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from ... import Endpoint, UrlConfig
class TftEndpoint | :
def __init__(self, url: str, **kwargs):
self._url = f"/tft{url}"
def __call__(self, **kwargs):
final_url = f"{UrlConfig.tft_url}{self._url}"
endpoint = Endpoint(final_url | , **kwargs)
return endpoint(**kwargs)
|
esponseCode, \
TicketBaiCancellationResponseCode
from odoo.addons.l10n_es_ticketbai_api.utils import utils as tbai_utils
from odoo.exceptions import ValidationError
class LROEOperationResponseState(Enum):
BUILD_ERROR = '-2'
REQUEST_ERROR = '-1'
CORRECT = 'Correcto'
PARTIALLY_CORRECT = 'Parcialment... | lroe_operation_type,
lroe_operation_chapter,
lroe_operation_model,
),
).value
xml_schema = LROEXMLSchema(operation_type)
else:
raise | LROEXMLSchemaModeNotSupported(
"Batuz LROE XML model not supported!")
return operation_type, xml_schema
def set_tbai_response_lroe_line():
response_line_record_data = response_line_record.get('SituacionRegistro')
response_line_record_state = response_lin... |
"""
(c) Copyright 2014. All Rights Reserved.
qball module setup and package.
"""
from setuptools import setup
setup(
name='qball',
autho | r='Matt Ferrante',
author_email='mferrante3@gmail.com',
description='Python integration | for qball',
license='(c) Copyright 2014. All Rights Reserved.',
packages=['qball'],
install_requires=['httplib2 >= 0.8'],
setup_requires=['httplib2'],
version='1.1.0',
url="https://github.com/ferrants/qball-python",
keywords = ['locking', 'resource locking', 'webservice'],
)
|
t.keyval == gtk.keysyms.Escape:
self.g_heading_entry.disconnect(sid)
self.g_heading_entry.disconnect(keyup_id)
self.g_heading_entry.hide()
self.g_heading.show()
return True
keyup_id = self.g_heading_entry.connect('key-release-event'... | lessonfile.mk_uri(fn)
# Small test to check that the file actually is a lesson file.
try:
lessonfile.infocache.get(fn, 'title')
except lessonfile.infocache.FileNotLessonfile:
continue
self.m_model.append(fn)
| self.g_link_box.pack_start(self.create_linkrow(fn), False)
def on_add_link_to_new_page(self, menuitem):
page = pd.Page(_("Untitled%s") % "", [pd.Column()])
self.m_model.append(page)
self.g_link_box.pack_start(self.create_linkrow(page))
def create_linkrow(self, link_this):
hb... |
"stateG2 = 0 & \n"
# Guarantee 3:
"stateG3_0 = 0 & \n"
"stateG3_1 = 0 & \n"
"stateG3_2 = 0 & \n")
# Guarantee 10:
for i in xrange(1, num_masters):
sys_initial += "stateG10_{i} = 0 & \n".format(i=i)
var = 'stateG10_{i}'.format(i=i)
output_vars.append(va... | & (stateA1_0 = 0))) & \n"
"[](((stateA1_1 = 0) & (stateA1_0 = 0) & "
" (hmastlock = 1) & (hburst0 = 0) & (hburst1 = 0)) ->\n"
" X((stateA1_1 = 1) & (stateA1_0 = 0))) & \n"
| # state 10
"[](((stateA1_1 = 1) & (stateA1_0 = 0) & (busreq = 1)) ->\n"
" X((stateA1_1 = 1) & (stateA1_0 = 0))) & \n"
"[](((stateA1_1 = 1) & (stateA1_0 = 0) & (busreq = 0) & "
"((hmastlock = 0) | (hburst0 = 1) | (hburst1 = 1))) ->\n"
" X((stateA1_1 = 0) & (stateA1_0 = 0))) & \n"
... |
import pyowm
owm | = pyowm.OWM('fa7813518ed203b75 | 9f116a3bac9bcce')
observation = owm.weather_at_place('London,uk')
w = observation.get_weather()
wtemp = str(w.get_temperature('celsius'))
print(wtemp.strip('{}'))
wtemp_list = list(wtemp)
print(wtemp_list) |
#
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | t Exception as e:
raise e
@classmethod
def get_filtered(cls, service, id, filter_) :
""" Use this API to fetch filtered set of bridgegroup_nsip6_binding resources.
Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
"""
try :
obj = bridgegroup_nsip6_binding()
obj.id = id
option... | _)
return response
except Exception as e:
raise e
@classmethod
def count(cls, service, id) :
""" Use this API to count bridgegroup_nsip6_binding resources configued on NetScaler.
"""
try :
obj = bridgegroup_nsip6_binding()
obj.id = id
option_ = options()
option_.count = True
response = o... |
efore loading the config file,
removes or upgrades any old settings.
"""
if self.configParser.has_section('system'):
system = self.configParser.system
if system.has_option('appDataDir'):
# Older config files had configDir stored as appDataDir
... |
# and UN-Load from the list of "deprecated" iDevices
if self.configParser.has_section('deprecated'):
deprecatedSection = self.configParser.deprecated
for key,value in deprecatedSection.items():
# emulate standard library's getboolean()
value ... | ecatediDevices:
self.deprecatediDevices.remove(key.lower())
# Load the "user" section
if self.configParser.has_section('user'):
if self.configParser.user.has_option('editorMode'):
self.editorMode = self.configParser.user.editorMode
... |
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at
# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
#
# 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... |
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific la | nguage governing permissions and
# limitations under the License.
import unittest
import subprocess
import os
import sys
from testRealtime import TestRealtime
if __name__ == '__main__':
realtime = unittest.TestLoader().loadTestsFromTestCase(TestRealtime)
allTests = unittest.TestSuite()
allTests.addTest(r... |
#!/usr/bin/env python3
import csv
import argparse
FLAG = None
def write_file(feats,lab_list, fn):
with open(fn,'w') as f:
for num, i in enumerate(feats):
for j in range(len(i)):
f.write(str(i[j]) + ',')
f.write(str([len(i)-1]) + '\n')
return
def transform(... | read_len(FLAG.len_file)
ark_list, lab_list = read_feat(FLAG.ark_file)
return
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Transfrom the fulfilled zeros to no')
parser.add_argument('--feat_dim',type=int, default=39,
help='each frame feat dimension')
pa... | ment('ark_file',
help='the transforming ark file')
parser.add_argument('len_file',
help='meaning the length of each utterance')
parser.add_argument('out_ark',
help='the output file')
FLAG = parser.parse_args()
main()
|
#!/usr/bin/env python
'''Simple viewer for DDS texture files.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from ctypes import *
import getopt
import sys
import textwrap
from SDL import *
from pyglet.gl.VERSION_1_1 import *
import pyglet.dds
import pyglet.event
import pyglet.image
import pyglet.sprit... | te & SDL_BUTTON(1):
texture_offset[0] += x - last_pos[0]
texture_offset[1] += y - last_pos[1]
update_texture_matrix()
last_pos = x, y
def update_texture_matrix():
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glTranslatef(-texture_offset[0] / float(textures[texture_in | dex].size[0]),
-texture_offset[1] / float(textures[texture_index].size[1]),
0)
glMatrixMode(GL_MODELVIEW)
def toggle_view():
global view
if view != 'flat':
pyglet.event.pop()
pyglet.window.set_2d()
view = 'flat'
else:
pyglet.event.push()... |
"""
Converts argparse parser actions into json "Build Specs"
"""
import argparse
from argparse import (
_CountAction,
_HelpAction,
_StoreConstAction,
_StoreFalseAction,
_StoreTrueAction,
ArgumentParser, _SubParsersAction)
from collections import OrderedDict
from functools import partial
VALID_WIDGETS = (... | itional or possessing the `required` flag'''
return action.option_strings and not action.required
def is_choice(action):
''' action with choices supplied '''
return action.choices
def is_standard(action):
""" actions which are general "sto | re" instructions.
e.g. anything which has an argument style like:
$ script.py -f myfilename.txt
"""
boolean_actions = (
_StoreConstAction, _StoreFalseAction,
_StoreTrueAction
)
return (not action.choices
and not isinstance(action, _CountAction)
and not isinstance(action, _Help... |
ate_zeros(tangent):
if type(tangent) is Zero:
return zeros_like_aval(tangent.aval)
else:
return tangent
# This function seems similar to instantiate_zeros, but it is sometimes used
# to instantiate zero abstract units with a different aval
def instantiate_zeros_aval(aval, tangent):
if type(tangent) is Ze... | imal, args),
[type(x) is not Zero for x in ct])
out_flat = primitive.bind(fun, *all_args, **new_params)
arg_cts = tree_unflatten(out_tree(), out_flat)
# The freevars are being fanned out (not mapped). During transpose the
# dual of fan-out is fan-in-sum. We apply it to the unmapp... | unmap_zero(zero, in_axis):
return (zero if in_axis is None else
Zero(core.unmapped_aval(params['axis_size'], params['axis_name'], in_axis, zero.aval)))
arg_cts = (unmap_zero(arg_ct, in_axis) if type(arg_ct) is Zero else
arg_ct if in_axis is not None else
arg_ct.sum(0)
... |
tile = [[0,1,4,5],
[2,3,6,7],
[8,9,12,13],
[10,11,14,15]]
shift = 0
align = 1
value = 0L
holder = []
import sys
basemask = [0x
fd = sys.stdout
indent = " "*9
for c in range(4):
fd.writ | e(indent + "*pdst++ = \n");
for l,line in enumerate(tile):
fd.write(indent + " %s_mm_shuffle_epi8(line%d, (__m128i){"%(l and '+' or ' ',l))
for i,pos in enumerate(line):
ma | sk = 0x00ffffffff & (~(0xffL << shift))
value = mask | ((pos) << shift)
holder.append(value)
if holder and (i + 1) %2 == 0:
fd.write("0x%8.0x"%(holder[0] + (holder[1] << 32)))
holder = []
if (i) %4 == 1:
fd.write( ',')
fd.write("})%s\n"%((l == 3) and ';' or ''))
print... |
import asyncio
import colorsys
import enum
import functools
import psmove
import time
import traceback
import random
SETTINGSFILE = 'joustsettings.yaml'
#Human speeds[slow, mid, fast]
#SLOW_WARNING = [0.1, 0.15, 0.28]
#SLOW_MAX = [0.25, 0.8, 1]
#FAST_WARNING = [0.5, 0.6, 0.8]
#FAST_MAX = [1, 1.4, 1.8]
SLOW_WARNING =... | s, **kwargs):
try:
await f(*args, **kwargs)
except asyncio.CancelledError:
| raise
except:
traceback.print_exc()
raise
return wrapper
# Represents a pace the game is played at, encapsulating the tempo of the music as well
# as controller sensitivity.
class GamePace:
__slots__ = ['tempo', 'warn_threshold', 'death_threshold']
def __init__(self, tempo, ... |
Y 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 SickGear. If not, see <http://www.gnu.org/licenses/>.
from __future__ impor... | s.split(',')]
for regfilter in filters:
if regfilter.search(name):
logger.log(u"" + name + " contains pattern: " + regfilter.pattern, logger.DEBUG)
return True
return False
def pickBestResult(results, show, quality_list=None):
logger.log(u"Picking the best ... | ack And white list
bwl = None
if show:
if show.is_anime:
bwl = BlackAndWhiteList(show.indexerid)
else:
logger.log("Could not create black and white list no show was given", logger.DEBUG)
# find the best result for the current episode
bestResult = None
for cur_result ... |
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as publish... | yword argument called
``job_queue`` will be passed to the callback function. It will be a
:class:`tel | egram.ext.JobQueue` instance created by the :class:`telegram.ext.Updater`
which can be used to schedule new jobs. Default is ``False``.
"""
def __init__(self, type, callback, strict=False, pass_update_queue=False,
pass_job_queue=False):
super(TypeHandler, self).__in... |
# -*- coding: utf-8 -*-
import sys
import time
from config import Config
from multiprocessing import managers, connection
def _new_init_timeout():
return time.time() + 0.2
sys.modules['multiprocessing'].__dict__['managers'].__dict__['connection']._init_timeout = _new_init_timeout
from multiprocessing.manage... | ger): pass
def set_data(port, k, v):
# create a shared Data object
DataManager.register('g | et_data')
manager = DataManager(address=(Config.hostname, port + 1),
authkey=Config.authkey)
manager.connect()
data = manager.get_data()
data[k] = v
|
class Floor_Object | (object) | :
"""docstring for Floor_Object"""
def __init__(self, coordinates, icon, name, interactions, description):
super(Floor_Object, self).__init__()
self.coordinates = coordinates
self.icon = icon
self.name = name
self.interactions = interactions
self.description = description
class Chest(Floor_Object):
"""A... |
import json
import urllib2
import time
import math
from pymongo import MongoClient
from pymongo import ASCENDING, DESCENDING
def debug(info):
print info
def log(info):
print info
def parseJson(url):
try:
data = json.load(urllib2.urlopen(url))
return data
except ValueError as e:
... | er() == "error":
log("Failed retrieve latency for " + key)
else:
value["name"] = key
data.append(value)
return data
def write(collection, posts):
for post in posts:
try:
| post_id = collection.insert(post)
debug(post_id)
except Exception:
log("Insertion failed for" + post["name"])
return True
def main(url):
# url = "http://stackoverflow.com/questions/1479776/too-many-values-to-unpack-exception"
data = parseJson(url)
posts = valid... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe, unittest
from frappe.defaults import *
class TestDefaults(unittest.TestCase):
def test_global(self):
clear_user_default("key1")
set_global_default("key1", "value1")
self.assertEqual(get_global_defaul... | self.assertEqual(get_user_default_as_list("key1"), ["value2", "value3"])
def test_user(self):
set_user_default("key1", "2value1")
self.assertEqual(get_user_default_as_list("key1"), ["2value1"])
set_user_default("key1", "2value2")
self.assertEqual(get_user_default("key1"), "2value2")
add_user_default("key1... | al(get_user_default_as_list("key1"), ["2value2", "3value3"])
def test_global_if_not_user(self):
set_global_default("key4", "value4")
self.assertEqual(get_user_default("key4"), "value4")
def test_clear(self):
set_user_default("key5", "value5")
self.assertEqual(get_user_default("key5"), "value5")
clear_user... |
from nose.tools import eq_
from django.test.client import RequestFactory
from airmozilla.base.tests.testbase import DjangoTestCase
from airmozilla.base.helpers import abs_static, show_duration
class TestAbsStaticHelpers(DjangoTestCase):
def tearDown(self):
super(TestAbsStaticHelpers, self).tearDown()
... | context = {}
context['request'] = RequestFactory().get('/')
result = abs_static(context, '/media/foo.png')
eq_(result, 'http://testserver/media/foo.png')
result = abs_static(context, '//my.cdn | .com/media/foo.png')
eq_(result, 'http://my.cdn.com/media/foo.png')
def test_abs_static_with_STATIC_URL(self):
context = {}
context['request'] = RequestFactory().get('/')
with self.settings(STATIC_URL='//my.cdn.com/static/'):
result = abs_static(context, 'foo.png')
... |
# Copyright 2017 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | t the full path to the dictionary's generated implementation header."""
interface_info = self.info_provider.enumerations[enum_name]
return ConvertPath(
interface_info['full_path'],
forward_slashes=True,
output_directory=self.generated_root,
output_extension='h',
base_dire... | e full path to the dictionary's conversion header."""
interface_info = self.info_provider.enumerations[enum_name]
return ConvertPath(
interface_info['full_path'],
forward_slashes=True,
output_directory=self.generated_root,
output_prefix='%s_' % self.engine_prefix,
output_... |
from Tkinter import *
root = Tk()
root.title('first test window')
#root.geometry('300x200')
frm = Frame(root)
frm_l = Frame(frm)
Label(frm_l, text='left_top').pack(side=TOP)
Label(frm_l, text='left_bottom').pack(side=BOTTOM)
frm_l.pack(side=LEFT)
frm_r = Frame(frm)
Label(frm_r, text='right_top').pack(side=TOP)
Label... | ##############################################
frm3 = Frame(root)
b = Button(frm3, text='move')
b.place(bordermode=OUTSIDE, height=100, width=100, x=50, y=50)
b.pack()
frm3.pack(side=TOP)
r | oot.mainloop()
|
import json
import threading
import time
import traceback
import urllib
from vtdb import cursor
from vtdb import dbexceptions
import environment
import framework
class TestStream(framework.TestCase):
def tearDown(self):
self.env.conn.begin()
self.env.execute("delete from vtocc_big")
self.env.conn.commi... | as cm:
cu.fetchall()
errMsg1 = "error: the query was killed either because it timed out or was canceled: Lost connectioy to MySQL serv | er during query (errno 2013)"
errMsg2 = "error: Query execution was interrupted (errno 1317)"
self.assertTrue(cm.exception not in (errMsg1, errMsg2), "did not raise interruption error: %s" % str(cm.exception))
cu.close()
except Exception, e:
self.fail("Failed with error %s %s" % (str(e), tra... |
from __future__ import print_function, unicode_literals
import importlib
import os
import sys
from django.apps import apps
from django.db.models.fields import NOT_PROVIDED
from django.utils import datetime_safe, six, timezone
from django.utils.six.moves import input
from .loader import MIGRATIONS_MODULE_NAME
class... | ask_rename(self, model_name, old_name, new_name, field_instance):
"Was this field really renamed?"
msg = "Did you rename %s.%s to %s.%s (a %s)? [y/N | ]"
return self._boolean_input(msg % (model_name, old_name, model_name, new_name,
field_instance.__class__.__name__), False)
def ask_rename_model(self, old_model_state, new_model_state):
"Was this model really renamed?"
msg = "Did you rename the %s.%... |
from sklearn2sql_heroku.te | sts.classification import generic as class_gen
|
class_gen.test_model("DecisionTreeClassifier" , "BinaryClass_10" , "db2")
|
")
ssim = self.get_ssim(image, expected)
expect(ssim).to_be_greater_than(0.98)
@gen_test
async def test_watermark_filter_centered_x(self):
image = await self.get_filtered(
"source.jpg",
"thumbor.filters.watermark",
"watermark(watermark.png,center,40,2... | 0p_80p(self):
image = await self.get_filtered(
"source.jpg",
"thumbor.filters.watermark",
"watermark(watermark.png,-30,-200,20,60,80)",
)
expected = self.get_fixture("watermarkResize60p80p.jpg")
ssim = self.get_ssim(image, expected)
expect(ssim... | lter_instance = watermark.Filter("http://dummy,0,0,0", self.context)
for source_image_width, source_image_height in SOURCE_IMAGE_SIZES:
for (
watermark_source_image_width,
watermark_source_image_height,
) in WATERMARK_IMAGE_SIZES:
for w_ra... |
qaid = cm.qaid
args = (qaid, daid, config_hash, draw_matches, view_orientation, )
match_thumb_fname = 'match_aids=%d,%d_cfgstr=%s_draw=%s_orientation=%s.jpg' % args
return match_thumb_fname
def ensure_match_img(ibs, cm, daid, qreq_=None, match_thumbtup_cache={}):
r"""
CommandLine:
pytho... | tch_thumbdir()
match_thumb_fname = get_match_thumb_fname(cm, daid, qreq_)
match_thum | b_fpath_ = ut.unixjoin(match_thumbdir, match_thumb_fname)
#if exists(match_thumb_fpath_):
# return match_thumb_fpath_
if match_thumb_fpath_ in match_thumbtup_cache:
fpath = match_thumbtup_cache[match_thumb_fpath_]
else:
# TODO: just draw the image at the correct thumbnail size
... |
import matplotlib.pyplot as plt
import numpy as np
import scalpplot
from scalpplot import plot_scalp
from positions import POS_10_5
from scipy import signal
def plot_timeseries(frames, time=None, offset=None, color='k', linestyle='-'):
frames = np.asarray(frames)
if offset == None:
offset = np.max(np.std(frame... | Scalps contains the diff | erent scalps in the
rows, sensors contains the names for the columns of scalps, locs is a dict
that maps the sensor-names to locations.
Width determines the width of the grid that contains the plots. Cmap selects
a colormap, for example plt.cm.RdBu_r is very useful for AUC-ROC plots.
Clim is a list containin... |
############################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source a... | peline):
module_remap = {
'CellLocation': [
(None, '0.9.3', None, {
'src_port_remap': {
'self': 'value'},
}),
],
'SheetReference': [
(None, '0.9.3', None, {
'src_port_r... | 'self': 'value'},
}),
],
'SingleCellSheetReference': [
(None, '0.9.3', None, {
|
AirflowSkipException)
from airflow.models import TaskInstance
from airflow.operators.bash_operator import BashOperator
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.sensors import HttpSensor, BaseSensorOperator, HdfsSensor, ExternalTaskSensor
from airflo... | low',
'start_date': DEFAULT_DATE,
'depends_ | on_past': False}
def test_external_task_sensor_fn_multiple_execution_dates(self):
bash_command_code = """
{% set s=execution_date.time().second %}
echo "second is {{ s }}"
if [[ $(( {{ s }} % 60 )) == 1 ]]
then
exit 1
fi
exit 0
"""
dag_external_id = TEST_DAG_ID + '_external'
dag... |
#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | otEquals(section.GetSection('Test'), None)
test_section = se | ction.GetSection('Test')
test_section.EmitCode('test4')
lines = section.GetLines()
self.assertTrue(lines[0] == 'test1')
self.assertTrue(lines[1] == 'test4')
self.assertTrue(lines[2] == 'test2')
self.assertTrue(lines[3] == 'test4')
self.assertTrue(lines[4] == 'test3')
if __name__ == '__main... |
# This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico | is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at | your option) any later version.
#
# Indico 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 Gen... |
obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for t... | Create a quantized dense (fully-connected) pattern.
Returns
-------
pattern : dataflow_pattern.A | ltPattern
Denotes the convolution pattern.
"""
pattern = is_op("qnn.dense")(
wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()
)
pattern = pattern.optional(lambda x: is_op("nn.bias_add")(x, is_constant()))
pattern = is_o... |
#!/usr/bin/env python
from distutils.core import setup
set | up(name='minimalisp',
version='1.0',
description='An implementation of a small lisp language',
author='Joe Jordan',
author_email='tehwalrus@h2j9k.org',
url='https://github.com/joe-jordan/minimalisp',
packages=['minimalisp'] | ,
scripts=['scripts/minimalisp'],
include_package_data=True
)
|
def get_related_fields(model):
| pass
def get_table_size(model):
pass
def get_row_size(model):
| pass
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.d | b import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Test.content'
db.alter_column(u'itest_test', 'content', self.gf('django.db.models.fields.CharField')(max_length=1850, null=True))
def backwards(self, orm):
# Changing field 'Test.content'
... | .gf('django.db.models.fields.CharField')(max_length=850, null=True))
models = {
'itest.tag': {
'Meta': {'object_name': 'Tag'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'word': ('django.db.models.fields.CharField', [], {'max_length': '35'... |
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QDragEnterEvent, QDropEvent
from urh.signalprocessing.IQArray import IQArray
from urh.cythonext import util
from urh.signalprocessing.ProtocolAnalyzer import ProtocolAnalyzer
from urh.signalprocessing.Signal import Signal
from urh.ui.painting.SignalSceneMana... |
self.scale(1, (data_max - data_min) / (plot_max-plot_min))
self.centerOn(self.view_rect().x() + self.view_rect().width() / 2, self.y_center)
def eliminate(self):
# Do _not_ call eliminate() for self.signal and self.proto_analyzer
# as these are references to the original data!
... | super().eliminate()
|
"""
Database Models Library
"""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# Model to store information about devices
class Device(db.Model):
__tablename__ = 'clients'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.Text)
api_key = db.Column(db.Text)
active ... | tamp = db.Column(db.DateTime)
# NOTE -120 -> all admins (also TODO when implementing GUI)
# NOTE -121 -> all users
def __init__(self, user_id, category, title, body, callback_url):
self.user_id = user_id
self.category = category
self.title = title
self.body = body
... | n
class Preference(db.Model):
__tablename__ = 'preferences'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
device_id = db.Column(db.Integer, db.ForeignKey('clients.id'))
key = db.Column(db.Text)
value = db.Column(db.Text)
access_... |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
# Copyright (C) 2011 Tim G L Lyons
#
# 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; eith... | hat 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# gui/editors/__init__.py
from .editaddress import Edi... |
#!/usr/bin/env python
from __future__ import absolute_import
import os
import sys
if __name__ == "__main__ | ":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "service.settings")
from django.core.management im | port execute_from_command_line
execute_from_command_line(sys.argv)
|
#_PYTHON_INSERT_SAO_COPYRIGHT_HERE_(2007)_
#_PYTHON_INSERT_GPL_LICENSE_HERE_
from numpy import arange
import sherpa.models.basic as basic
from sherpa.utils import SherpaFloat, SherpaTestCase
from sherpa.models.model import ArithmeticModel
def userfunc(pars, x, *args, **kwargs):
return x
class test_basic(SherpaTes... | else:
xx = x
pt_out = m(xx)
int_out = m(xx, xx)
except ValueEr | ror:
self.fail("evaluation of model '%s' failed" % cls)
for out in (pt_out, int_out):
self.assert_(out.dtype.type is SherpaFloat)
self.assertEqual(out.shape, x.shape)
self.assertEqual(count, 31)
|
from devassistant.command_runners import CommandRunner
from devassistant.logger import logger
class CR1(CommandRunner):
@classmethod
def matches(cls, c):
return c.comm_type | == 'barbarbar'
@classmethod
def run(cls, c):
logger.info('CR1: Doing s | omething ...')
x = c.input_res + 'bar'
return (True, x)
class CR2(CommandRunner):
@classmethod
def matches(cls, c):
return c.comm_type == 'spamspamspam'
@classmethod
def run(cls, c):
logger.info('CR2: Doing something ...')
x = c.input_res + 'spam'
retur... |
#
# TESTS
#
from nose.tools import assert_true, assert_equal, assert_raises
from mixedges import Edges, EdgeKeys, EdgeData, EdgeItems
class BaseEdgeTests(object):
def setup_edges(self):
self.edlist = [{1:"one"}, {1:"two"}, {1:"three"}, {1:"four"}]
ed1, ed2, ed3, ed4 = self.edlist
Ge = se... | else:
edgs = [(0,1), (0,0), (2,3)]
assert_equal(Ge | extras, set(edgs) | set(extras) )
assert_equal(Ge & extras, set(edgs) & set(extras) )
assert_equal(Ge ^ extras, set(edgs) ^ set(extras) )
assert_equal(Ge - extras, set(edgs) - set(extras) )
assert_equal(extra... | {}}
succ = {}
pred = {}
self.Ge = Edges(node, succ, pred, directed=False)
self.setup_edges()
class TestUndiEdges(BaseEdgeTests):
def setUp(self):
node ={4:{}}
succ = {}
pred = {}
self.Ge = Edges(node, succ, pred, directed=False)
self.setup_edge... |
#!/usr/bin/python
# Copyright (C) 2013 rapidhere
#
# Author: rapidhere <rapidhere@gmail.com>
# Maintainer: rapidhere <rapidhere@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, ... |
)
parser.add_option(
"","--key-help",
action = "store_true",default = False,
help = "show game keys"
)
opts,args = parser.parse_args()
parser.destroy()
if opts.key_help:
print "'w' or 'W' or UP-Arrow up"
print "'a' or 'A' or LF-Arrow left"
print "'s' or 'S' or DW-Arrow down"
print ... | t"
print "'q' or 'Q' quit"
sys.exit(0)
else:
app = skapp.SKApp()
app.run()
|
# $HeadURL$
__RCSID__ = "$Id$"
#
#
VM_WEB_OPERATION = "VmWebOperation"
#
VM_RPC_OPERATION = "VmRpcOperation"
#...............................................................................
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF | #EOF#EOF#EOF#EOF#E | OF
|
get
dummy_data = json.dumps(dict(
name='first_test_list',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it was actually made
self.assertTrue(created_list['listID'])
# put the id ... | def test_update_list(self):
# make a list to update
dummy_data = json.dumps(dict(
name='delete_me',
dynamic=False,
portalId=PORTAL_ID
))
created_list = self.client.create_list(dummy_data)
# make sure it was actually made
self.assertT... | date_list_id = created_list['listId']
# this is the data updating the list
update_data = json.dumps(dict(
list_name='really_delete_me',
))
# try and do the update
http_response = self.client.update_list(update_list_id, update_data)
if http_response >= 400:
... |
# Environment configuration
# Copyright (c) 2016, Tieto Corporation
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
#
# Currently static definition, in the future this could be a config file,
# or even common database with host management.
#
import logging
logge... | 8.254.50", "ifname" : "wlan1", "port": "9877", "name" : "t1-ath10k"}]
#
# HWSIM - ifaces available after modprobe mac80211_hwsim
#
devices = [{"hostname": "localhost", "ifname": "wlan0", | "port": "9868", "name": "hwsim0", "flags": "AP_VHT80 STA_VHT80"},
{"hostname": "localhost", "ifname": "wlan1", "port": "9878", "name": "hwsim1", "flags": "AP_VHT80 STA_VHT80"},
{"hostname": "localhost", "ifname": "wlan2", "port": "9888", "name": "hwsim2", "flags": "AP_VHT80 STA_VHT80"},
... |
from unittest import TestCase
import dogma
from test_dogma_values import *
class TestDogmaExtra(TestCase):
def test(self):
ctx = dogma.Context()
slot = ctx.add_module(TYPE_125mmGatlingAutoCannonII)
loc = dogma.Location.module(slot)
affectors = ctx.get_affectors(loc)
ctx.... | utes(loc, effect)
self.assertEqual(falloff, 7500)
self.assertEqual(att_range, 1200)
self.assertEqual(discharge, 0)
| capacitors = ctx.get_capacitor_all(False)
self.assertEqual(len(capacitors), 1)
self.assertIn(ctx, capacitors)
|
import datetime
from django.contrib.gis.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.core import exceptions
from django.db.models import Q
from django.conf import settings
from django_date_extensions.fields import ApproximateDa... | f.end_date else ''
# set the value or default to something sane
sorting_start_date = start or '0000-00-00'
sorting_end_date = end or start or '0000-00-00'
# To make the sorting consistent special case some parts
if not end and start == 'future':
... | self.sorting_end_date = sorting_end_date
return True
def save(self, *args, **kwargs):
self._set_sorting_dates()
super(Position, self).save(*args, **kwargs)
class PositionDataKey(DataKey):
class Meta:
app_label = 'popit'
class PositionData(Data):
person = models.... |
a = int(input())
s = "odd"
s1 = "even"
for i in range(1, a):
if i%2==0 :
print | (str(i) + | " even")
else:
print(str(i)+" odd")
|
import argparse, json
import boto3
from boto.mturk.connection import MTurkConnection
from boto.mturk.qualification import *
from jinja2 import Environment, FileSystemLoader
"""
A bunch of free functions that we use in all scripts.
"""
def get_jinja_env(config):
"""
Get a jinja2 Environment object that we can use... | s_access_key is not None:
kwargs['aws_access_key_id'] = aws_access_key
if aws_secret_key is not None:
kwargs['aws_secret_access_key'] = aws_secret_key
if sandbox:
host = 'mechanicalturk.sandbox.amazonaws.com'
else:
host='mechanicalturk.amazonaws.com'
return MTurkConnection(host=host, **kwargs)
... | some of the human-readable keys from the raw HIT properties
JSON data structure with boto-specific objects.
"""
qual = Qualifications()
if 'country' in hit_properties:
qual.add(LocaleRequirement('In', hit_properties['country']))
del hit_properties['country']
if 'hits_approved' in hit_properties:
... |
l chars that may be in an identifier
ID_CHARS = string.ascii_letters + string.digits + "_"
# These constants represent the two different types of completions
COMPLETE_ATTRIBUTES, COMPLETE_FILES = range(1, 2+1)
SEPS = os.sep
if os.altsep: # e.g. '/' on Windows...
SEPS += os.altsep
class AutoComplete:
menude... | n the current
module may be inoperative if the module was not the last to run.
"""
try:
rpcclt = | self.editwin.flist.pyshell.interp.rpcclt
except:
rpcclt = None
if rpcclt:
return rpcclt.remotecall("exec", "get_the_completion_list",
(what, mode), {})
else:
if mode == COMPLETE_ATTRIBUTES:
if what == "":
... |
self.timers[count] = timer
def repeat(self, interval, function, *args):
timer = QTimer()
timer.setSingleShot(False)
count = self.count
self.count += 1
timer.start(0)
self.app.connect(timer, SIGNAL("timeout()"), lambda: self.timeout(count, interval, function, ... | ul_opened = True
else:
msg += u'</li>'
msg += u'<li><b>%s</b>' % | m.group(1)
else:
msg += u'<br />%s' % to_unicode(line)
if ul_opened:
msg += u'</li></ul>'
print >>sys.stderr, error
print >>sys.stderr, backtrace
QMessageBox.critical(None, unicode(self.tr('Error with backend %s')) % backend... |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | stderr=None)
if test.stdout() != "Hello World\n" or test.stderr() != '' or test.status:
sys.stdout.write(test.stdout())
sys.stderr.write(test.stderr())
# The test might be run on a system that doesn't have an X server
# running, or may be run by an ID that can't connect to the server.
| # If so, then print whatever it showed us (which is in and of itself
# an indication that it built correctly) but don't fail the test.
expect = 'cannot connect to X server'
test.fail_test(test.stdout())
test.fail_test(test.stderr().find(expect) == -1)
if test.status != 1 and (test.status>>8) != 1:
... |
:')[1]\
.strip()
elif re.search('^logs can be found at', line):
parsed_ica['logPath'] = line.split()[-1]
elif re.search('^lis version', line):
parsed_ica['lisVersion'] = line.split(':')[1].strip()
return parsed_ica
def parse_from_csv(csv... | les:
f_match = re.match(self.log_matcher, os.path.basename(log_file) | )
if not f_match:
continue
log_dict = dict.fromkeys(self.headers, '')
collected_data = self.collect_data(f_match, log_file, log_dict)
try:
if any(d for d in list_log_dict if
(d.get('BlockSize_KB', None)
... |
ython3
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | 'age=gt30'
Returns:
List[dict]: a list of resources matching the search criteria.
"""
response = http.request('GET', format_url(path, query=query))
if response.status > 299:
LOGGER.error("Failed to search resource %s, response: %s" % (query,
response.data))
return None
bundle = json.lo... | :
"""Finds a RiskAssessment.
The target references a certain QuestionnaireResponse and is about the
specified disease
"""
def match(res):
return extract_qid(res) == qid and extract_disease(res) == disease
return next(filter(match, resources), None)
def build_examples(patient, questionnaire_response)... |
econdary ) ) \
or ( isinstance( types[1], main ) and isinstance( types[0], secondary ) ) ):
return True
elif 3 <= len( types ):
classes = set( [tp.__class__ for tp in types[:3]] )
desired = set( [main] + list( secondary ) )
return classes == desired
else:
return ... | lf, type ):
for f in self.sequence:
type | = f( type )
return type
def is_my_case( self, type ):
"""returns True, if type represents the desired declaration, False otherwise"""
return isinstance( self.__apply_sequence( type ), self.declaration_class )
def get_declaration( self, type ):
"""returns reference to the declar... |
def ch | eck(m | sg):
if msg == 'hello':
print(hello)
else:
print(goodbye)
check('greetings') |
az.plot_dist | (b, rug=True, quantiles=[.25, .5, .75], cumulative=Tru | e)
|
#!/usr/bin/python
import os
from setuptools import setup, find_packages
SRC_DIR = os.path.dirname(__file__)
CHANGES_FILE = os.path.join(SRC_DIR, "CHANGES")
with open(CHANGES_FILE) as fil:
version = fil.readline().split()[0]
setup(
name="state-machine-crawler",
description="A library for fo | llowing automata based programming model.",
version=version,
packages=find_packages(),
setup_requires=["nose"],
tests_require=["mock==1.0.1", "coverage"],
install_requires=["werkzeug", "pydot2", "pyparsing==1.5.2"],
test_suite='nose.collector',
author="Anton Berezin",
author_email="gurun... | machine_crawler:entry_point'
]
},
include_package_data=True
)
|
# This file is part of jobservice.
# Copyright 2010 Jacob Peddicord <jpeddicord@ubuntu.com>
#
# jobservice 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)... | POSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with jobservice. If not, see <http://www.gnu.org/licenses/>.
import logging
from dbus import SystemBus, DBusException, Interface, UInt64
log = logging.getLogger | ('policy')
class DeniedByPolicy(DBusException):
_dbus_error_name = 'com.ubuntu.JobService.DeniedByPolicy'
class Policy:
def __init__(self, enforce=True):
self.enforce = enforce
self.bus = SystemBus()
self.dbus_iface = None
self.pk = Interface(self.bus.get_object('org.freed... |
from sys import maxsize
class Contact:
def __init__(self, Firstname=None, Middlename=None, Lastname=None, Nickname=None, Title=None, Company=None, Address=None, Home=None, Mobile=None, Work=None,
Fax=None, Email=None, Email2=None, Email3=None, Homepage=None, Bday=None, Bmonth=None, Byear=Non... | return (self.id is None or other.id is Non | e or self.id == other.id) and self.Firstname == other.Firstname and self.Lastname == other.Lastname
def __repr__(self):
return "%s:%s;%s" % (self.Firstname, self.Lastname, self.Middlename)
def id_or_max(self):
if self.id:
return int(self.id)
else:
return maxsize... |
"""
Estimation of the total magnetization vector of homogeneous bodies.
It estimates parameters related to the magnetization vector of homogeneous
bodies.
**Algorithms**
* :class:`~fatiando.gravmag.magdir.DipoleMagDir`: This class estimates
the Cartesian components of the magnetization vector of homogeneous
dipo... | ely, R. (1996), Potential theory in gravity and magnetic applications:
CUP
.. note:: Assumes x = North, y = East, z = Down.
Parameters:
* x, y, z : 1d-arrays
| The x, y, z coordinates of each data point.
* data : 1d-array
The total field magnetic anomaly data at each point.
* inc, dec : floats
The inclination and declination of the inducing field
* points : list of points [x, y, z]
Each point [x, y, z] is the center of a dipole. Will in... |
leDefinition'
t[0] = t[1] + [t[2]]
def p_module_list_2 (t):
'module_list : ModuleDefinition'
t[0] = [t[1]]
#--- ITU-T Recommendation X.680 -----------------------------------------------
# 11 ASN.1 lexical items --------------------------------------------------------
# 11.2 Type references
def p_type... | .val == 'Remote-Operations-Information-Objects':
x880_module_begin()
def p_TagDefault_1 (t):
'''TagDefault : EXPLICIT TAGS
| | IMPLICIT TAGS
| AUTOMATIC TAGS '''
t[0] = Default_Tags (dfl_tag = t[1])
def p_TagDefault_2 (t):
'TagDefault : '
# 12.2 The "TagDefault" is taken as EXPLICIT TAGS if it is "empty".
t[0] = Default_Tags (dfl_tag = 'EXPLICIT')
def p_ModuleIdentifier_1 (t):
'ModuleIdentifi... |
#!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from __future__ import unicode_literals
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os | .path.join(here, 'README.rst'), 'rb').read().decode('utf-8')
except IOError:
README = ''
old_python = sys.versi | on_info < (2, 7)
setup(
name='Powerline',
version='beta',
description='The ultimate statusline/prompt utility.',
long_description=README,
classifiers=[],
author='Kim Silkebaekken',
author_email='kim.silkebaekken+vim@gmail.com',
url='https://github.com/Lokaltog/powerline',
scripts=[
'scripts/powerline',
's... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-22 07:11
from __future__ import unicode_literals
from django.core.management.sql import emit_post_migrate_signal
from | django.db import migrations
def add_executive_group(apps, schema_editor):
# create group
db_alias = schema_editor.connection.alias
emit_post_migrate_signal(2, False, db_alias)
Group = apps.get_model('auth', 'Group')
Permission = apps.get_model('auth', 'Permission')
executive_group, created = G... | et(codename='can_access_learningunit')
executive_group.permissions.add(can_access_learningunit)
class Migration(migrations.Migration):
dependencies = [
('base', '0207_auto_20171220_1035'),
]
operations = [
migrations.RunPython(add_executive_group),
] |
# Twitter profile image updater
# http://twitter.com/account/update_profile_image.json
# image = [imagefile]
import sys
import os
import random
import re
import urllib
import json
import urllib2
import oauth2 as oauth
import time
import wcommon
def encode_file_data(image):
boundary = hex(int(time.time()))[2:]
he... | postdata = encode_fil | e_data(image)
r, c = wcommon.oauth_req(url, http_method="POST", post_body=postdata, http_headers=headers)
if r.status != 200:
print "Updating profile image did not succeed: Status %d" % (r.status)
|
1, 256
if not fits(a):
fontsize = a
elif fits(b):
fontsize = b
else:
while b - a > 1:
c = (a + b) // 2
if fits(c):
a = c
else:
b = c
fontsize = a
_fit_cache[key] = fontsize
return fontsi... | me, bold, italic, underline,
width, widthem, strip, color, background, antialias,
ocolor, owidth, scolor, shadow, gcolor=gcolor, shade=0, align=align,
lineheight=lineheight, pspace=pspace, cache=cache)
surf = surf0.copy()
_surf... | pygame.surfarray.pixels_alpha(surf)
# array[:, :] = (array[:, :] * alpha).astype(array.dtype)
# del array
elif spx is not None:
surf0 = getsurf(text, fontname, fontsize, sysfontname, bold, italic, underline,
width, widthem, strip, color=color, background=(0, 0,... |
decl(self, value):
self._decl = value
@property
def entry(self):
return self._entry
@entry.setter
def entry(self, value):
self._entry = value
@property
def entry_node(self):
return self._entry_node
@entry_node.setter
def entry_node(self, value):
self._entry_node = value
@prope... | ores the resulting CFG.
"""
bytecode = self.decl.bytecode
self.entry = BasicBlock(BasicBlock.ENTRY, self.decl, -1)
self.exit = Basi | cBlock(BasicBlock.IMPLICIT_RETURN, self.decl, -1)
self._blocks = ControlFlow.make_blocks(self.decl, bytecode)
self.__build_flowgraph(bytecode)
# logger.debug("CFG(%s) :=\n%s", self.decl, self.graph.to_dot())
def __build_flowgraph(self, bytecode):
g = DiGraph(multiple_edges=False)
self.entry_node... |
we are not dealing with a chain of orphan blocks
if cur_block is None and block_ids[-1] != BLOCK_GENESIS_HASH:
self.logger.error('Block processing failed (chain of orphan blocks)')
return False
# For now, the longest chain wins
if len(block_ids) + from_height > latest_in... | contracts.insert(index, dependency)
# Calculate final merkle | root hash + sign block
block.merkle_root_hash = block.merkle_tree.build()
block.sign(self.my_member)
if self.check_block(block):
self.logger.debug('Created block with target difficulty 0x%064x', block.target_difficulty)
if self.process_block(block):
self.... |
from __future__ import absolute_import
import os.path
from dpark.util import get_logger
logger = get_logger(__name__)
# workdir used in slaves for internal f | iles
#
DPARK_WORK_DIR = '/tmp/dpark'
if os.path.exists('/dev/ | shm'):
DPARK_WORK_DIR = '/dev/shm,/tmp/dpark'
# uri of mesos master, host[:5050] or or zk://...
MESOS_MASTER = 'localhost'
# mount points of MooseFS, must be available on all slaves
# for example: '/mfs' : 'mfsmaster',
MOOSEFS_MOUNT_POINTS = {
}
# consistant dir cache in client, need patched mfsmaster
MOOSEFS_DI... |
import cPickle as pickle
import numpy as np
import re
from math import log
from dic import Info
from config.config import config
from tools import tokenlize, comp_tuple, weights
class query_voc(object):
def __init__(self, tokens, dic):
self.tokens = tokens
self.dic = dic
class query_entry(objec... | es, query, index_type='tiered'):
tokens = tokenlize(query)
query_match = [[]]
for token in tokens:
match_tokens = []
if '*' in token:
regex = re.compile(token)
match_tokens = | [string for string in voc.tokens if re.match(regex, string)]
else:
match_tokens.append(token)
tmp = []
if len(match_tokens) > 0:
for t1 in match_tokens:
for t2 in query_match:
tmp.append(t2 + [t1])
query_match = tmp
tmp... |
'''
Created on 21 Dec 2013
@author: huw
'''
from ConfigParser import ConfigParser
class TftpudSettings:
'''
A class to hold the settings for the TftpudServerGui application.
'''
def __init__(self):
'''
Constructor
'''
self.saveLastUsed = False
self.defaultDir... | 'defaultDirectory', self.defaultDirectory)
cfg.set(serverSection, 'saveLastUsed', self.saveLastUsed)
cfg.write(f)
def read(self, f):
'''Read the settings from the given file handle.'''
cfg = ConfigParser()
cfg.readfp(f)
netSection = 'Network'
... | (netSection, 'defaultIpAddress')
if cfg.has_option(netSection, 'defaultPort'):
self.defaultPort = cfg.getint(netSection, 'defaultPort')
if cfg.has_option(netSection, 'ephemeralPortsFrom'):
self.ephemeralPorts[0] = cfg.getint(netSection, 'ephemeralPortsFrom')
... |
# -*- coding: utf-8 -*-
# EDIS - a simple cross-platform IDE for C
#
# This file is part of Edis
# Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail>
# License: GPLv3 (see http://www.gnu.org/licenses/gpl.html)
from PyQt4.Qsci import QsciLexerCPP
from PyQt4.QtGui import QColor
from src import editor_sc... | double')
elif kset == 2:
# Funciones definidas en stdio.h y stdlib.h
return ('fprintf fscanf printf scanf sprintf | sscanf vfprintf '
'vprintf vsprintf fclose fflush fopen freopen remove '
'rename setbuf tmpfile tmpnam fgetc fgets fputc fputs '
'getc getchar gets putc putchar puts ungetc fread fseek '
'fsetpos ftell rewind clearerr feof ferror perror '
... |
import pytest
from unittest.mock import patch
from case import mock
from kombu import Connection
class test_get_manager:
@mock.mask_modules('pyrabbit')
def test_without_pyrabbit(self):
with pytest.raises(ImportError):
Connection('amqp://').get_manager()
@mock.module_exists('pyrabbi... |
'manager_userid': 'george',
| 'manager_password': 'bosco',
}).get_manager()
assert manager is not None
Client.assert_called_with(
'admin.mq.vandelay.com:808', 'george', 'bosco',
)
|
# Script Version: 1.0
# Author: Te Chen
# Project: AMA3D
# Task Step: 1
import sys
import urllib2
import time
VERSION = '4.0.0'
def prepare_cath():
ver = VERSION.replace('.', '_')
download_file(ver, 'CathDomainList')
download_file(ver, 'CathNames')
download_file(ver, 'CathDomainDescriptionFile')
def download_fil... | " + file_name
if __name__ == '__main__':
# Download necessary files when start
prepare_cath()
# This part triggers all the tasks afterwards.
|
print "trigger\t%s\t%d\t%d"%('', 2, 1)
sys.stdout.flush()
print "trigger\t%s\t%d\t%d"%('', 3, 1)
sys.stdout.flush()
# Write result to a file as well just for testing
with open("Domain_Result", "w") as f:
f.write("Topology\tPDB ID\tR\tResolution\tChain Length\tScore\n") |
'''
This script helps you scrap stock data avaliable on Bloomberg Finance
and store them locally.
Please obey applicable local and federal laws and applicable API term of use
when using this scripts. I, the creater of this script, will not be responsible
for any legal issues resulting from the use of this script.
@au... | wil | l scrap minute by minute data for one day, while others will be daily close price
# Feel free to modify them for your own need
options = ["1_DAY", "1_MONTH", "1_YEAR", "5_YEAR"]
def setup():
try:
os.mkdir("data")
except Exception as e:
pass
for option in options:
try:
os... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Stefan Mauerberger"
__copyright__ = "Copyright (C) 2017 Stefan Mauerberger"
__license__ = "GPLv3"
import numpy as np
from sys import stdout
from matplotlib import pyplot as plt
from matplotlib import animation
from plotting import prepare_map, lllat, lllon,... | bar
p = int(100.*(i+1)/mu_C.shape[0]) # Progress
stdout.write('\r[' + p*'#' + (100-p)*'-' + '] %3i' % p + '%' )
if (i+1) == mu_C.shape[0]:
stdout.write('\n')
return tpc_mu, tpc_sd
frames = mu_C.shape[0]
duration | = 30. # s
interval = 1000.*duration/frames # ms
anim = animation.FuncAnimation(fig, animate, save_count=0, \
frames=frames, interval=interval, blit=False)
# Save video
anim.save('../animation.avi', dpi=dpi, extra_args=['-vcodec', 'msmpeg4v2'])
# Last frame; Necessary for LaTeX beamer
... |
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
dp = []
for _ in range(m):
dp.append([None] * (n))
... | elif col == n-1:
cost = grid[row][col] + solve(row+1, col)
else:
cost = grid[row][col] + min(solve(row, col+1), solve(row+1, col))
dp[row][col] = cost
# print 'dp(%s,%s) is %s' % (row, | col, ans)
return cost
return solve(0, 0) |
from django.test import TestCase
from morelia.decorators import tags
from smarttest.decorators import no_db_testcase
from tasks.factories import TaskFactory, UserFactory
@no_db_testcase
@tags(['unit'])
class TaskGetAbsoluteUrlTest(TestCase):
''' :py:meth:`tasks.models.Task.get_absolute_url` '''
def test_sh... | # Arrange
owner = UserFactory.build(pk=1)
task = TaskF | actory.build(owner=owner, author=owner)
# Act
url = task.get_absolute_url()
# Assert
self.assertEqual(url, '/%s/' % owner.username)
|
"""Offers a simple XML-RPC dispatcher for django_xmlrpc
Author::
Graham Binns
Credit must go to Brendan W. McAdams <brendan.mcadams@thewintergrp.com>, who
posted the original SimpleXMLRPCDispatcher to the Django wiki:
http://code.djangoproject.com/wiki/XML-RPC
New BSD License
===============
Copyright (c) 2007, ... | ML-RPC method to get the details for
"""
# See if we can find the method in our funcs dict
# TODO: Handle this better: We really should return something more
# formal than an AttributeError
func = self.funcs[met | hod]
try:
sig = func._xmlrpc_signature
except:
sig = {
'returns': 'string',
'args': ['string' for arg in getargspec(func)[0]],
}
return [sig['returns']] + sig['args']
|
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | debba1406a5')
version('6.1.1', '4c175f86e11eb32d8bf9872ca3a8e11d')
version('6.1.0', '86ee6e54ebfc4a90b643a65e402c4048')
version('6.0.0a', 'b7ff2d88cae7f8085bd5006096eed470')
version('6.0.0', '6ef5869ae735db9995619135bd856b84')
version('5.1.3', 'a082867cbca5e898371a97bb27b31fea')
# Old version... | ='build')
depends_on('automake', type='build')
depends_on('libtool', type='build')
depends_on('m4', type='build')
# gmp's configure script seems to be broken; it sometimes misdetects
# shared library support. Regenerating it fixes the issue.
force_autoreconf = True
def configure_args(self)... |
l('ABCDEFGH', expected_patch),
root_device_args)
def test_minimum_size(self):
baremetal._apply_root_device_strategy(
self.app.client_manager,
node_uuid='MOCK_UUID',
strategy='smallest',
minimum_size=10)
self.assertEqual(self.b... | '10.0.0. | 0/30',
[623, 6230, 6235],
[['admin', 'password'], ['admin', 'admin']],
self.existing_nodes)
self.assertEqual([
{'ip': '10.0.0.1', 'port': 6230,
'username': 'admin', 'password': 'password'},
{'ip': '10.0.0.1', 'port': 6230,
'us... |
#!/usr/bin/env python
#
# This file is part of the SSM_LinearArray (Sound Sources Mapping
# using a Linear Microphone Array)
# developed by Daobilige Su <daobilige DOT su AT student DOT uts DOT edu DOT au>
#
# This file is under the GPLv3 licence.
#
import rospy
from std_msgs.msg import String
from std_msgs.msg impo... | pyaudio
from rospy.numpy_msg import numpy_msg
import numpy as np
import time
import signal
import os
import sys
CHUNK = 3200
FORMAT = pyaudio.paInt16
CHANNELS = 4
RATE = 16000
DEV_IDX = 5
p = pyaudio.PyAudio()
pub_mic_array = rospy.Publisher("/microphone_array_raw", numpy_msg(Int32MultiArray),queue_size=1)
def callb... | ng(in_data, dtype=np.int16)
print('sending...')
numpydata_msg = Int32MultiArray()
numpydata_msg.data = numpydata
pub_mic_array.publish(numpydata_msg)
return (in_data, pyaudio.paContinue)
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
inp... |
from __future__ import unicode_literals
from logging import getLogger
from django.conf import settings
from django.core.cache import cache
from django.views.generic import View
from django.http import JsonResponse, HttpResponseBadRequest
from django.template.defaultfilters import slugify
from ratelimit.mixins import ... | cache.set(self.get_cache_key(), data, self.cache_timeout)
return data
class AutoCompleteView(BaseApiView):
def get(self, request, *args, **kwargs):
"""
Store the `q` keyword in the class namespace.
| """
if not self.request.GET.get('q'):
return HttpResponseBadRequest('No search term given')
self.q = self.request.GET['q']
if len(self.q) < self.min_keyword_length:
error_str = 'Search term must be at least {} characters long.'
return HttpResponseBadRequest(
... |
#
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# versio... | urces = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
... | %d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename)
def test_can_supply_... |
# -*- coding: utf-8 -*-
# Copyright(C) | 2012-2019 Budget Insight
# yapf-compatible
from weboob.browser import AbstractBrowser
class NetfincaBrowser(AbstractBrowser):
PARENT = 'netfinca'
BASEURL = 'https://www. | cabourse.credit-agricole.fr'
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... |
self.v3_users.append(self.v3_user)
def setup_test_project(self):
"""Set up a test project."""
self.test_project = rand_name('test_project_')
self.test_description = rand_name('desc_')
resp, self.project = self.client.create_project(
n... | a test v3 role."""
self.test_role = rand_name('role')
resp, self.v3_role = self.client.create_role(self.test_role)
self.v3_roles.append(self.v3_role)
def teardown_all(self):
for user in self.users:
self.client.delete_user(user['id'])
f... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 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.
from cinder import test
c... |
scheme = 'http'
scheme = app.config['S3_URL_SCHEME'] or 'https'
bucket_path = '%s.%s' % (app.config['S3_BUCKET_NAME'],
app.config['S3_BUCKET_DOMAIN'])
if app.config['S3_CDN_DOMAIN']:
bucket_path = '%s' % app.config['S3_CDN_DOMAIN']
if a... | n's configuration using the Flask-S3
`configuration`_ variables.
:param app: a :class:`flask.Flask` application object.
:param user: an AWS Access Key ID. You can find this key in the
Security Credentials section of your AWS account.
:type user: `basestring` or None
:param passwo... | the Security Credentials section of your AWS
account.
:type password: `basestring` or None
:param bucket_name: the name of the bucket you wish to server your
static assets from. **Note**: while a valid
character, it is recommended... |
# Generated by Django 2.1 on 2018-08-13 08:04
from django.d | b import migrations
class Migration(migrations.Migration):
dependencies = [
('ibms', '0006_auto_20180813_1603'),
]
operations = [
migrations.RenameField(
model_name='serviceprioritymappings',
| old_name='costcentreName',
new_name='costCentreName',
),
]
|
import numpy as np
from scipy.interpolate import interp1d
from astropy.io import ascii
from astropy import units as u
from newdust import constants as c
from newdust.graindist.composition import _find_cmfile
__all__ = ['CmSilicate']
RHO_SIL = 3.8 # g cm^-3
class CmSilicate(object):
"""
| **ATTRIBUTES... | lam_cm = c._lam_cm(lam, unit)
return self._interp_helper(lam_cm, self.interps[1])
def cm(self, lam, unit='kev'):
return self.rp(lam, unit=unit) + 1j * self.ip(lam, unit=unit)
def plot(self, ax, lam=None, unit='kev', rppart=True, impart=True):
if lam is None:
rp_m1 =... | th (um)"
else:
rp_m1 = np.abs(self.rp(lam, unit=unit)-1.0)
ip = self.ip(lam, unit)
x = lam
assert unit in c.ALLOWED_LAM_UNITS
if unit == 'kev': xlabel = "Energy (keV)"
if unit == 'angs': xlabel = "Wavelength (Angstroms)"
if rppart:... |
specific language governing permissions and
# limitations under the License.
"""Handlers for generating various frontend pages."""
__author__ = 'Saifu Angto (saifu@google.com)'
import json
from models import models
from models.config import ConfigProperty
from models.counters import PerfCounter
from utils import Bas... | (
'activity?unit=%s&lesson=%s' % (unit_id, lesson_id))
elif lesson_id == len(lessons):
self.template_value['next_button_url'] = ''
else:
self.template_value['next_button_url'] = (
'unit?unit=%s&lesson=%s' % (unit_id, lesson_id + 1))
self.r... | e(unit_id)
self.response.out.write(lesson_id)
#self.render('unit.html')
class UnitHandler(BaseHandler):
"""Handler for generating unit page."""
def get(self):
"""Handles GET requests."""
if not self.personalize_page_and_get_enrolled():
return
user = se... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResConfigSettings(mode | ls.TransientModel):
_inherit = 'res.config.settings'
group_l10n_in_reseller = fields.Boolean(implied_grou | p='l10n_in.group_l10n_in_reseller', string="Manage Reseller(E-Commerce)")
|
from __future__ import print_function
import flask
import os
import threading
import time
import webbrowser
from tornado.wsgi import WSGIContainer
from tor | nado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
_basedir = os.path.join("..", os.path.dirname(__file__))
app = flask.Flask(__name__, static_path="/unused")
PORT=5009
http_server = HTTPServer(WSGIContainer(app))
"""this is a simple server to facilitate developing the | docs. by
serving up static files from this server, we avoid the need to use a
symlink.
"""
@app.route('/')
def welcome():
return """
<h1>Welcome to the Bokeh documentation server</h1>
You probably want to go to <a href="/en/latest/index.html"> Index</a>
"""
@app.route('/en/latest/<path:filename>')... |
"""
Regression tests for rescinding outstanding subscription requests.
"""
from twisted.words.protocols.jabber.client import IQ
from servicetest import (EventPattern, wrap_channel, assertLength,
assertEquals, call_async, sync_dbus)
from hazetest import exec_test
import constants as cs
import ns
jid = 'marco@... | y')).addElement('item')
item['jid'] = jid
item['subscription'] = 'none'
item['ask'] = 'subscribe'
stream.send(iq)
# In response, Haze should add Marco to subscribe:remote-pending,
# but libpurple has no such concept, so nothing much happens.
# The user decides that they don't care what Mar... | remove him from stored
stored.Group.RemoveMembers([h], '')
event = q.expect('stream-iq', iq_type='set', query_ns=ns.ROSTER)
item = event.query.firstChildElement()
assertEquals(jid, item['jid'])
assertEquals('remove', item['subscription'])
else:
... |
, COMMENTS_FIRST_FEW, SITE_ID
import base64, datetime
COMMENTS_PER_PAGE = 20
class PublicCommentManipulator(AuthenticationForm):
"Manipulator that handles public registered comments"
def __init__(self, user, ratings_required, ratings_range, num_rating_choices):
AuthenticationForm.__init__(self)
... | return
return validators.hasNo | Profanities(field_data, all_data)
def get_comment(self, new_data):
"Helper function"
return comments.Comment(None, self.get_user_id(), new_data["content_type_id"],
new_data["object_id"], new_data.get("headline", "").strip(),
new_data["comment"].strip(), new_data.get("rating1... |
import unittest
from unittest.mock import patch, MagicMock
from twitchcancer.api.pubsubmanager import PubSubManager
# PubSubManager.instance()
class TestPubSubManagerInstance(unittest.TestCase):
# check that we only store one instance of any topic
@patch('twitchcancer.api.pubsubmanager.PubSubManager.__new__... | p.unsubscribe("client", "topic")
# check that the topic wasn't created
self.assertTrue("topic" not in p.subscriptions)
# PubSubManager.unsubscribe_all()
class TestPubSubManagerUnsubscribeAll(unittest.TestCase):
# check t | hat unsubcribe is called for all topics
@patch('twitchcancer.api.pubsubmanager.PubSubManager.unsubscribe')
def test_unsubscribe_all(self, unsubscribe):
p = PubSubManager()
p.subscriptions["topic"] = {"client"}
p.subscriptions["topic 2"] = {"client"}
p.unsubscribe_all("client")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.